Code
stringlengths
131
28.2k
Unit Test
stringlengths
40
32.1k
__index_level_0__
int64
0
2.63k
#ifndef AROLLA_UTIL_TEXT_H_ #define AROLLA_UTIL_TEXT_H_ #include <ostream> #include <string> #include <utility> #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { class Text { public: Text() = default; explicit Text(const char* s) : data_(s) {} explicit Text(absl::string_view view) : data_(view) {} explicit Text(const std::string& s) : data_(s) {} explicit Text(std::string&& s) : data_(std::move(s)) {} explicit Text(const absl::Cord& cord) : data_(std::move(cord)) {} Text& operator=(const char* s) { data_ = s; return *this; } Text& operator=(absl::string_view s) { data_.assign(s.data(), s.size()); return *this; } Text& operator=(const std::string& s) { data_ = s; return *this; } Text& operator=(std::string&& s) { data_ = std::move(s); return *this; } Text& operator=(const absl::Cord& cord) { data_ = std::string(cord); return *this; } absl::string_view view() const { return data_; } operator absl::string_view() const { return data_; } friend bool operator==(const Text& lhs, const Text& rhs) { return lhs.data_ == rhs.data_; } friend bool operator==(const char* lhs, const Text& rhs) { return lhs == rhs.data_; } friend bool operator==(const Text& lhs, const char* rhs) { return lhs.data_ == rhs; } friend bool operator!=(const Text& lhs, const Text& rhs) { return !(lhs == rhs); } friend bool operator<(const Text& lhs, const Text& rhs) { return lhs.data_ < rhs.data_; } friend bool operator<=(const Text& lhs, const Text& rhs) { return lhs.data_ <= rhs.data_; } friend bool operator>(const Text& lhs, const Text& rhs) { return lhs.data_ > rhs.data_; } friend bool operator>=(const Text& lhs, const Text& rhs) { return lhs.data_ >= rhs.data_; } private: std::string data_; }; inline std::ostream& operator<<(std::ostream& stream, const Text& value) { return stream << "Text{" << value.view() << "}"; } AROLLA_DECLARE_REPR(Text); AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(Text); } #endif #include "arolla/util/text.h" #include <cstddef> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "arolla/util/fingerprint.h" #include "arolla/util/repr.h" namespace arolla { namespace { absl::string_view Utf8CopyFirstNCodePoints(size_t n, absl::string_view data) { size_t offset = 0; for (; n > 0 && offset < data.size(); --n) { const auto byte = data[offset]; if ((byte & 0x80) == 0) { offset += 1; } else if ((byte & 0xe0) == 0xc0) { offset += 2; } else if ((byte & 0xf0) == 0xe0) { offset += 3; } else if ((byte & 0xf8) == 0xf0) { offset += 4; } else { offset += 1; } } return data.substr(0, offset); } } ReprToken ReprTraits<Text>::operator()(const Text& value) const { constexpr size_t kTextAbbrevLimit = 120; ReprToken result; auto text = value.view(); auto prefix = Utf8CopyFirstNCodePoints(kTextAbbrevLimit, text); if (prefix.size() == text.size()) { result.str = absl::StrCat("'", absl::Utf8SafeCHexEscape(text), "'"); } else { result.str = absl::StrCat("'", absl::Utf8SafeCHexEscape(prefix), "... (TEXT of ", text.size(), " bytes total)'"); } return result; } void FingerprintHasherTraits<Text>::operator()(FingerprintHasher* hasher, const Text& value) const { hasher->Combine(value.view()); } }
#include "arolla/util/text.h" #include <string> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::testing::Eq; using ::testing::MatchesRegex; TEST(TextTest, Constructor) { EXPECT_THAT(Text("Hello").view(), Eq("Hello")); std::string hello = "Hello"; EXPECT_THAT(Text(hello).view(), Eq("Hello")); absl::string_view hello_view = hello; EXPECT_THAT(Text(hello_view).view(), Eq("Hello")); absl::Cord hello_cord(hello); EXPECT_THAT(Text(hello_cord).view(), Eq("Hello")); } TEST(TextTest, CopyAndMoveConstructors) { static_assert(std::is_nothrow_move_constructible<Text>::value); Text src("Google"); Text copied(src); EXPECT_THAT(copied, Eq(src)); Text moved(std::move(src)); EXPECT_THAT(moved, Eq(copied)); } TEST(TextTest, CopyAndMoveAssignment) { static_assert(std::is_nothrow_move_assignable<Text>::value); Text src("Google"); Text copied = src; EXPECT_THAT(copied, Eq(src)); Text moved = std::move(src); EXPECT_THAT(moved, Eq(copied)); } TEST(TextTest, AssignmentFromString) { std::string google = "Google"; { Text val("x"); val = "Google"; EXPECT_THAT(val.view(), Eq(google)); } { Text val("x"); val = google; EXPECT_THAT(val.view(), Eq(google)); } { absl::string_view google_view = google; Text val("x"); val = google_view; EXPECT_THAT(val.view(), Eq("Google")); } { absl::Cord google_cord(google); Text val("x"); val = google_cord; EXPECT_THAT(val.view(), Eq("Google")); } { Text val("x"); val = std::move(google); EXPECT_THAT(val.view(), Eq("Google")); } } TEST(TextTest, Repr) { EXPECT_THAT( GenReprToken( Text("\"\xe8\xb0\xb7\xe6\xad\x8c\" is Google\'s Chinese name\n")), ReprTokenEq( "'\\\"\xe8\xb0\xb7\xe6\xad\x8c\\\" is Google\\'s Chinese name\\n'")); const std::string pattern = "A" "\xc3\x86" "\xe0\xa0\x80" "\xf0\x90\x80\x80"; std::string data = pattern; for (int i = 0; i < 8; ++i) { data += data; } EXPECT_THAT(Repr(Text(data)), MatchesRegex("'(" + pattern + "){30}[.]{3} \\(TEXT of 2560 bytes total\\)'")); } } }
2,487
#ifndef AROLLA_UTIL_PREALLOCATED_BUFFERS_H_ #define AROLLA_UTIL_PREALLOCATED_BUFFERS_H_ #include <cstddef> namespace arolla { constexpr size_t kZeroInitializedBufferAlignment = 32; constexpr size_t kZeroInitializedBufferSize = 16 * 1024; const void* GetZeroInitializedBuffer(); } #endif #include "arolla/util/preallocated_buffers.h" #include <cstring> #include "arolla/util/memory.h" namespace arolla { namespace { const void* CreateBuffer() { auto alloc = AlignedAlloc(Alignment{kZeroInitializedBufferAlignment}, kZeroInitializedBufferSize); std::memset(alloc.get(), 0, kZeroInitializedBufferSize); return alloc.release(); } } const void* GetZeroInitializedBuffer() { static const void* const kBuffer = CreateBuffer(); return kBuffer; } }
#include "arolla/util/preallocated_buffers.h" #include <cstddef> #include <cstdint> #include "gtest/gtest.h" #include "absl/types/span.h" namespace arolla { namespace { template <typename T> class ZeroInitializedBufferTest : public ::testing::Test { public: typedef T value_type; }; using Types = testing::Types<char, int, float, int64_t, double, uint64_t>; TYPED_TEST_SUITE(ZeroInitializedBufferTest, Types); TYPED_TEST(ZeroInitializedBufferTest, TestAccess) { using T = typename TestFixture::value_type; static_assert(alignof(T) <= kZeroInitializedBufferAlignment); size_t size = kZeroInitializedBufferSize / sizeof(T); absl::Span<const T> data(static_cast<const T*>(GetZeroInitializedBuffer()), size); for (const T& v : data) { ASSERT_EQ(v, 0); } } } }
2,488
#ifndef AROLLA_UTIL_BINARY_SEARCH_H_ #define AROLLA_UTIL_BINARY_SEARCH_H_ #include <cstddef> #include <cstdint> #include <optional> #include "absl/base/attributes.h" #include "absl/types/span.h" namespace arolla { size_t LowerBound(float value, absl::Span<const float> array); size_t LowerBound(double value, absl::Span<const double> array); size_t LowerBound(int32_t value, absl::Span<const int32_t> array); size_t LowerBound(int64_t value, absl::Span<const int64_t> array); size_t UpperBound(float value, absl::Span<const float> array); size_t UpperBound(double value, absl::Span<const double> array); size_t UpperBound(int32_t value, absl::Span<const int32_t> array); size_t UpperBound(int64_t value, absl::Span<const int64_t> array); template <typename T, typename Iter> Iter GallopingLowerBound(Iter begin, Iter end, const T& value); } namespace arolla::binary_search_details { constexpr size_t kSupremacySizeThreshold = 1'000'000; template <typename T> size_t LowerBound(T value, absl::Span<const T> array); template <typename T> size_t UpperBound(T value, absl::Span<const T> array); template <typename T, typename Predicate> inline ABSL_ATTRIBUTE_ALWAYS_INLINE std::optional<size_t> SmallLinearSearch( absl::Span<const T> array, Predicate predicate) { if (array.size() <= 2) { if (array.empty() || predicate(array[0])) { return 0; } else if (array.size() == 1 || predicate(array[1])) { return 1; } return 2; } return std::nullopt; } size_t UpperBoundImpl(float value, absl::Span<const float> array); size_t UpperBoundImpl(double value, absl::Span<const double> array); size_t UpperBoundImpl(int32_t value, absl::Span<const int32_t> array); size_t UpperBoundImpl(int64_t value, absl::Span<const int64_t> array); size_t LowerBoundImpl(float value, absl::Span<const float> array); size_t LowerBoundImpl(double value, absl::Span<const double> array); size_t LowerBoundImpl(int32_t value, absl::Span<const int32_t> array); size_t LowerBoundImpl(int64_t value, absl::Span<const int64_t> array); template <typename T> inline ABSL_ATTRIBUTE_ALWAYS_INLINE size_t LowerBound(T value, absl::Span<const T> array) { if (auto result = SmallLinearSearch(array, [value](T arg) { return !(arg < value); })) { return *result; } return LowerBoundImpl(value, array); } template <typename T> inline ABSL_ATTRIBUTE_ALWAYS_INLINE size_t UpperBound(T value, absl::Span<const T> array) { if (auto result = SmallLinearSearch(array, [value](T arg) { return value < arg; })) { return *result; } return UpperBoundImpl(value, array); } } namespace arolla { inline size_t LowerBound(float value, absl::Span<const float> array) { return binary_search_details::LowerBound<float>(value, array); } inline size_t LowerBound(double value, absl::Span<const double> array) { return binary_search_details::LowerBound<double>(value, array); } inline size_t LowerBound(int32_t value, absl::Span<const int32_t> array) { return binary_search_details::LowerBound<int32_t>(value, array); } inline size_t LowerBound(int64_t value, absl::Span<const int64_t> array) { return binary_search_details::LowerBound<int64_t>(value, array); } inline size_t UpperBound(float value, absl::Span<const float> array) { return binary_search_details::UpperBound<float>(value, array); } inline size_t UpperBound(double value, absl::Span<const double> array) { return binary_search_details::UpperBound<double>(value, array); } inline size_t UpperBound(int32_t value, absl::Span<const int32_t> array) { return binary_search_details::UpperBound<int32_t>(value, array); } inline size_t UpperBound(int64_t value, absl::Span<const int64_t> array) { return binary_search_details::UpperBound<int64_t>(value, array); } template <typename T, typename Iter> Iter GallopingLowerBound(Iter begin, Iter end, const T& value) { size_t i = 0; size_t size = end - begin; if (begin >= end || !(*begin < value)) { return std::min<Iter>(begin, end); } size_t d = 1; while (i + d < size && begin[i + d] < value) { i += d; d <<= 1; } while (d > 1) { d >>= 1; if (i + d < size && begin[i + d] < value) { i += d; } } return begin + i + 1; } } #endif #include "arolla/util/binary_search.h" #include <cassert> #include <cmath> #include <cstddef> #include <cstdint> #include "absl/types/span.h" #include "arolla/util/bits.h" #include "arolla/util/switch_index.h" namespace arolla::binary_search_details { namespace { template <size_t kArraySize, typename T, class Predicate> size_t FastBinarySearchT(const T* const array, Predicate predicate) { static_assert((kArraySize & (kArraySize + 1)) == 0); size_t offset = 0; for (size_t k = kArraySize; k > 0;) { k >>= 1; offset = (!predicate(array[offset + k]) ? offset + k + 1 : offset); } return offset; } template <typename T, typename Predicate> size_t BinarySearchT(absl::Span<const T> array, Predicate predicate) { assert(!array.empty()); const int log2_size = BitScanReverse(array.size()); return switch_index<8 * sizeof(size_t)>( log2_size, [array, predicate](auto constexpr_log2_size) { constexpr size_t size = (1ULL << static_cast<int>(constexpr_log2_size)) - 1; size_t offset = 0; #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" #endif offset = (!predicate(array[size]) ? array.size() - size : offset); #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic pop #endif return offset + FastBinarySearchT<size>(array.begin() + offset, predicate); }); } } size_t LowerBoundImpl(float value, absl::Span<const float> array) { return BinarySearchT(array, [value](auto arg) { return !(arg < value); }); } size_t LowerBoundImpl(double value, absl::Span<const double> array) { return BinarySearchT(array, [value](auto arg) { return !(arg < value); }); } size_t LowerBoundImpl(int32_t value, absl::Span<const int32_t> array) { return BinarySearchT(array, [value](auto arg) { return arg >= value; }); } size_t LowerBoundImpl(int64_t value, absl::Span<const int64_t> array) { return BinarySearchT(array, [value](auto arg) { return arg >= value; }); } size_t UpperBoundImpl(float value, absl::Span<const float> array) { if (std::isnan(value)) { return array.size(); } return BinarySearchT(array, [value](auto arg) { return !(arg <= value); }); } size_t UpperBoundImpl(double value, absl::Span<const double> array) { if (std::isnan(value)) { return array.size(); } return BinarySearchT(array, [value](auto arg) { return !(arg <= value); }); } size_t UpperBoundImpl(int32_t value, absl::Span<const int32_t> array) { return BinarySearchT(array, [value](auto arg) { return arg > value; }); } size_t UpperBoundImpl(int64_t value, absl::Span<const int64_t> array) { return BinarySearchT(array, [value](auto arg) { return arg > value; }); } }
#include "arolla/util/binary_search.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <functional> #include <limits> #include <random> #include <vector> #include "gtest/gtest.h" #include "absl/types/span.h" namespace arolla { namespace { size_t StdLowerBound(float value, absl::Span<const float> array) { return std::lower_bound(array.begin(), array.end(), value) - array.begin(); } size_t StdLowerBound(double value, absl::Span<const double> array) { return std::lower_bound(array.begin(), array.end(), value) - array.begin(); } size_t StdLowerBound(int32_t value, absl::Span<const int32_t> array) { return std::lower_bound(array.begin(), array.end(), value) - array.begin(); } size_t StdLowerBound(int64_t value, absl::Span<const int64_t> array) { return std::lower_bound(array.begin(), array.end(), value) - array.begin(); } size_t RlGallopingLowerBound(float value, absl::Span<const float> array) { return GallopingLowerBound(array.begin(), array.end(), value) - array.begin(); } TEST(Algorithms, LowerBound_General) { for (int n : {0, 1, 5, 7, 100, 1000}) { std::vector<float> thresholds(n); for (int i = 0; i < n; ++i) { thresholds[i] = 2 * i + 1; } for (int i = 0; i < static_cast<int>(2 * thresholds.size()); ++i) { size_t expected = StdLowerBound(i, thresholds); ASSERT_EQ(LowerBound(i, thresholds), expected); ASSERT_EQ(RlGallopingLowerBound(i, thresholds), expected); } ASSERT_EQ(LowerBound(-10 * n, thresholds), StdLowerBound(-10 * n, thresholds)); ASSERT_EQ(LowerBound(10 * n, thresholds), StdLowerBound(10 * n, thresholds)); } } TEST(Algorithms, LowerBound_Duplicates) { for (int n : {2, 140}) { std::vector<float> thresholds(n, 0.); ASSERT_EQ(LowerBound(-1, thresholds), 0); ASSERT_EQ(LowerBound(0., thresholds), 0); ASSERT_EQ(LowerBound(1., thresholds), n); ASSERT_EQ(RlGallopingLowerBound(-1, thresholds), 0); ASSERT_EQ(RlGallopingLowerBound(0., thresholds), 0); ASSERT_EQ(RlGallopingLowerBound(1., thresholds), n); } } TEST(Algorithms, LowerBound_Infs) { const auto kInf = std::numeric_limits<float>::infinity(); for (int n : {2, 140}) { std::vector<float> thresholds(n); for (int i = 0; i < n; ++i) { thresholds.push_back(i); } thresholds.front() = -kInf; thresholds.back() = kInf; ASSERT_EQ(LowerBound(-kInf, thresholds), StdLowerBound(-kInf, thresholds)); ASSERT_EQ(LowerBound(kInf, thresholds), StdLowerBound(kInf, thresholds)); ASSERT_EQ(RlGallopingLowerBound(kInf, thresholds), StdLowerBound(kInf, thresholds)); } } TEST(Algorithms, LowerBound_Nan) { const auto kNan = std::numeric_limits<float>::quiet_NaN(); const auto kInf = std::numeric_limits<float>::infinity(); for (int n : {2, 140}) { std::vector<float> thresholds; for (int i = 0; i < n; ++i) { thresholds.push_back(i); } thresholds.front() = -kInf; thresholds.back() = kInf; ASSERT_EQ(LowerBound(kNan, thresholds), StdLowerBound(kNan, thresholds)); ASSERT_EQ(RlGallopingLowerBound(kNan, thresholds), StdLowerBound(kNan, thresholds)); } } size_t StdUpperBound(float value, absl::Span<const float> array) { return std::upper_bound(array.begin(), array.end(), value) - array.begin(); } size_t StdUpperBound(double value, absl::Span<const double> array) { return std::upper_bound(array.begin(), array.end(), value) - array.begin(); } size_t StdUpperBound(int32_t value, absl::Span<const int32_t> array) { return std::upper_bound(array.begin(), array.end(), value) - array.begin(); } size_t StdUpperBound(int64_t value, absl::Span<const int64_t> array) { return std::upper_bound(array.begin(), array.end(), value) - array.begin(); } TEST(Algorithms, UpperBound_General) { for (int n : {0, 1, 5, 7, 100, 1000}) { std::vector<float> thresholds(n); for (int i = 0; i < n; ++i) { thresholds[i] = 2 * i + 1; } for (int i = 0; i < static_cast<int>(2 * thresholds.size()); ++i) { ASSERT_EQ(UpperBound(i, thresholds), StdUpperBound(i, thresholds)); } ASSERT_EQ(UpperBound(-10 * n, thresholds), StdUpperBound(-10 * n, thresholds)); ASSERT_EQ(UpperBound(10 * n, thresholds), StdUpperBound(10 * n, thresholds)); } } TEST(Algorithms, UpperBound_Duplicates) { for (int n : {2, 140}) { std::vector<float> thresholds(n, 0.); ASSERT_EQ(UpperBound(-1, thresholds), StdUpperBound(-1., thresholds)); ASSERT_EQ(UpperBound(0., thresholds), StdUpperBound(0., thresholds)); } } TEST(Algorithms, UpperBound_Infs) { const auto kInf = std::numeric_limits<float>::infinity(); for (int n : {2, 140}) { std::vector<float> thresholds(n); for (int i = 0; i < n; ++i) { thresholds.push_back(i); } thresholds.front() = -kInf; thresholds.back() = kInf; ASSERT_EQ(UpperBound(-kInf, thresholds), StdUpperBound(-kInf, thresholds)); ASSERT_EQ(UpperBound(kInf, thresholds), StdUpperBound(kInf, thresholds)); } } TEST(Algorithms, UpperBound_Nan) { const auto kNan = std::numeric_limits<float>::quiet_NaN(); const auto kInf = std::numeric_limits<float>::infinity(); for (int n : {2, 140}) { std::vector<float> thresholds; for (int i = 0; i < n; ++i) { thresholds.push_back(i); } thresholds.front() = -kInf; thresholds.back() = kInf; ASSERT_EQ(UpperBound(kNan, thresholds), StdUpperBound(kNan, thresholds)); } } template <typename T> std::vector<T> RandomVector(size_t seed, size_t size) { std::mt19937 gen(seed); std::vector<T> result(size); if constexpr (std::is_integral_v<T>) { std::uniform_int_distribution<T> uniform(0, 1 << 30); for (auto& x : result) { x = uniform(gen); } } else { std::uniform_real_distribution<T> uniform01; for (auto& x : result) { x = uniform01(gen); } } return result; } template <typename T> std::vector<T> Sorted(std::vector<T> vec) { std::sort(vec.begin(), vec.end()); return vec; } template <typename T> using AlgoFn = std::function<size_t(T, const std::vector<T>&)>; template <typename T> void BinarySearchStressTest(size_t size, AlgoFn<T> algoFn, AlgoFn<T> referenceAlgoFn) { const auto seed = 34 + size; const auto array = Sorted(RandomVector<T>(seed, size)); for (auto value : RandomVector<T>(seed, 2 * size)) { const auto actual_value = algoFn(value, array); const auto expected_value = referenceAlgoFn(value, array); if (actual_value != expected_value) { ADD_FAILURE() << "Actual value: " << actual_value << '\n' << "Expected value: " << expected_value << '\n' << "size: " << size; return; } } } TEST(Algorithms, LowerBound_Stress) { for (int size : {10, 100, 1000, 100000}) { BinarySearchStressTest<float>( size, [](float value, absl::Span<const float> array) { return LowerBound(value, array); }, [](float value, absl::Span<const float> array) { return StdLowerBound(value, array); }); BinarySearchStressTest<float>( size, [](float value, absl::Span<const float> array) { return RlGallopingLowerBound(value, array); }, [](float value, absl::Span<const float> array) { return StdLowerBound(value, array); }); BinarySearchStressTest<double>( size, [](double value, absl::Span<const double> array) { return LowerBound(value, array); }, [](double value, absl::Span<const double> array) { return StdLowerBound(value, array); }); BinarySearchStressTest<int32_t>( size, [](int32_t value, absl::Span<const int32_t> array) { return LowerBound(value, array); }, [](int32_t value, absl::Span<const int32_t> array) { return StdLowerBound(value, array); }); BinarySearchStressTest<int64_t>( size, [](int64_t value, absl::Span<const int64_t> array) { return LowerBound(value, array); }, [](int64_t value, absl::Span<const int64_t> array) { return StdLowerBound(value, array); }); } } TEST(Algorithms, UpperBound_Stress) { for (int size : {10, 100, 1000, 100000}) { BinarySearchStressTest<float>( size, [](float value, absl::Span<const float> array) { return UpperBound(value, array); }, [](float value, absl::Span<const float> array) { return StdUpperBound(value, array); }); BinarySearchStressTest<double>( size, [](double value, absl::Span<const double> array) { return UpperBound(value, array); }, [](double value, absl::Span<const double> array) { return StdUpperBound(value, array); }); BinarySearchStressTest<int32_t>( size, [](int32_t value, absl::Span<const int32_t> array) { return UpperBound(value, array); }, [](int32_t value, absl::Span<const int32_t> array) { return StdUpperBound(value, array); }); BinarySearchStressTest<int64_t>( size, [](int64_t value, absl::Span<const int64_t> array) { return UpperBound(value, array); }, [](int64_t value, absl::Span<const int64_t> array) { return StdUpperBound(value, array); }); } } } }
2,489
#ifndef AROLLA_UTIL_ALGORITHMS_H_ #define AROLLA_UTIL_ALGORITHMS_H_ #include <algorithm> #include <cstddef> #include <iterator> #include <limits> #include <type_traits> #include "absl/log/check.h" namespace arolla { template <class FwdIter, class T, class Compare> inline FwdIter exp_lower_bound(FwdIter first, FwdIter last, const T& val, Compare comp) { typename std::iterator_traits<FwdIter>::difference_type count, step; count = std::distance(first, last); step = 1; FwdIter it = first; while (step < count) { if (comp(*it, val)) { first = ++it; count -= step; std::advance(it, step); step *= 2; } else { last = it; break; } } return std::lower_bound(first, last, val, comp); } template <class FwdIter, class T> inline FwdIter exp_lower_bound(FwdIter first, FwdIter last, const T& val) { using T1 = typename std::iterator_traits<FwdIter>::value_type; return exp_lower_bound(first, last, val, [](const T1& a, const T& b) { return a < b; }); } template <typename Word> inline void LogicalAnd(const Word* src1, const Word* src2, Word* result, size_t word_count) { const size_t e = (word_count / 8) * 8; for (size_t i = 0; i < e; i += 8) { result[i] = src1[i] & src2[i]; result[i + 1] = src1[i + 1] & src2[i + 1]; result[i + 2] = src1[i + 2] & src2[i + 2]; result[i + 3] = src1[i + 3] & src2[i + 3]; result[i + 4] = src1[i + 4] & src2[i + 4]; result[i + 5] = src1[i + 5] & src2[i + 5]; result[i + 6] = src1[i + 6] & src2[i + 6]; result[i + 7] = src1[i + 7] & src2[i + 7]; } switch (word_count - e) { case 7: result[e + 6] = src1[e + 6] & src2[e + 6]; [[fallthrough]]; case 6: result[e + 5] = src1[e + 5] & src2[e + 5]; [[fallthrough]]; case 5: result[e + 4] = src1[e + 4] & src2[e + 4]; [[fallthrough]]; case 4: result[e + 3] = src1[e + 3] & src2[e + 3]; [[fallthrough]]; case 3: result[e + 2] = src1[e + 2] & src2[e + 2]; [[fallthrough]]; case 2: result[e + 1] = src1[e + 1] & src2[e + 1]; [[fallthrough]]; case 1: result[e] = src1[e] & src2[e]; } } template <typename Word> inline void InPlaceLogicalAnd(const Word* src, Word* dest, size_t word_count) { const size_t e = (word_count / 8) * 8; for (size_t i = 0; i < e; i += 8) { dest[i] &= src[i]; dest[i + 1] &= src[i + 1]; dest[i + 2] &= src[i + 2]; dest[i + 3] &= src[i + 3]; dest[i + 4] &= src[i + 4]; dest[i + 5] &= src[i + 5]; dest[i + 6] &= src[i + 6]; dest[i + 7] &= src[i + 7]; } switch (word_count - e) { case 7: dest[e + 6] &= src[e + 6]; [[fallthrough]]; case 6: dest[e + 5] &= src[e + 5]; [[fallthrough]]; case 5: dest[e + 4] &= src[e + 4]; [[fallthrough]]; case 4: dest[e + 3] &= src[e + 3]; [[fallthrough]]; case 3: dest[e + 2] &= src[e + 2]; [[fallthrough]]; case 2: dest[e + 1] &= src[e + 1]; [[fallthrough]]; case 1: dest[e] &= src[e]; } } template <typename Word> void InplaceLogicalAndWithOffsets( size_t bitmaps_size, const Word* rhs, int rhs_skip, Word* lhs, int lhs_skip) { static_assert(std::is_unsigned<Word>::value); static constexpr int bits_per_word = std::numeric_limits<Word>::digits; DCHECK_LT(lhs_skip, bits_per_word); DCHECK_GE(lhs_skip, 0); DCHECK_LT(rhs_skip, bits_per_word); DCHECK_GE(rhs_skip, 0); size_t rhs_words = (bitmaps_size + rhs_skip + bits_per_word - 1) / bits_per_word; size_t lhs_words = (bitmaps_size + lhs_skip + bits_per_word - 1) / bits_per_word; if (lhs_skip == rhs_skip) { InPlaceLogicalAnd(rhs, lhs, rhs_words); } else if (lhs_skip < rhs_skip) { int a = rhs_skip - lhs_skip; int b = bits_per_word - a; size_t i = 0; for (; i < rhs_words - 1; ++i) { lhs[i] &= (rhs[i] >> a) | (rhs[i + 1] << b); } if (i < lhs_words) { lhs[i] &= (rhs[i] >> a); } } else { int a = lhs_skip - rhs_skip; int b = bits_per_word - a; lhs[0] &= rhs[0] << a; size_t i; for (i = 1; i < rhs_words; ++i) { lhs[i] &= (rhs[i - 1] >> b) | (rhs[i] << a); } if (i < lhs_words) { lhs[i] &= rhs[i - 1] >> b; } } } template <typename Word> void CopyBits(size_t bitmaps_size, const Word* rhs, int rhs_skip, Word* lhs, int lhs_skip) { static_assert(std::is_unsigned<Word>::value); static constexpr int bits_per_word = std::numeric_limits<Word>::digits; DCHECK_LT(lhs_skip, bits_per_word); DCHECK_GE(lhs_skip, 0); DCHECK_LT(rhs_skip, bits_per_word); DCHECK_GE(rhs_skip, 0); if (bitmaps_size == 0) { return; } size_t rhs_words = (bitmaps_size + rhs_skip + bits_per_word - 1) / bits_per_word; size_t lhs_words = (bitmaps_size + lhs_skip + bits_per_word - 1) / bits_per_word; int lhs_tail = lhs_words * bits_per_word - (bitmaps_size + lhs_skip); DCHECK_LT(lhs_tail, bits_per_word); if (lhs_skip != 0) { Word rhs_val; if (lhs_skip == rhs_skip) { rhs_val = *rhs; } else if (lhs_skip < rhs_skip) { int a = rhs_skip - lhs_skip; rhs_val = rhs[0] >> a; if (rhs_words > 1) { rhs_val |= rhs[1] << (bits_per_word - a); } } else { rhs_val = rhs[0] << (lhs_skip - rhs_skip); } if (lhs_words == 1) { Word output_mask = (~Word{0} << lhs_skip) & (~Word{0} >> lhs_tail); *lhs = (*lhs & ~output_mask) | (rhs_val & output_mask); return; } else { Word output_mask = (~Word{0} << lhs_skip); *lhs = (*lhs & ~output_mask) | (rhs_val & output_mask); if (lhs_skip > rhs_skip) { rhs_skip += bits_per_word - lhs_skip; } else { ++rhs; --rhs_words; rhs_skip -= lhs_skip; } lhs_skip = 0; ++lhs; --lhs_words; } } DCHECK_EQ(lhs_skip, 0); size_t full_lhs_words = (lhs_tail == 0) ? lhs_words : lhs_words - 1; if (full_lhs_words > 0) { if (rhs_skip == 0) { for (size_t i = 0; i < full_lhs_words; ++i) { lhs[i] = rhs[i]; } } else { size_t i = 0; for (; i < std::min(rhs_words - 1, full_lhs_words); ++i) { lhs[i] = (rhs[i] >> rhs_skip) | (rhs[i + 1] << (bits_per_word - rhs_skip)); } if (i < full_lhs_words) { lhs[i] = (rhs[i] >> rhs_skip); } } lhs += full_lhs_words; lhs_words -= full_lhs_words; rhs += full_lhs_words; rhs_words -= full_lhs_words; } if (lhs_tail) { Word rhs_val = rhs[0] >> rhs_skip; if (rhs_words == 2) { rhs_val |= rhs[1] << (bits_per_word - rhs_skip); } Word output_mask = (~Word{0} >> lhs_tail); *lhs = (*lhs & ~output_mask) | (rhs_val & output_mask); } } template <typename Integer> Integer RoundUp(Integer value, Integer divisor) { return (value + divisor - 1) / divisor * divisor; } } #endif
#include "arolla/util/algorithms.h" #include <array> #include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::Eq; TEST(Algorithms, ExponentialLowerBound) { std::vector<int> v{2, 4, 5, 6}; auto i1 = exp_lower_bound(v.begin(), v.end(), 4); EXPECT_THAT(i1, Eq(v.begin() + 1)); } TEST(Algorithms, InplaceLogicalAndWithOffsets) { const std::array<uint32_t, 3> a = {0xf0ff0000, 0xff0fffff, 0x0000fff0}; int a_bit_offset = 16; const std::array<uint32_t, 2> b = {0x87654321, 0x0fedcba9}; int b_bit_offset = 0; const std::array<uint32_t, 3> c = {0x43210000, 0xcba98765, 0x00000fed}; int c_bit_offset = 16; auto a_copy = a; InplaceLogicalAndWithOffsets(64, b.data(), b_bit_offset, a_copy.data(), a_bit_offset); EXPECT_THAT(a_copy, ElementsAre(0x40210000, 0xcb098765, 0x00000fe0)); auto b_copy = b; InplaceLogicalAndWithOffsets(64, a.data(), a_bit_offset, b_copy.data(), b_bit_offset); EXPECT_THAT(b_copy, ElementsAre(0x87654021, 0x0fe0cb09)); auto c_copy = c; InplaceLogicalAndWithOffsets(64, a.data(), a_bit_offset, c_copy.data(), c_bit_offset); EXPECT_THAT(a_copy, ElementsAre(0x40210000, 0xcb098765, 0x00000fe0)); } TEST(Algorithms, CopyBits) { const std::array<uint32_t, 3> src = {0x3210dead, 0xba987654, 0xbeeffedc}; const std::array<uint32_t, 3> empty = {0x5a5a5a5a, 0x5a5a5a5a, 0x5a5a5a5a}; auto dest1 = empty; CopyBits(64, src.data(), 16, dest1.data(), 16); EXPECT_THAT(dest1, ElementsAre(0x32105a5a, 0xba987654, 0x5a5afedc)); auto dest2 = empty; CopyBits(64, src.data(), 16, dest2.data(), 8); EXPECT_THAT(dest2, ElementsAre(0x5432105a, 0xdcba9876, 0x5a5a5afe)); auto dest3 = empty; CopyBits(64, src.data(), 16, dest3.data(), 24); EXPECT_THAT(dest3, ElementsAre(0x105a5a5a, 0x98765432, 0x5afedcba)); uint32_t dest4 = 0xffffffff; CopyBits(16, src.data(), 16, &dest4, 8); EXPECT_THAT(dest4, Eq(0xff3210ff)); uint32_t src5 = 0xdcba; std::array<uint32_t, 2> dest5 = {0xffffffff, 0xffffffff}; CopyBits(16, &src5, 0, dest5.data(), 24); EXPECT_THAT(dest5, ElementsAre(0xbaffffff, 0xffffffdc)); } } }
2,490
#ifndef AROLLA_UTIL_INIT_AROLLA_H_ #define AROLLA_UTIL_INIT_AROLLA_H_ #include "absl/status/status.h" namespace arolla { absl::Status InitArolla(); enum class ArollaInitializerPriority { kHighest = 0, kRegisterQExprOperators, kRegisterIndividualQExprOperators, kRegisterSerializationCodecs, kRegisterExprOperatorsBootstrap, kRegisterExprOperatorsStandard, kRegisterExprOperatorsStandardCpp, kRegisterExprOperatorsExtraLazy, kRegisterExprOperatorsExtraJagged, kRegisterExprOperatorsLowest, kLowest, }; static_assert(static_cast<int>(ArollaInitializerPriority::kLowest) < 32, "Re-evaluate design when exceeding the threshold."); #define AROLLA_REGISTER_INITIALIZER(priority, name, ...) \ extern "C" { \ static ::arolla::init_arolla_internal::ArollaInitializer \ AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT(arolla_initializer_, \ __COUNTER__)( \ (::arolla::ArollaInitializerPriority::priority), (#name), \ (__VA_ARGS__)); \ } #define AROLLA_REGISTER_ANONYMOUS_INITIALIZER(priority, ...) \ extern "C" { \ static ::arolla::init_arolla_internal::ArollaInitializer \ AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT(arolla_initializer_, \ __COUNTER__)( \ (::arolla::ArollaInitializerPriority::priority), nullptr, \ (__VA_ARGS__)); \ } #define AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT_INNER(x, y) x##y #define AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT(x, y) \ AROLLA_REGISTER_INITIALIZER_IMPL_CONCAT_INNER(x, y) namespace init_arolla_internal { class ArollaInitializer { public: using VoidInitFn = void (*)(); using StatusInitFn = absl::Status (*)(); static absl::Status ExecuteAll(); ArollaInitializer(ArollaInitializerPriority priority, const char* name, VoidInitFn init_fn); ArollaInitializer(ArollaInitializerPriority priority, const char* name, StatusInitFn init_fn); private: static bool execution_flag_; static const ArollaInitializer* head_; const ArollaInitializer* const next_; const ArollaInitializerPriority priority_; const char* const name_; const VoidInitFn void_init_fn_ = nullptr; const StatusInitFn status_init_fn_ = nullptr; }; } } #endif #include "arolla/util/init_arolla.h" #include <algorithm> #include <cstddef> #include <cstring> #include <utility> #include <vector> #include "absl/log/log.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "arolla/util/indestructible.h" namespace arolla { absl::Status InitArolla() { return init_arolla_internal::ArollaInitializer::ExecuteAll(); } namespace init_arolla_internal { bool ArollaInitializer::execution_flag_ = false; const ArollaInitializer* ArollaInitializer::head_ = nullptr; absl::Status ArollaInitializer::ExecuteAll() { static const Indestructible<absl::Status> result([]() -> absl::Status { execution_flag_ = true; std::vector<const ArollaInitializer*> list; for (auto* it = head_; it != nullptr; it = it->next_) { list.push_back(it); } std::stable_sort(list.begin(), list.end(), [](auto* it, auto* jt) { return (it->name_ != nullptr && (jt->name_ == nullptr || std::strcmp(it->name_, jt->name_) < 0)); }); for (size_t i = 1; i < list.size() && list[i]->name_ != nullptr; ++i) { if (std::strcmp(list[i - 1]->name_, list[i]->name_) == 0) { return absl::InternalError(absl::StrCat( "name collision in arolla initializers: ", list[i]->name_)); } } std::stable_sort(list.begin(), list.end(), [](auto* it, auto* jt) { return it->priority_ < jt->priority_; }); for (auto* it : list) { if (it->void_init_fn_ != nullptr) { it->void_init_fn_(); } else if (auto status = it->status_init_fn_(); !status.ok()) { return status; } } return absl::OkStatus(); }()); return *result; } ArollaInitializer::ArollaInitializer(ArollaInitializerPriority priority, const char* name, VoidInitFn init_fn) : next_(std::exchange(head_, this)), priority_(priority), name_(name), void_init_fn_(init_fn) { if (init_fn == nullptr) { LOG(FATAL) << "init_fn == nullptr"; } if (execution_flag_) { LOG(FATAL) << "A new initializer has been registered after calling " "::arolla::InitArolla()"; } } ArollaInitializer::ArollaInitializer(ArollaInitializerPriority priority, const char* name, StatusInitFn init_fn) : next_(std::exchange(head_, this)), priority_(priority), name_(name), status_init_fn_(init_fn) { if (init_fn == nullptr) { LOG(FATAL) << "init_fn == nullptr"; } if (execution_flag_) { LOG(FATAL) << "A new initializer has been registered after calling " "::arolla::InitArolla()"; } } } }
#include "arolla/util/init_arolla.h" #include <string> #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/util/indestructible.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOk; std::string& GetBuffer() { static Indestructible<std::string> result; return *result; } AROLLA_REGISTER_INITIALIZER(kHighest, Foo, [] { GetBuffer() += "Hello"; }) AROLLA_REGISTER_INITIALIZER(kLowest, Bar, []() -> absl::Status { GetBuffer() += "World"; return absl::OkStatus(); }) AROLLA_REGISTER_ANONYMOUS_INITIALIZER(kLowest, [] { GetBuffer() += "!"; }) AROLLA_REGISTER_INITIALIZER(kLowest, Baz, []() -> absl::Status { std::tuple<int, int>(); return absl::OkStatus(); }) TEST(InitArollaTest, Complex) { { EXPECT_EQ(GetBuffer(), ""); } { ASSERT_THAT(InitArolla(), IsOk()); EXPECT_EQ(GetBuffer(), "HelloWorld!"); } { ASSERT_THAT(InitArolla(), IsOk()); EXPECT_EQ(GetBuffer(), "HelloWorld!"); } } } }
2,491
#ifndef AROLLA_UTIL_FINGERPRINT_H_ #define AROLLA_UTIL_FINGERPRINT_H_ #include <cstddef> #include <cstdint> #include <iosfwd> #include <memory> #include <string> #include <type_traits> #include <utility> #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/util/meta.h" #include "arolla/util/struct_field.h" #include "arolla/util/types.h" namespace arolla { struct Fingerprint { absl::uint128 value; std::string AsString() const; signed_size_t PythonHash() const; }; Fingerprint RandomFingerprint(); class FingerprintHasher { public: explicit FingerprintHasher(absl::string_view salt); Fingerprint Finish() &&; template <typename... Args> FingerprintHasher& Combine(const Args&... args) &; template <typename... Args> FingerprintHasher&& Combine(const Args&... args) &&; template <typename SpanT> FingerprintHasher& CombineSpan(SpanT&& values) &; template <typename SpanT> FingerprintHasher&& CombineSpan(SpanT&& values) &&; void CombineRawBytes(const void* data, size_t size); private: std::pair<uint64_t, uint64_t> state_; }; namespace fingerprint_impl { template <typename T, class = void> struct HasArollaFingerprintMethod : std::false_type {}; template <class T> struct HasArollaFingerprintMethod< T, std::void_t<decltype(static_cast<void (T::*)(FingerprintHasher*) const>( &T::ArollaFingerprint))>> : std::true_type {}; } template <typename T> struct FingerprintHasherTraits { FingerprintHasherTraits() = delete; }; inline bool operator==(const Fingerprint& lhs, const Fingerprint& rhs) { return lhs.value == rhs.value; } inline bool operator!=(const Fingerprint& lhs, const Fingerprint& rhs) { return !(lhs == rhs); } inline bool operator<(const Fingerprint& lhs, const Fingerprint& rhs) { return lhs.value < rhs.value; } std::ostream& operator<<(std::ostream& ostream, const Fingerprint& fingerprint); template <typename H> H AbslHashValue(H state, const Fingerprint& fingerprint) { return H::combine(std::move(state), fingerprint.value); } template <typename... Args> FingerprintHasher& FingerprintHasher::Combine(const Args&... args) & { auto combine = [this](const auto& arg) { using Arg = std::decay_t<decltype(arg)>; if constexpr (fingerprint_impl::HasArollaFingerprintMethod<Arg>::value) { arg.ArollaFingerprint(this); } else if constexpr (std::is_default_constructible_v< FingerprintHasherTraits<Arg>>) { FingerprintHasherTraits<Arg>()(this, arg); } else if constexpr (std::is_arithmetic_v<Arg> || std::is_enum_v<Arg>) { CombineRawBytes(&arg, sizeof(arg)); } else { static_assert(sizeof(Arg) == 0, "Please, define `void " "T::ArollaFingerprint(FingerprintHasher* hasher) const` " "or specialise FingerprintHasherTraits for your type."); } }; (combine(args), ...); return *this; } template <typename... Args> FingerprintHasher&& FingerprintHasher::Combine(const Args&... args) && { Combine(args...); return std::move(*this); } template <typename SpanT> FingerprintHasher& FingerprintHasher::CombineSpan(SpanT&& values) & { const auto span = absl::MakeConstSpan(values); using T = typename decltype(span)::value_type; Combine(values.size()); if constexpr (std::is_default_constructible_v<FingerprintHasherTraits<T>>) { constexpr FingerprintHasherTraits<T> traits; for (const auto& x : values) { traits(this, x); } } else if constexpr (std::is_arithmetic_v<T> || std::is_enum_v<T>) { CombineRawBytes(values.data(), values.size() * sizeof(values[0])); } else { static_assert(sizeof(T) == 0, "Please specialise FingerprintHasherTraits for your type."); } return *this; } template <typename SpanT> FingerprintHasher&& FingerprintHasher::CombineSpan(SpanT&& values) && { CombineSpan(std::forward<SpanT>(values)); return std::move(*this); } template <> struct FingerprintHasherTraits<Fingerprint> { void operator()(FingerprintHasher* hasher, const Fingerprint& value) const { hasher->CombineRawBytes(&value.value, sizeof(value.value)); } }; template <> struct FingerprintHasherTraits<std::string> { void operator()(FingerprintHasher* hasher, const std::string& value) const { hasher->Combine(value.size()).CombineRawBytes(value.data(), value.size()); } }; template <> struct FingerprintHasherTraits<absl::string_view> { void operator()(FingerprintHasher* hasher, absl::string_view value) const { hasher->Combine(value.size()).CombineRawBytes(value.data(), value.size()); } }; template <class Struct> void CombineStructFields(FingerprintHasher* hasher, const Struct& value) { static_assert(HasStructFields<Struct>(), "no struct fields found"); meta::foreach_tuple_element( GetStructFields<Struct>(), [&](const auto& struct_field) { hasher->Combine(*UnsafeGetStructFieldPtr(struct_field, &value)); }); } template <typename T> struct FingerprintHasherTraits<T*> { static_assert(sizeof(T*) == 0, "Pointer values are runtime specific and not fingerprintable."); }; template <typename T> struct FingerprintHasherTraits<std::unique_ptr<T>> { static_assert( sizeof(std::unique_ptr<T>) == 0, "Unique pointer values are runtime specific and not fingerprintable."); }; template <typename T> struct FingerprintHasherTraits<std::shared_ptr<T>> { static_assert( sizeof(std::shared_ptr<T>) == 0, "Shared pointer values are runtime specific and not fingerprintable."); }; #define AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(CPP_TYPE) \ template <> \ struct FingerprintHasherTraits<CPP_TYPE> { \ void operator()(FingerprintHasher* hasher, const CPP_TYPE& value) const; \ } } #endif #include "arolla/util/fingerprint.h" #include <cstddef> #include <cstdint> #include <ostream> #include <string> #include "absl/hash/hash.h" #include "absl/numeric/int128.h" #include "absl/random/random.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "cityhash/city.h" #include "arolla/util/types.h" namespace arolla { namespace { uint32_t RuntimeSeed() { static uint32_t result = absl::Hash<int>{}(501816262); return result; } } std::string Fingerprint::AsString() const { return absl::StrFormat("%032x", value); } signed_size_t Fingerprint::PythonHash() const { return absl::Hash<Fingerprint>()(*this); } std::ostream& operator<<(std::ostream& ostream, const Fingerprint& fingerprint) { return ostream << absl::StreamFormat("%032x", fingerprint.value); } Fingerprint RandomFingerprint() { absl::BitGen bitgen; return Fingerprint{absl::MakeUint128(absl::Uniform<uint64_t>(bitgen), absl::Uniform<uint64_t>(bitgen))}; } FingerprintHasher::FingerprintHasher(absl::string_view salt) : state_{3102879407, 2758948377} { Combine(RuntimeSeed(), salt); } Fingerprint FingerprintHasher::Finish() && { return Fingerprint{absl::MakeUint128(state_.second, state_.first)}; } void FingerprintHasher::CombineRawBytes(const void* data, size_t size) { state_ = cityhash::CityHash128WithSeed( static_cast<const char*>(data), size, state_); } }
#include "arolla/util/fingerprint.h" #include <limits> #include <string> #include <tuple> #include <type_traits> #include <utility> #include "gtest/gtest.h" #include "absl/container/flat_hash_set.h" #include "arolla/util/struct_field.h" namespace arolla { namespace { static_assert( std::is_trivially_constructible_v<Fingerprint>, "Make sure that fingerprint is trivially constructed, so that adding it to " "a struct does not slow down the struct's initialization time."); struct A {}; static_assert(!std::is_default_constructible_v<FingerprintHasherTraits<A>>); struct AWithFingerPrintMethod { void ArollaFingerprint(FingerprintHasher* hasher) const { hasher->Combine(19); } }; struct AWithStructFields { int a; double b; constexpr static auto ArollaStructFields() { using CppType = AWithStructFields; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(a), AROLLA_DECLARE_STRUCT_FIELD(b), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; template <typename... Ts> Fingerprint MakeDummyFingerprint(const Ts&... values) { return FingerprintHasher("dummy-salt").Combine(values...).Finish(); } TEST(FingerprintTest, Empty) { Fingerprint fgpt{}; EXPECT_EQ(fgpt.AsString(), "00000000000000000000000000000000"); } TEST(FingerprintTest, RandomFingerprint) { constexpr int N = 1024; absl::flat_hash_set<Fingerprint> set; set.reserve(N); for (int i = 0; i < N; ++i) { set.insert(RandomFingerprint()); } EXPECT_EQ(set.size(), N); } TEST(FingerprintTest, AWithFingerPrintMethod) { EXPECT_EQ(MakeDummyFingerprint(AWithFingerPrintMethod()), MakeDummyFingerprint(19)); } TEST(FingerprintTest, AWithStructFields) { EXPECT_EQ(MakeDummyFingerprint(AWithStructFields{.a = 5, .b = 7.}), MakeDummyFingerprint(5, 7.)); } TEST(FingerprintTest, TestPrimitives) { EXPECT_NE(MakeDummyFingerprint(5), MakeDummyFingerprint(6)); EXPECT_NE(MakeDummyFingerprint<std::string>("5"), MakeDummyFingerprint<std::string>("6")); } TEST(FingerprintTest, FloatingPointZero) { EXPECT_NE(MakeDummyFingerprint(0.0).PythonHash(), MakeDummyFingerprint(-0.0).PythonHash()); EXPECT_NE(MakeDummyFingerprint(0.f).PythonHash(), MakeDummyFingerprint(-0.f).PythonHash()); } TEST(FingerprintTest, FloatingPointNAN) { EXPECT_NE(MakeDummyFingerprint(std::numeric_limits<float>::quiet_NaN()) .PythonHash(), MakeDummyFingerprint(-std::numeric_limits<float>::quiet_NaN()) .PythonHash()); EXPECT_NE(MakeDummyFingerprint(std::numeric_limits<double>::quiet_NaN()) .PythonHash(), MakeDummyFingerprint(-std::numeric_limits<double>::quiet_NaN()) .PythonHash()); } TEST(FingerprintTest, PythonHash) { EXPECT_EQ(MakeDummyFingerprint(4).PythonHash(), MakeDummyFingerprint(4).PythonHash()); EXPECT_NE(MakeDummyFingerprint(5).PythonHash(), MakeDummyFingerprint(6).PythonHash()); } TEST(FingerprintTest, Less) { EXPECT_LT(Fingerprint{27}, Fingerprint{37}); EXPECT_FALSE(Fingerprint{27} < Fingerprint{27}); } TEST(FingerprintTest, CombineRawBytes) { { FingerprintHasher h1("dummy-salt"); FingerprintHasher h2("dummy-salt"); h1.CombineRawBytes("foobar", 6); h2.CombineRawBytes("foobar", 6); EXPECT_EQ(std::move(h1).Finish(), std::move(h2).Finish()); } { FingerprintHasher h1("dummy-salt"); FingerprintHasher h2("dummy-salt"); h1.CombineRawBytes("foobar", 6); h2.CombineRawBytes("barfoo", 6); EXPECT_NE(std::move(h1).Finish(), std::move(h2).Finish()); } } class Circle { public: Circle(int x, int y, int r) : center_(x, y), radius_(r) { FingerprintHasher hasher("arolla::TestCircle"); hasher.Combine(center_.first, center_.second, radius_); fingerprint_ = std::move(hasher).Finish(); } const Fingerprint& fingerprint() { return fingerprint_; } private: std::pair<int, int> center_; int radius_; Fingerprint fingerprint_; }; TEST(FingerprintTest, UserDefined) { EXPECT_NE(Circle(0, 0, 1).fingerprint(), Circle(0, 0, 2).fingerprint()); EXPECT_NE(Circle(1, 1, 1).fingerprint(), Circle(0, 0, 1).fingerprint()); } TEST(FingerprintTest, HasArollaFingerprintMethodRegression) { struct OverloadedType { int ArollaFingerprint() const { return 0; } void ArollaFingerprint(FingerprintHasher*) const {} }; EXPECT_TRUE( fingerprint_impl::HasArollaFingerprintMethod<OverloadedType>::value); struct WrongType { int ArollaFingerprint() const { return 0; } }; EXPECT_FALSE(fingerprint_impl::HasArollaFingerprintMethod<WrongType>::value); } } }
2,492
#ifndef AROLLA_UTIL_BYTES_H_ #define AROLLA_UTIL_BYTES_H_ #include <string> #include "arolla/util/repr.h" namespace arolla { using Bytes = std::string; AROLLA_DECLARE_REPR(Bytes); } #endif #include "arolla/util/bytes.h" #include <cstddef> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "arolla/util/repr.h" namespace arolla { ReprToken ReprTraits<Bytes>::operator()(const Bytes& value) const { constexpr size_t kBytesAbbrevLimit = 120; ReprToken result; absl::string_view bytes = value; if (bytes.size() <= kBytesAbbrevLimit) { result.str = absl::StrCat("b'", absl::CHexEscape(bytes), "'"); } else { result.str = absl::StrCat("b'", absl::CHexEscape(bytes.substr(0, kBytesAbbrevLimit)), "... (", bytes.size(), " bytes total)'"); } return result; } }
#include "arolla/util/bytes.h" #include <string> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "arolla/util/repr.h" #include "arolla/util/testing/repr_token_eq.h" namespace arolla { namespace { using ::arolla::testing::ReprTokenEq; using ::testing::Eq; using ::testing::MatchesRegex; TEST(BytesTest, Constructor) { EXPECT_THAT(Bytes("Hello"), Eq("Hello")); std::string hello = "Hello"; EXPECT_THAT(Bytes(hello), Eq("Hello")); absl::string_view hello_view = hello; EXPECT_THAT(Bytes(hello_view), Eq("Hello")); } TEST(BytesTest, CopyAndMoveConstructors) { static_assert(std::is_nothrow_move_constructible<Bytes>::value); Bytes src("Google"); Bytes copied(src); EXPECT_THAT(copied, Eq(src)); Bytes moved(std::move(src)); EXPECT_THAT(moved, Eq(copied)); } TEST(BytesTest, CopyAndMoveAssignment) { static_assert(std::is_nothrow_move_assignable<Bytes>::value); Bytes src("Google"); Bytes copied = src; EXPECT_THAT(copied, Eq(src)); Bytes moved = std::move(src); EXPECT_THAT(moved, Eq(copied)); } TEST(BytesTest, AssignmentFromString) { std::string google = "Google"; { Bytes val("x"); val = "Google"; EXPECT_THAT(val, Eq(google)); } { Bytes val("x"); val = google; EXPECT_THAT(val, Eq(google)); } { absl::string_view google_view = google; Bytes val("x"); val = google_view; EXPECT_THAT(val, Eq("Google")); } { Bytes val("x"); val = std::move(google); EXPECT_THAT(val, Eq("Google")); } } TEST(BytesTest, Repr) { EXPECT_THAT(GenReprToken(Bytes("G'\"\t\xff")), ReprTokenEq(R"(b'G\'\"\t\xff')")); EXPECT_THAT(Repr(Bytes(std::string(1024, 'x'))), MatchesRegex(R"(b'x{120}[.]{3} \(1024 bytes total\)')")); } } }
2,493
#ifndef AROLLA_UTIL_STATUS_H_ #define AROLLA_UTIL_STATUS_H_ #include <array> #include <cstdint> #include <initializer_list> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/util/meta.h" #include "arolla/util/status_macros_backport.h" namespace arolla { absl::Status SizeMismatchError(std::initializer_list<int64_t> sizes); template <class T> absl::Status GetStatusOrOk(const T&) { return absl::OkStatus(); } template <class T> absl::Status GetStatusOrOk(const absl::StatusOr<T>& v_or) { return v_or.status(); } inline absl::Status GetStatusOrOk(const absl::Status& status) { return status; } template <class T> bool IsOkStatus(const T&) { return true; } template <class T> bool IsOkStatus(const absl::StatusOr<T>& v_or) { return v_or.ok(); } inline bool IsOkStatus(const absl::Status& status) { return status.ok(); } template <class... Ts> absl::Status CheckInputStatus(const Ts&... status_or_ts) { if ((IsOkStatus(status_or_ts) && ...)) { return absl::OkStatus(); } for (auto& status : std::array<absl::Status, sizeof...(Ts)>{ GetStatusOrOk(status_or_ts)...}) { RETURN_IF_ERROR(std::move(status)); } return absl::OkStatus(); } template <typename T> struct IsStatusOrT : std::false_type {}; template <typename T> struct IsStatusOrT<absl::StatusOr<T>> : std::true_type {}; template <typename T> using strip_statusor_t = meta::strip_template_t<absl::StatusOr, T>; template <class T> decltype(auto) UnStatus(T&& t) { if constexpr (IsStatusOrT<std::decay_t<T>>()) { return *std::forward<T>(t); } else { return std::forward<T>(t); } } template <class Fn> struct UnStatusCaller { template <class... Ts> auto operator()(const Ts&... status_or_ts) const -> absl::StatusOr<strip_statusor_t< decltype(std::declval<Fn>()(UnStatus(status_or_ts)...))>> { if ((IsOkStatus(status_or_ts) && ...)) { return fn(UnStatus(status_or_ts)...); } return CheckInputStatus(status_or_ts...); } Fn fn; }; template <class Fn> UnStatusCaller<Fn> MakeUnStatusCaller(Fn&& fn) { return UnStatusCaller<Fn>{std::forward<Fn>(fn)}; } template <class... Ts> static absl::StatusOr<std::tuple<Ts...>> LiftStatusUp( absl::StatusOr<Ts>... status_or_ts) { RETURN_IF_ERROR(CheckInputStatus(status_or_ts...)); return std::make_tuple(*std::move(status_or_ts)...); } template <class T> absl::StatusOr<std::vector<T>> LiftStatusUp( std::vector<absl::StatusOr<T>>&& status_or_ts) { std::vector<T> result; result.reserve(status_or_ts.size()); for (auto& status_or_t : status_or_ts) { if (!status_or_t.ok()) { return std::move(status_or_t).status(); } result.push_back(*std::move(status_or_t)); } return result; } template <class T> absl::StatusOr<std::vector<T>> LiftStatusUp( absl::Span<const absl::StatusOr<T>> status_or_ts) { std::vector<T> result; result.reserve(status_or_ts.size()); for (const auto& status_or_t : status_or_ts) { if (!status_or_t.ok()) { return status_or_t.status(); } result.push_back(*status_or_t); } return result; } template <class K, class V> absl::StatusOr<absl::flat_hash_map<K, V>> LiftStatusUp( absl::flat_hash_map<K, absl::StatusOr<V>> status_or_kvs) { absl::flat_hash_map<K, V> result; result.reserve(status_or_kvs.size()); for (const auto& [key, status_or_v] : status_or_kvs) { if (!status_or_v.ok()) { return status_or_v.status(); } result.emplace(key, *status_or_v); } return result; } template <class K, class V> absl::StatusOr<absl::flat_hash_map<K, V>> LiftStatusUp( std::initializer_list<std::pair<K, absl::StatusOr<V>>> status_or_kvs) { return LiftStatusUp(absl::flat_hash_map<K, absl::StatusOr<V>>{status_or_kvs}); } template <class K, class V> absl::StatusOr<absl::flat_hash_map<K, V>> LiftStatusUp( std::initializer_list<std::pair<absl::StatusOr<K>, absl::StatusOr<V>>> status_or_kvs) { absl::flat_hash_map<K, V> result; result.reserve(status_or_kvs.size()); for (const auto& [status_or_k, status_or_v] : status_or_kvs) { if (!status_or_k.ok()) { return status_or_k.status(); } if (!status_or_v.ok()) { return status_or_v.status(); } result.emplace(*status_or_k, *status_or_v); } return result; } inline absl::Status FirstErrorStatus( std::initializer_list<absl::Status> statuses) { for (const absl::Status& status : statuses) { RETURN_IF_ERROR(status); } return absl::OkStatus(); } } #endif #include "absl/status/status.h" #include <cstdint> #include <initializer_list> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" namespace arolla { absl::Status SizeMismatchError(std::initializer_list<int64_t> sizes) { return absl::InvalidArgumentError(absl::StrCat( "argument sizes mismatch: (", absl::StrJoin(sizes, ", "), ")")); } }
#include "arolla/util/status.h" #include <initializer_list> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla { namespace { using ::arolla::testing::IsOkAndHolds; using ::testing::AnyOf; using ::testing::Eq; using ::testing::Test; TEST(StatusTest, CheckInputStatus) { EXPECT_OK(CheckInputStatus()); EXPECT_OK(CheckInputStatus(13)); EXPECT_OK(CheckInputStatus(13, "a")); EXPECT_OK(CheckInputStatus(absl::StatusOr<int>(13), "a")); EXPECT_OK(CheckInputStatus(13, absl::StatusOr<std::string>("a"))); EXPECT_OK(CheckInputStatus(absl::StatusOr<int>(13), absl::StatusOr<std::string>("a"))); absl::Status bad_status1{absl::StatusCode::kInvalidArgument, "bad 1"}; absl::Status bad_status2{absl::StatusCode::kDataLoss, "bad 2"}; EXPECT_EQ(CheckInputStatus(absl::StatusOr<int>(bad_status1)), bad_status1); EXPECT_EQ(CheckInputStatus(13, absl::StatusOr<int>(bad_status1)), bad_status1); EXPECT_EQ(CheckInputStatus(absl::StatusOr<int>(13), absl::StatusOr<int>(bad_status1)), bad_status1); EXPECT_EQ(CheckInputStatus(absl::StatusOr<int>(bad_status1), absl::StatusOr<int>(bad_status2)), bad_status1); } TEST(StatusTest, LiftStatusUpSuccess) { std::tuple<> empty = LiftStatusUp().value(); EXPECT_THAT(empty, Eq(std::make_tuple())); std::tuple<int> one = LiftStatusUp(absl::StatusOr<int>(1)).value(); EXPECT_THAT(one, Eq(std::make_tuple(1))); std::tuple<std::string, int> two = LiftStatusUp(absl::StatusOr<std::string>("one"), absl::StatusOr<int>(2)) .value(); EXPECT_THAT(two, Eq(std::make_tuple(std::string("one"), 2))); ASSERT_OK_AND_ASSIGN( std::vector<int> vec, LiftStatusUp(absl::Span<const absl::StatusOr<int>>{1, 2})); EXPECT_THAT(vec, ::testing::ElementsAre(1, 2)); absl::flat_hash_map<int, int> fhm = LiftStatusUp(std::initializer_list<std::pair<int, absl::StatusOr<int>>>{ {1, 2}, {3, 4}}) .value(); EXPECT_THAT(fhm, Eq(absl::flat_hash_map<int, int>{{1, 2}, {3, 4}})); absl::flat_hash_map<int, int> fhm1 = LiftStatusUp(std::initializer_list< std::pair<absl::StatusOr<int>, absl::StatusOr<int>>>{ {1, 2}, {3, 4}}) .value(); EXPECT_THAT(fhm, Eq(absl::flat_hash_map<int, int>{{1, 2}, {3, 4}})); } TEST(StatusTest, LiftStatusUpErrors) { absl::Status bad_status1{absl::StatusCode::kInvalidArgument, "bad 1"}; absl::Status bad_status2{absl::StatusCode::kDataLoss, "bad 2"}; EXPECT_EQ(LiftStatusUp(absl::StatusOr<int>(bad_status1)).status(), bad_status1); EXPECT_EQ(LiftStatusUp(absl::StatusOr<std::string>("one"), absl::StatusOr<int>(bad_status2)) .status(), bad_status2); EXPECT_EQ(LiftStatusUp(absl::StatusOr<std::string>("one"), absl::StatusOr<int>(bad_status1), absl::StatusOr<float>(bad_status2)) .status(), bad_status1); EXPECT_EQ(LiftStatusUp(absl::StatusOr<float>(bad_status2), absl::StatusOr<std::string>("one"), absl::StatusOr<int>(bad_status1)) .status(), bad_status2); EXPECT_THAT(LiftStatusUp(absl::Span<const absl::StatusOr<int>>{bad_status1, bad_status2}) .status(), bad_status1); EXPECT_THAT( LiftStatusUp(std::initializer_list<std::pair<int, absl::StatusOr<int>>>{ {1, bad_status1}, {2, 3}, {4, bad_status2}}) .status(), AnyOf(bad_status1, bad_status2)); EXPECT_THAT( LiftStatusUp(std::initializer_list< std::pair<absl::StatusOr<int>, absl::StatusOr<int>>>{ {bad_status1, 1}, {2, 3}, {4, bad_status2}}) .status(), AnyOf(bad_status1, bad_status2)); EXPECT_THAT( LiftStatusUp(std::initializer_list< std::pair<absl::StatusOr<int>, absl::StatusOr<int>>>{ {1, bad_status1}, {2, 3}, {4, bad_status2}}) .status(), AnyOf(bad_status1, bad_status2)); } TEST(StatusTest, UnStatus) { using T = std::unique_ptr<int>; using StatusOrT = absl::StatusOr<T>; { StatusOrT status_or_t = std::make_unique<int>(1); const T& value = UnStatus(status_or_t); EXPECT_EQ(*value, 1); EXPECT_EQ(value.get(), status_or_t.value().get()); } { StatusOrT status_or_t = std::make_unique<int>(1); T value = UnStatus(std::move(status_or_t)); EXPECT_EQ(*value, 1); } { T original_value = std::make_unique<int>(1); const T& value = UnStatus(original_value); EXPECT_EQ(*value, 1); EXPECT_EQ(value.get(), original_value.get()); } { T original_value = std::make_unique<int>(1); T value = UnStatus(std::move(original_value)); EXPECT_EQ(*value, 1); } } TEST(StatusTest, FirstErrorStatus) { absl::Status ok_status = absl::OkStatus(); absl::Status failed_precondition = absl::FailedPreconditionError("msg1"); absl::Status internal_error = absl::InternalError("msg2"); EXPECT_OK(FirstErrorStatus({})); EXPECT_OK(FirstErrorStatus({ok_status, ok_status})); EXPECT_EQ(FirstErrorStatus({failed_precondition}), failed_precondition); EXPECT_EQ(FirstErrorStatus({ok_status, failed_precondition}), failed_precondition); EXPECT_EQ(FirstErrorStatus({failed_precondition, ok_status}), failed_precondition); EXPECT_EQ(FirstErrorStatus({failed_precondition, internal_error}), failed_precondition); EXPECT_EQ(FirstErrorStatus({internal_error, failed_precondition}), internal_error); } TEST(StatusTest, GetStatusOrOk) { absl::Status ok_status = absl::OkStatus(); EXPECT_OK(GetStatusOrOk(5)); EXPECT_OK(GetStatusOrOk(ok_status)); EXPECT_OK(GetStatusOrOk(absl::StatusOr<int>(5))); absl::Status failed_precondition = absl::FailedPreconditionError("msg1"); EXPECT_EQ(GetStatusOrOk(failed_precondition), failed_precondition); EXPECT_EQ(GetStatusOrOk(absl::StatusOr<int>(failed_precondition)), failed_precondition); } TEST(StatusTest, IsOkStatus) { absl::Status ok_status = absl::OkStatus(); EXPECT_TRUE(IsOkStatus(5)); EXPECT_TRUE(IsOkStatus(ok_status)); EXPECT_TRUE(IsOkStatus(absl::StatusOr<int>(5))); absl::Status failed_precondition = absl::FailedPreconditionError("msg1"); EXPECT_FALSE(IsOkStatus(failed_precondition)); EXPECT_FALSE(IsOkStatus(absl::StatusOr<int>(failed_precondition))); } TEST(StatusTest, UnStatusCaller) { absl::Status failed_precondition = absl::FailedPreconditionError("msg1"); absl::Status failed_precondition2 = absl::FailedPreconditionError("msg2"); auto add_op = [](int a, int b) { return a + b; }; UnStatusCaller<decltype(add_op)> add_op_wrap{add_op}; auto add_op_with_status = [](int a, int b) -> absl::StatusOr<int> { return a + b; }; auto add_op_with_status_wrap = MakeUnStatusCaller(add_op_with_status); auto add_op_always_error = [&](int a, int b) -> absl::StatusOr<int> { return failed_precondition; }; auto add_op_always_error_wrap = MakeUnStatusCaller(add_op_always_error); EXPECT_THAT(add_op_wrap(5, 7), IsOkAndHolds(12)); EXPECT_THAT(add_op_with_status_wrap(5, 7), IsOkAndHolds(12)); EXPECT_EQ(add_op_always_error_wrap(5, 7).status(), failed_precondition); EXPECT_EQ(add_op_wrap(5, absl::StatusOr<int>(failed_precondition)).status(), failed_precondition); EXPECT_EQ(add_op_wrap(absl::StatusOr<int>(failed_precondition), absl::StatusOr<int>(failed_precondition2)) .status(), failed_precondition); EXPECT_EQ( add_op_always_error_wrap(5, absl::StatusOr<int>(failed_precondition2)) .status(), failed_precondition2); } } }
2,494
#ifndef AROLLA_MEMORY_STRINGS_BUFFER_H_ #define AROLLA_MEMORY_STRINGS_BUFFER_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include <tuple> #include <utility> #include "absl/log/check.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/memory/simple_buffer.h" #include "arolla/util/fingerprint.h" #include "arolla/util/iterator.h" #include "arolla/util/preallocated_buffers.h" namespace arolla { class StringsBuffer { public: using value_type = absl::string_view; using size_type = int64_t; using difference_type = int64_t; using const_iterator = ConstArrayIterator<StringsBuffer>; using offset_type = int64_t; struct Offsets { offset_type start; offset_type end; }; StringsBuffer() = default; StringsBuffer(SimpleBuffer<Offsets> offsets, SimpleBuffer<char> characters, offset_type base_offset = 0); class Builder; class Inserter { public: void Add(absl::string_view v) { builder_->Set(offset_++, v); } void Add(const absl::Cord& v) { builder_->Set(offset_++, std::string(v)); } void SkipN(int64_t count) { offset_ += count; DCHECK_LE(offset_, builder_->offsets_.size()); } private: friend class Builder; explicit Inserter(Builder* builder, int64_t offset) : builder_(builder), offset_(offset) {} Builder* builder_; int64_t offset_; }; class Builder { public: Builder() = default; Builder(Builder&&) = default; Builder& operator=(Builder&&) = default; explicit Builder(int64_t max_size, RawBufferFactory* factory = GetHeapBufferFactory()); Inserter GetInserter(int64_t offset = 0) { return Inserter(this, offset); } void Set(int64_t offset, absl::string_view v) { DCHECK_GE(offset, 0); DCHECK_LT(offset, offsets_.size()); if (v.size() + num_chars_ > characters_.size()) { size_t new_size = characters_.size() * 2; while (v.size() + num_chars_ > new_size) { new_size *= 2; } ResizeCharacters(new_size); } std::copy(v.begin(), v.end(), characters_.data() + num_chars_); offsets_[offset].start = num_chars_; num_chars_ += v.size(); offsets_[offset].end = num_chars_; } void Set(int64_t offset, const absl::Cord& v) { Set(offset, std::string(v)); } void Copy(int64_t offset_from, int64_t offset_to) { offsets_[offset_to] = offsets_[offset_from]; } template <typename NextValueFn> void SetN(int64_t first_offset, int64_t count, NextValueFn fn) { for (int64_t i = first_offset; i < first_offset + count; ++i) { Set(i, fn()); } } void SetNConst(int64_t first_offset, int64_t count, absl::string_view v) { DCHECK_GE(count, 0); DCHECK_GE(first_offset, 0); DCHECK_LE(first_offset + count, offsets_.size()); if (count <= 0) return; Set(first_offset, v); auto d = offsets_[first_offset]; std::fill(offsets_.data() + first_offset + 1, offsets_.data() + first_offset + count, d); } StringsBuffer Build(Inserter ins) && { if (!ins.builder_) return StringsBuffer(); DCHECK_EQ(ins.builder_, this); return std::move(*this).Build(ins.offset_); } StringsBuffer Build(int64_t size) &&; StringsBuffer Build() && { return std::move(*this).Build(offsets_.size()); } private: friend class Inserter; void ResizeCharacters(size_t new_size); void InitDataPointers(std::tuple<RawBufferPtr, void*>&& buf, int64_t offsets_count, int64_t characters_size); RawBufferFactory* factory_; RawBufferPtr buf_; absl::Span<Offsets> offsets_; absl::Span<char> characters_; offset_type num_chars_ = 0; }; class ReshuffleBuilder { public: explicit ReshuffleBuilder( int64_t max_size, const StringsBuffer& buffer, const OptionalValue<absl::string_view>& default_value, RawBufferFactory* buf_factory = GetHeapBufferFactory()); void CopyValue(int64_t new_index, int64_t old_index) { offsets_bldr_.Set(new_index, old_offsets_[old_index]); } void CopyValueToRange(int64_t new_index_from, int64_t new_index_to, int64_t old_index) { auto* new_offsets = offsets_bldr_.GetMutableSpan().begin(); std::fill(new_offsets + new_index_from, new_offsets + new_index_to, old_offsets_[old_index]); } StringsBuffer Build(int64_t size) && { return StringsBuffer(std::move(offsets_bldr_).Build(size), std::move(characters_), base_offset_); } StringsBuffer Build() && { return StringsBuffer(std::move(offsets_bldr_).Build(), std::move(characters_), base_offset_); } private: SimpleBuffer<Offsets>::Builder offsets_bldr_; SimpleBuffer<Offsets> old_offsets_; SimpleBuffer<char> characters_; offset_type base_offset_; }; static StringsBuffer CreateUninitialized( size_t size, RawBufferFactory* factory = GetHeapBufferFactory()) { if (size <= kZeroInitializedBufferSize / sizeof(Offsets)) { return StringsBuffer( SimpleBuffer<Offsets>(nullptr, absl::Span<const Offsets>( static_cast<const Offsets*>( GetZeroInitializedBuffer()), size)), SimpleBuffer<char>{nullptr, absl::Span<const char>()}); } SimpleBuffer<Offsets>::Builder builder(size, factory); std::memset(builder.GetMutableSpan().data(), 0, size * sizeof(Offsets)); return StringsBuffer(std::move(builder).Build(), SimpleBuffer<char>{nullptr, absl::Span<const char>()}); } template <class InputIt> static StringsBuffer Create( InputIt begin, InputIt end, RawBufferFactory* factory = GetHeapBufferFactory()) { auto size = std::distance(begin, end); if (size > 0) { Builder builder(size, factory); for (int64_t offset = 0; offset < size; begin++, offset++) { builder.Set(offset, *begin); } return std::move(builder).Build(size); } else { return StringsBuffer(); } } bool empty() const { return offsets_.empty(); } bool is_owner() const { return offsets_.is_owner() && characters_.is_owner(); } size_type size() const { return offsets_.size(); } size_t memory_usage() const { return offsets().memory_usage() + characters().memory_usage(); } absl::string_view operator[](size_type i) const { DCHECK_LE(0, i); DCHECK_LT(i, size()); auto start = offsets_[i].start; auto end = offsets_[i].end; return absl::string_view(characters_.begin() + start - base_offset_, end - start); } bool operator==(const StringsBuffer& other) const; bool operator!=(const StringsBuffer& other) const { return !(*this == other); } StringsBuffer ShallowCopy() const; StringsBuffer DeepCopy(RawBufferFactory* = GetHeapBufferFactory()) const; const_iterator begin() const { return const_iterator{this, 0}; } const_iterator end() const { return const_iterator{this, size()}; } absl::string_view front() const { return (*this)[0]; } absl::string_view back() const { return (*this)[size() - 1]; } StringsBuffer Slice(size_type offset) const& { return Slice(offset, size() - offset); } StringsBuffer Slice(size_type offset, size_type count) const&; StringsBuffer Slice(size_type offset) && { return std::move(*this).Slice(offset, size() - offset); } StringsBuffer Slice(size_type offset, size_type count) &&; const SimpleBuffer<Offsets>& offsets() const { return offsets_; } const SimpleBuffer<char>& characters() const { return characters_; } offset_type base_offset() const { return base_offset_; } template <typename H> friend H AbslHashValue(H h, const StringsBuffer& buffer) { h = H::combine(std::move(h), buffer.size()); if (!buffer.empty()) { auto* start = reinterpret_cast<const char*>(&*buffer.offsets().begin()); const size_t size = buffer.size() * sizeof(Offsets); h = H::combine_contiguous(std::move(h), start, size); h = H::combine(std::move(h), buffer.characters()); } return h; } private: SimpleBuffer<Offsets> offsets_; SimpleBuffer<char> characters_; offset_type base_offset_ = 0; }; template <> struct ArenaTraits<StringsBuffer> { static StringsBuffer MakeOwned(StringsBuffer&& v, RawBufferFactory* buf_factory) { return v.DeepCopy(buf_factory); } }; AROLLA_DECLARE_FINGERPRINT_HASHER_TRAITS(StringsBuffer); } #endif #include "arolla/memory/strings_buffer.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <limits> #include <tuple> #include <utility> #include "absl/log/check.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/memory/optional_value.h" #include "arolla/memory/raw_buffer_factory.h" #include "arolla/memory/simple_buffer.h" #include "arolla/util/fingerprint.h" namespace arolla { StringsBuffer::Builder::Builder(int64_t max_size, RawBufferFactory* factory) : factory_(factory) { size_t initial_char_buffer_size = max_size * 16; DCHECK_LT(initial_char_buffer_size, std::numeric_limits<offset_type>::max()); size_t offsets_size = max_size * sizeof(Offsets); InitDataPointers( factory->CreateRawBuffer(offsets_size + initial_char_buffer_size), max_size, initial_char_buffer_size); std::memset(offsets_.data(), 0, offsets_size); } StringsBuffer::ReshuffleBuilder::ReshuffleBuilder( int64_t max_size, const StringsBuffer& buffer, const OptionalValue<absl::string_view>& default_value, RawBufferFactory* buf_factory) : offsets_bldr_(max_size, buf_factory), old_offsets_(buffer.offsets()), characters_(buffer.characters()), base_offset_(buffer.base_offset()) { if (default_value.present && !default_value.value.empty()) { int64_t def_value_size = default_value.value.size(); offsets_bldr_.SetNConst( 0, max_size, {characters_.size(), def_value_size + characters_.size()}); SimpleBuffer<char>::Builder chars_bldr(characters_.size() + def_value_size, buf_factory); char* data = chars_bldr.GetMutableSpan().data(); std::memcpy(data, characters_.begin(), characters_.size()); std::memcpy(data + characters_.size(), default_value.value.begin(), def_value_size); characters_ = std::move(chars_bldr).Build(); } else { std::memset(offsets_bldr_.GetMutableSpan().begin(), 0, max_size * sizeof(Offsets)); } } StringsBuffer StringsBuffer::Builder::Build(int64_t size) && { DCHECK_LE(size, offsets_.size()); if (num_chars_ != characters_.size()) { ResizeCharacters(num_chars_); } SimpleBuffer<Offsets> offsets(buf_, offsets_.subspan(0, size)); SimpleBuffer<char> characters(std::move(buf_), characters_.subspan(0, num_chars_)); return StringsBuffer(std::move(offsets), std::move(characters)); } void StringsBuffer::Builder::ResizeCharacters(size_t new_size) { DCHECK_LT(new_size, std::numeric_limits<offset_type>::max()); size_t offsets_size = offsets_.size() * sizeof(Offsets); InitDataPointers(factory_->ReallocRawBuffer(std::move(buf_), offsets_.begin(), offsets_size + characters_.size(), offsets_size + new_size), offsets_.size(), new_size); } void StringsBuffer::Builder::InitDataPointers( std::tuple<RawBufferPtr, void*>&& buf, int64_t offsets_count, int64_t characters_size) { buf_ = std::move(std::get<0>(buf)); void* data = std::get<1>(buf); offsets_ = absl::Span<Offsets>(reinterpret_cast<Offsets*>(data), offsets_count); characters_ = absl::Span<char>( reinterpret_cast<char*>(data) + offsets_count * sizeof(Offsets), characters_size); } StringsBuffer::StringsBuffer(SimpleBuffer<StringsBuffer::Offsets> offsets, SimpleBuffer<char> characters, offset_type base_offset) : offsets_(std::move(offsets)), characters_(std::move(characters)), base_offset_(base_offset) { for (int64_t i = 0; i < offsets_.size(); ++i) { DCHECK_LE(base_offset_, offsets_[i].start); DCHECK_LE(offsets_[i].start, offsets_[i].end); DCHECK_LE(offsets_[i].end, base_offset_ + characters_.size()); } } bool StringsBuffer::operator==(const StringsBuffer& other) const { if (this == &other) { return true; } if (size() != other.size()) { return false; } return std::equal(begin(), end(), other.begin()); } StringsBuffer StringsBuffer::Slice(int64_t offset, int64_t count) const& { if (count == 0) { return StringsBuffer{}; } return StringsBuffer{offsets_.Slice(offset, count), characters_, base_offset_}; } StringsBuffer StringsBuffer::Slice(int64_t offset, int64_t count) && { if (count == 0) { return StringsBuffer{}; } return StringsBuffer{std::move(offsets_).Slice(offset, count), std::move(characters_), base_offset_}; } StringsBuffer StringsBuffer::ShallowCopy() const { return StringsBuffer(offsets_.ShallowCopy(), characters_.ShallowCopy(), base_offset_); } StringsBuffer StringsBuffer::DeepCopy(RawBufferFactory* buffer_factory) const { if (size() == 0) { return StringsBuffer{}; } offset_type min_offset = offsets_[0].start; offset_type max_offset = offsets_[0].end; for (int64_t i = 1; i < size(); ++i) { min_offset = std::min(min_offset, offsets_[i].start); max_offset = std::max(max_offset, offsets_[i].end); } auto characters_slice = characters_.Slice(min_offset - base_offset_, max_offset - min_offset); return StringsBuffer(offsets_.DeepCopy(buffer_factory), characters_slice.DeepCopy(buffer_factory), min_offset); } void FingerprintHasherTraits<StringsBuffer>::operator()( FingerprintHasher* hasher, const StringsBuffer& value) const { hasher->Combine(value.size()); if (!value.empty()) { auto offsets_span = value.offsets().span(); hasher->CombineRawBytes(offsets_span.data(), offsets_span.size() * sizeof(offsets_span[0])); hasher->CombineSpan(value.characters().span()); } } }
#include <array> #include <cstddef> #include <initializer_list> #include <optional> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/hash/hash_testing.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "arolla/memory/buffer.h" #include "arolla/util/fingerprint.h" namespace arolla { namespace { using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::IsEmpty; using ::testing::Not; class StringsBufferTest : public ::testing::Test { public: Buffer<std::string> CreateTestBuffer(int num_rows) { std::vector<std::string> values(num_rows); for (int i = 0; i < num_rows; i++) { values[i] = absl::StrFormat("str%d", i); } return Buffer<std::string>::Create(values.begin(), values.end()); } template <typename T> Buffer<std::string> CreateTestBuffer(std::initializer_list<T> values) { return Buffer<std::string>::Create(values.begin(), values.end()); } }; TEST_F(StringsBufferTest, Simple) { Buffer<std::string> buffer = CreateTestBuffer(4); EXPECT_TRUE(buffer.is_owner()); EXPECT_THAT(buffer, ElementsAre("str0", "str1", "str2", "str3")); EXPECT_EQ(buffer[0], "str0"); EXPECT_EQ(buffer[3], "str3"); } TEST_F(StringsBufferTest, Empty) { Buffer<std::string> buffer1 = CreateTestBuffer(0); EXPECT_THAT(buffer1, IsEmpty()); Buffer<std::string> buffer2 = buffer1.DeepCopy(); EXPECT_THAT(buffer2, IsEmpty()); Buffer<std::string> buffer3; EXPECT_THAT(buffer3, IsEmpty()); } TEST_F(StringsBufferTest, Move) { size_t num_rows = 4; Buffer<std::string> buffer = CreateTestBuffer(num_rows); EXPECT_TRUE(buffer.is_owner()); Buffer<std::string> buffer2 = std::move(buffer); EXPECT_TRUE(buffer2.is_owner()); EXPECT_FALSE(buffer.is_owner()); EXPECT_THAT(buffer2, ElementsAre("str0", "str1", "str2", "str3")); Buffer<std::string> buffer3; EXPECT_TRUE(buffer3.is_owner()); buffer3 = std::move(buffer2); EXPECT_TRUE(buffer3.is_owner()); EXPECT_FALSE(buffer2.is_owner()); EXPECT_THAT(buffer3, ElementsAre("str0", "str1", "str2", "str3")); } TEST_F(StringsBufferTest, MemoryUsage) { EXPECT_EQ(sizeof(Buffer<StringsBuffer::Offsets>), 4 * sizeof(void*)); EXPECT_EQ(sizeof(Buffer<char>), 4 * sizeof(void*)); EXPECT_EQ(sizeof(Buffer<std::string>), sizeof(Buffer<StringsBuffer::Offsets>) + sizeof(Buffer<char>) + 8); for (size_t sz = 0; sz < 10; sz += 1) { const size_t chars = sz * 4; const size_t offsets = sz * sizeof(StringsBuffer::Offsets); Buffer<std::string> buffer = CreateTestBuffer(sz); EXPECT_EQ(chars + offsets, buffer.memory_usage()); } } TEST_F(StringsBufferTest, MoveSlice) { size_t num_rows = 10; Buffer<std::string> buffer = CreateTestBuffer(num_rows); EXPECT_TRUE(buffer.is_owner()); buffer = std::move(buffer).Slice(0, 5); EXPECT_TRUE(buffer.is_owner()); EXPECT_THAT(buffer, ElementsAre("str0", "str1", "str2", "str3", "str4")); Buffer<std::string> buffer2 = std::move(buffer).Slice(2, 3); EXPECT_TRUE(buffer2.is_owner()); EXPECT_FALSE(buffer.is_owner()); EXPECT_THAT(buffer2, ElementsAre("str2", "str3", "str4")); } TEST_F(StringsBufferTest, ShallowCopy) { size_t num_rows = 10; Buffer<std::string> buffer = CreateTestBuffer(num_rows); Buffer<std::string> buffer_copy1 = buffer.ShallowCopy(); EXPECT_FALSE(buffer_copy1.is_owner()); EXPECT_EQ(buffer.begin(), buffer_copy1.begin()); EXPECT_EQ(buffer.end(), buffer_copy1.end()); EXPECT_THAT(buffer, ElementsAreArray(buffer_copy1)); Buffer<std::string> buffer_copy2 = buffer.Slice(5, 5); EXPECT_THAT(buffer, Not(ElementsAreArray(buffer_copy2))); EXPECT_TRUE(buffer_copy2.is_owner()); EXPECT_EQ(buffer[5], buffer_copy2[0]); } TEST_F(StringsBufferTest, DeepCopy) { size_t num_rows = 5; Buffer<std::string> buffer = CreateTestBuffer(num_rows); Buffer<std::string> buffer_copy = buffer.DeepCopy(); Buffer<std::string> buffer_slice_copy = buffer.Slice(1, 3).DeepCopy(); buffer = Buffer<std::string>(); EXPECT_TRUE(buffer_copy.is_owner()); EXPECT_THAT(buffer_copy, ElementsAre("str0", "str1", "str2", "str3", "str4")); EXPECT_TRUE(buffer_slice_copy.is_owner()); EXPECT_THAT(buffer_slice_copy, ElementsAre("str1", "str2", "str3")); buffer_copy = buffer.DeepCopy(); EXPECT_THAT(buffer_copy, IsEmpty()); } TEST_F(StringsBufferTest, EmptySlice) { size_t num_rows = 10; Buffer<std::string> buffer = CreateTestBuffer(num_rows); Buffer<std::string> copy = buffer.Slice(3, 0); EXPECT_THAT(copy, IsEmpty()); buffer = std::move(buffer).Slice(3, 0); EXPECT_THAT(buffer, IsEmpty()); copy = buffer.Slice(0, 0); EXPECT_THAT(copy, IsEmpty()); } TEST_F(StringsBufferTest, HugeString) { StringsBuffer::Builder builder(2); builder.Set(0, "small string"); std::string huge_string; for (int i = 0; i < 1000; ++i) huge_string.append("huge string; "); builder.Set(1, huge_string); StringsBuffer buffer = std::move(builder).Build(2); EXPECT_EQ(buffer.size(), 2); EXPECT_EQ(buffer[0], "small string"); EXPECT_EQ(buffer[1], huge_string); } TEST_F(StringsBufferTest, SupportsAbslHash) { StringsBuffer empty; std::array<absl::string_view, 5> values = {"one", "two", "three", "four", "five"}; StringsBuffer test1 = StringsBuffer::Create(values.begin(), values.end()); StringsBuffer test2 = StringsBuffer::Create(values.rbegin(), values.rend()); EXPECT_TRUE( absl::VerifyTypeImplementsAbslHashCorrectly({empty, test1, test2})); } TEST_F(StringsBufferTest, Fingerprint) { std::array<absl::string_view, 5> values = {"one", "two", "three", "four", "five"}; StringsBuffer test1 = StringsBuffer::Create(values.begin(), values.end()); StringsBuffer test2 = StringsBuffer::Create(values.begin(), values.end()); StringsBuffer test3 = StringsBuffer::Create(values.rbegin(), values.rend()); Fingerprint f1 = FingerprintHasher("salt").Combine(test1).Finish(); Fingerprint f2 = FingerprintHasher("salt").Combine(test2).Finish(); Fingerprint f3 = FingerprintHasher("salt").Combine(test3).Finish(); EXPECT_EQ(f1, f2); EXPECT_NE(f1, f3); } TEST(StringsBufferBuilder, Inserter) { Buffer<std::string>::Builder builder(10); auto inserter = builder.GetInserter(1); for (int i = 0; i < 4; ++i) inserter.Add(absl::StrFormat("str%d", i)); builder.Set(0, "aba"); auto buffer = std::move(builder).Build(inserter); EXPECT_THAT(buffer, ElementsAre("aba", "str0", "str1", "str2", "str3")); } TEST(StringsBufferBuilder, InserterCord) { Buffer<std::string>::Builder builder(10); auto inserter = builder.GetInserter(1); for (int i = 0; i < 4; ++i) { inserter.Add(absl::Cord(absl::StrFormat("str%d", i))); } builder.Set(0, "aba"); auto buffer = std::move(builder).Build(inserter); EXPECT_THAT(buffer, ElementsAre("aba", "str0", "str1", "str2", "str3")); } TEST(StringsBufferBuilder, Generator) { Buffer<std::string>::Builder builder(10); builder.SetNConst(0, 10, "default"); int i = 0; builder.SetN(2, 3, [&]() { return absl::StrFormat("str%d", ++i); }); auto buffer = std::move(builder).Build(6); EXPECT_THAT(buffer, ElementsAre("default", "default", "str1", "str2", "str3", "default")); } TEST(StringsBufferBuilder, RandomAccess) { Buffer<std::string>::Builder builder(10); builder.Set(4, "s1"); builder.Set(2, "s2"); builder.Set(1, "s3"); builder.Set(0, "s4"); builder.Set(3, "s5"); builder.Set(1, "s6"); auto buffer = std::move(builder).Build(5); EXPECT_THAT(buffer, ElementsAre("s4", "s6", "s2", "s5", "s1")); } TEST(StringsBufferBuilder, RandomAccessCord) { Buffer<std::string>::Builder builder(10); builder.Set(4, absl::Cord("s1")); builder.Set(2, absl::Cord("s2")); builder.Set(1, absl::Cord("s3")); builder.Set(0, absl::Cord("s4")); builder.Set(3, absl::Cord("s5")); builder.Set(1, absl::Cord("s6")); auto buffer = std::move(builder).Build(5); EXPECT_THAT(buffer, ElementsAre("s4", "s6", "s2", "s5", "s1")); } TEST(StringsBufferBuilder, ReshuffleBuilder) { auto buf = CreateBuffer<std::string>({"5v", "4ab", "3", "2", "1"}); { Buffer<std::string>::ReshuffleBuilder bldr(7, buf, std::nullopt); bldr.CopyValue(3, 1); bldr.CopyValue(1, 2); bldr.CopyValue(2, 0); bldr.CopyValueToRange(4, 7, 0); auto res = std::move(bldr).Build(); EXPECT_THAT(res, ElementsAre("", "3", "5v", "4ab", "5v", "5v", "5v")); EXPECT_EQ(res.characters().begin(), buf.characters().begin()); } { Buffer<std::string>::ReshuffleBuilder bldr(4, buf, {true, ""}); bldr.CopyValue(3, 1); bldr.CopyValue(1, 2); bldr.CopyValue(2, 0); auto res = std::move(bldr).Build(); EXPECT_THAT(res, ElementsAre("", "3", "5v", "4ab")); EXPECT_EQ(res.characters().begin(), buf.characters().begin()); } { Buffer<std::string>::ReshuffleBuilder bldr(4, buf, {true, "0abc"}); bldr.CopyValue(3, 1); bldr.CopyValue(1, 2); bldr.CopyValue(2, 0); auto res = std::move(bldr).Build(); EXPECT_THAT(res, ElementsAre("0abc", "3", "5v", "4ab")); } } } }
2,495
#ifndef AROLLA_MEMORY_FRAME_H_ #define AROLLA_MEMORY_FRAME_H_ #include <algorithm> #include <cstddef> #include <cstdlib> #include <cstring> #include <initializer_list> #include <ostream> #include <tuple> #include <type_traits> #include <typeindex> #include <typeinfo> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/types/span.h" #include "arolla/memory/frame.h" #include "arolla/util/algorithms.h" #include "arolla/util/demangle.h" #include "arolla/util/is_bzero_constructible.h" #include "arolla/util/memory.h" #include "arolla/util/struct_field.h" namespace arolla { class FrameLayout { public: class Builder; template <typename T> class Slot; FrameLayout() = default; size_t AllocSize() const { return alloc_size_; } Alignment AllocAlignment() const { return alloc_alignment_; } void InitializeAlignedAlloc(void* alloc) const; void DestroyAlloc(void* alloc) const; void InitializeAlignedAllocN(void* alloc, size_t n) const; void DestroyAllocN(void* alloc, size_t n) const; bool HasField(size_t offset, const std::type_info& type) const; private: explicit FrameLayout(Builder&& builder); class FieldFactory; struct FieldInitializers { void AddOffsetToFactory(size_t offset, FieldFactory empty_factory); void AddDerived(size_t extra_offset, const FieldInitializers& derived_initializers); template <class T> void Add(size_t offset); std::vector<FieldFactory> factories; absl::flat_hash_map<std::type_index, size_t> type2factory; }; #ifndef NDEBUG absl::flat_hash_set<std::pair<size_t, std::type_index>> registered_fields_; #endif FieldInitializers initializers_; size_t alloc_size_{0}; Alignment alloc_alignment_{1}; }; template <typename T> struct TypesToSlotTypes; template <typename... Ts> struct TypesToSlotTypes<std::tuple<Ts...>> { using type = std::tuple<FrameLayout::Slot<Ts>...>; }; template <typename T> class FrameLayout::Slot { static constexpr size_t kNumSubslots = StructFieldCount<T>(); static_assert(std::is_standard_layout<T>::value || (kNumSubslots == 0), "Only standard layout classes support access to subfields."); public: using value_type = T; Slot(const Slot& other) = default; size_t byte_offset() const { return byte_offset_; } static Slot<T> UnsafeSlotFromOffset(size_t byte_offset) { return Slot(byte_offset); } static constexpr size_t kUninitializedOffset = ~static_cast<size_t>(0); static Slot<T> UnsafeUninitializedSlot() { return Slot(kUninitializedOffset); } friend std::ostream& operator<<(std::ostream& stream, const FrameLayout::Slot<T>& slot) { return stream << "Slot<" << TypeName<T>() << ">(" << slot.byte_offset() << ")"; } static constexpr size_t NumSubslots() { return kNumSubslots; } template <size_t I> auto GetSubslot() { static_assert(I < kNumSubslots, "Subslot Index out of range."); const auto& struct_field = std::get<I>(GetStructFields<T>()); return FrameLayout::Slot< typename std::decay_t<decltype(struct_field)>::field_type>:: UnsafeSlotFromOffset(byte_offset_ + struct_field.field_offset); } private: friend class Builder; friend class FramePtr; friend class ConstFramePtr; explicit Slot(size_t byte_offset) : byte_offset_(byte_offset) {} decltype(auto) UnsafeGet(const void* alloc) const { DCHECK_NE(byte_offset_, kUninitializedOffset); return *reinterpret_cast<const T*>(static_cast<const char*>(alloc) + byte_offset_); } T* UnsafeGetMutable(void* alloc) const { DCHECK_NE(byte_offset_, kUninitializedOffset); return reinterpret_cast<T*>(static_cast<char*>(alloc) + byte_offset_); } size_t byte_offset_; }; class FrameLayout::FieldFactory { public: template <typename T> static FieldFactory Create() { static_assert(!is_bzero_constructible<T>() || !std::is_trivially_destructible<T>()); FactoryFn construct; FactoryNFn construct_n; if constexpr (is_bzero_constructible<T>()) { construct = [](void*, absl::Span<const size_t>) {}; construct_n = [](void*, absl::Span<const size_t>, size_t, size_t) {}; } else { construct = [](void* ptr, absl::Span<const size_t> offsets) { for (size_t offset : offsets) { void* shifted_ptr = static_cast<char*>(ptr) + offset; new (shifted_ptr) T; } }; construct_n = [](void* ptr, absl::Span<const size_t> offsets, size_t block_size, size_t n) { for (size_t i = 0; i < n; ++i) { for (size_t offset : offsets) { void* shifted_ptr = static_cast<char*>(ptr) + offset + i * block_size; new (shifted_ptr) T; } } }; } FactoryFn destruct; FactoryNFn destruct_n; if constexpr (std::is_trivially_destructible<T>()) { destruct = [](void*, absl::Span<const size_t>) {}; destruct_n = [](void*, absl::Span<const size_t>, size_t, size_t) {}; } else { destruct = [](void* ptr, absl::Span<const size_t> offsets) { for (size_t offset : offsets) { void* shifted_ptr = static_cast<char*>(ptr) + offset; static_cast<T*>(shifted_ptr)->~T(); } }; destruct_n = [](void* ptr, absl::Span<const size_t> offsets, size_t block_size, size_t n) { for (size_t i = 0; i < n; ++i) { for (size_t offset : offsets) { void* shifted_ptr = static_cast<char*>(ptr) + offset + i * block_size; static_cast<T*>(shifted_ptr)->~T(); } } }; } return FieldFactory(std::type_index(typeid(T)), construct, destruct, construct_n, destruct_n); } std::type_index type_index() const; void Add(size_t offset); void AddDerived(const FieldFactory& derived_factory); FieldFactory Derive(size_t offset) const; void Construct(void* ptr) const { construct_(ptr, offsets_); } void Destroy(void* ptr) const { destruct_(ptr, offsets_); } void ConstructN(void* ptr, size_t block_size, size_t n) const { construct_n_(ptr, offsets_, block_size, n); } void DestroyN(void* ptr, size_t block_size, size_t n) const { destruct_n_(ptr, offsets_, block_size, n); } private: using FactoryFn = void (*)(void*, absl::Span<const size_t>); using FactoryNFn = void (*)(void*, absl::Span<const size_t>, size_t, size_t); FieldFactory(std::type_index tpe, FactoryFn construct, FactoryFn destruct, FactoryNFn construct_n, FactoryNFn destruct_n) : type_(tpe), construct_(construct), destruct_(destruct), construct_n_(construct_n), destruct_n_(destruct_n) {} std::type_index type_; FactoryFn construct_; FactoryFn destruct_; std::vector<size_t> offsets_; FactoryNFn construct_n_; FactoryNFn destruct_n_; }; template <class T> void FrameLayout::FieldInitializers::Add(size_t offset) { AddOffsetToFactory(offset, FieldFactory::Create<T>()); } inline void FrameLayout::InitializeAlignedAlloc(void* alloc) const { DCHECK(IsAlignedPtr(alloc_alignment_, alloc)) << "invalid alloc alignment"; memset(alloc, 0, alloc_size_); for (const auto& factory : initializers_.factories) { factory.Construct(alloc); } } inline void FrameLayout::DestroyAlloc(void* alloc) const { for (const auto& factory : initializers_.factories) { factory.Destroy(alloc); } } inline void FrameLayout::InitializeAlignedAllocN(void* alloc, size_t n) const { DCHECK(IsAlignedPtr(alloc_alignment_, alloc)) << "invalid alloc alignment"; memset(alloc, 0, alloc_size_ * n); for (const auto& factory : initializers_.factories) { factory.ConstructN(alloc, alloc_size_, n); } } inline void FrameLayout::DestroyAllocN(void* alloc, size_t n) const { for (const auto& factory : initializers_.factories) { factory.DestroyN(alloc, alloc_size_, n); } } class FrameLayout::Builder { public: template <typename T> ABSL_ATTRIBUTE_ALWAYS_INLINE Slot<T> AddSlot() { static_assert(alignof(T) <= 16, "Types with strong alignments are not supported."); alloc_size_ = RoundUp(alloc_size_, alignof(T)); size_t offset = alloc_size_; Slot<T> slot(offset); alloc_size_ += sizeof(T); alloc_alignment_ = std::max(alloc_alignment_, alignof(T)); if constexpr (!is_bzero_constructible<T>() || !std::is_trivially_destructible<T>()) { initializers_.Add<T>(offset); } auto status = RegisterSlot(slot.byte_offset(), sizeof(T), typeid(T)); DCHECK(status.ok()) << status.message() << "Internal error during RegisterSlot."; status = RegisterSubslots(slot, std::make_index_sequence<slot.NumSubslots()>()); DCHECK(status.ok()) << status.message() << "Internal error during RegisterSubslots."; return slot; } Slot<void> AddSubFrame(const FrameLayout& subframe); absl::Status RegisterUnsafeSlot(size_t byte_offset, size_t byte_size, const std::type_info& type); template <typename T> absl::Status RegisterUnsafeSlot(const Slot<T>& slot, bool allow_duplicates = false) { return RegisterSlot(slot.byte_offset(), sizeof(T), typeid(T), allow_duplicates); } FrameLayout Build() && { alloc_size_ = RoundUp(alloc_size_, alloc_alignment_); return FrameLayout(std::move(*this)); } private: friend class FrameLayout; template <typename T, size_t... Is> absl::Status RegisterSubslots( Slot<T> slot ABSL_ATTRIBUTE_UNUSED, std::index_sequence<Is...>) { ABSL_ATTRIBUTE_UNUSED auto register_slot_recursively = [&](auto subslot) -> absl::Status { absl::Status status = RegisterUnsafeSlot(subslot); if constexpr (decltype(subslot)::NumSubslots() != 0) { if (status.ok()) { status = RegisterSubslots( subslot, std::make_index_sequence<decltype(subslot)::NumSubslots()>()); } } return status; }; for (absl::Status status : std::initializer_list<absl::Status>{ register_slot_recursively(slot.template GetSubslot<Is>())...}) { if (!status.ok()) return status; } return absl::OkStatus(); } absl::Status RegisterSlot(size_t byte_offset, size_t byte_size, const std::type_info& type, bool allow_duplicates = false); #ifndef NDEBUG absl::flat_hash_set<std::pair<size_t, std::type_index>> registered_fields_; #endif FieldInitializers initializers_; size_t alloc_size_{0}; size_t alloc_alignment_{1}; }; template <typename T> FrameLayout MakeTypeLayout() { FrameLayout::Builder builder; auto slot = builder.AddSlot<T>(); DCHECK_EQ(slot.byte_offset(), size_t{0}); return std::move(builder).Build(); } class FramePtr { public: FramePtr(void* base_ptr, const FrameLayout* layout); template <typename T> T* GetMutable(FrameLayout::Slot<T> slot) const { DCheckFieldType(slot.byte_offset(), typeid(T)); return slot.UnsafeGetMutable(base_ptr_); } template <typename T, typename S = T> void Set(FrameLayout::Slot<T> slot, S&& value) const { DCheckFieldType(slot.byte_offset(), typeid(T)); *GetMutable(slot) = std::forward<S>(value); } template <typename T> const T& Get(FrameLayout::Slot<T> slot) const { DCheckFieldType(slot.byte_offset(), typeid(T)); return slot.UnsafeGet(base_ptr_); } void* GetRawPointer(size_t byte_offset) const { return static_cast<char*>(base_ptr_) + byte_offset; } void DCheckFieldType(size_t offset, const std::type_info& type) const; private: friend class ConstFramePtr; void* base_ptr_; #ifndef NDEBUG const FrameLayout* layout_; #endif }; class ConstFramePtr { public: ConstFramePtr(const void* base_ptr, const FrameLayout* layout); ConstFramePtr(FramePtr frame_ptr); template <typename T> const T& Get(FrameLayout::Slot<T> slot) const { DCheckFieldType(slot.byte_offset(), typeid(T)); return slot.UnsafeGet(base_ptr_); } const void* GetRawPointer(size_t byte_offset) const { return static_cast<const char*>(base_ptr_) + byte_offset; } void DCheckFieldType(size_t offset, const std::type_info& type) const; private: const void* base_ptr_; #ifndef NDEBUG const FrameLayout* layout_; #endif }; #ifndef NDEBUG inline bool FrameLayout::HasField(size_t offset, const std::type_info& type) const { return registered_fields_.contains({offset, std::type_index(type)}); } inline FrameLayout::FrameLayout(Builder&& builder) : registered_fields_(std::move(builder.registered_fields_)), initializers_(std::move(builder.initializers_)), alloc_size_(builder.alloc_size_), alloc_alignment_{builder.alloc_alignment_} {} inline FramePtr::FramePtr(void* base_ptr, const FrameLayout* layout) : base_ptr_(base_ptr), layout_(layout) {} inline void FramePtr::DCheckFieldType(size_t offset, const std::type_info& type) const { DCHECK(layout_->HasField(offset, type)) << "Field with given offset and type not found: Slot<" << type.name() << ">(" << offset << ")"; } inline ConstFramePtr::ConstFramePtr(const void* base_ptr, const FrameLayout* layout) : base_ptr_(base_ptr), layout_(layout) {} inline ConstFramePtr::ConstFramePtr(FramePtr frame_ptr) : base_ptr_(frame_ptr.base_ptr_), layout_(frame_ptr.layout_) {} inline void ConstFramePtr::DCheckFieldType(size_t offset, const std::type_info& type) const { DCHECK(layout_->HasField(offset, type)) << "Field with given offset and type not found: Slot<" << type.name() << ">(" << offset << ")"; } #else inline bool FrameLayout::HasField(size_t, const std::type_info&) const { return true; } inline FrameLayout::FrameLayout(Builder&& builder) : initializers_(std::move(builder.initializers_)), alloc_size_(builder.alloc_size_), alloc_alignment_{builder.alloc_alignment_} {} inline FramePtr::FramePtr(void* base_ptr, const FrameLayout* ) : base_ptr_(base_ptr) {} inline void FramePtr::DCheckFieldType(size_t , const std::type_info& ) const {} inline ConstFramePtr::ConstFramePtr(const void* base_ptr, const FrameLayout* ) : base_ptr_(base_ptr) {} inline ConstFramePtr::ConstFramePtr(FramePtr frame_ptr) : base_ptr_(frame_ptr.base_ptr_) {} inline void ConstFramePtr::DCheckFieldType( size_t , const std::type_info& ) const {} #endif } #endif #include "arolla/memory/frame.h" #include <algorithm> #include <cstddef> #include <cstring> #include <tuple> #include <typeindex> #include <typeinfo> #include <utility> #include "absl/log/check.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "arolla/util/algorithms.h" #include "arolla/util/memory.h" namespace arolla { std::type_index FrameLayout::FieldFactory::type_index() const { return type_; } void FrameLayout::FieldFactory::Add(size_t offset) { offsets_.push_back(offset); } void FrameLayout::FieldFactory::AddDerived( const FieldFactory& derived_factory) { DCHECK(type_index() == derived_factory.type_index()); for (size_t cur_offset : derived_factory.offsets_) { offsets_.push_back(cur_offset); } } FrameLayout::FieldFactory FrameLayout::FieldFactory::Derive( size_t offset) const { FieldFactory res = *this; for (size_t& cur_offset : res.offsets_) { cur_offset += offset; } return res; } void FrameLayout::FieldInitializers::AddOffsetToFactory( size_t offset, FieldFactory empty_factory) { auto it = type2factory.find(empty_factory.type_index()); if (it == type2factory.end()) { bool inserted; std::tie(it, inserted) = type2factory.emplace(empty_factory.type_index(), factories.size()); factories.push_back(std::move(empty_factory)); } DCHECK_LT(it->second, factories.size()); if (it->second < factories.size()) { factories[it->second].Add(offset); } } void FrameLayout::FieldInitializers::AddDerived( size_t offset, const FieldInitializers& derived_initializers) { for (const auto& [derived_tpe, derived_id] : derived_initializers.type2factory) { const auto& derived_factory = derived_initializers.factories[derived_id]; if (auto it = type2factory.find(derived_tpe); it != type2factory.end()) { factories[it->second].AddDerived(derived_factory.Derive(offset)); } else { type2factory.emplace(derived_tpe, factories.size()); factories.push_back(derived_factory.Derive(offset)); } } } FrameLayout::Slot<void> FrameLayout::Builder::AddSubFrame( const FrameLayout& subframe) { alloc_size_ = RoundUp(alloc_size_, subframe.AllocAlignment().value); size_t offset = alloc_size_; alloc_size_ += subframe.AllocSize(); alloc_alignment_ = std::max(alloc_alignment_, subframe.AllocAlignment().value); initializers_.AddDerived(offset, subframe.initializers_); #ifndef NDEBUG for (const auto& [field_offset, field_type] : subframe.registered_fields_) { registered_fields_.emplace(offset + field_offset, field_type); } #endif return FrameLayout::Slot<void>(offset); } absl::Status FrameLayout::Builder::RegisterUnsafeSlot( size_t byte_offset, size_t byte_size, const std::type_info& type) { return RegisterSlot(byte_offset, byte_size, type); } absl::Status FrameLayout::Builder::RegisterSlot(size_t byte_offset, size_t byte_size, const std::type_info& type, bool allow_duplicates) { if (byte_offset == FrameLayout::Slot<float>::kUninitializedOffset) { return absl::FailedPreconditionError( "unable to register uninitialized slot"); } if (byte_offset > alloc_size_ || byte_size > alloc_size_ - byte_offset) { return absl::FailedPreconditionError(absl::StrCat( "unable to register slot after the end of alloc, offset: ", byte_offset, ", size: ", byte_size, ", alloc size: ", alloc_size_)); } #ifndef NDEBUG if (!registered_fields_.emplace(byte_offset, std::type_index(type)).second && !allow_duplicates) { return absl::FailedPreconditionError(absl::StrCat( "slot is already registered ", byte_offset, " ", type.name())); } #endif return absl::OkStatus(); } }
#include "arolla/memory/frame.h" #include <array> #include <cstddef> #include <cstdint> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <variant> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/dynamic_annotations.h" #include "absl/status/status.h" #include "arolla/memory/memory_allocation.h" #include "arolla/util/demangle.h" #include "arolla/util/is_bzero_constructible.h" #include "arolla/util/memory.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::testing { namespace { using ::arolla::testing::IsOk; using ::arolla::testing::StatusIs; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsEmpty; struct SimpleStruct { int a; float b; }; struct InitializedStruct { int a = 1; float b = 2.0; }; TEST(FrameLayoutTest, SlotOutput) { FrameLayout::Builder builder; auto slot = builder.AddSlot<int>(); std::ostringstream ss; ss << slot; EXPECT_EQ(ss.str(), std::string("Slot<") + TypeName<int>() + ">(0)"); } TEST(FrameLayoutTest, SimpleFields) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<int>(); auto slot2 = builder.AddSlot<float>(); auto slot3 = builder.AddSlot<double>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); EXPECT_THAT(frame.Get(slot1), Eq(0)); EXPECT_THAT(frame.Get(slot2), Eq(0.0f)); EXPECT_THAT(frame.Get(slot3), Eq(0.0)); frame.Set(slot1, 1); frame.Set(slot2, 2.0f); frame.Set(slot3, M_PI); EXPECT_THAT(frame.Get(slot1), Eq(1)); EXPECT_THAT(frame.Get(slot2), Eq(2.0f)); EXPECT_THAT(frame.Get(slot3), Eq(M_PI)); } TEST(FrameLayoutTest, SimpleArrays) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<std::array<int, 4>>(); auto slot2 = builder.AddSlot<std::array<float, 4>>(); auto slot3 = builder.AddSlot<std::array<char, 4>>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); EXPECT_THAT(frame.Get(slot1), ElementsAre(0, 0, 0, 0)); EXPECT_THAT(frame.Get(slot2), ElementsAre(0.0f, 0.0f, 0.0f, 0.0f)); EXPECT_THAT(frame.Get(slot3), ElementsAre(0, 0, 0, 0)); frame.Set(slot1, std::array<int, 4>{1, 2, 3, 4}); frame.Set(slot2, std::array<float, 4>{1.0f, 2.0f, 3.0f, 4.0f}); frame.Set(slot3, std::array<char, 4>{'a', 'b', 'c', 'd'}); EXPECT_THAT(frame.Get(slot1), ElementsAre(1, 2, 3, 4)); EXPECT_THAT(frame.Get(slot2), ElementsAre(1.0f, 2.0f, 3.0f, 4.0f)); EXPECT_THAT(frame.Get(slot3), ElementsAre('a', 'b', 'c', 'd')); } TEST(FrameLayoutTest, SimplePointers) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<int*>(); auto slot2 = builder.AddSlot<char*>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); EXPECT_THAT(frame.Get(slot1), Eq(nullptr)); EXPECT_THAT(frame.Get(slot2), Eq(nullptr)); int int_values[] = {1, 2, 3, 4}; char text[] = "It was a dark and stormy night."; frame.Set(slot1, int_values); frame.Set(slot2, text); EXPECT_THAT(frame.Get(slot1), Eq(int_values)); EXPECT_THAT(frame.Get(slot2), Eq(text)); } TEST(FrameLayoutTest, SmartPointers) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<std::unique_ptr<int>>(); auto slot2 = builder.AddSlot<std::unique_ptr<std::string>>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); EXPECT_THAT(frame.Get(slot1), Eq(nullptr)); EXPECT_THAT(frame.Get(slot2), Eq(nullptr)); frame.Set(slot1, std::make_unique<int>(12)); frame.Set(slot2, std::make_unique<std::string>("It was a dark and stormy night.")); EXPECT_THAT(*frame.Get(slot1), Eq(12)); EXPECT_THAT(*frame.Get(slot2), Eq("It was a dark and stormy night.")); } TEST(FrameLayoutTest, Vector) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<std::vector<int>>(); auto slot2 = builder.AddSlot<std::vector<std::string>>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); EXPECT_THAT(frame.Get(slot1), IsEmpty()); EXPECT_THAT(frame.Get(slot2), IsEmpty()); auto* int_vector = frame.GetMutable(slot1); int_vector->push_back(1); int_vector->push_back(2); int_vector->push_back(3); auto* string_vector = frame.GetMutable(slot2); string_vector->push_back("How"); string_vector->push_back("now"); string_vector->push_back("brown"); string_vector->push_back("cow?"); EXPECT_THAT(frame.Get(slot1), ElementsAre(1, 2, 3)); EXPECT_THAT(frame.Get(slot2), ElementsAre("How", "now", "brown", "cow?")); } TEST(FrameLayoutTest, Structs) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<SimpleStruct>(); auto slot2 = builder.AddSlot<InitializedStruct>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); const SimpleStruct& s1 = frame.Get(slot1); EXPECT_THAT(s1.a, Eq(0)); EXPECT_THAT(s1.b, Eq(0.0f)); const InitializedStruct& s2 = frame.Get(slot2); EXPECT_THAT(s2.a, Eq(1)); EXPECT_THAT(s2.b, Eq(2.0f)); } TEST(FrameLayoutTest, AFewDifferentTypesWellInitialized) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<std::vector<int>>(); auto slot2 = builder.AddSlot<std::vector<std::string>>(); auto slot3 = builder.AddSlot<std::vector<int>>(); auto slot4 = builder.AddSlot<SimpleStruct>(); auto slot5 = builder.AddSlot<InitializedStruct>(); auto slot6 = builder.AddSlot<std::vector<int>>(); auto slot7 = builder.AddSlot<std::vector<std::string>>(); auto slot8 = builder.AddSlot<std::vector<double>>(); auto slot9 = builder.AddSlot<InitializedStruct>(); auto layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); EXPECT_THAT(frame.Get(slot1), IsEmpty()); EXPECT_THAT(frame.Get(slot2), IsEmpty()); EXPECT_THAT(frame.Get(slot3), IsEmpty()); EXPECT_THAT(frame.Get(slot6), IsEmpty()); EXPECT_THAT(frame.Get(slot7), IsEmpty()); EXPECT_THAT(frame.Get(slot8), IsEmpty()); const SimpleStruct& simple = frame.Get(slot4); EXPECT_THAT(simple.a, Eq(0)); EXPECT_THAT(simple.b, Eq(0.0f)); for (const InitializedStruct& init : {frame.Get(slot5), frame.Get(slot9)}) { EXPECT_THAT(init.a, Eq(1)); EXPECT_THAT(init.b, Eq(2.0f)); } } TEST(FrameLayoutTest, HasField) { FrameLayout::Builder builder; auto slot1 = builder.AddSlot<int>(); auto slot2 = builder.AddSlot<std::vector<int>>(); auto slot3 = builder.AddSlot<SimpleStruct>(); auto slot4 = builder.AddSlot<std::array<SimpleStruct, 4>>(); auto slot5 = builder.AddSlot<InitializedStruct>(); auto slot6 = builder.AddSlot<std::array<InitializedStruct, 4>>(); auto layout = std::move(builder).Build(); EXPECT_TRUE(layout.HasField(slot1.byte_offset(), typeid(int))); EXPECT_TRUE(layout.HasField(slot2.byte_offset(), typeid(std::vector<int>))); EXPECT_TRUE(layout.HasField(slot3.byte_offset(), typeid(SimpleStruct))); EXPECT_TRUE(layout.HasField(slot4.byte_offset(), typeid(std::array<SimpleStruct, 4>))); EXPECT_TRUE(layout.HasField(slot5.byte_offset(), typeid(InitializedStruct))); EXPECT_TRUE(layout.HasField(slot6.byte_offset(), typeid(std::array<InitializedStruct, 4>))); } TEST(FrameLayoutTest, RegisterUnsafeSlotWithEmptyField) { FrameLayout::Builder builder; ASSERT_TRUE(builder.RegisterUnsafeSlot(0, 0, typeid(std::monostate())).ok()); auto layout = std::move(builder).Build(); EXPECT_TRUE(layout.HasField(0, typeid(std::monostate()))); } TEST(FrameLayoutTest, FieldDescriptorsRegisterUnsafe) { FrameLayout::Builder builder; auto slot = builder.AddSlot<int32_t>(); auto slot_1part = FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset()); auto slot_2part = FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset() + 2); ASSERT_THAT(builder.RegisterUnsafeSlot(slot_1part), IsOk()); ASSERT_THAT(builder.RegisterUnsafeSlot(slot_2part), IsOk()); ASSERT_THAT(builder.RegisterUnsafeSlot(slot.byte_offset() + 2, sizeof(int8_t), typeid(int8_t)), IsOk()); #ifndef NDEBUG EXPECT_THAT(builder.RegisterUnsafeSlot(slot_2part), StatusIs(absl::StatusCode::kFailedPrecondition, HasSubstr("slot is already registered"))); EXPECT_THAT(builder.RegisterUnsafeSlot(slot_2part, true), IsOk()); #endif auto layout = std::move(builder).Build(); EXPECT_TRUE(layout.HasField(slot.byte_offset(), typeid(int32_t))); EXPECT_TRUE(layout.HasField(slot.byte_offset(), typeid(int16_t))); EXPECT_TRUE(layout.HasField(slot.byte_offset() + 2, typeid(int16_t))); EXPECT_TRUE(layout.HasField(slot.byte_offset() + 2, typeid(int8_t))); #ifndef NDEBUG EXPECT_FALSE(layout.HasField(slot.byte_offset() + 2, typeid(float))); EXPECT_FALSE(layout.HasField(slot.byte_offset() + 1, typeid(int8_t))); #endif } TEST(FrameLayoutTest, FieldDescriptorsRegisterUnsafeErrors) { FrameLayout::Builder builder; auto slot = builder.AddSlot<int32_t>(); auto slot_1part = FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset()); auto slot_after_end = FrameLayout::Slot<int16_t>::UnsafeSlotFromOffset(slot.byte_offset() + 4); auto uninitialized_slot = FrameLayout::Slot<int16_t>::UnsafeUninitializedSlot(); auto status = builder.RegisterUnsafeSlot(slot_1part); ASSERT_OK(status); #ifndef NDEBUG status = builder.RegisterUnsafeSlot(slot); ASSERT_FALSE(status.ok()); ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition); EXPECT_THAT(status.message(), HasSubstr("slot is already registered")); status = builder.RegisterUnsafeSlot(slot_1part); ASSERT_FALSE(status.ok()); ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition); EXPECT_THAT(status.message(), HasSubstr("slot is already registered")); #endif status = builder.RegisterUnsafeSlot(slot_after_end); ASSERT_FALSE(status.ok()); ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition); EXPECT_THAT(status.message(), HasSubstr("unable to register slot after the end of alloc")); status = builder.RegisterUnsafeSlot(100, sizeof(int), typeid(int)); ASSERT_FALSE(status.ok()); ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition); EXPECT_THAT(status.message(), HasSubstr("unable to register slot after the end of alloc, " "offset: 100, size: 4, alloc size: 4")); status = builder.RegisterUnsafeSlot(uninitialized_slot); ASSERT_FALSE(status.ok()); ASSERT_EQ(status.code(), absl::StatusCode::kFailedPrecondition); EXPECT_THAT(status.message(), HasSubstr("unable to register uninitialized slot")); } struct SelfReference { const SelfReference* self; SelfReference() : self(this) {} SelfReference(const SelfReference&) = delete; SelfReference& operator=(const SelfReference&) = delete; ~SelfReference() { self = nullptr; } }; TEST(FrameLayoutTest, AddSubFrame) { FrameLayout subframe_layout; std::vector<FrameLayout::Slot<SelfReference>> field_slots; { FrameLayout::Builder builder; for (int i = 0; i < 2; ++i) { field_slots.push_back(builder.AddSlot<SelfReference>()); } subframe_layout = std::move(builder).Build(); } FrameLayout frame_layout; std::vector<FrameLayout::Slot<void>> subframe_slots; { FrameLayout::Builder builder; builder.AddSlot<float>(); for (int j = 0; j < 3; ++j) { subframe_slots.push_back(builder.AddSubFrame(subframe_layout)); builder.AddSlot<double>(); } frame_layout = std::move(builder).Build(); } for (const auto& subframe_slot : subframe_slots) { for (const auto& field_slot : field_slots) { EXPECT_TRUE(frame_layout.HasField( subframe_slot.byte_offset() + field_slot.byte_offset(), typeid(SelfReference))); } } const auto alloc = AlignedAlloc(frame_layout.AllocAlignment(), frame_layout.AllocSize()); frame_layout.InitializeAlignedAlloc(alloc.get()); FramePtr frame(alloc.get(), &frame_layout); for (const auto& subframe_slot : subframe_slots) { for (const auto& field_slot : field_slots) { const void* subframe_ptr = frame.GetRawPointer(subframe_slot.byte_offset()); ConstFramePtr subframe(subframe_ptr, &subframe_layout); const SelfReference& field = subframe.Get(field_slot); EXPECT_TRUE(field.self == &field); } } frame_layout.DestroyAlloc(alloc.get()); ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(alloc.get(), frame_layout.AllocSize()); for (const auto& subframe_slot : subframe_slots) { for (const auto& field_slot : field_slots) { const void* subframe_ptr = frame.GetRawPointer(subframe_slot.byte_offset()); ConstFramePtr subframe(subframe_ptr, &subframe_layout); const SelfReference& field = subframe.Get(field_slot); EXPECT_TRUE(field.self == nullptr); } } } TEST(FrameLayoutTest, AddSubFrameAllocAlignment) { FrameLayout::Builder builder; builder.AddSubFrame(MakeTypeLayout<std::aligned_storage_t<16, 16>>()); builder.AddSubFrame(MakeTypeLayout<std::aligned_storage_t<16, 16>>()); auto frame_layout = std::move(builder).Build(); EXPECT_EQ(frame_layout.AllocSize(), 32); EXPECT_EQ(frame_layout.AllocAlignment().value, 16); } TEST(FrameLayoutTest, ArrayCompatibility) { FrameLayout::Builder builder; builder.AddSlot<std::aligned_storage_t<16, 16>>(); builder.AddSlot<std::aligned_storage_t<1, 1>>(); auto frame_layout = std::move(builder).Build(); EXPECT_EQ(frame_layout.AllocSize(), 32); EXPECT_EQ(frame_layout.AllocAlignment().value, 16); } TEST(FrameLayoutTest, InitDestroyAllocN) { static int instance_counter = 0; struct InstanceCounted { InstanceCounted() { ++instance_counter; } ~InstanceCounted() { --instance_counter; } }; struct SelfReferenced { SelfReferenced() : self(this) {} SelfReferenced* self; }; FrameLayout::Builder builder; auto int_slot = builder.AddSlot<int>(); auto self_ref_slot = builder.AddSlot<SelfReferenced>(); builder.AddSlot<InstanceCounted>(); auto layout = std::move(builder).Build(); const int n = 10; const auto alloc = AlignedAlloc(layout.AllocAlignment(), layout.AllocSize() * n); layout.InitializeAlignedAllocN(alloc.get(), n); EXPECT_EQ(instance_counter, n); for (int i = 0; i < n; ++i) { ConstFramePtr ith_frame( static_cast<const std::byte*>(alloc.get()) + i * layout.AllocSize(), &layout); EXPECT_EQ(ith_frame.Get(int_slot), 0); EXPECT_EQ(ith_frame.Get(self_ref_slot).self, &ith_frame.Get(self_ref_slot)); } layout.DestroyAllocN(alloc.get(), n); EXPECT_EQ(instance_counter, 0); } struct IsBZeroConstructible { static bool ctor_called; static bool dtor_called; IsBZeroConstructible() { ctor_called = true; } ~IsBZeroConstructible() { dtor_called = true; } }; bool IsBZeroConstructible::ctor_called; bool IsBZeroConstructible::dtor_called; } } namespace arolla { template <> struct is_bzero_constructible<::arolla::testing::IsBZeroConstructible> : std::true_type {}; } namespace arolla::testing { namespace { TEST(FrameLayoutTest, IsBZeroConstructibleHandling) { ASSERT_FALSE(IsBZeroConstructible::ctor_called); ASSERT_FALSE(IsBZeroConstructible::dtor_called); { auto layout = MakeTypeLayout<IsBZeroConstructible>(); MemoryAllocation alloc(&layout); } EXPECT_FALSE(IsBZeroConstructible::ctor_called); EXPECT_TRUE(IsBZeroConstructible::dtor_called); } } }
2,496
#ifndef AROLLA_MEMORY_RAW_BUFFER_FACTORY_H_ #define AROLLA_MEMORY_RAW_BUFFER_FACTORY_H_ #include <cstddef> #include <cstdint> #include <memory> #include <tuple> #include "absl/container/inlined_vector.h" #include "google/protobuf/arena.h" #include "arolla/util/indestructible.h" namespace arolla { using RawBufferPtr = std::shared_ptr<const void>; class RawBufferFactory { public: virtual ~RawBufferFactory() = default; virtual std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) = 0; virtual std::tuple<RawBufferPtr, void*> ReallocRawBuffer( RawBufferPtr&& old_buffer, void* data, size_t old_size, size_t new_size) = 0; }; class HeapBufferFactory : public RawBufferFactory { public: std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) final; std::tuple<RawBufferPtr, void*> ReallocRawBuffer(RawBufferPtr&& old_buffer, void* old_data, size_t old_size, size_t new_size) final; }; inline RawBufferFactory* GetHeapBufferFactory() { static Indestructible<HeapBufferFactory> factory; return factory.get(); } class ProtobufArenaBufferFactory final : public RawBufferFactory { public: explicit ProtobufArenaBufferFactory(google::protobuf::Arena& arena) : arena_(arena) {} std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) override; std::tuple<RawBufferPtr, void*> ReallocRawBuffer(RawBufferPtr&& old_buffer, void* data, size_t old_size, size_t new_size) override; private: google::protobuf::Arena& arena_; }; class UnsafeArenaBufferFactory : public RawBufferFactory { public: UnsafeArenaBufferFactory(const UnsafeArenaBufferFactory&) = delete; UnsafeArenaBufferFactory& operator=(const UnsafeArenaBufferFactory&) = delete; UnsafeArenaBufferFactory(UnsafeArenaBufferFactory&&) = delete; UnsafeArenaBufferFactory& operator=(UnsafeArenaBufferFactory&&) = delete; explicit UnsafeArenaBufferFactory( int64_t page_size, RawBufferFactory& base_factory = *GetHeapBufferFactory()) : page_size_(page_size), base_factory_(base_factory) {} std::tuple<RawBufferPtr, void*> CreateRawBuffer(size_t nbytes) override; std::tuple<RawBufferPtr, void*> ReallocRawBuffer(RawBufferPtr&& old_buffer, void* data, size_t old_size, size_t new_size) override; void Reset(); private: using Alloc = std::tuple<RawBufferPtr, void*>; void NextPage(); void* SlowAlloc(size_t nbytes); int64_t page_id_ = -1; char* current_ = reinterpret_cast<char*>(0x8); char* end_ = reinterpret_cast<char*>(0x8); int64_t page_size_; RawBufferFactory& base_factory_; absl::InlinedVector<Alloc, 16> pages_; absl::InlinedVector<Alloc, 16> big_allocs_; }; template <typename T> struct ArenaTraits { static T MakeOwned(T&& v, RawBufferFactory*) { return std::move(v); } }; } #endif #include "arolla/memory/raw_buffer_factory.h" #include <algorithm> #include <cstddef> #include <cstdlib> #include <cstring> #include <memory> #include <tuple> #include <utility> #include "absl/base/attributes.h" #include "absl/base/dynamic_annotations.h" #include "absl/base/optimization.h" #include "absl/log/check.h" namespace arolla { namespace { void noop_free(void*) noexcept {} void AnnotateMemoryIsInitialized(void* data, size_t size) { ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(data, size); } } std::tuple<RawBufferPtr, void*> HeapBufferFactory::CreateRawBuffer( size_t nbytes) { if (ABSL_PREDICT_FALSE(nbytes == 0)) return {nullptr, nullptr}; void* data = malloc(nbytes); AnnotateMemoryIsInitialized(data, nbytes); return {std::shared_ptr<void>(data, free), data}; } std::tuple<RawBufferPtr, void*> HeapBufferFactory::ReallocRawBuffer( RawBufferPtr&& old_buffer, void* old_data, size_t old_size, size_t new_size) { if (new_size == 0) return {nullptr, nullptr}; if (old_size == 0) return CreateRawBuffer(new_size); DCHECK_EQ(old_buffer.use_count(), 1); void* new_data = realloc(old_data, new_size); if (new_size > old_size) { AnnotateMemoryIsInitialized(static_cast<char*>(new_data) + old_size, new_size - old_size); } *std::get_deleter<decltype(&free)>(old_buffer) = &noop_free; old_buffer.reset(new_data, free); return {std::move(old_buffer), new_data}; } std::tuple<RawBufferPtr, void*> ProtobufArenaBufferFactory::CreateRawBuffer( size_t nbytes) { char* data = arena_.CreateArray<char>(&arena_, nbytes); AnnotateMemoryIsInitialized(data, nbytes); return {nullptr, data}; } std::tuple<RawBufferPtr, void*> ProtobufArenaBufferFactory::ReallocRawBuffer( RawBufferPtr&& old_buffer, void* data, size_t old_size, size_t new_size) { if (old_size >= new_size) return {nullptr, data}; char* new_data = arena_.CreateArray<char>(&arena_, new_size); memcpy(new_data, data, std::min(old_size, new_size)); AnnotateMemoryIsInitialized(new_data + old_size, new_size - old_size); return {nullptr, new_data}; } std::tuple<RawBufferPtr, void*> UnsafeArenaBufferFactory::CreateRawBuffer( size_t nbytes) { auto last_alloc = reinterpret_cast<char*>(reinterpret_cast<size_t>(current_ + 7) & ~7ull); if (ABSL_PREDICT_FALSE(last_alloc + nbytes > end_)) { return {nullptr, SlowAlloc(nbytes)}; } current_ = last_alloc + nbytes; return {nullptr, last_alloc}; } std::tuple<RawBufferPtr, void*> UnsafeArenaBufferFactory::ReallocRawBuffer( RawBufferPtr&& old_buffer, void* data, size_t old_size, size_t new_size) { char* last_alloc = current_ - old_size; if ((data != last_alloc) || last_alloc + new_size > end_) { if (old_size >= new_size) return {nullptr, data}; if (data == last_alloc) current_ = last_alloc; void* new_data = SlowAlloc(new_size); memcpy(new_data, data, std::min(old_size, new_size)); AnnotateMemoryIsInitialized(data, old_size); return {nullptr, new_data}; } current_ = last_alloc + new_size; if (new_size < old_size) { AnnotateMemoryIsInitialized(current_, old_size - new_size); } return {nullptr, last_alloc}; } void UnsafeArenaBufferFactory::Reset() { if (page_id_ >= 0) { page_id_ = 0; current_ = reinterpret_cast<char*>(std::get<1>(pages_[0])); AnnotateMemoryIsInitialized(current_, page_size_); end_ = current_ + page_size_; } big_allocs_.clear(); } ABSL_ATTRIBUTE_NOINLINE void* UnsafeArenaBufferFactory::SlowAlloc( size_t nbytes) { if (ABSL_PREDICT_FALSE(nbytes > page_size_ || end_ - current_ >= page_size_ / 2)) { auto [holder, memory] = base_factory_.CreateRawBuffer(nbytes); AnnotateMemoryIsInitialized(memory, nbytes); big_allocs_.emplace_back(std::move(holder), memory); return memory; } NextPage(); auto last_alloc = current_; current_ += nbytes; return last_alloc; } void UnsafeArenaBufferFactory::NextPage() { ++page_id_; if (ABSL_PREDICT_FALSE(page_id_ == pages_.size())) { auto [holder, page] = base_factory_.CreateRawBuffer(page_size_); current_ = reinterpret_cast<char*>(page); pages_.emplace_back(std::move(holder), page); } else { current_ = reinterpret_cast<char*>(std::get<1>(pages_[page_id_])); } AnnotateMemoryIsInitialized(current_, page_size_); end_ = current_ + page_size_; } }
#include "arolla/memory/raw_buffer_factory.h" #include <cstddef> #include <cstdint> #include <cstring> #include <utility> #include <vector> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "google/protobuf/arena.h" namespace arolla { namespace { using ::testing::AnyOf; using ::testing::Eq; using ::testing::Ge; using ::testing::Le; void VerifyCanReadUninitialized(const void* ptr, size_t size) { const char* char_ptr = static_cast<const char*>(ptr); for (size_t i = 0; i != size; ++i) { char c = *(char_ptr + i); benchmark::DoNotOptimize(c); } } TEST(HeapBufferFactory, CreateEmptyBuffer) { auto [buf, data] = GetHeapBufferFactory()->CreateRawBuffer(0); EXPECT_EQ(buf, nullptr); EXPECT_EQ(data, nullptr); } TEST(HeapBufferFactory, CreateRawBuffer) { const size_t size = 13; auto [buf, data] = GetHeapBufferFactory()->CreateRawBuffer(size); EXPECT_NE(buf, nullptr); VerifyCanReadUninitialized(data, size); EXPECT_EQ(reinterpret_cast<size_t>(data) & 7, 0); memset(data, 0, size); } TEST(HeapBufferFactory, ReallocRawBuffer) { size_t size = 13; RawBufferPtr buf; char* data; { auto res = GetHeapBufferFactory()->CreateRawBuffer(size); buf = std::get<0>(res); data = reinterpret_cast<char*>(std::get<1>(res)); VerifyCanReadUninitialized(data, size); } auto resize_fn = [&](size_t new_size) { auto res = GetHeapBufferFactory()->ReallocRawBuffer(std::move(buf), data, size, new_size); buf = std::get<0>(res); data = reinterpret_cast<char*>(std::get<1>(res)); size = new_size; }; data[0] = 5; resize_fn(4); EXPECT_EQ(data[0], 5); VerifyCanReadUninitialized(data + 1, size - 1); resize_fn(145); EXPECT_EQ(data[0], 5); VerifyCanReadUninitialized(data + 1, 144); } TEST(ProtobufArenaBufferFactory, CreateAndResize) { google::protobuf::Arena arena; ProtobufArenaBufferFactory buf_factory(arena); auto [buf1, data1] = buf_factory.CreateRawBuffer(2); VerifyCanReadUninitialized(data1, 2); char* d = reinterpret_cast<char*>(data1); d[0] = 'A'; d[1] = 'B'; auto [buf2, data2] = buf_factory.ReallocRawBuffer(std::move(buf1), data1, 2, 1); EXPECT_EQ(data1, data2); auto [buf3, data3] = buf_factory.ReallocRawBuffer(std::move(buf2), data2, 1, 3); EXPECT_NE(data2, data3); d = reinterpret_cast<char*>(data3); EXPECT_EQ(d[0], 'A'); VerifyCanReadUninitialized(d + 1, 2); } TEST(UnsafeArenaBufferFactory, CreateEmptyBuffer) { UnsafeArenaBufferFactory arena(25); auto [buf1, data1] = arena.CreateRawBuffer(0); auto [buf2, data2] = arena.CreateRawBuffer(0); auto [buf3, data3] = arena.CreateRawBuffer(1); VerifyCanReadUninitialized(data3, 1); auto [buf4, data4] = arena.CreateRawBuffer(0); auto [buf5, data5] = arena.CreateRawBuffer(0); EXPECT_EQ(data1, data2); EXPECT_NE(data3, nullptr); EXPECT_NE(data2, data4); EXPECT_NE(data3, data4); EXPECT_EQ(data4, data5); } TEST(UnsafeArenaBufferFactory, CreateRawBuffer) { std::vector<int64_t> sizes = {17, 1, 15, 1, 10}; std::vector<RawBufferPtr> bufs; std::vector<char*> ptrs; bufs.reserve(sizes.size()); ptrs.reserve(sizes.size()); UnsafeArenaBufferFactory arena1(25); google::protobuf::Arena proto_arena; ProtobufArenaBufferFactory proto_buf_factory(proto_arena); UnsafeArenaBufferFactory arena2(25, proto_buf_factory); for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) { UnsafeArenaBufferFactory& arena = *arena_ptr; for (size_t i = 0; i < sizes.size(); ++i) { auto [buf, data] = arena.CreateRawBuffer(sizes[i]); VerifyCanReadUninitialized(data, sizes[i]); EXPECT_EQ(reinterpret_cast<size_t>(data) & 7, 0); memset(data, i, sizes[i]); bufs.push_back(buf); ptrs.push_back(reinterpret_cast<char*>(data)); } EXPECT_EQ(ptrs[0] + 24, ptrs[1]); EXPECT_EQ(ptrs[2] + 16, ptrs[3]); for (size_t i = 0; i < sizes.size(); ++i) { for (int64_t j = 0; j < sizes[i]; ++j) { EXPECT_EQ(ptrs[i][j], i); } } } } TEST(UnsafeArenaBufferFactory, ReallocRawBuffer) { UnsafeArenaBufferFactory arena1(25); google::protobuf::Arena proto_arena; ProtobufArenaBufferFactory proto_buf_factory(proto_arena); UnsafeArenaBufferFactory arena2(25, proto_buf_factory); for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) { UnsafeArenaBufferFactory& arena = *arena_ptr; auto [buf1, data1] = arena.CreateRawBuffer(10); VerifyCanReadUninitialized(data1, 10); EXPECT_EQ(buf1, nullptr); reinterpret_cast<char*>(data1)[0] = 7; auto [buf2, data2] = arena.ReallocRawBuffer(std::move(buf1), data1, 10, 25); reinterpret_cast<char*>(data1)[24] = -1; EXPECT_EQ(reinterpret_cast<char*>(data2)[0], 7); EXPECT_EQ(data1, data2); auto [buf3, data3] = arena.ReallocRawBuffer(std::move(buf2), data2, 25, 26); VerifyCanReadUninitialized(data2, 25); EXPECT_NE(data1, data3); EXPECT_EQ(reinterpret_cast<char*>(data3)[0], 7); auto [buf4, data4] = arena.ReallocRawBuffer(std::move(buf3), data3, 26, 10); EXPECT_NE(data1, data4); EXPECT_EQ(reinterpret_cast<char*>(data4)[0], 7); auto [buf5, data5] = arena.CreateRawBuffer(20); VerifyCanReadUninitialized(data5, 20); auto [buf6, data6] = arena.ReallocRawBuffer(std::move(buf5), data5, 20, 15); VerifyCanReadUninitialized(static_cast<const char*>(data6) + 15, 5); EXPECT_EQ(data1, data5); EXPECT_EQ(data1, data6); auto [buf7, data7] = arena.CreateRawBuffer(8); VerifyCanReadUninitialized(data7, 8); EXPECT_EQ(reinterpret_cast<char*>(data1) + 16, reinterpret_cast<char*>(data7)); reinterpret_cast<char*>(data7)[0] = 3; auto [buf8, data8] = arena.ReallocRawBuffer(std::move(buf7), data7, 8, 20); EXPECT_EQ(reinterpret_cast<char*>(data8)[0], 3); auto [buf9, data9] = arena.CreateRawBuffer(1); VerifyCanReadUninitialized(data9, 1); EXPECT_EQ(reinterpret_cast<char*>(data8) + 24, reinterpret_cast<char*>(data9)); } } TEST(UnsafeArenaBufferFactory, BigAlloc) { UnsafeArenaBufferFactory arena1(32); google::protobuf::Arena proto_arena; ProtobufArenaBufferFactory proto_buf_factory(proto_arena); UnsafeArenaBufferFactory arena2(32, proto_buf_factory); for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) { UnsafeArenaBufferFactory& arena = *arena_ptr; auto [buf1, data1] = arena.CreateRawBuffer(16); VerifyCanReadUninitialized(data1, 16); auto [buf2, data2] = arena.CreateRawBuffer(64); VerifyCanReadUninitialized(data2, 64); auto [buf3, data3] = arena.CreateRawBuffer(16); VerifyCanReadUninitialized(data3, 16); EXPECT_THAT(reinterpret_cast<char*>(data3), Eq(reinterpret_cast<char*>(data1) + 16)); EXPECT_THAT(reinterpret_cast<char*>(data2) - reinterpret_cast<char*>(data1), AnyOf(Le(-64), Ge(32))); memset(data2, 0, 64); EXPECT_THAT(reinterpret_cast<int64_t*>(data2)[0], Eq(0)); } } TEST(UnsafeArenaBufferFactory, Reset) { UnsafeArenaBufferFactory arena1(32); google::protobuf::Arena proto_arena; ProtobufArenaBufferFactory proto_buf_factory(proto_arena); UnsafeArenaBufferFactory arena2(32, proto_buf_factory); for (UnsafeArenaBufferFactory* arena_ptr : {&arena1, &arena2}) { UnsafeArenaBufferFactory& arena = *arena_ptr; arena.Reset(); auto [buf1, data1] = arena.CreateRawBuffer(16); VerifyCanReadUninitialized(data1, 16); auto [buf2, data2] = arena.CreateRawBuffer(16); VerifyCanReadUninitialized(data2, 16); auto [buf3, data3] = arena.CreateRawBuffer(16); VerifyCanReadUninitialized(data3, 16); std::memset(data1, 255, 16); std::memset(data2, 255, 16); std::memset(data3, 255, 16); arena.Reset(); auto [buf4, data4] = arena.CreateRawBuffer(8); VerifyCanReadUninitialized(data4, 16); auto [buf5, data5] = arena.CreateRawBuffer(16); VerifyCanReadUninitialized(data5, 16); auto [buf6, data6] = arena.CreateRawBuffer(24); VerifyCanReadUninitialized(data6, 16); EXPECT_EQ(data1, data4); EXPECT_EQ(reinterpret_cast<char*>(data2), reinterpret_cast<char*>(data5) + 8); EXPECT_EQ(data3, data6); } } TEST(UnsafeArenaBufferFactory, BaseFactory) { UnsafeArenaBufferFactory arena1(1024); auto [buf_before, ptr_before] = arena1.CreateRawBuffer(1); UnsafeArenaBufferFactory arena2(32, arena1); auto [buf_small, ptr_small] = arena2.CreateRawBuffer(8); auto [buf_big, ptr_big] = arena2.CreateRawBuffer(128); auto [buf_after, ptr_after] = arena1.CreateRawBuffer(1); EXPECT_LT(ptr_before, ptr_small); EXPECT_LT(ptr_before, ptr_big); EXPECT_GT(ptr_after, ptr_small); EXPECT_GT(ptr_after, ptr_big); } } }
2,497
#ifndef AROLLA_MEMORY_OPTIONAL_VALUE_H_ #define AROLLA_MEMORY_OPTIONAL_VALUE_H_ #include <cstdint> #include <optional> #include <ostream> #include <tuple> #include <type_traits> #include "absl/base/attributes.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/util/bytes.h" #include "arolla/util/fingerprint.h" #include "arolla/util/is_bzero_constructible.h" #include "arolla/util/meta.h" #include "arolla/util/repr.h" #include "arolla/util/status.h" #include "arolla/util/struct_field.h" #include "arolla/util/text.h" #include "arolla/util/unit.h" #include "arolla/util/view_types.h" #include "arolla/util/status_macros_backport.h" namespace arolla { template <typename T> struct OptionalValue { static_assert(std::is_default_constructible<T>(), "OptionalValue<T> T must be default constructible."); static_assert(std::is_standard_layout<T>(), "OptionalValue<T> T must have standard layout."); using value_type = T; constexpr OptionalValue() : present(false), value() {} constexpr OptionalValue(T v) : present(true), value(std::move(v)) {} constexpr OptionalValue(std::nullopt_t) : present(false), value() {} constexpr OptionalValue(bool present, T value) : present(present), value(std::move(value)) {} template <typename X = T, typename = std::enable_if_t< std::is_same_v<X, T> && !std::is_same_v<X, view_type_t<X>>, X>> explicit OptionalValue(view_type_t<X> value) : present(true), value(value) {} template <typename X = T, typename = std::enable_if_t< std::is_same_v<X, T> && !std::is_same_v<X, view_type_t<X>>, X>> explicit OptionalValue(OptionalValue<view_type_t<X>> v) : present(v.present) { if (v.present) value = T(v.value); } template <typename X = T, typename = std::enable_if_t<std::is_same_v<X, T>>> constexpr OptionalValue(std::optional<X> opt) : present(opt.has_value()), value(std::move(opt).value_or(T{})) {} operator OptionalValue<view_type_t<T>>() const { return {present, value}; } OptionalValue<T>& operator=(const OptionalValue<T>&) & = default; OptionalValue<T>& operator=(const OptionalValue<T>&) && = delete; OptionalValue<T>& operator=(T value) & { this->present = true; this->value = std::move(value); return *this; } OptionalValue<T>& operator=(T) && = delete; explicit operator bool() const { return present; } constexpr std::optional<T> AsOptional() const& { if (present) { return value; } return {}; } constexpr std::optional<T> AsOptional() && { if (present) { return std::move(value); } return {}; } bool present; value_type value = {}; void ArollaFingerprint(FingerprintHasher* hasher) const { if (present) { hasher->Combine(true, value); } else { hasher->Combine(false); } } constexpr static auto ArollaStructFields() { using CppType = OptionalValue; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(present), AROLLA_DECLARE_STRUCT_FIELD(value), }; } }; template <typename T> using strip_optional_t = meta::strip_template_t<OptionalValue, T>; template <typename T> using wrap_with_optional_t = OptionalValue<strip_optional_t<T>>; template <typename T> constexpr bool is_optional_v = meta::is_wrapped_with_v<OptionalValue, T>; template <typename T> struct view_type<OptionalValue<T>> { using type = OptionalValue<view_type_t<T>>; }; template <> struct OptionalValue<Unit> { using value_type = Unit; constexpr OptionalValue() : present(false) {} constexpr OptionalValue(Unit v) : present(true) {} constexpr OptionalValue( std::nullopt_t) : present(false) {} constexpr OptionalValue(bool present, Unit value) : present(present) {} constexpr explicit OptionalValue(bool present) : present(present) {} constexpr OptionalValue( std::optional<Unit> opt) : present(opt.has_value()) {} OptionalValue<Unit>& operator=(const OptionalValue<Unit>&) & = default; OptionalValue<Unit>& operator=(const OptionalValue<Unit>&) && = delete; explicit operator bool() const { return present; } constexpr std::optional<Unit> AsOptional() const { if (present) { return Unit{}; } return {}; } template <typename H> friend H AbslHashValue(H h, const OptionalValue& v) { return H::combine(std::move(h), v.present); } bool present; static constexpr Unit value = {}; constexpr static auto ArollaStructFields() { using CppType = OptionalValue; return std::tuple{ AROLLA_DECLARE_STRUCT_FIELD(present), }; } void ArollaFingerprint(FingerprintHasher* hasher) const { CombineStructFields(hasher, *this); } }; using OptionalUnit = OptionalValue<Unit>; constexpr OptionalUnit kPresent{Unit{}}; constexpr OptionalUnit kMissing{}; template <class T> constexpr OptionalValue<T> MakeOptionalValue(T v) { return {std::move(v)}; } template <class T> absl::StatusOr<OptionalValue<T>> MakeStatusOrOptionalValue( absl::StatusOr<T> v) { using ResultT = absl::StatusOr<OptionalValue<T>>; return v.ok() ? ResultT{OptionalValue<T>{*std::move(v)}} : ResultT{v.status()}; } AROLLA_DECLARE_REPR(OptionalValue<bool>); AROLLA_DECLARE_REPR(OptionalValue<int32_t>); AROLLA_DECLARE_REPR(OptionalValue<int64_t>); AROLLA_DECLARE_REPR(OptionalValue<uint64_t>); AROLLA_DECLARE_REPR(OptionalValue<float>); AROLLA_DECLARE_REPR(OptionalValue<double>); AROLLA_DECLARE_REPR(OptionalValue<Bytes>); AROLLA_DECLARE_REPR(OptionalValue<Text>); AROLLA_DECLARE_REPR(OptionalUnit); template <class T, typename = std::enable_if_t< std::is_invocable_v<ReprTraits<OptionalValue<T>>, T>>> std::ostream& operator<<(std::ostream& stream, const OptionalValue<T>& value) { return stream << Repr(value); } template <typename T> struct is_bzero_constructible<OptionalValue<T>> : is_bzero_constructible<T> {}; template <typename T> constexpr bool operator==(const OptionalValue<T>& a, const OptionalValue<T>& b) { if (a.present && b.present) { return a.value == b.value; } return (a.present == b.present); } template <typename T> constexpr bool operator==(const OptionalValue<T>& a, const T& b) { return a.present && a.value == b; } template <typename T> constexpr bool operator==(const T& a, const OptionalValue<T>& b) { return b.present && a == b.value; } template <typename T> constexpr bool operator==(const OptionalValue<T>& a, std::nullopt_t) { return !a.present; } template <typename T> constexpr bool operator==(std::nullopt_t, const OptionalValue<T>& a) { return !a.present; } template <typename T> constexpr bool operator!=(const OptionalValue<T>& a, const OptionalValue<T>& b) { return !(a == b); } template <typename T> constexpr bool operator!=(const OptionalValue<T>& a, const T& b) { return !(a == b); } template <typename T> constexpr bool operator!=(const T& a, const OptionalValue<T>& b) { return !(a == b); } template <typename T> constexpr bool operator!=(const OptionalValue<T>& a, std::nullopt_t) { return a.present; } template <typename T> constexpr bool operator!=(std::nullopt_t, const OptionalValue<T>& a) { return a.present; } constexpr bool operator==(const OptionalUnit& a, const OptionalUnit& b) { return a.present == b.present; } constexpr bool operator==(const OptionalUnit& a, const Unit& b) { return a.present; } constexpr bool operator==(const Unit& a, const OptionalUnit& b) { return b.present; } constexpr bool operator==(const OptionalValue<absl::string_view>& a, absl::string_view b) { return a.present && a.value == b; } template <typename T> OptionalValue(T value) -> OptionalValue<T>; namespace optional_value_impl { template <class Fn, class ArgList> class OptionalFn; template <class To, class From> ABSL_ATTRIBUTE_ALWAYS_INLINE inline bool is_available(const From& v) { if constexpr (!is_optional_v<To>) { return v.present; } else { return true; } } template <class To, class From> ABSL_ATTRIBUTE_ALWAYS_INLINE inline const To& value(const From& v) { if constexpr (!is_optional_v<To>) { return v.value; } else { return v; } } template <class Fn, class... Args> class OptionalFn<Fn, meta::type_list<Args...>> { private: using FnResT = std::decay_t<typename meta::function_traits<Fn>::return_type>; static constexpr bool kHasStatus = IsStatusOrT<FnResT>::value; using OptResT = wrap_with_optional_t<strip_statusor_t<FnResT>>; using ResT = std::conditional_t<kHasStatus, absl::StatusOr<OptResT>, OptResT>; public: explicit constexpr OptionalFn(Fn fn) : fn_(std::move(fn)) {} ResT operator()( const wrap_with_optional_t<std::decay_t<Args>>&... args) const { if ((is_available<std::decay_t<Args>>(args) && ...)) { if constexpr (kHasStatus && !std::is_same_v<FnResT, ResT>) { ASSIGN_OR_RETURN(auto res, fn_(value<std::decay_t<Args>>(args)...)); return OptResT(res); } else { return fn_(value<std::decay_t<Args>>(args)...); } } else { return OptResT(std::nullopt); } } private: Fn fn_; }; } template <class Fn> constexpr auto WrapFnToAcceptOptionalArgs(Fn fn) { return optional_value_impl::OptionalFn< Fn, typename meta::function_traits<Fn>::arg_types>(fn); } } #endif #include "arolla/memory/optional_value.h" #include <cstdint> #include "absl/strings/str_cat.h" #include "arolla/util/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/text.h" namespace arolla { ReprToken ReprTraits<OptionalValue<bool>>::operator()( const OptionalValue<bool>& value) const { return ReprToken{ value.present ? absl::StrCat("optional_boolean{", Repr(value.value), "}") : "optional_boolean{NA}"}; } ReprToken ReprTraits<OptionalValue<int32_t>>::operator()( const OptionalValue<int32_t>& value) const { return ReprToken{value.present ? absl::StrCat("optional_int32{", Repr(value.value), "}") : "optional_int32{NA}"}; } ReprToken ReprTraits<OptionalValue<int64_t>>::operator()( const OptionalValue<int64_t>& value) const { return ReprToken{value.present ? absl::StrCat("optional_", Repr(value.value)) : "optional_int64{NA}"}; } ReprToken ReprTraits<OptionalValue<uint64_t>>::operator()( const OptionalValue<uint64_t>& value) const { return ReprToken{value.present ? absl::StrCat("optional_", Repr(value.value)) : "optional_uint64{NA}"}; } ReprToken ReprTraits<OptionalValue<float>>::operator()( const OptionalValue<float>& value) const { return ReprToken{ value.present ? absl::StrCat("optional_float32{", Repr(value.value), "}") : "optional_float32{NA}"}; } ReprToken ReprTraits<OptionalValue<double>>::operator()( const OptionalValue<double>& value) const { return ReprToken{value.present ? absl::StrCat("optional_", Repr(value.value)) : "optional_float64{NA}"}; } ReprToken ReprTraits<OptionalValue<Bytes>>::operator()( const OptionalValue<Bytes>& value) const { return ReprToken{value.present ? absl::StrCat("optional_bytes{", Repr(value.value), "}") : "optional_bytes{NA}"}; } ReprToken ReprTraits<OptionalValue<Text>>::operator()( const OptionalValue<Text>& value) const { return ReprToken{value.present ? absl::StrCat("optional_text{", Repr(value.value), "}") : "optional_text{NA}"}; } ReprToken ReprTraits<OptionalUnit>::operator()( const OptionalUnit& value) const { return ReprToken{value.present ? "present" : "missing"}; } }
#include "arolla/memory/optional_value.h" #include <cstdint> #include <cstring> #include <memory> #include <new> #include <optional> #include <sstream> #include <string> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/memory/frame.h" #include "arolla/memory/memory_allocation.h" #include "arolla/util/bytes.h" #include "arolla/util/repr.h" #include "arolla/util/testing/status_matchers_backport.h" #include "arolla/util/text.h" #include "arolla/util/view_types.h" namespace arolla { namespace testing { namespace { using ::testing::HasSubstr; using ::testing::Test; TEST(OptionalValueTest, TestEmptyValues) { OptionalValue<float> v1; EXPECT_FALSE(v1.present); OptionalValue<float> v2(std::optional<float>{}); EXPECT_FALSE(v2.present); OptionalValue<float> v3(std::nullopt); EXPECT_FALSE(v3.present); EXPECT_EQ(v1, v2); EXPECT_EQ(v1, v3); v1.value = 1.0f; v2.value = 2.0f; EXPECT_EQ(v1, v2); auto absl_v = v2.AsOptional(); EXPECT_FALSE(absl_v.has_value()); } TEST(OptionalValueTest, TestConstExpr) { static_assert(!OptionalValue<int>().present); static_assert(OptionalValue<int>(5).present); static_assert(OptionalValue<int>(5).value == 5); static_assert(MakeOptionalValue(5).present); static_assert(MakeOptionalValue(5).value == 5); } TEST(OptionalValueTest, TestPresentValues) { OptionalValue<float> v1(1.0f); EXPECT_TRUE(v1.present); EXPECT_EQ(1.0f, v1.value); EXPECT_EQ(Repr(v1), "optional_float32{1.}"); auto v_auto = MakeOptionalValue(1.0f); EXPECT_TRUE(v_auto.present); EXPECT_EQ(1.0f, v_auto.value); EXPECT_EQ(Repr(v_auto), "optional_float32{1.}"); OptionalValue<float> v2(std::optional<float>{2.0f}); EXPECT_TRUE(v2.present); EXPECT_EQ(2.0f, v2.value); EXPECT_EQ(Repr(v2), "optional_float32{2.}"); EXPECT_NE(v1, v2); v1.value = 2.0f; EXPECT_EQ(v1, v2); } TEST(OptionalValueTest, TestAssignment) { OptionalValue<float> v1; v1 = 1.0f; EXPECT_TRUE(v1.present); EXPECT_EQ(v1.value, 1.0f); v1 = std::nullopt; EXPECT_FALSE(v1.present); } TEST(OptionalValueTest, MakeStatusOrOptionalValue) { absl::StatusOr<OptionalValue<float>> v = MakeStatusOrOptionalValue(absl::StatusOr<float>(1.0f)); ASSERT_OK(v.status()); EXPECT_TRUE(v.value().present); EXPECT_EQ(v.value().value, 1.0f); absl::StatusOr<OptionalValue<float>> v_error = MakeStatusOrOptionalValue( absl::StatusOr<float>(absl::InternalError("fake"))); EXPECT_THAT(v_error.status(), StatusIs(absl::StatusCode::kInternal, HasSubstr("fake"))); } TEST(OptionalValueTest, OptionalUnit) { EXPECT_EQ(OptionalUnit(), kMissing); EXPECT_EQ(OptionalUnit(false), kMissing); EXPECT_FALSE(kMissing); EXPECT_FALSE(kMissing.present); EXPECT_EQ(Repr(kMissing), "missing"); EXPECT_EQ(OptionalUnit(true), kPresent); EXPECT_TRUE(kPresent); EXPECT_TRUE(kPresent.present); EXPECT_EQ(Repr(kPresent), "present"); } TEST(OptionalValueTest, Comparison) { OptionalValue<float> v0; v0.value = 1.0f; OptionalValue<float> v1(1.0f); OptionalValue<float> v2(2.0f); { EXPECT_TRUE(v1 == v1); EXPECT_TRUE(v0 == v0); EXPECT_FALSE(v1 == v2); EXPECT_FALSE(v1 == v0); EXPECT_FALSE(v1 != v1); EXPECT_FALSE(v0 != v0); EXPECT_TRUE(v1 != v2); EXPECT_TRUE(v1 != v0); OptionalValue<float> v0_2; v0_2.value = 2.0f; EXPECT_TRUE(v0 == v0_2); EXPECT_FALSE(v0 != v0_2); } { EXPECT_TRUE(v1 == 1.0f); EXPECT_TRUE(1.0f == v1); EXPECT_FALSE(v1 != 1.0f); EXPECT_FALSE(1.0f != v1); EXPECT_FALSE(v1 == 2.0f); EXPECT_FALSE(2.0f == v1); EXPECT_TRUE(v1 != 2.0f); EXPECT_TRUE(2.0f != v1); } { EXPECT_FALSE(v1 == std::nullopt); EXPECT_FALSE(std::nullopt == v1); EXPECT_TRUE(v0 == std::nullopt); EXPECT_TRUE(std::nullopt == v0); EXPECT_TRUE(v1 != std::nullopt); EXPECT_TRUE(std::nullopt != v1); EXPECT_FALSE(v0 != std::nullopt); EXPECT_FALSE(std::nullopt != v0); } } TEST(OptionalValueTest, TestImplicitConstructors) { OptionalValue<float> v = {}; EXPECT_EQ(v, OptionalValue<float>()); v = 3.5; EXPECT_EQ(v, OptionalValue<float>(3.5)); v = std::optional<float>(2.5); EXPECT_EQ(v, OptionalValue<float>(2.5)); } TEST(OptionalValueTest, TestMoves) { auto ptr = std::make_unique<std::string>("Hello!"); OptionalValue<std::unique_ptr<std::string>> v1(std::move(ptr)); EXPECT_TRUE(v1.present); EXPECT_EQ("Hello!", *(v1.value)); std::optional<std::unique_ptr<std::string>> v2(std::move(v1).AsOptional()); EXPECT_TRUE(v2.has_value()); EXPECT_EQ("Hello!", **v2); } template <typename T> using Slot = FrameLayout::Slot<T>; TEST(OptionalValueTest, TestFrameLayout) { FrameLayout::Builder builder; builder.AddSlot<double>(); builder.AddSlot<int32_t>(); auto optional_slot = builder.AddSlot<OptionalValue<float>>(); Slot<bool> presence_slot = optional_slot.GetSubslot<0>(); Slot<float> value_slot = optional_slot.GetSubslot<1>(); FrameLayout layout = std::move(builder).Build(); MemoryAllocation alloc(&layout); FramePtr frame = alloc.frame(); frame.Set(optional_slot, OptionalValue<float>{1.0f}); EXPECT_EQ(true, frame.Get(presence_slot)); EXPECT_EQ(1.0f, frame.Get(value_slot)); frame.Set(value_slot, 2.0f); EXPECT_EQ(2.0, frame.Get(optional_slot).value); } TEST(OptionalValue, IsBZeroConstructible) { EXPECT_TRUE(is_bzero_constructible<OptionalValue<float>>()); EXPECT_TRUE(is_bzero_constructible<OptionalValue<int>>()); EXPECT_FALSE(is_bzero_constructible<OptionalValue<std::string>>()); } TEST(OptionalValue, BZeroStateIsEmptyValue) { using T = OptionalValue<float>; std::aligned_storage_t<sizeof(T), alignof(T)> storage; memset(&storage, 0, sizeof(storage)); EXPECT_FALSE(std::launder(reinterpret_cast<const T*>(&storage))->present); } TEST(OptionalValue, StructuredBindings) { { OptionalValue<float> f; auto [present, value] = f; EXPECT_FALSE(present); } { OptionalValue<float> f = 17.0; auto [present, value] = f; EXPECT_TRUE(present); EXPECT_EQ(value, 17.0); } } TEST(OptionalValue, ViewType) { static_assert(std::is_same_v<view_type_t<OptionalValue<int64_t>>, OptionalValue<int64_t>>); static_assert(std::is_same_v<view_type_t<OptionalValue<Bytes>>, OptionalValue<absl::string_view>>); auto fn = [](OptionalValue<absl::string_view> v) -> char { return (v.present && !v.value.empty()) ? v.value[0] : 'X'; }; EXPECT_EQ(fn(OptionalValue<Text>(Text("Hello"))), 'H'); EXPECT_EQ(fn(std::nullopt), 'X'); } TEST(OptionalValue, WrapFnToAcceptOptionalArgs) { { auto fn = [](int a, OptionalValue<int64_t> b, int64_t c) -> int { return a + c + (b.present ? b.value : 10); }; auto opt_fn = WrapFnToAcceptOptionalArgs(fn); EXPECT_EQ(opt_fn(1, 2, 3), OptionalValue<int>(6)); EXPECT_EQ(opt_fn(std::nullopt, 2, 3), OptionalValue<int>()); EXPECT_EQ(opt_fn(1, std::nullopt, 3), OptionalValue<int>(14)); EXPECT_EQ(opt_fn(1, 2, std::nullopt), OptionalValue<int>()); } { auto fn = [](const Bytes& v) -> const Bytes& { return v; }; auto opt_fn = WrapFnToAcceptOptionalArgs(fn); EXPECT_EQ(opt_fn(Bytes("123")), OptionalValue<Bytes>("123")); } { auto fn = [](absl::string_view v) { return v; }; auto opt_fn = WrapFnToAcceptOptionalArgs(fn); EXPECT_EQ(opt_fn(MakeOptionalValue(Bytes("123"))), MakeOptionalValue(absl::string_view("123"))); } { auto fn = [](int a, OptionalValue<int64_t> b, int64_t c) -> absl::StatusOr<int> { if (c < 0) { return absl::InvalidArgumentError("c < 0"); } else { return a + c + (b.present ? b.value : 10); } }; auto opt_fn = WrapFnToAcceptOptionalArgs(fn); EXPECT_THAT(opt_fn(1, 2, 3), IsOkAndHolds(OptionalValue<int>(6))); EXPECT_THAT(opt_fn(1, 2, -3), StatusIs(absl::StatusCode::kInvalidArgument, "c < 0")); EXPECT_THAT(opt_fn(std::nullopt, 2, -3), IsOkAndHolds(OptionalValue<int>())); } } TEST(OptionalValueReprTest, bool) { EXPECT_EQ(Repr(OptionalValue<bool>(true)), "optional_boolean{true}"); EXPECT_EQ(Repr(OptionalValue<bool>()), "optional_boolean{NA}"); } TEST(OptionalValueReprTest, int32_t) { EXPECT_EQ(Repr(OptionalValue<int32_t>(1)), "optional_int32{1}"); EXPECT_EQ(Repr(OptionalValue<int32_t>()), "optional_int32{NA}"); } TEST(OptionalValueReprTest, int64_t) { EXPECT_EQ(Repr(OptionalValue<int64_t>(1)), "optional_int64{1}"); EXPECT_EQ(Repr(OptionalValue<int64_t>()), "optional_int64{NA}"); } TEST(OptionalValueReprTest, uint64_t) { EXPECT_EQ(Repr(OptionalValue<uint64_t>(1)), "optional_uint64{1}"); EXPECT_EQ(Repr(OptionalValue<uint64_t>()), "optional_uint64{NA}"); } TEST(OptionalValueReprTest, float) { EXPECT_EQ(Repr(OptionalValue<float>(1.5)), "optional_float32{1.5}"); EXPECT_EQ(Repr(OptionalValue<float>()), "optional_float32{NA}"); } TEST(OptionalValueReprTest, double) { EXPECT_EQ(Repr(OptionalValue<double>(1.5)), "optional_float64{1.5}"); EXPECT_EQ(Repr(OptionalValue<double>()), "optional_float64{NA}"); } TEST(OptionalValueReprTest, Bytes) { EXPECT_EQ(Repr(OptionalValue<Bytes>("abc")), "optional_bytes{b'abc'}"); EXPECT_EQ(Repr(OptionalValue<Bytes>()), "optional_bytes{NA}"); } TEST(OptionalValueReprTest, Text) { EXPECT_EQ(Repr(OptionalValue<Text>("abc")), "optional_text{'abc'}"); EXPECT_EQ(Repr(OptionalValue<Text>()), "optional_text{NA}"); } TEST(OptionalValueReprTest, StreamOp) { { std::ostringstream oss; oss << OptionalValue<float>(1.5); EXPECT_EQ(oss.str(), "optional_float32{1.5}"); } { std::ostringstream oss; oss << OptionalValue<float>(); EXPECT_EQ(oss.str(), "optional_float32{NA}"); } } } } }
2,498
#ifndef AROLLA_OPTOOLS_OPTOOLS_H_ #define AROLLA_OPTOOLS_OPTOOLS_H_ #include <cstddef> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/qexpr/operator_factory.h" #include "arolla/qexpr/operators.h" #include "arolla/util/status_macros_backport.h" namespace arolla::optools { namespace optools_impl { absl::Status RegisterFunctionAsOperatorImpl( std::vector<OperatorPtr> qexpr_ops, expr::ExprOperatorSignature signature, absl::string_view description); template <typename Fn> struct MakeQExprOps { absl::StatusOr<std::vector<OperatorPtr>> operator()(absl::string_view name, Fn fn) { ASSIGN_OR_RETURN(OperatorPtr op, OperatorFactory() .WithName(std::string(name)) .BuildFromFunction(std::move(fn))); return std::vector<OperatorPtr>{op}; } }; template <typename... FNs> struct MakeQExprOps<std::tuple<FNs...>> { absl::StatusOr<std::vector<OperatorPtr>> operator()(absl::string_view name, std::tuple<FNs...> fns) { return impl(name, std::move(fns), std::index_sequence_for<FNs...>{}); } template <size_t... Is> absl::StatusOr<std::vector<OperatorPtr>> impl(absl::string_view name, std::tuple<FNs...> fns, std::index_sequence<Is...>) { std::vector<OperatorPtr> res; res.reserve(sizeof...(FNs)); auto factory = OperatorFactory().WithName(std::string(name)); for (auto status_or_op : {factory.BuildFromFunction(std::move(std::get<Is>(fns)))...}) { RETURN_IF_ERROR(status_or_op.status()); res.push_back(*status_or_op); } return res; } }; } template <typename Fn> absl::Status RegisterFunctionAsOperator( Fn&& fns, absl::string_view name, absl::StatusOr<expr::ExprOperatorSignature> signature = expr::ExprOperatorSignature(), absl::string_view doc = "") { RETURN_IF_ERROR(signature.status()); ASSIGN_OR_RETURN(std::vector<OperatorPtr> ops, optools_impl::MakeQExprOps<Fn>()(name, fns)); return optools_impl::RegisterFunctionAsOperatorImpl( std::move(ops), *std::move(signature), doc); } } #endif #include "arolla/optools/optools.h" #include <cstddef> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "arolla/expr/basic_expr_operator.h" #include "arolla/expr/expr_operator.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/registered_expr_operator.h" #include "arolla/qexpr/operators.h" #include "arolla/qtype/qtype.h" #include "arolla/util/fingerprint.h" #include "arolla/util/string.h" #include "arolla/util/status_macros_backport.h" namespace arolla::optools::optools_impl { namespace { class QExprWrappingOperator final : public expr::BackendExprOperatorTag, public expr::BasicExprOperator { public: QExprWrappingOperator(absl::string_view name, std::vector<OperatorPtr> qexpr_ops, expr::ExprOperatorSignature signature, absl::string_view description) : expr::BasicExprOperator( name, signature, description, FingerprintHasher("arolla::optools_impl::QExprWrappingOperator") .Combine(name, signature) .Finish()), qexpr_ops_(std::move(qexpr_ops)) {} absl::StatusOr<QTypePtr> GetOutputQType( absl::Span<const QTypePtr> input_qtypes) const override { for (const OperatorPtr& op : qexpr_ops_) { absl::Span<const QTypePtr> required_qtypes = op->signature()->input_types(); bool match = true; for (size_t i = 0; i < input_qtypes.size(); ++i) { if (input_qtypes[i] != required_qtypes[i]) { match = false; break; } } if (match) { return op->signature()->output_type(); } } std::string msg = "no such overload; available signatures: "; bool is_first = true; for (const auto& op : qexpr_ops_) { absl::StrAppend(&msg, op->signature(), NonFirstComma(is_first, ", ")); } return absl::InvalidArgumentError(msg); } private: std::vector<OperatorPtr> qexpr_ops_; }; } absl::Status RegisterFunctionAsOperatorImpl( std::vector<OperatorPtr> qexpr_ops, expr::ExprOperatorSignature signature, absl::string_view description) { RETURN_IF_ERROR(expr::ValidateSignature(signature)); if (expr::HasVariadicParameter(signature)) { return absl::InvalidArgumentError( "incorrect operator signature: RegisterFunctionAsOperator doesn't " "support variadic args"); } if (qexpr_ops.empty()) { return absl::InvalidArgumentError( "at least one qexpr operator is required"); } size_t arg_count = qexpr_ops[0]->signature()->input_types().size(); absl::string_view name = qexpr_ops[0]->name(); for (const OperatorPtr& op : qexpr_ops) { if (op->signature()->input_types().size() != arg_count) { return absl::InvalidArgumentError( "arg count must be the same for all overloads"); } if (op->name() != name) { return absl::InvalidArgumentError( "all overloads must have the same name"); } RETURN_IF_ERROR( ::arolla::OperatorRegistry::GetInstance()->RegisterOperator(op)); } if (signature.parameters.empty()) { signature = expr::ExprOperatorSignature::MakeArgsN(arg_count); } else if (signature.parameters.size() != arg_count) { return absl::InvalidArgumentError( "operator signature doesn't match the function"); } return expr::RegisterOperator<QExprWrappingOperator>( name, name, std::move(qexpr_ops), signature, description) .status(); } }
#include "arolla/optools/optools.h" #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "arolla/expr/expr_operator_signature.h" #include "arolla/expr/testing/testing.h" #include "arolla/qtype/typed_value.h" #include "arolla/util/testing/status_matchers_backport.h" namespace arolla::testing { namespace { using ::testing::HasSubstr; int Add(int a, int b) { return a + b; } template <typename T> T Mul(T a, T b) { return a * b; } TEST(OpTools, RegisterFunctionAsOperator) { ASSERT_OK(optools::RegisterFunctionAsOperator(Add, "optools_test.add")); ASSERT_OK(optools::RegisterFunctionAsOperator( std::make_tuple(Mul<float>, Mul<int>), "optools_test.mul")); { ASSERT_OK_AND_ASSIGN(TypedValue res, InvokeExprOperator("optools_test.add", {TypedValue::FromValue<int>(3), TypedValue::FromValue<int>(4)})); ASSERT_OK_AND_ASSIGN(int r, res.As<int>()); EXPECT_EQ(r, 7); } { ASSERT_OK_AND_ASSIGN(TypedValue res, InvokeExprOperator("optools_test.mul", {TypedValue::FromValue<int>(3), TypedValue::FromValue<int>(4)})); ASSERT_OK_AND_ASSIGN(int r, res.As<int>()); EXPECT_EQ(r, 12); } { ASSERT_OK_AND_ASSIGN(TypedValue res, InvokeExprOperator("optools_test.mul", {TypedValue::FromValue<float>(3), TypedValue::FromValue<float>(2)})); ASSERT_OK_AND_ASSIGN(float r, res.As<float>()); EXPECT_FLOAT_EQ(r, 6.0); } EXPECT_THAT( InvokeExprOperator("optools_test.add", {TypedValue::FromValue<float>(3), TypedValue::FromValue<int>(4)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no such overload"))); EXPECT_THAT( InvokeExprOperator("optools_test.mul", {TypedValue::FromValue<float>(3), TypedValue::FromValue<int>(4)}), StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("no such overload"))); EXPECT_OK(optools::RegisterFunctionAsOperator( Add, "optools_test.add_with_description", expr::ExprOperatorSignature::Make("a, b"), "Sum A and B")); EXPECT_THAT(optools::RegisterFunctionAsOperator( Add, "optools_test.add_with_wrong_signature", expr::ExprOperatorSignature::Make("a, b, c"), "Sum A and B"), StatusIs(absl::StatusCode::kInvalidArgument, "operator signature doesn't match the function")); } } }
2,499
#ifndef ABSL_FLAGS_USAGE_CONFIG_H_ #define ABSL_FLAGS_USAGE_CONFIG_H_ #include <functional> #include <string> #include "absl/base/config.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { using FlagKindFilter = std::function<bool (absl::string_view)>; } struct FlagsUsageConfig { flags_internal::FlagKindFilter contains_helpshort_flags; flags_internal::FlagKindFilter contains_help_flags; flags_internal::FlagKindFilter contains_helppackage_flags; std::function<std::string()> version_string; std::function<std::string(absl::string_view)> normalize_filename; }; void SetFlagsUsageConfig(FlagsUsageConfig usage_config); namespace flags_internal { FlagsUsageConfig GetUsageConfig(); void ReportUsageError(absl::string_view msg, bool is_fatal); } ABSL_NAMESPACE_END } extern "C" { void ABSL_INTERNAL_C_SYMBOL(AbslInternalReportFatalUsageError)( absl::string_view); } #endif #include "absl/flags/usage_config.h" #include <functional> #include <iostream> #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/const_init.h" #include "absl/base/thread_annotations.h" #include "absl/flags/internal/path_util.h" #include "absl/flags/internal/program_name.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/synchronization/mutex.h" extern "C" { ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL( AbslInternalReportFatalUsageError)(absl::string_view) {} } namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { namespace { bool ContainsHelpshortFlags(absl::string_view filename) { auto suffix = flags_internal::Basename(filename); auto program_name = flags_internal::ShortProgramInvocationName(); absl::string_view program_name_ref = program_name; #if defined(_WIN32) absl::ConsumeSuffix(&program_name_ref, ".exe"); #endif if (!absl::ConsumePrefix(&suffix, program_name_ref)) return false; return absl::StartsWith(suffix, ".") || absl::StartsWith(suffix, "-main.") || absl::StartsWith(suffix, "_main."); } bool ContainsHelppackageFlags(absl::string_view filename) { return ContainsHelpshortFlags(filename); } std::string VersionString() { std::string version_str(flags_internal::ShortProgramInvocationName()); version_str += "\n"; #if !defined(NDEBUG) version_str += "Debug build (NDEBUG not #defined)\n"; #endif return version_str; } std::string NormalizeFilename(absl::string_view filename) { auto pos = filename.find_first_not_of("\\/"); if (pos == absl::string_view::npos) return ""; filename.remove_prefix(pos); return std::string(filename); } ABSL_CONST_INIT absl::Mutex custom_usage_config_guard(absl::kConstInit); ABSL_CONST_INIT FlagsUsageConfig* custom_usage_config ABSL_GUARDED_BY(custom_usage_config_guard) = nullptr; } FlagsUsageConfig GetUsageConfig() { absl::MutexLock l(&custom_usage_config_guard); if (custom_usage_config) return *custom_usage_config; FlagsUsageConfig default_config; default_config.contains_helpshort_flags = &ContainsHelpshortFlags; default_config.contains_help_flags = &ContainsHelppackageFlags; default_config.contains_helppackage_flags = &ContainsHelppackageFlags; default_config.version_string = &VersionString; default_config.normalize_filename = &NormalizeFilename; return default_config; } void ReportUsageError(absl::string_view msg, bool is_fatal) { std::cerr << "ERROR: " << msg << std::endl; if (is_fatal) { ABSL_INTERNAL_C_SYMBOL(AbslInternalReportFatalUsageError)(msg); } } } void SetFlagsUsageConfig(FlagsUsageConfig usage_config) { absl::MutexLock l(&flags_internal::custom_usage_config_guard); if (!usage_config.contains_helpshort_flags) usage_config.contains_helpshort_flags = flags_internal::ContainsHelpshortFlags; if (!usage_config.contains_help_flags) usage_config.contains_help_flags = flags_internal::ContainsHelppackageFlags; if (!usage_config.contains_helppackage_flags) usage_config.contains_helppackage_flags = flags_internal::ContainsHelppackageFlags; if (!usage_config.version_string) usage_config.version_string = flags_internal::VersionString; if (!usage_config.normalize_filename) usage_config.normalize_filename = flags_internal::NormalizeFilename; if (flags_internal::custom_usage_config) *flags_internal::custom_usage_config = usage_config; else flags_internal::custom_usage_config = new FlagsUsageConfig(usage_config); } ABSL_NAMESPACE_END }
#include "absl/flags/usage_config.h" #include <string> #include "gtest/gtest.h" #include "absl/flags/internal/path_util.h" #include "absl/flags/internal/program_name.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" namespace { class FlagsUsageConfigTest : public testing::Test { protected: void SetUp() override { absl::FlagsUsageConfig default_config; absl::SetFlagsUsageConfig(default_config); } }; namespace flags = absl::flags_internal; bool TstContainsHelpshortFlags(absl::string_view f) { return absl::StartsWith(flags::Basename(f), "progname."); } bool TstContainsHelppackageFlags(absl::string_view f) { return absl::EndsWith(flags::Package(f), "aaa/"); } bool TstContainsHelpFlags(absl::string_view f) { return absl::EndsWith(flags::Package(f), "zzz/"); } std::string TstVersionString() { return "program 1.0.0"; } std::string TstNormalizeFilename(absl::string_view filename) { return std::string(filename.substr(2)); } void TstReportUsageMessage(absl::string_view msg) {} TEST_F(FlagsUsageConfigTest, TestGetSetFlagsUsageConfig) { EXPECT_TRUE(flags::GetUsageConfig().contains_helpshort_flags); EXPECT_TRUE(flags::GetUsageConfig().contains_help_flags); EXPECT_TRUE(flags::GetUsageConfig().contains_helppackage_flags); EXPECT_TRUE(flags::GetUsageConfig().version_string); EXPECT_TRUE(flags::GetUsageConfig().normalize_filename); absl::FlagsUsageConfig empty_config; empty_config.contains_helpshort_flags = &TstContainsHelpshortFlags; empty_config.contains_help_flags = &TstContainsHelpFlags; empty_config.contains_helppackage_flags = &TstContainsHelppackageFlags; empty_config.version_string = &TstVersionString; empty_config.normalize_filename = &TstNormalizeFilename; absl::SetFlagsUsageConfig(empty_config); EXPECT_TRUE(flags::GetUsageConfig().contains_helpshort_flags); EXPECT_TRUE(flags::GetUsageConfig().contains_help_flags); EXPECT_TRUE(flags::GetUsageConfig().contains_helppackage_flags); EXPECT_TRUE(flags::GetUsageConfig().version_string); EXPECT_TRUE(flags::GetUsageConfig().normalize_filename); } TEST_F(FlagsUsageConfigTest, TestContainsHelpshortFlags) { #if defined(_WIN32) flags::SetProgramInvocationName("usage_config_test.exe"); #else flags::SetProgramInvocationName("usage_config_test"); #endif auto config = flags::GetUsageConfig(); EXPECT_TRUE(config.contains_helpshort_flags("adir/cd/usage_config_test.cc")); EXPECT_TRUE( config.contains_helpshort_flags("aaaa/usage_config_test-main.cc")); EXPECT_TRUE(config.contains_helpshort_flags("abc/usage_config_test_main.cc")); EXPECT_FALSE(config.contains_helpshort_flags("usage_config_main.cc")); absl::FlagsUsageConfig empty_config; empty_config.contains_helpshort_flags = &TstContainsHelpshortFlags; absl::SetFlagsUsageConfig(empty_config); EXPECT_TRUE( flags::GetUsageConfig().contains_helpshort_flags("aaa/progname.cpp")); EXPECT_FALSE( flags::GetUsageConfig().contains_helpshort_flags("aaa/progmane.cpp")); } TEST_F(FlagsUsageConfigTest, TestContainsHelpFlags) { flags::SetProgramInvocationName("usage_config_test"); auto config = flags::GetUsageConfig(); EXPECT_TRUE(config.contains_help_flags("zzz/usage_config_test.cc")); EXPECT_TRUE( config.contains_help_flags("bdir/a/zzz/usage_config_test-main.cc")); EXPECT_TRUE( config.contains_help_flags(" EXPECT_FALSE(config.contains_help_flags("zzz/aa/usage_config_main.cc")); absl::FlagsUsageConfig empty_config; empty_config.contains_help_flags = &TstContainsHelpFlags; absl::SetFlagsUsageConfig(empty_config); EXPECT_TRUE(flags::GetUsageConfig().contains_help_flags("zzz/main-body.c")); EXPECT_FALSE( flags::GetUsageConfig().contains_help_flags("zzz/dir/main-body.c")); } TEST_F(FlagsUsageConfigTest, TestContainsHelppackageFlags) { flags::SetProgramInvocationName("usage_config_test"); auto config = flags::GetUsageConfig(); EXPECT_TRUE(config.contains_helppackage_flags("aaa/usage_config_test.cc")); EXPECT_TRUE( config.contains_helppackage_flags("bbdir/aaa/usage_config_test-main.cc")); EXPECT_TRUE(config.contains_helppackage_flags( " EXPECT_FALSE(config.contains_helppackage_flags("aadir/usage_config_main.cc")); absl::FlagsUsageConfig empty_config; empty_config.contains_helppackage_flags = &TstContainsHelppackageFlags; absl::SetFlagsUsageConfig(empty_config); EXPECT_TRUE( flags::GetUsageConfig().contains_helppackage_flags("aaa/main-body.c")); EXPECT_FALSE( flags::GetUsageConfig().contains_helppackage_flags("aadir/main-body.c")); } TEST_F(FlagsUsageConfigTest, TestVersionString) { flags::SetProgramInvocationName("usage_config_test"); #ifdef NDEBUG std::string expected_output = "usage_config_test\n"; #else std::string expected_output = "usage_config_test\nDebug build (NDEBUG not #defined)\n"; #endif EXPECT_EQ(flags::GetUsageConfig().version_string(), expected_output); absl::FlagsUsageConfig empty_config; empty_config.version_string = &TstVersionString; absl::SetFlagsUsageConfig(empty_config); EXPECT_EQ(flags::GetUsageConfig().version_string(), "program 1.0.0"); } TEST_F(FlagsUsageConfigTest, TestNormalizeFilename) { EXPECT_EQ(flags::GetUsageConfig().normalize_filename("a/a.cc"), "a/a.cc"); EXPECT_EQ(flags::GetUsageConfig().normalize_filename("/a/a.cc"), "a/a.cc"); EXPECT_EQ(flags::GetUsageConfig().normalize_filename(" EXPECT_EQ(flags::GetUsageConfig().normalize_filename("/"), ""); absl::FlagsUsageConfig empty_config; empty_config.normalize_filename = &TstNormalizeFilename; absl::SetFlagsUsageConfig(empty_config); EXPECT_EQ(flags::GetUsageConfig().normalize_filename("a/a.cc"), "a.cc"); EXPECT_EQ(flags::GetUsageConfig().normalize_filename("aaa/a.cc"), "a/a.cc"); empty_config.normalize_filename = nullptr; absl::SetFlagsUsageConfig(empty_config); EXPECT_EQ(flags::GetUsageConfig().normalize_filename("a/a.cc"), "a/a.cc"); EXPECT_EQ(flags::GetUsageConfig().normalize_filename("/a/a.cc"), "a/a.cc"); EXPECT_EQ(flags::GetUsageConfig().normalize_filename(" EXPECT_EQ(flags::GetUsageConfig().normalize_filename("\\a\\a.cc"), "a\\a.cc"); EXPECT_EQ(flags::GetUsageConfig().normalize_filename(" EXPECT_EQ(flags::GetUsageConfig().normalize_filename("\\\\"), ""); } }
2,500
#ifndef ABSL_FLAGS_INTERNAL_PARSE_H_ #define ABSL_FLAGS_INTERNAL_PARSE_H_ #include <iostream> #include <ostream> #include <string> #include <vector> #include "absl/base/config.h" #include "absl/flags/declare.h" #include "absl/flags/internal/usage.h" #include "absl/strings/string_view.h" ABSL_DECLARE_FLAG(std::vector<std::string>, flagfile); ABSL_DECLARE_FLAG(std::vector<std::string>, fromenv); ABSL_DECLARE_FLAG(std::vector<std::string>, tryfromenv); ABSL_DECLARE_FLAG(std::vector<std::string>, undefok); namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { enum class UsageFlagsAction { kHandleUsage, kIgnoreUsage }; enum class OnUndefinedFlag { kIgnoreUndefined, kReportUndefined, kAbortIfUndefined }; std::vector<char*> ParseCommandLineImpl( int argc, char* argv[], UsageFlagsAction usage_flag_action, OnUndefinedFlag undef_flag_action, std::ostream& error_help_output = std::cout); bool WasPresentOnCommandLine(absl::string_view flag_name); std::vector<std::string> GetMisspellingHints(absl::string_view flag); } ABSL_NAMESPACE_END } #endif #include "absl/flags/parse.h" #include <stdlib.h> #include <algorithm> #include <cstdint> #include <cstdlib> #include <fstream> #include <iostream> #include <ostream> #include <string> #include <tuple> #include <utility> #include <vector> #ifdef _WIN32 #include <windows.h> #endif #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/const_init.h" #include "absl/base/thread_annotations.h" #include "absl/flags/commandlineflag.h" #include "absl/flags/config.h" #include "absl/flags/flag.h" #include "absl/flags/internal/commandlineflag.h" #include "absl/flags/internal/flag.h" #include "absl/flags/internal/parse.h" #include "absl/flags/internal/private_handle_accessor.h" #include "absl/flags/internal/program_name.h" #include "absl/flags/internal/usage.h" #include "absl/flags/reflection.h" #include "absl/flags/usage.h" #include "absl/flags/usage_config.h" #include "absl/strings/ascii.h" #include "absl/strings/internal/damerau_levenshtein_distance.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { namespace { ABSL_CONST_INIT absl::Mutex processing_checks_guard(absl::kConstInit); ABSL_CONST_INIT bool flagfile_needs_processing ABSL_GUARDED_BY(processing_checks_guard) = false; ABSL_CONST_INIT bool fromenv_needs_processing ABSL_GUARDED_BY(processing_checks_guard) = false; ABSL_CONST_INIT bool tryfromenv_needs_processing ABSL_GUARDED_BY(processing_checks_guard) = false; ABSL_CONST_INIT absl::Mutex specified_flags_guard(absl::kConstInit); ABSL_CONST_INIT std::vector<const CommandLineFlag*>* specified_flags ABSL_GUARDED_BY(specified_flags_guard) = nullptr; ABSL_CONST_INIT const size_t kMaxHints = 100; ABSL_CONST_INIT const size_t kMaxDistance = 3; struct SpecifiedFlagsCompare { bool operator()(const CommandLineFlag* a, const CommandLineFlag* b) const { return a->Name() < b->Name(); } bool operator()(const CommandLineFlag* a, absl::string_view b) const { return a->Name() < b; } bool operator()(absl::string_view a, const CommandLineFlag* b) const { return a < b->Name(); } }; } } ABSL_NAMESPACE_END } ABSL_FLAG(std::vector<std::string>, flagfile, {}, "comma-separated list of files to load flags from") .OnUpdate([]() { if (absl::GetFlag(FLAGS_flagfile).empty()) return; absl::MutexLock l(&absl::flags_internal::processing_checks_guard); if (absl::flags_internal::flagfile_needs_processing) { ABSL_INTERNAL_LOG(WARNING, "flagfile set twice before it is handled"); } absl::flags_internal::flagfile_needs_processing = true; }); ABSL_FLAG(std::vector<std::string>, fromenv, {}, "comma-separated list of flags to set from the environment" " [use 'export FLAGS_flag1=value']") .OnUpdate([]() { if (absl::GetFlag(FLAGS_fromenv).empty()) return; absl::MutexLock l(&absl::flags_internal::processing_checks_guard); if (absl::flags_internal::fromenv_needs_processing) { ABSL_INTERNAL_LOG(WARNING, "fromenv set twice before it is handled."); } absl::flags_internal::fromenv_needs_processing = true; }); ABSL_FLAG(std::vector<std::string>, tryfromenv, {}, "comma-separated list of flags to try to set from the environment if " "present") .OnUpdate([]() { if (absl::GetFlag(FLAGS_tryfromenv).empty()) return; absl::MutexLock l(&absl::flags_internal::processing_checks_guard); if (absl::flags_internal::tryfromenv_needs_processing) { ABSL_INTERNAL_LOG(WARNING, "tryfromenv set twice before it is handled."); } absl::flags_internal::tryfromenv_needs_processing = true; }); ABSL_FLAG(std::vector<std::string>, undefok, {}, "comma-separated list of flag names that it is okay to specify " "on the command line even if the program does not define a flag " "with that name"); namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { namespace { class ArgsList { public: ArgsList() : next_arg_(0) {} ArgsList(int argc, char* argv[]) : args_(argv, argv + argc), next_arg_(0) {} explicit ArgsList(const std::vector<std::string>& args) : args_(args), next_arg_(0) {} bool ReadFromFlagfile(const std::string& flag_file_name); size_t Size() const { return args_.size() - next_arg_; } size_t FrontIndex() const { return next_arg_; } absl::string_view Front() const { return args_[next_arg_]; } void PopFront() { next_arg_++; } private: std::vector<std::string> args_; size_t next_arg_; }; bool ArgsList::ReadFromFlagfile(const std::string& flag_file_name) { std::ifstream flag_file(flag_file_name); if (!flag_file) { flags_internal::ReportUsageError( absl::StrCat("Can't open flagfile ", flag_file_name), true); return false; } args_.emplace_back(""); std::string line; bool success = true; while (std::getline(flag_file, line)) { absl::string_view stripped = absl::StripLeadingAsciiWhitespace(line); if (stripped.empty() || stripped[0] == '#') { continue; } if (stripped[0] == '-') { if (stripped == "--") { flags_internal::ReportUsageError( "Flagfile can't contain position arguments or --", true); success = false; break; } args_.emplace_back(stripped); continue; } flags_internal::ReportUsageError( absl::StrCat("Unexpected line in the flagfile ", flag_file_name, ": ", line), true); success = false; } return success; } bool GetEnvVar(const char* var_name, std::string& var_value) { #ifdef _WIN32 char buf[1024]; auto get_res = GetEnvironmentVariableA(var_name, buf, sizeof(buf)); if (get_res >= sizeof(buf)) { return false; } if (get_res == 0) { return false; } var_value = std::string(buf, get_res); #else const char* val = ::getenv(var_name); if (val == nullptr) { return false; } var_value = val; #endif return true; } std::tuple<absl::string_view, absl::string_view, bool> SplitNameAndValue( absl::string_view arg) { absl::ConsumePrefix(&arg, "-"); if (arg.empty()) { return std::make_tuple("", "", false); } auto equal_sign_pos = arg.find('='); absl::string_view flag_name = arg.substr(0, equal_sign_pos); absl::string_view value; bool is_empty_value = false; if (equal_sign_pos != absl::string_view::npos) { value = arg.substr(equal_sign_pos + 1); is_empty_value = value.empty(); } return std::make_tuple(flag_name, value, is_empty_value); } std::tuple<CommandLineFlag*, bool> LocateFlag(absl::string_view flag_name) { CommandLineFlag* flag = absl::FindCommandLineFlag(flag_name); bool is_negative = false; if (!flag && absl::ConsumePrefix(&flag_name, "no")) { flag = absl::FindCommandLineFlag(flag_name); is_negative = true; } return std::make_tuple(flag, is_negative); } void CheckDefaultValuesParsingRoundtrip() { #ifndef NDEBUG flags_internal::ForEachFlag([&](CommandLineFlag& flag) { if (flag.IsRetired()) return; #define ABSL_FLAGS_INTERNAL_IGNORE_TYPE(T, _) \ if (flag.IsOfType<T>()) return; ABSL_FLAGS_INTERNAL_SUPPORTED_TYPES(ABSL_FLAGS_INTERNAL_IGNORE_TYPE) #undef ABSL_FLAGS_INTERNAL_IGNORE_TYPE flags_internal::PrivateHandleAccessor::CheckDefaultValueParsingRoundtrip( flag); }); #endif } bool ReadFlagfiles(const std::vector<std::string>& flagfiles, std::vector<ArgsList>& input_args) { bool success = true; for (auto it = flagfiles.rbegin(); it != flagfiles.rend(); ++it) { ArgsList al; if (al.ReadFromFlagfile(*it)) { input_args.push_back(al); } else { success = false; } } return success; } bool ReadFlagsFromEnv(const std::vector<std::string>& flag_names, std::vector<ArgsList>& input_args, bool fail_on_absent_in_env) { bool success = true; std::vector<std::string> args; args.emplace_back(""); for (const auto& flag_name : flag_names) { if (flag_name == "fromenv" || flag_name == "tryfromenv") { flags_internal::ReportUsageError( absl::StrCat("Infinite recursion on flag ", flag_name), true); success = false; continue; } const std::string envname = absl::StrCat("FLAGS_", flag_name); std::string envval; if (!GetEnvVar(envname.c_str(), envval)) { if (fail_on_absent_in_env) { flags_internal::ReportUsageError( absl::StrCat(envname, " not found in environment"), true); success = false; } continue; } args.push_back(absl::StrCat("--", flag_name, "=", envval)); } if (success) { input_args.emplace_back(args); } return success; } bool HandleGeneratorFlags(std::vector<ArgsList>& input_args, std::vector<std::string>& flagfile_value) { bool success = true; absl::MutexLock l(&flags_internal::processing_checks_guard); if (flags_internal::flagfile_needs_processing) { auto flagfiles = absl::GetFlag(FLAGS_flagfile); if (input_args.size() == 1) { flagfile_value.insert(flagfile_value.end(), flagfiles.begin(), flagfiles.end()); } success &= ReadFlagfiles(flagfiles, input_args); flags_internal::flagfile_needs_processing = false; } if (flags_internal::fromenv_needs_processing) { auto flags_list = absl::GetFlag(FLAGS_fromenv); success &= ReadFlagsFromEnv(flags_list, input_args, true); flags_internal::fromenv_needs_processing = false; } if (flags_internal::tryfromenv_needs_processing) { auto flags_list = absl::GetFlag(FLAGS_tryfromenv); success &= ReadFlagsFromEnv(flags_list, input_args, false); flags_internal::tryfromenv_needs_processing = false; } return success; } void ResetGeneratorFlags(const std::vector<std::string>& flagfile_value) { if (!flagfile_value.empty()) { absl::SetFlag(&FLAGS_flagfile, flagfile_value); absl::MutexLock l(&flags_internal::processing_checks_guard); flags_internal::flagfile_needs_processing = false; } if (!absl::GetFlag(FLAGS_fromenv).empty()) { absl::SetFlag(&FLAGS_fromenv, {}); } if (!absl::GetFlag(FLAGS_tryfromenv).empty()) { absl::SetFlag(&FLAGS_tryfromenv, {}); } absl::MutexLock l(&flags_internal::processing_checks_guard); flags_internal::fromenv_needs_processing = false; flags_internal::tryfromenv_needs_processing = false; } std::tuple<bool, absl::string_view> DeduceFlagValue(const CommandLineFlag& flag, absl::string_view value, bool is_negative, bool is_empty_value, ArgsList* curr_list) { if (flag.IsOfType<bool>()) { if (value.empty()) { if (is_empty_value) { flags_internal::ReportUsageError( absl::StrCat( "Missing the value after assignment for the boolean flag '", flag.Name(), "'"), true); return std::make_tuple(false, ""); } value = is_negative ? "0" : "1"; } else if (is_negative) { flags_internal::ReportUsageError( absl::StrCat("Negative form with assignment is not valid for the " "boolean flag '", flag.Name(), "'"), true); return std::make_tuple(false, ""); } } else if (is_negative) { flags_internal::ReportUsageError( absl::StrCat("Negative form is not valid for the flag '", flag.Name(), "'"), true); return std::make_tuple(false, ""); } else if (value.empty() && (!is_empty_value)) { if (curr_list->Size() == 1) { flags_internal::ReportUsageError( absl::StrCat("Missing the value for the flag '", flag.Name(), "'"), true); return std::make_tuple(false, ""); } curr_list->PopFront(); value = curr_list->Front(); if (!value.empty() && value[0] == '-' && flag.IsOfType<std::string>()) { auto maybe_flag_name = std::get<0>(SplitNameAndValue(value.substr(1))); if (maybe_flag_name.empty() || std::get<0>(LocateFlag(maybe_flag_name)) != nullptr) { ABSL_INTERNAL_LOG( WARNING, absl::StrCat("Did you really mean to set flag '", flag.Name(), "' to the value '", value, "'?")); } } } return std::make_tuple(true, value); } bool CanIgnoreUndefinedFlag(absl::string_view flag_name) { auto undefok = absl::GetFlag(FLAGS_undefok); if (std::find(undefok.begin(), undefok.end(), flag_name) != undefok.end()) { return true; } if (absl::ConsumePrefix(&flag_name, "no") && std::find(undefok.begin(), undefok.end(), flag_name) != undefok.end()) { return true; } return false; } void ReportUnrecognizedFlags( const std::vector<UnrecognizedFlag>& unrecognized_flags, bool report_as_fatal_error) { for (const auto& unrecognized : unrecognized_flags) { std::vector<std::string> misspelling_hints; if (unrecognized.source == UnrecognizedFlag::kFromArgv) { misspelling_hints = flags_internal::GetMisspellingHints(unrecognized.flag_name); } if (misspelling_hints.empty()) { flags_internal::ReportUsageError( absl::StrCat("Unknown command line flag '", unrecognized.flag_name, "'"), report_as_fatal_error); } else { flags_internal::ReportUsageError( absl::StrCat("Unknown command line flag '", unrecognized.flag_name, "'. Did you mean: ", absl::StrJoin(misspelling_hints, ", "), " ?"), report_as_fatal_error); } } } } bool WasPresentOnCommandLine(absl::string_view flag_name) { absl::ReaderMutexLock l(&specified_flags_guard); ABSL_INTERNAL_CHECK(specified_flags != nullptr, "ParseCommandLine is not invoked yet"); return std::binary_search(specified_flags->begin(), specified_flags->end(), flag_name, SpecifiedFlagsCompare{}); } struct BestHints { explicit BestHints(uint8_t _max) : best_distance(_max + 1) {} bool AddHint(absl::string_view hint, uint8_t distance) { if (hints.size() >= kMaxHints) return false; if (distance == best_distance) { hints.emplace_back(hint); } if (distance < best_distance) { best_distance = distance; hints = std::vector<std::string>{std::string(hint)}; } return true; } uint8_t best_distance; std::vector<std::string> hints; }; std::vector<std::string> GetMisspellingHints(const absl::string_view flag) { const size_t maxCutoff = std::min(flag.size() / 2 + 1, kMaxDistance); auto undefok = absl::GetFlag(FLAGS_undefok); BestHints best_hints(static_cast<uint8_t>(maxCutoff)); flags_internal::ForEachFlag([&](const CommandLineFlag& f) { if (best_hints.hints.size() >= kMaxHints) return; uint8_t distance = strings_internal::CappedDamerauLevenshteinDistance( flag, f.Name(), best_hints.best_distance); best_hints.AddHint(f.Name(), distance); if (f.IsOfType<bool>()) { const std::string negated_flag = absl::StrCat("no", f.Name()); distance = strings_internal::CappedDamerauLevenshteinDistance( flag, negated_flag, best_hints.best_distance); best_hints.AddHint(negated_flag, distance); } }); absl::c_for_each(undefok, [&](const absl::string_view f) { if (best_hints.hints.size() >= kMaxHints) return; uint8_t distance = strings_internal::CappedDamerauLevenshteinDistance( flag, f, best_hints.best_distance); best_hints.AddHint(absl::StrCat(f, " (undefok)"), distance); }); return best_hints.hints; } std::vector<char*> ParseCommandLineImpl(int argc, char* argv[], UsageFlagsAction usage_flag_action, OnUndefinedFlag undef_flag_action, std::ostream& error_help_output) { std::vector<char*> positional_args; std::vector<UnrecognizedFlag> unrecognized_flags; auto help_mode = flags_internal::ParseAbseilFlagsOnlyImpl( argc, argv, positional_args, unrecognized_flags, usage_flag_action); if (undef_flag_action != OnUndefinedFlag::kIgnoreUndefined) { flags_internal::ReportUnrecognizedFlags( unrecognized_flags, (undef_flag_action == OnUndefinedFlag::kAbortIfUndefined)); if (undef_flag_action == OnUndefinedFlag::kAbortIfUndefined) { if (!unrecognized_flags.empty()) { flags_internal::HandleUsageFlags(error_help_output, ProgramUsageMessage()); std::exit(1); } } } flags_internal::MaybeExit(help_mode); return positional_args; } HelpMode ParseAbseilFlagsOnlyImpl( int argc, char* argv[], std::vector<char*>& positional_args, std::vector<UnrecognizedFlag>& unrecognized_flags, UsageFlagsAction usage_flag_action) { ABSL_INTERNAL_CHECK(argc > 0, "Missing argv[0]"); using flags_internal::ArgsList; using flags_internal::specified_flags; std::vector<std::string> flagfile_value; std::vector<ArgsList> input_args; flags_internal::FinalizeRegistry(); flags_internal::CheckDefaultValuesParsingRoundtrip(); input_args.push_back(ArgsList(argc, argv)); if (flags_internal::ProgramInvocationName() == "UNKNOWN") { flags_internal::SetProgramInvocationName(argv[0]); } positional_args.push_back(argv[0]); absl::MutexLock l(&flags_internal::specified_flags_guard); if (specified_flags == nullptr) { specified_flags = new std::vector<const CommandLineFlag*>; } else { specified_flags->clear(); } bool success = true; while (!input_args.empty()) { success &= flags_internal::HandleGeneratorFlags(input_args, flagfile_value); ArgsList& curr_list = input_args.back(); curr_list.PopFront(); if (curr_list.Size() == 0) { input_args.pop_back(); continue; } absl::string_view arg(curr_list.Front()); bool arg_from_argv = input_args.size() == 1; if (!absl::ConsumePrefix(&arg, "-") || arg.empty()) { ABSL_INTERNAL_CHECK(arg_from_argv, "Flagfile cannot contain positional argument"); positional_args.push_back(argv[curr_list.FrontIndex()]); continue; } absl::string_view flag_name; absl::string_view value; bool is_empty_value = false; std::tie(flag_name, value, is_empty_value) = flags_internal::SplitNameAndValue(arg); if (flag_name.empty()) { ABSL_INTERNAL_CHECK(arg_from_argv, "Flagfile cannot contain positional argument"); curr_list.PopFront(); break; } CommandLineFlag* flag = nullptr; bool is_negative = false; std::tie(flag, is_negative) = flags_internal::LocateFlag(flag_name); if (flag == nullptr) { if (flags_internal::DeduceUsageFlags(flag_name, value)) { continue; } unrecognized_flags.emplace_back(arg_from_argv ? UnrecognizedFlag::kFromArgv : UnrecognizedFlag::kFromFlagfile, flag_name); continue; } bool value_success = true; std::tie(value_success, value) = flags_internal::DeduceFlagValue( *flag, value, is_negative, is_empty_value, &curr_list); success &= value_success; std::string error; if (!flags_internal::PrivateHandleAccessor::ParseFrom( *flag, value, flags_internal::SET_FLAGS_VALUE, flags_internal::kCommandLine, error)) { if (flag->IsRetired()) continue; flags_internal::ReportUsageError(error, true); success = false; } else { specified_flags->push_back(flag); } } flags_internal::ResetGeneratorFlags(flagfile_value); if (!input_args.empty()) { for (size_t arg_index = i
#include "absl/flags/parse.h" #include <stdlib.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/internal/scoped_set_env.h" #include "absl/flags/config.h" #include "absl/flags/flag.h" #include "absl/flags/internal/parse.h" #include "absl/flags/internal/usage.h" #include "absl/flags/reflection.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "absl/types/span.h" #ifdef _WIN32 #include <windows.h> #endif #define FLAG_MULT(x) F3(x) #define TEST_FLAG_HEADER FLAG_HEADER_ #define F(name) ABSL_FLAG(int, name, 0, "") #define F1(name) \ F(name##1); \ F(name##2); \ F(name##3); \ F(name##4); \ F(name##5) #define F2(name) \ F1(name##1); \ F1(name##2); \ F1(name##3); \ F1(name##4); \ F1(name##5) #define F3(name) \ F2(name##1); \ F2(name##2); \ F2(name##3); \ F2(name##4); \ F2(name##5) FLAG_MULT(TEST_FLAG_HEADER); namespace { using absl::base_internal::ScopedSetEnv; struct UDT { UDT() = default; UDT(const UDT&) = default; UDT& operator=(const UDT&) = default; UDT(int v) : value(v) {} int value; }; bool AbslParseFlag(absl::string_view in, UDT* udt, std::string* err) { if (in == "A") { udt->value = 1; return true; } if (in == "AAA") { udt->value = 10; return true; } *err = "Use values A, AAA instead"; return false; } std::string AbslUnparseFlag(const UDT& udt) { return udt.value == 1 ? "A" : "AAA"; } std::string GetTestTmpDirEnvVar(const char* const env_var_name) { #ifdef _WIN32 char buf[MAX_PATH]; auto get_res = GetEnvironmentVariableA(env_var_name, buf, sizeof(buf)); if (get_res >= sizeof(buf) || get_res == 0) { return ""; } return std::string(buf, get_res); #else const char* val = ::getenv(env_var_name); if (val == nullptr) { return ""; } return val; #endif } const std::string& GetTestTempDir() { static std::string* temp_dir_name = []() -> std::string* { std::string* res = new std::string(GetTestTmpDirEnvVar("TEST_TMPDIR")); if (res->empty()) { *res = GetTestTmpDirEnvVar("TMPDIR"); } if (res->empty()) { #ifdef _WIN32 char temp_path_buffer[MAX_PATH]; auto len = GetTempPathA(MAX_PATH, temp_path_buffer); if (len < MAX_PATH && len != 0) { std::string temp_dir_name = temp_path_buffer; if (!absl::EndsWith(temp_dir_name, "\\")) { temp_dir_name.push_back('\\'); } absl::StrAppend(&temp_dir_name, "parse_test.", GetCurrentProcessId()); if (CreateDirectoryA(temp_dir_name.c_str(), nullptr)) { *res = temp_dir_name; } } #else char temp_dir_template[] = "/tmp/parse_test.XXXXXX"; if (auto* unique_name = ::mkdtemp(temp_dir_template)) { *res = unique_name; } #endif } if (res->empty()) { LOG(FATAL) << "Failed to make temporary directory for data files"; } #ifdef _WIN32 *res += "\\"; #else *res += "/"; #endif return res; }(); return *temp_dir_name; } struct FlagfileData { const absl::string_view file_name; const absl::Span<const char* const> file_lines; }; constexpr const char* const ff1_data[] = { "# comment ", " # comment ", "", " ", "--int_flag=-1", " --string_flag=q2w2 ", " ## ", " --double_flag=0.1", "--bool_flag=Y " }; constexpr const char* const ff2_data[] = { "# Setting legacy flag", "--legacy_int=1111", "--legacy_bool", "--nobool_flag", "--legacy_str=aqsw", "--int_flag=100", " ## =============" }; const char* GetFlagfileFlag(const std::vector<FlagfileData>& ffd, std::string& flagfile_flag) { flagfile_flag = "--flagfile="; absl::string_view separator; for (const auto& flagfile_data : ffd) { std::string flagfile_name = absl::StrCat(GetTestTempDir(), flagfile_data.file_name); std::ofstream flagfile_out(flagfile_name); for (auto line : flagfile_data.file_lines) { flagfile_out << absl::Substitute(line, GetTestTempDir()) << "\n"; } absl::StrAppend(&flagfile_flag, separator, flagfile_name); separator = ","; } return flagfile_flag.c_str(); } } ABSL_FLAG(int, int_flag, 1, ""); ABSL_FLAG(double, double_flag, 1.1, ""); ABSL_FLAG(std::string, string_flag, "a", ""); ABSL_FLAG(bool, bool_flag, false, ""); ABSL_FLAG(UDT, udt_flag, -1, ""); ABSL_RETIRED_FLAG(int, legacy_int, 1, ""); ABSL_RETIRED_FLAG(bool, legacy_bool, false, ""); ABSL_RETIRED_FLAG(std::string, legacy_str, "l", ""); namespace { namespace flags = absl::flags_internal; using testing::AllOf; using testing::ElementsAreArray; using testing::HasSubstr; class ParseTest : public testing::Test { public: ~ParseTest() override { flags::SetFlagsHelpMode(flags::HelpMode::kNone); } void SetUp() override { #if ABSL_FLAGS_STRIP_NAMES GTEST_SKIP() << "This test requires flag names to be present"; #endif } private: absl::FlagSaver flag_saver_; }; template <int N> flags::HelpMode InvokeParseAbslOnlyImpl(const char* (&in_argv)[N]) { std::vector<char*> positional_args; std::vector<absl::UnrecognizedFlag> unrecognized_flags; return flags::ParseAbseilFlagsOnlyImpl(N, const_cast<char**>(in_argv), positional_args, unrecognized_flags, flags::UsageFlagsAction::kHandleUsage); } template <int N> void InvokeParseAbslOnly(const char* (&in_argv)[N]) { std::vector<char*> positional_args; std::vector<absl::UnrecognizedFlag> unrecognized_flags; absl::ParseAbseilFlagsOnly(2, const_cast<char**>(in_argv), positional_args, unrecognized_flags); } template <int N> std::vector<char*> InvokeParseCommandLineImpl(const char* (&in_argv)[N]) { return flags::ParseCommandLineImpl( N, const_cast<char**>(in_argv), flags::UsageFlagsAction::kHandleUsage, flags::OnUndefinedFlag::kAbortIfUndefined, std::cerr); } template <int N> std::vector<char*> InvokeParse(const char* (&in_argv)[N]) { return absl::ParseCommandLine(N, const_cast<char**>(in_argv)); } template <int N> void TestParse(const char* (&in_argv)[N], int int_flag_value, double double_flag_val, absl::string_view string_flag_val, bool bool_flag_val, int exp_position_args = 0) { auto out_args = InvokeParse(in_argv); EXPECT_EQ(out_args.size(), 1 + exp_position_args); EXPECT_STREQ(out_args[0], "testbin"); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), int_flag_value); EXPECT_NEAR(absl::GetFlag(FLAGS_double_flag), double_flag_val, 0.0001); EXPECT_EQ(absl::GetFlag(FLAGS_string_flag), string_flag_val); EXPECT_EQ(absl::GetFlag(FLAGS_bool_flag), bool_flag_val); } TEST_F(ParseTest, TestEmptyArgv) { const char* in_argv[] = {"testbin"}; auto out_args = InvokeParse(in_argv); EXPECT_EQ(out_args.size(), 1); EXPECT_STREQ(out_args[0], "testbin"); } TEST_F(ParseTest, TestValidIntArg) { const char* in_args1[] = { "testbin", "--int_flag=10", }; TestParse(in_args1, 10, 1.1, "a", false); const char* in_args2[] = { "testbin", "-int_flag=020", }; TestParse(in_args2, 20, 1.1, "a", false); const char* in_args3[] = { "testbin", "--int_flag", "-30", }; TestParse(in_args3, -30, 1.1, "a", false); const char* in_args4[] = { "testbin", "-int_flag", "0x21", }; TestParse(in_args4, 33, 1.1, "a", false); } TEST_F(ParseTest, TestValidDoubleArg) { const char* in_args1[] = { "testbin", "--double_flag=2.3", }; TestParse(in_args1, 1, 2.3, "a", false); const char* in_args2[] = { "testbin", "--double_flag=0x1.2", }; TestParse(in_args2, 1, 1.125, "a", false); const char* in_args3[] = { "testbin", "--double_flag", "99.7", }; TestParse(in_args3, 1, 99.7, "a", false); const char* in_args4[] = { "testbin", "--double_flag", "0x20.1", }; TestParse(in_args4, 1, 32.0625, "a", false); } TEST_F(ParseTest, TestValidStringArg) { const char* in_args1[] = { "testbin", "--string_flag=aqswde", }; TestParse(in_args1, 1, 1.1, "aqswde", false); const char* in_args2[] = { "testbin", "-string_flag=a=b=c", }; TestParse(in_args2, 1, 1.1, "a=b=c", false); const char* in_args3[] = { "testbin", "--string_flag", "zaxscd", }; TestParse(in_args3, 1, 1.1, "zaxscd", false); const char* in_args4[] = { "testbin", "-string_flag", "--int_flag", }; TestParse(in_args4, 1, 1.1, "--int_flag", false); const char* in_args5[] = { "testbin", "--string_flag", "--no_a_flag=11", }; TestParse(in_args5, 1, 1.1, "--no_a_flag=11", false); } TEST_F(ParseTest, TestValidBoolArg) { const char* in_args1[] = { "testbin", "--bool_flag", }; TestParse(in_args1, 1, 1.1, "a", true); const char* in_args2[] = { "testbin", "--nobool_flag", }; TestParse(in_args2, 1, 1.1, "a", false); const char* in_args3[] = { "testbin", "--bool_flag=true", }; TestParse(in_args3, 1, 1.1, "a", true); const char* in_args4[] = { "testbin", "-bool_flag=false", }; TestParse(in_args4, 1, 1.1, "a", false); } TEST_F(ParseTest, TestValidUDTArg) { const char* in_args1[] = { "testbin", "--udt_flag=A", }; InvokeParse(in_args1); EXPECT_EQ(absl::GetFlag(FLAGS_udt_flag).value, 1); const char* in_args2[] = {"testbin", "--udt_flag", "AAA"}; InvokeParse(in_args2); EXPECT_EQ(absl::GetFlag(FLAGS_udt_flag).value, 10); } TEST_F(ParseTest, TestValidMultipleArg) { const char* in_args1[] = { "testbin", "--bool_flag", "--int_flag=2", "--double_flag=0.1", "--string_flag=asd", }; TestParse(in_args1, 2, 0.1, "asd", true); const char* in_args2[] = { "testbin", "--string_flag=", "--nobool_flag", "--int_flag", "-011", "--double_flag", "-1e-2", }; TestParse(in_args2, -11, -0.01, "", false); const char* in_args3[] = { "testbin", "--int_flag", "-0", "--string_flag", "\"\"", "--bool_flag=true", "--double_flag=1e18", }; TestParse(in_args3, 0, 1e18, "\"\"", true); } TEST_F(ParseTest, TestPositionalArgs) { const char* in_args1[] = { "testbin", "p1", "p2", }; TestParse(in_args1, 1, 1.1, "a", false, 2); auto out_args1 = InvokeParse(in_args1); EXPECT_STREQ(out_args1[1], "p1"); EXPECT_STREQ(out_args1[2], "p2"); const char* in_args2[] = { "testbin", "--int_flag=2", "p1", }; TestParse(in_args2, 2, 1.1, "a", false, 1); auto out_args2 = InvokeParse(in_args2); EXPECT_STREQ(out_args2[1], "p1"); const char* in_args3[] = {"testbin", "p1", "--int_flag=3", "p2", "--bool_flag", "true"}; TestParse(in_args3, 3, 1.1, "a", true, 3); auto out_args3 = InvokeParse(in_args3); EXPECT_STREQ(out_args3[1], "p1"); EXPECT_STREQ(out_args3[2], "p2"); EXPECT_STREQ(out_args3[3], "true"); const char* in_args4[] = { "testbin", "--", "p1", "p2", }; TestParse(in_args4, 3, 1.1, "a", true, 2); auto out_args4 = InvokeParse(in_args4); EXPECT_STREQ(out_args4[1], "p1"); EXPECT_STREQ(out_args4[2], "p2"); const char* in_args5[] = { "testbin", "p1", "--int_flag=4", "--", "--bool_flag", "false", "p2", }; TestParse(in_args5, 4, 1.1, "a", true, 4); auto out_args5 = InvokeParse(in_args5); EXPECT_STREQ(out_args5[1], "p1"); EXPECT_STREQ(out_args5[2], "--bool_flag"); EXPECT_STREQ(out_args5[3], "false"); EXPECT_STREQ(out_args5[4], "p2"); } using ParseDeathTest = ParseTest; TEST_F(ParseDeathTest, TestUndefinedArg) { const char* in_args1[] = { "testbin", "--undefined_flag", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args1), "Unknown command line flag 'undefined_flag'"); const char* in_args2[] = { "testbin", "--noprefixed_flag", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args2), "Unknown command line flag 'noprefixed_flag'"); const char* in_args3[] = { "testbin", "--Int_flag=1", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args3), "Unknown command line flag 'Int_flag'"); } TEST_F(ParseDeathTest, TestInvalidBoolFlagFormat) { const char* in_args1[] = { "testbin", "--bool_flag=", }; EXPECT_DEATH_IF_SUPPORTED( InvokeParse(in_args1), "Missing the value after assignment for the boolean flag 'bool_flag'"); const char* in_args2[] = { "testbin", "--nobool_flag=true", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args2), "Negative form with assignment is not valid for the boolean " "flag 'bool_flag'"); } TEST_F(ParseDeathTest, TestInvalidNonBoolFlagFormat) { const char* in_args1[] = { "testbin", "--nostring_flag", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args1), "Negative form is not valid for the flag 'string_flag'"); const char* in_args2[] = { "testbin", "--int_flag", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args2), "Missing the value for the flag 'int_flag'"); } TEST_F(ParseDeathTest, TestInvalidUDTFlagFormat) { const char* in_args1[] = { "testbin", "--udt_flag=1", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args1), "Illegal value '1' specified for flag 'udt_flag'; Use values A, " "AAA instead"); const char* in_args2[] = { "testbin", "--udt_flag", "AA", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args2), "Illegal value 'AA' specified for flag 'udt_flag'; Use values " "A, AAA instead"); } TEST_F(ParseDeathTest, TestFlagSuggestions) { const char* in_args1[] = { "testbin", "--legacy_boo", }; EXPECT_DEATH_IF_SUPPORTED( InvokeParse(in_args1), "Unknown command line flag 'legacy_boo'. Did you mean: legacy_bool ?"); const char* in_args2[] = {"testbin", "--foo", "--undefok=foo1"}; EXPECT_DEATH_IF_SUPPORTED( InvokeParse(in_args2), "Unknown command line flag 'foo'. Did you mean: foo1 \\(undefok\\)?"); const char* in_args3[] = { "testbin", "--nolegacy_ino", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args3), "Unknown command line flag 'nolegacy_ino'. Did " "you mean: nolegacy_bool, legacy_int ?"); } TEST_F(ParseTest, GetHints) { EXPECT_THAT(absl::flags_internal::GetMisspellingHints("legacy_boo"), testing::ContainerEq(std::vector<std::string>{"legacy_bool"})); EXPECT_THAT(absl::flags_internal::GetMisspellingHints("nolegacy_itn"), testing::ContainerEq(std::vector<std::string>{"legacy_int"})); EXPECT_THAT(absl::flags_internal::GetMisspellingHints("nolegacy_int1"), testing::ContainerEq(std::vector<std::string>{"legacy_int"})); EXPECT_THAT(absl::flags_internal::GetMisspellingHints("nolegacy_int"), testing::ContainerEq(std::vector<std::string>{"legacy_int"})); EXPECT_THAT(absl::flags_internal::GetMisspellingHints("nolegacy_ino"), testing::ContainerEq( std::vector<std::string>{"nolegacy_bool", "legacy_int"})); EXPECT_THAT( absl::flags_internal::GetMisspellingHints("FLAG_HEADER_000").size(), 100); } TEST_F(ParseTest, TestLegacyFlags) { const char* in_args1[] = { "testbin", "--legacy_int=11", }; TestParse(in_args1, 1, 1.1, "a", false); const char* in_args2[] = { "testbin", "--legacy_bool", }; TestParse(in_args2, 1, 1.1, "a", false); const char* in_args3[] = { "testbin", "--legacy_int", "22", "--int_flag=2", "--legacy_bool", "true", "--legacy_str", "--string_flag=qwe", }; TestParse(in_args3, 2, 1.1, "a", false, 1); } TEST_F(ParseTest, TestSimpleValidFlagfile) { std::string flagfile_flag; const char* in_args1[] = { "testbin", GetFlagfileFlag({{"parse_test.ff1", absl::MakeConstSpan(ff1_data)}}, flagfile_flag), }; TestParse(in_args1, -1, 0.1, "q2w2 ", true); const char* in_args2[] = { "testbin", GetFlagfileFlag({{"parse_test.ff2", absl::MakeConstSpan(ff2_data)}}, flagfile_flag), }; TestParse(in_args2, 100, 0.1, "q2w2 ", false); } TEST_F(ParseTest, TestValidMultiFlagfile) { std::string flagfile_flag; const char* in_args1[] = { "testbin", GetFlagfileFlag({{"parse_test.ff2", absl::MakeConstSpan(ff2_data)}, {"parse_test.ff1", absl::MakeConstSpan(ff1_data)}}, flagfile_flag), }; TestParse(in_args1, -1, 0.1, "q2w2 ", true); } TEST_F(ParseTest, TestFlagfileMixedWithRegularFlags) { std::string flagfile_flag; const char* in_args1[] = { "testbin", "--int_flag=3", GetFlagfileFlag({{"parse_test.ff1", absl::MakeConstSpan(ff1_data)}}, flagfile_flag), "-double_flag=0.2"}; TestParse(in_args1, -1, 0.2, "q2w2 ", true); } TEST_F(ParseTest, TestFlagfileInFlagfile) { std::string flagfile_flag; constexpr const char* const ff3_data[] = { "--flagfile=$0/parse_test.ff1", "--flagfile=$0/parse_test.ff2", }; GetFlagfileFlag({{"parse_test.ff2", absl::MakeConstSpan(ff2_data)}, {"parse_test.ff1", absl::MakeConstSpan(ff1_data)}}, flagfile_flag); const char* in_args1[] = { "testbin", GetFlagfileFlag({{"parse_test.ff3", absl::MakeConstSpan(ff3_data)}}, flagfile_flag), }; TestParse(in_args1, 100, 0.1, "q2w2 ", false); } TEST_F(ParseDeathTest, TestInvalidFlagfiles) { std::string flagfile_flag; constexpr const char* const ff4_data[] = { "--unknown_flag=10" }; const char* in_args1[] = { "testbin", GetFlagfileFlag({{"parse_test.ff4", absl::MakeConstSpan(ff4_data)}}, flagfile_flag), }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args1), "Unknown command line flag 'unknown_flag'"); constexpr const char* const ff5_data[] = { "--int_flag 10", }; const char* in_args2[] = { "testbin", GetFlagfileFlag({{"parse_test.ff5", absl::MakeConstSpan(ff5_data)}}, flagfile_flag), }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args2), "Unknown command line flag 'int_flag 10'"); constexpr const char* const ff6_data[] = { "--int_flag=10", "--", "arg1", "arg2", "arg3", }; const char* in_args3[] = { "testbin", GetFlagfileFlag({{"parse_test.ff6", absl::MakeConstSpan(ff6_data)}}, flagfile_flag), }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args3), "Flagfile can't contain position arguments or --"); const char* in_args4[] = { "testbin", "--flagfile=invalid_flag_file", }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args4), "Can't open flagfile invalid_flag_file"); constexpr const char* const ff7_data[] = { "--int_flag=10", "*bin*", "--str_flag=aqsw", }; const char* in_args5[] = { "testbin", GetFlagfileFlag({{"parse_test.ff7", absl::MakeConstSpan(ff7_data)}}, flagfile_flag), }; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args5), "Unexpected line in the flagfile .*: \\*bin\\*"); } TEST_F(ParseTest, TestReadingRequiredFlagsFromEnv) { const char* in_args1[] = {"testbin", "--fromenv=int_flag,bool_flag,string_flag"}; ScopedSetEnv set_int_flag("FLAGS_int_flag", "33"); ScopedSetEnv set_bool_flag("FLAGS_bool_flag", "True"); ScopedSetEnv set_string_flag("FLAGS_string_flag", "AQ12"); TestParse(in_args1, 33, 1.1, "AQ12", true); } TEST_F(ParseDeathTest, TestReadingUnsetRequiredFlagsFromEnv) { const char* in_args1[] = {"testbin", "--fromenv=int_flag"}; EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args1), "FLAGS_int_flag not found in environment"); } TEST_F(ParseDeathTest, TestRecursiveFlagsFromEnv) { const char* in_args1[] = {"testbin", "--fromenv=tryfromenv"}; ScopedSetEnv set_tryfromenv("FLAGS_tryfromenv", "int_flag"); EXPECT_DEATH_IF_SUPPORTED(InvokeParse(in_args1), "Infinite recursion on flag tryfromenv"); } TEST_F(ParseTest, TestReadingOptionalFlagsFromEnv) { const char* in_args1[] = { "testbin", "--tryfromenv=int_flag,bool_flag,string_flag,other_flag"}; ScopedSetEnv set_int_flag("FLAGS_int_flag", "17"); ScopedSetEnv set_bool_flag("FLAGS_bool_flag", "Y"); TestParse(in_args1, 17, 1.1, "a", true); } TEST_F(ParseTest, TestReadingFlagsFromEnvMoxedWithRegularFlags) { const char* in_args1[] = { "testbin", "--bool_flag=T", "--tryfromenv=int_flag,bool_flag", "--int_flag=-21", }; ScopedSetEnv set_int_flag("FLAGS_int_flag", "-15"); ScopedSetEnv set_bool_flag("FLAGS_bool_flag", "F"); TestParse(in_args1, -21, 1.1, "a", false); } TEST_F(ParseDeathTest, TestSimpleHelpFlagHandling) { const char* in_args1[] = { "testbin", "--help", }; EXPECT_EQ(InvokeParseAbslOnlyImpl(in_args1), flags::HelpMode::kImportant); EXPECT_EXIT(InvokeParse(in_args1), testing::ExitedWithCode(1), ""); const char* in_args2[] = { "testbin", "--help", "--int_flag=3", }; EXPECT_EQ(InvokeParseAbslOnlyImpl(in_args2), flags::HelpMode::kImportant); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 3); const char* in_args3[] = {"testbin", "--help", "some_positional_arg"}; EXPECT_EQ(InvokeParseAbslOnlyImpl(in_args3), flags::HelpMode::kImportant); } TEST_F(ParseTest, TestSubstringHelpFlagHandling) { const char* in_args1[] = { "testbin", "--help=abcd", }; EXPECT_EQ(InvokeParseAbslOnlyImpl(in_args1), flags::HelpMode::kMatch); EXPECT_EQ(flags::GetFlagsHelpMatchSubstr(), "abcd"); } TEST_F(ParseDeathTest, TestVersionHandling) { const char* in_args1[] = { "testbin", "--version", }; EXPECT_EQ(InvokeParseAbslOnlyImpl(in_args1), flags::HelpMode::kVersion); } TEST_F(ParseTest, TestCheckArgsHandling) { const char* in_args1[] = {"testbin", "--only_check_args", "--int_flag=211"}; EXPECT_EQ(InvokeParseAbslOnlyImpl(in_args1), flags::HelpMode::kOnlyCheckArgs); EXPECT_EXIT(InvokeParseAbslOnly(in_args1), testing::ExitedWithCode(0), ""); EXPECT_EXIT(InvokeParse(in_args1), testing::ExitedWithCode(0), ""); const char* in_args2[] = {"testbin", "--only_check_args", "--unknown_flag=a"}; EXPECT_EQ(InvokeParseAbslOnlyImpl(in_args2), flags::HelpMode::kOnlyCheckArgs); EXPECT_EXIT(InvokeParseAbslOnly(in_args2), testing::ExitedWithCode(0), ""); EXPECT_EXIT(InvokeParse(in_args2), testing::ExitedWithCode(1), ""); } TEST_F(ParseTest, WasPresentOnCommandLine) { const char* in_args1[] = { "testbin", "arg1", "--bool_flag", "--int_flag=211", "arg2", "--double_flag=1.1", "--string_flag", "asd", "--", "--some_flag", "arg4", }; InvokeParse(in_args1); EXPECT_TRUE(flags::WasPresentOnCommandLine("bool_flag")); EXPECT_TRUE(flags::WasPresentOnCommandLine("int_flag")); EXPECT_TRUE(flags::WasPresentOnCommandLine("double_flag")); EXPECT_TRUE(flags::WasPresentOnCommandLine("string_flag")); EXPECT_FALSE(flags::WasPresentOnCommandLine("some_flag")); EXPECT_FALSE(flags::WasPresentOnCommandLine("another_flag")); } TEST_F(ParseTest, ParseAbseilFlagsOnlySuccess) { const char* in_args[] = { "testbin", "arg1", "--bool_flag", "--int_flag=211", "arg2", "--double_flag=1.1", "--undef_flag1", "--undef_flag2=123", "--string_flag", "asd", "--", "--some_flag", "arg4", }; std::vector<char*> positional_args; std::vector<absl::UnrecognizedFlag> unrecognized_flags; absl::ParseAbseilFlagsOnly(13, const_cast<char**>(in_args), positional_args, unrecognized_flags); EXPECT_THAT(positional_args, ElementsAreArray( {absl::string_view("testbin"), absl::string_view("arg1"), absl::string_view("arg2"), absl::string_view("--some_flag"), absl::string_view("arg4")})); EXPECT_THAT(unrecognized_flags, ElementsAreArray( {absl::UnrecognizedFlag(absl::UnrecognizedFlag::kFromArgv, "undef_flag1"), absl::UnrecognizedFlag(absl::UnrecognizedFlag::kFromArgv, "undef_flag2")})); } TEST_F(ParseDeathTest, ParseAbseilFlagsOnlyFailure) { const char* in_args[] = { "testbin", "--int_flag=21.1", }; EXPECT_DEATH_IF_SUPPORTED( InvokeParseAbslOnly(in_args), "Illegal value '21.1' specified for flag 'int_flag'"); } TEST_F(ParseTest, UndefOkFlagsAreIgnored) { const char* in_args[] = { "testbin", "--undef_flag1", "--undef_flag2=123", "--undefok=undef_flag2", "--undef_flag3", "value", }; std::vector<char*> positional_args; std::vector<absl::UnrecognizedFlag> unrecognized_flags; absl::ParseAbseilFlagsOnly(6, const_cast<char**>(in_args), positional_args, unrecognized_flags); EXPECT_THAT(positional_args, ElementsAreArray({absl::string_view("testbin"), absl::string_view("value")})); EXPECT_THAT(unrecognized_flags, ElementsAreArray( {absl::UnrecognizedFlag(absl::UnrecognizedFlag::kFromArgv, "undef_flag1"), absl::UnrecognizedFlag(absl::UnrecognizedFlag::kFromArgv, "undef_flag3")})); } TEST_F(ParseTest, AllUndefOkFlagsAreIgnored) { const char* in_args[] = { "testbin", "--undef_flag1", "--undef_flag2=123", "--undefok=undef_flag2,undef_flag1,undef_flag3", "--undef_flag3", "value", "--", "--undef_flag4", }; std::vector<char*> positional_args; std::vector<absl::UnrecognizedFlag> unrecognized_flags; absl::ParseAbseilFlagsOnly(8, const_cast<char**>(in_args), positional_args, unrecognized_flags); EXPECT_THAT(positional_args, ElementsAreArray({absl::string_view("testbin"), absl::string_view("value"), absl::string_view("--undef_flag4")})); EXPECT_THAT(unrecognized_flags, testing::IsEmpty()); } TEST_F(ParseDeathTest, ExitOnUnrecognizedFlagPrintsHelp) { const char* in_args[] = { "testbin", "--undef_flag1", "--help=int_flag", }; EXPECT_EXIT(InvokeParseCommandLineImpl(in_args), testing::ExitedWithCode(1), AllOf(HasSubstr("Unknown command line flag 'undef_flag1'"), HasSubstr("Try --helpfull to get a list of all flags"))); } }
2,501
#ifndef ABSL_FLAGS_INTERNAL_COMMANDLINEFLAG_H_ #define ABSL_FLAGS_INTERNAL_COMMANDLINEFLAG_H_ #include "absl/base/config.h" #include "absl/base/internal/fast_type_id.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { using FlagFastTypeId = absl::base_internal::FastTypeIdType; enum FlagSettingMode { SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, SET_FLAGS_DEFAULT }; enum ValueSource { kCommandLine, kProgrammaticChange, }; class FlagStateInterface { public: virtual ~FlagStateInterface(); virtual void Restore() const = 0; }; } ABSL_NAMESPACE_END } #endif #include "absl/flags/internal/commandlineflag.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { FlagStateInterface::~FlagStateInterface() = default; } ABSL_NAMESPACE_END }
#include "absl/flags/commandlineflag.h" #include <memory> #include <string> #include "gtest/gtest.h" #include "absl/flags/config.h" #include "absl/flags/flag.h" #include "absl/flags/internal/private_handle_accessor.h" #include "absl/flags/reflection.h" #include "absl/flags/usage_config.h" #include "absl/memory/memory.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" ABSL_FLAG(int, int_flag, 201, "int_flag help"); ABSL_FLAG(std::string, string_flag, "dflt", absl::StrCat("string_flag", " help")); ABSL_RETIRED_FLAG(bool, bool_retired_flag, false, "bool_retired_flag help"); ABSL_FLAG(int, int_flag2, 201, ""); ABSL_FLAG(std::string, string_flag2, "dflt", ""); namespace { namespace flags = absl::flags_internal; class CommandLineFlagTest : public testing::Test { protected: static void SetUpTestSuite() { absl::FlagsUsageConfig default_config; default_config.normalize_filename = &CommandLineFlagTest::NormalizeFileName; absl::SetFlagsUsageConfig(default_config); } void SetUp() override { #if ABSL_FLAGS_STRIP_NAMES GTEST_SKIP() << "This test requires flag names to be present"; #endif flag_saver_ = absl::make_unique<absl::FlagSaver>(); } void TearDown() override { flag_saver_.reset(); } private: static std::string NormalizeFileName(absl::string_view fname) { #ifdef _WIN32 std::string normalized(fname); std::replace(normalized.begin(), normalized.end(), '\\', '/'); fname = normalized; #endif return std::string(fname); } std::unique_ptr<absl::FlagSaver> flag_saver_; }; TEST_F(CommandLineFlagTest, TestAttributesAccessMethods) { auto* flag_01 = absl::FindCommandLineFlag("int_flag"); ASSERT_TRUE(flag_01); EXPECT_EQ(flag_01->Name(), "int_flag"); EXPECT_EQ(flag_01->Help(), "int_flag help"); EXPECT_TRUE(!flag_01->IsRetired()); EXPECT_TRUE(flag_01->IsOfType<int>()); EXPECT_TRUE(!flag_01->IsOfType<bool>()); EXPECT_TRUE(!flag_01->IsOfType<std::string>()); EXPECT_TRUE(absl::EndsWith(flag_01->Filename(), "absl/flags/commandlineflag_test.cc")) << flag_01->Filename(); auto* flag_02 = absl::FindCommandLineFlag("string_flag"); ASSERT_TRUE(flag_02); EXPECT_EQ(flag_02->Name(), "string_flag"); EXPECT_EQ(flag_02->Help(), "string_flag help"); EXPECT_TRUE(!flag_02->IsRetired()); EXPECT_TRUE(flag_02->IsOfType<std::string>()); EXPECT_TRUE(!flag_02->IsOfType<bool>()); EXPECT_TRUE(!flag_02->IsOfType<int>()); EXPECT_TRUE(absl::EndsWith(flag_02->Filename(), "absl/flags/commandlineflag_test.cc")) << flag_02->Filename(); } TEST_F(CommandLineFlagTest, TestValueAccessMethods) { absl::SetFlag(&FLAGS_int_flag2, 301); auto* flag_01 = absl::FindCommandLineFlag("int_flag2"); ASSERT_TRUE(flag_01); EXPECT_EQ(flag_01->CurrentValue(), "301"); EXPECT_EQ(flag_01->DefaultValue(), "201"); absl::SetFlag(&FLAGS_string_flag2, "new_str_value"); auto* flag_02 = absl::FindCommandLineFlag("string_flag2"); ASSERT_TRUE(flag_02); EXPECT_EQ(flag_02->CurrentValue(), "new_str_value"); EXPECT_EQ(flag_02->DefaultValue(), "dflt"); } TEST_F(CommandLineFlagTest, TestParseFromCurrentValue) { std::string err; auto* flag_01 = absl::FindCommandLineFlag("int_flag"); EXPECT_FALSE( flags::PrivateHandleAccessor::IsSpecifiedOnCommandLine(*flag_01)); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "11", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 11); EXPECT_FALSE( flags::PrivateHandleAccessor::IsSpecifiedOnCommandLine(*flag_01)); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "-123", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), -123); EXPECT_FALSE( flags::PrivateHandleAccessor::IsSpecifiedOnCommandLine(*flag_01)); EXPECT_TRUE(!flags::PrivateHandleAccessor::ParseFrom( *flag_01, "xyz", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), -123); EXPECT_EQ(err, "Illegal value 'xyz' specified for flag 'int_flag'"); EXPECT_FALSE( flags::PrivateHandleAccessor::IsSpecifiedOnCommandLine(*flag_01)); EXPECT_TRUE(!flags::PrivateHandleAccessor::ParseFrom( *flag_01, "A1", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), -123); EXPECT_EQ(err, "Illegal value 'A1' specified for flag 'int_flag'"); EXPECT_FALSE( flags::PrivateHandleAccessor::IsSpecifiedOnCommandLine(*flag_01)); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "0x10", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 16); EXPECT_FALSE( flags::PrivateHandleAccessor::IsSpecifiedOnCommandLine(*flag_01)); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "011", flags::SET_FLAGS_VALUE, flags::kCommandLine, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 11); EXPECT_TRUE(flags::PrivateHandleAccessor::IsSpecifiedOnCommandLine(*flag_01)); EXPECT_TRUE(!flags::PrivateHandleAccessor::ParseFrom( *flag_01, "", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(err, "Illegal value '' specified for flag 'int_flag'"); auto* flag_02 = absl::FindCommandLineFlag("string_flag"); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_02, "xyz", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_string_flag), "xyz"); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_02, "", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_string_flag), ""); } TEST_F(CommandLineFlagTest, TestParseFromDefaultValue) { std::string err; auto* flag_01 = absl::FindCommandLineFlag("int_flag"); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "111", flags::SET_FLAGS_DEFAULT, flags::kProgrammaticChange, err)); EXPECT_EQ(flag_01->DefaultValue(), "111"); auto* flag_02 = absl::FindCommandLineFlag("string_flag"); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_02, "abc", flags::SET_FLAGS_DEFAULT, flags::kProgrammaticChange, err)); EXPECT_EQ(flag_02->DefaultValue(), "abc"); } TEST_F(CommandLineFlagTest, TestParseFromIfDefault) { std::string err; auto* flag_01 = absl::FindCommandLineFlag("int_flag"); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "22", flags::SET_FLAG_IF_DEFAULT, flags::kProgrammaticChange, err)) << err; EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 22); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "33", flags::SET_FLAG_IF_DEFAULT, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 22); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "201", flags::SET_FLAGS_VALUE, flags::kProgrammaticChange, err)); EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom( *flag_01, "33", flags::SET_FLAG_IF_DEFAULT, flags::kProgrammaticChange, err)); EXPECT_EQ(absl::GetFlag(FLAGS_int_flag), 201); } }
2,502
#ifndef ABSL_FLAGS_REFLECTION_H_ #define ABSL_FLAGS_REFLECTION_H_ #include <string> #include "absl/base/config.h" #include "absl/container/flat_hash_map.h" #include "absl/flags/commandlineflag.h" #include "absl/flags/internal/commandlineflag.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { class FlagSaverImpl; } absl::CommandLineFlag* FindCommandLineFlag(absl::string_view name); absl::flat_hash_map<absl::string_view, absl::CommandLineFlag*> GetAllFlags(); class FlagSaver { public: FlagSaver(); ~FlagSaver(); FlagSaver(const FlagSaver&) = delete; void operator=(const FlagSaver&) = delete; private: flags_internal::FlagSaverImpl* impl_; }; ABSL_NAMESPACE_END } #endif #include "absl/flags/reflection.h" #include <assert.h> #include <atomic> #include <string> #include "absl/base/config.h" #include "absl/base/no_destructor.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/flags/commandlineflag.h" #include "absl/flags/internal/private_handle_accessor.h" #include "absl/flags/internal/registry.h" #include "absl/flags/usage_config.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { class FlagRegistry { public: FlagRegistry() = default; ~FlagRegistry() = default; void RegisterFlag(CommandLineFlag& flag, const char* filename); void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION(lock_) { lock_.Lock(); } void Unlock() ABSL_UNLOCK_FUNCTION(lock_) { lock_.Unlock(); } CommandLineFlag* FindFlag(absl::string_view name); static FlagRegistry& GlobalRegistry(); private: friend class flags_internal::FlagSaverImpl; friend void ForEachFlag(std::function<void(CommandLineFlag&)> visitor); friend void FinalizeRegistry(); using FlagMap = absl::flat_hash_map<absl::string_view, CommandLineFlag*>; using FlagIterator = FlagMap::iterator; using FlagConstIterator = FlagMap::const_iterator; FlagMap flags_; std::vector<CommandLineFlag*> flat_flags_; std::atomic<bool> finalized_flags_{false}; absl::Mutex lock_; FlagRegistry(const FlagRegistry&); FlagRegistry& operator=(const FlagRegistry&); }; namespace { class FlagRegistryLock { public: explicit FlagRegistryLock(FlagRegistry& fr) : fr_(fr) { fr_.Lock(); } ~FlagRegistryLock() { fr_.Unlock(); } private: FlagRegistry& fr_; }; } CommandLineFlag* FlagRegistry::FindFlag(absl::string_view name) { if (finalized_flags_.load(std::memory_order_acquire)) { auto it = std::partition_point( flat_flags_.begin(), flat_flags_.end(), [=](CommandLineFlag* f) { return f->Name() < name; }); if (it != flat_flags_.end() && (*it)->Name() == name) return *it; } FlagRegistryLock frl(*this); auto it = flags_.find(name); return it != flags_.end() ? it->second : nullptr; } void FlagRegistry::RegisterFlag(CommandLineFlag& flag, const char* filename) { if (filename != nullptr && flag.Filename() != GetUsageConfig().normalize_filename(filename)) { flags_internal::ReportUsageError( absl::StrCat( "Inconsistency between flag object and registration for flag '", flag.Name(), "', likely due to duplicate flags or an ODR violation. Relevant " "files: ", flag.Filename(), " and ", filename), true); std::exit(1); } FlagRegistryLock registry_lock(*this); std::pair<FlagIterator, bool> ins = flags_.insert(FlagMap::value_type(flag.Name(), &flag)); if (ins.second == false) { CommandLineFlag& old_flag = *ins.first->second; if (flag.IsRetired() != old_flag.IsRetired()) { flags_internal::ReportUsageError( absl::StrCat( "Retired flag '", flag.Name(), "' was defined normally in file '", (flag.IsRetired() ? old_flag.Filename() : flag.Filename()), "'."), true); } else if (flags_internal::PrivateHandleAccessor::TypeId(flag) != flags_internal::PrivateHandleAccessor::TypeId(old_flag)) { flags_internal::ReportUsageError( absl::StrCat("Flag '", flag.Name(), "' was defined more than once but with " "differing types. Defined in files '", old_flag.Filename(), "' and '", flag.Filename(), "'."), true); } else if (old_flag.IsRetired()) { return; } else if (old_flag.Filename() != flag.Filename()) { flags_internal::ReportUsageError( absl::StrCat("Flag '", flag.Name(), "' was defined more than once (in files '", old_flag.Filename(), "' and '", flag.Filename(), "')."), true); } else { flags_internal::ReportUsageError( absl::StrCat( "Something is wrong with flag '", flag.Name(), "' in file '", flag.Filename(), "'. One possibility: file '", flag.Filename(), "' is being linked both statically and dynamically into this " "executable. e.g. some files listed as srcs to a test and also " "listed as srcs of some shared lib deps of the same test."), true); } std::exit(1); } } FlagRegistry& FlagRegistry::GlobalRegistry() { static absl::NoDestructor<FlagRegistry> global_registry; return *global_registry; } void ForEachFlag(std::function<void(CommandLineFlag&)> visitor) { FlagRegistry& registry = FlagRegistry::GlobalRegistry(); if (registry.finalized_flags_.load(std::memory_order_acquire)) { for (const auto& i : registry.flat_flags_) visitor(*i); } FlagRegistryLock frl(registry); for (const auto& i : registry.flags_) visitor(*i.second); } bool RegisterCommandLineFlag(CommandLineFlag& flag, const char* filename) { FlagRegistry::GlobalRegistry().RegisterFlag(flag, filename); return true; } void FinalizeRegistry() { auto& registry = FlagRegistry::GlobalRegistry(); FlagRegistryLock frl(registry); if (registry.finalized_flags_.load(std::memory_order_relaxed)) { return; } registry.flat_flags_.reserve(registry.flags_.size()); for (const auto& f : registry.flags_) { registry.flat_flags_.push_back(f.second); } std::sort(std::begin(registry.flat_flags_), std::end(registry.flat_flags_), [](const CommandLineFlag* lhs, const CommandLineFlag* rhs) { return lhs->Name() < rhs->Name(); }); registry.flags_.clear(); registry.finalized_flags_.store(true, std::memory_order_release); } namespace { #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" #endif class RetiredFlagObj final : public CommandLineFlag { public: constexpr RetiredFlagObj(const char* name, FlagFastTypeId type_id) : name_(name), type_id_(type_id) {} private: absl::string_view Name() const override { return name_; } std::string Filename() const override { OnAccess(); return "RETIRED"; } FlagFastTypeId TypeId() const override { return type_id_; } std::string Help() const override { OnAccess(); return ""; } bool IsRetired() const override { return true; } bool IsSpecifiedOnCommandLine() const override { OnAccess(); return false; } std::string DefaultValue() const override { OnAccess(); return ""; } std::string CurrentValue() const override { OnAccess(); return ""; } bool ValidateInputValue(absl::string_view) const override { OnAccess(); return true; } std::unique_ptr<flags_internal::FlagStateInterface> SaveState() override { return nullptr; } bool ParseFrom(absl::string_view, flags_internal::FlagSettingMode, flags_internal::ValueSource, std::string&) override { OnAccess(); return false; } void CheckDefaultValueParsingRoundtrip() const override { OnAccess(); } void Read(void*) const override { OnAccess(); } void OnAccess() const { flags_internal::ReportUsageError( absl::StrCat("Accessing retired flag '", name_, "'"), false); } const char* const name_; const FlagFastTypeId type_id_; }; #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif } void Retire(const char* name, FlagFastTypeId type_id, char* buf) { static_assert(sizeof(RetiredFlagObj) == kRetiredFlagObjSize, ""); static_assert(alignof(RetiredFlagObj) == kRetiredFlagObjAlignment, ""); auto* flag = ::new (static_cast<void*>(buf)) flags_internal::RetiredFlagObj(name, type_id); FlagRegistry::GlobalRegistry().RegisterFlag(*flag, nullptr); } class FlagSaverImpl { public: FlagSaverImpl() = default; FlagSaverImpl(const FlagSaverImpl&) = delete; void operator=(const FlagSaverImpl&) = delete; void SaveFromRegistry() { assert(backup_registry_.empty()); flags_internal::ForEachFlag([&](CommandLineFlag& flag) { if (auto flag_state = flags_internal::PrivateHandleAccessor::SaveState(flag)) { backup_registry_.emplace_back(std::move(flag_state)); } }); } void RestoreToRegistry() { for (const auto& flag_state : backup_registry_) { flag_state->Restore(); } } private: std::vector<std::unique_ptr<flags_internal::FlagStateInterface>> backup_registry_; }; } FlagSaver::FlagSaver() : impl_(new flags_internal::FlagSaverImpl) { impl_->SaveFromRegistry(); } FlagSaver::~FlagSaver() { if (!impl_) return; impl_->RestoreToRegistry(); delete impl_; } CommandLineFlag* FindCommandLineFlag(absl::string_view name) { if (name.empty()) return nullptr; flags_internal::FlagRegistry& registry = flags_internal::FlagRegistry::GlobalRegistry(); return registry.FindFlag(name); } absl::flat_hash_map<absl::string_view, absl::CommandLineFlag*> GetAllFlags() { absl::flat_hash_map<absl::string_view, absl::CommandLineFlag*> res; flags_internal::ForEachFlag([&](CommandLineFlag& flag) { if (!flag.IsRetired()) res.insert({flag.Name(), &flag}); }); return res; } ABSL_NAMESPACE_END }
#include "absl/flags/reflection.h" #include <memory> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/flags/config.h" #include "absl/flags/flag.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" ABSL_FLAG(int, int_flag, 1, "int_flag help"); ABSL_FLAG(std::string, string_flag, "dflt", "string_flag help"); ABSL_RETIRED_FLAG(bool, bool_retired_flag, false, "bool_retired_flag help"); namespace { class ReflectionTest : public testing::Test { protected: void SetUp() override { #if ABSL_FLAGS_STRIP_NAMES GTEST_SKIP() << "This test requires flag names to be present"; #endif flag_saver_ = absl::make_unique<absl::FlagSaver>(); } void TearDown() override { flag_saver_.reset(); } private: std::unique_ptr<absl::FlagSaver> flag_saver_; }; TEST_F(ReflectionTest, TestFindCommandLineFlag) { auto* handle = absl::FindCommandLineFlag("some_flag"); EXPECT_EQ(handle, nullptr); handle = absl::FindCommandLineFlag("int_flag"); EXPECT_NE(handle, nullptr); handle = absl::FindCommandLineFlag("string_flag"); EXPECT_NE(handle, nullptr); handle = absl::FindCommandLineFlag("bool_retired_flag"); EXPECT_NE(handle, nullptr); } TEST_F(ReflectionTest, TestGetAllFlags) { auto all_flags = absl::GetAllFlags(); EXPECT_NE(all_flags.find("int_flag"), all_flags.end()); EXPECT_EQ(all_flags.find("bool_retired_flag"), all_flags.end()); EXPECT_EQ(all_flags.find("some_undefined_flag"), all_flags.end()); std::vector<absl::string_view> flag_names_first_attempt; auto all_flags_1 = absl::GetAllFlags(); for (auto f : all_flags_1) { flag_names_first_attempt.push_back(f.first); } std::vector<absl::string_view> flag_names_second_attempt; auto all_flags_2 = absl::GetAllFlags(); for (auto f : all_flags_2) { flag_names_second_attempt.push_back(f.first); } EXPECT_THAT(flag_names_first_attempt, ::testing::UnorderedElementsAreArray(flag_names_second_attempt)); } struct CustomUDT { CustomUDT() : a(1), b(1) {} CustomUDT(int a_, int b_) : a(a_), b(b_) {} friend bool operator==(const CustomUDT& f1, const CustomUDT& f2) { return f1.a == f2.a && f1.b == f2.b; } int a; int b; }; bool AbslParseFlag(absl::string_view in, CustomUDT* f, std::string*) { std::vector<absl::string_view> parts = absl::StrSplit(in, ':', absl::SkipWhitespace()); if (parts.size() != 2) return false; if (!absl::SimpleAtoi(parts[0], &f->a)) return false; if (!absl::SimpleAtoi(parts[1], &f->b)) return false; return true; } std::string AbslUnparseFlag(const CustomUDT& f) { return absl::StrCat(f.a, ":", f.b); } } ABSL_FLAG(bool, test_flag_01, true, ""); ABSL_FLAG(int, test_flag_02, 1234, ""); ABSL_FLAG(int16_t, test_flag_03, -34, ""); ABSL_FLAG(uint16_t, test_flag_04, 189, ""); ABSL_FLAG(int32_t, test_flag_05, 10765, ""); ABSL_FLAG(uint32_t, test_flag_06, 40000, ""); ABSL_FLAG(int64_t, test_flag_07, -1234567, ""); ABSL_FLAG(uint64_t, test_flag_08, 9876543, ""); ABSL_FLAG(double, test_flag_09, -9.876e-50, ""); ABSL_FLAG(float, test_flag_10, 1.234e12f, ""); ABSL_FLAG(std::string, test_flag_11, "", ""); ABSL_FLAG(absl::Duration, test_flag_12, absl::Minutes(10), ""); static int counter = 0; ABSL_FLAG(int, test_flag_13, 200, "").OnUpdate([]() { counter++; }); ABSL_FLAG(CustomUDT, test_flag_14, {}, ""); namespace { TEST_F(ReflectionTest, TestFlagSaverInScope) { { absl::FlagSaver s; counter = 0; absl::SetFlag(&FLAGS_test_flag_01, false); absl::SetFlag(&FLAGS_test_flag_02, -1021); absl::SetFlag(&FLAGS_test_flag_03, 6009); absl::SetFlag(&FLAGS_test_flag_04, 44); absl::SetFlag(&FLAGS_test_flag_05, +800); absl::SetFlag(&FLAGS_test_flag_06, -40978756); absl::SetFlag(&FLAGS_test_flag_07, 23405); absl::SetFlag(&FLAGS_test_flag_08, 975310); absl::SetFlag(&FLAGS_test_flag_09, 1.00001); absl::SetFlag(&FLAGS_test_flag_10, -3.54f); absl::SetFlag(&FLAGS_test_flag_11, "asdf"); absl::SetFlag(&FLAGS_test_flag_12, absl::Hours(20)); absl::SetFlag(&FLAGS_test_flag_13, 4); absl::SetFlag(&FLAGS_test_flag_14, CustomUDT{-1, -2}); } EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_01), true); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_02), 1234); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_03), -34); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_04), 189); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_05), 10765); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_06), 40000); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_07), -1234567); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), 9876543); EXPECT_NEAR(absl::GetFlag(FLAGS_test_flag_09), -9.876e-50, 1e-55); EXPECT_NEAR(absl::GetFlag(FLAGS_test_flag_10), 1.234e12f, 1e5f); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_11), ""); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_12), absl::Minutes(10)); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_13), 200); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_14), CustomUDT{}); EXPECT_EQ(counter, 2); } TEST_F(ReflectionTest, TestFlagSaverVsUpdateViaReflection) { { absl::FlagSaver s; counter = 0; std::string error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_01")->ParseFrom("false", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_02")->ParseFrom("-4536", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_03")->ParseFrom("111", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_04")->ParseFrom("909", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_05")->ParseFrom("-2004", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_06")->ParseFrom("1000023", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_07")->ParseFrom("69305", &error)) << error; EXPECT_TRUE(absl::FindCommandLineFlag("test_flag_08") ->ParseFrom("1000000001", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_09")->ParseFrom("2.09021", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_10")->ParseFrom("-33.1", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_11")->ParseFrom("ADD_FOO", &error)) << error; EXPECT_TRUE(absl::FindCommandLineFlag("test_flag_12") ->ParseFrom("3h11m16s", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_13")->ParseFrom("0", &error)) << error; EXPECT_TRUE( absl::FindCommandLineFlag("test_flag_14")->ParseFrom("10:1", &error)) << error; } EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_01), true); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_02), 1234); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_03), -34); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_04), 189); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_05), 10765); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_06), 40000); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_07), -1234567); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), 9876543); EXPECT_NEAR(absl::GetFlag(FLAGS_test_flag_09), -9.876e-50, 1e-55); EXPECT_NEAR(absl::GetFlag(FLAGS_test_flag_10), 1.234e12f, 1e5f); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_11), ""); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_12), absl::Minutes(10)); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_13), 200); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_14), CustomUDT{}); EXPECT_EQ(counter, 2); } TEST_F(ReflectionTest, TestMultipleFlagSaversInEnclosedScopes) { { absl::FlagSaver s; absl::SetFlag(&FLAGS_test_flag_08, 10); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), 10); { absl::FlagSaver s; absl::SetFlag(&FLAGS_test_flag_08, 20); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), 20); { absl::FlagSaver s; absl::SetFlag(&FLAGS_test_flag_08, -200); EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), -200); } EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), 20); } EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), 10); } EXPECT_EQ(absl::GetFlag(FLAGS_test_flag_08), 9876543); } }
2,503
#ifndef ABSL_FLAGS_INTERNAL_USAGE_H_ #define ABSL_FLAGS_INTERNAL_USAGE_H_ #include <iosfwd> #include <ostream> #include <string> #include "absl/base/config.h" #include "absl/flags/commandlineflag.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { enum class HelpFormat { kHumanReadable, }; enum class HelpMode { kNone, kImportant, kShort, kFull, kPackage, kMatch, kVersion, kOnlyCheckArgs }; void FlagHelp(std::ostream& out, const CommandLineFlag& flag, HelpFormat format = HelpFormat::kHumanReadable); void FlagsHelp(std::ostream& out, absl::string_view filter, HelpFormat format, absl::string_view program_usage_message); HelpMode HandleUsageFlags(std::ostream& out, absl::string_view program_usage_message); void MaybeExit(HelpMode mode); std::string GetFlagsHelpMatchSubstr(); HelpMode GetFlagsHelpMode(); HelpFormat GetFlagsHelpFormat(); void SetFlagsHelpMatchSubstr(absl::string_view); void SetFlagsHelpMode(HelpMode); void SetFlagsHelpFormat(HelpFormat); bool DeduceUsageFlags(absl::string_view name, absl::string_view value); } ABSL_NAMESPACE_END } #endif #include "absl/flags/internal/usage.h" #include <stdint.h> #include <algorithm> #include <cstdlib> #include <functional> #include <iterator> #include <map> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/const_init.h" #include "absl/base/thread_annotations.h" #include "absl/flags/commandlineflag.h" #include "absl/flags/flag.h" #include "absl/flags/internal/flag.h" #include "absl/flags/internal/path_util.h" #include "absl/flags/internal/private_handle_accessor.h" #include "absl/flags/internal/program_name.h" #include "absl/flags/internal/registry.h" #include "absl/flags/usage_config.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/synchronization/mutex.h" bool FLAGS_help = false; bool FLAGS_helpfull = false; bool FLAGS_helpshort = false; bool FLAGS_helppackage = false; bool FLAGS_version = false; bool FLAGS_only_check_args = false; bool FLAGS_helpon = false; bool FLAGS_helpmatch = false; namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { namespace { using PerFlagFilter = std::function<bool(const absl::CommandLineFlag&)>; constexpr size_t kHrfMaxLineLength = 80; class XMLElement { public: XMLElement(absl::string_view tag, absl::string_view txt) : tag_(tag), txt_(txt) {} friend std::ostream& operator<<(std::ostream& out, const XMLElement& xml_elem) { out << "<" << xml_elem.tag_ << ">"; for (auto c : xml_elem.txt_) { switch (c) { case '"': out << "&quot;"; break; case '\'': out << "&apos;"; break; case '&': out << "&amp;"; break; case '<': out << "&lt;"; break; case '>': out << "&gt;"; break; case '\n': case '\v': case '\f': case '\t': out << " "; break; default: if (IsValidXmlCharacter(static_cast<unsigned char>(c))) { out << c; } break; } } return out << "</" << xml_elem.tag_ << ">"; } private: static bool IsValidXmlCharacter(unsigned char c) { return c >= 0x20; } absl::string_view tag_; absl::string_view txt_; }; class FlagHelpPrettyPrinter { public: FlagHelpPrettyPrinter(size_t max_line_len, size_t min_line_len, size_t wrapped_line_indent, std::ostream& out) : out_(out), max_line_len_(max_line_len), min_line_len_(min_line_len), wrapped_line_indent_(wrapped_line_indent), line_len_(0), first_line_(true) {} void Write(absl::string_view str, bool wrap_line = false) { if (str.empty()) return; std::vector<absl::string_view> tokens; if (wrap_line) { for (auto line : absl::StrSplit(str, absl::ByAnyChar("\n\r"))) { if (!tokens.empty()) { tokens.emplace_back("\n"); } for (auto token : absl::StrSplit(line, absl::ByAnyChar(" \t"), absl::SkipEmpty())) { tokens.push_back(token); } } } else { tokens.push_back(str); } for (auto token : tokens) { bool new_line = (line_len_ == 0); if (token == "\n") { EndLine(); continue; } if (!new_line && (line_len_ + token.size() >= max_line_len_)) { EndLine(); new_line = true; } if (new_line) { StartLine(); } else { out_ << ' '; ++line_len_; } out_ << token; line_len_ += token.size(); } } void StartLine() { if (first_line_) { line_len_ = min_line_len_; first_line_ = false; } else { line_len_ = min_line_len_ + wrapped_line_indent_; } out_ << std::string(line_len_, ' '); } void EndLine() { out_ << '\n'; line_len_ = 0; } private: std::ostream& out_; const size_t max_line_len_; const size_t min_line_len_; const size_t wrapped_line_indent_; size_t line_len_; bool first_line_; }; void FlagHelpHumanReadable(const CommandLineFlag& flag, std::ostream& out) { FlagHelpPrettyPrinter printer(kHrfMaxLineLength, 4, 2, out); printer.Write(absl::StrCat("--", flag.Name())); printer.Write(absl::StrCat("(", flag.Help(), ");"), true); std::string dflt_val = flag.DefaultValue(); std::string curr_val = flag.CurrentValue(); bool is_modified = curr_val != dflt_val; if (flag.IsOfType<std::string>()) { dflt_val = absl::StrCat("\"", dflt_val, "\""); } printer.Write(absl::StrCat("default: ", dflt_val, ";")); if (is_modified) { if (flag.IsOfType<std::string>()) { curr_val = absl::StrCat("\"", curr_val, "\""); } printer.Write(absl::StrCat("currently: ", curr_val, ";")); } printer.EndLine(); } void FlagsHelpImpl(std::ostream& out, PerFlagFilter filter_cb, HelpFormat format, absl::string_view program_usage_message) { if (format == HelpFormat::kHumanReadable) { out << flags_internal::ShortProgramInvocationName() << ": " << program_usage_message << "\n\n"; } else { out << "<?xml version=\"1.0\"?>\n" << "<!-- This output should be used with care. We do not report type " "names for flags with user defined types -->\n" << "<!-- Prefer flag only_check_args for validating flag inputs -->\n" << "<AllFlags>\n" << XMLElement("program", flags_internal::ShortProgramInvocationName()) << '\n' << XMLElement("usage", program_usage_message) << '\n'; } std::map<std::string, std::map<std::string, std::vector<const absl::CommandLineFlag*>>> matching_flags; flags_internal::ForEachFlag([&](absl::CommandLineFlag& flag) { if (flag.IsRetired()) return; if (flag.Help() == flags_internal::kStrippedFlagHelp) return; if (!filter_cb(flag)) return; std::string flag_filename = flag.Filename(); matching_flags[std::string(flags_internal::Package(flag_filename))] [flag_filename] .push_back(&flag); }); absl::string_view package_separator; absl::string_view file_separator; for (auto& package : matching_flags) { if (format == HelpFormat::kHumanReadable) { out << package_separator; package_separator = "\n\n"; } file_separator = ""; for (auto& flags_in_file : package.second) { if (format == HelpFormat::kHumanReadable) { out << file_separator << " Flags from " << flags_in_file.first << ":\n"; file_separator = "\n"; } std::sort(std::begin(flags_in_file.second), std::end(flags_in_file.second), [](const CommandLineFlag* lhs, const CommandLineFlag* rhs) { return lhs->Name() < rhs->Name(); }); for (const auto* flag : flags_in_file.second) { flags_internal::FlagHelp(out, *flag, format); } } } if (format == HelpFormat::kHumanReadable) { FlagHelpPrettyPrinter printer(kHrfMaxLineLength, 0, 0, out); if (filter_cb && matching_flags.empty()) { printer.Write("No flags matched.\n", true); } printer.EndLine(); printer.Write( "Try --helpfull to get a list of all flags or --help=substring " "shows help for flags which include specified substring in either " "in the name, or description or path.\n", true); } else { out << "</AllFlags>\n"; } } void FlagsHelpImpl(std::ostream& out, flags_internal::FlagKindFilter filename_filter_cb, HelpFormat format, absl::string_view program_usage_message) { FlagsHelpImpl( out, [&](const absl::CommandLineFlag& flag) { return filename_filter_cb && filename_filter_cb(flag.Filename()); }, format, program_usage_message); } } void FlagHelp(std::ostream& out, const CommandLineFlag& flag, HelpFormat format) { if (format == HelpFormat::kHumanReadable) flags_internal::FlagHelpHumanReadable(flag, out); } void FlagsHelp(std::ostream& out, absl::string_view filter, HelpFormat format, absl::string_view program_usage_message) { flags_internal::FlagKindFilter filter_cb = [&](absl::string_view filename) { return filter.empty() || absl::StrContains(filename, filter); }; flags_internal::FlagsHelpImpl(out, filter_cb, format, program_usage_message); } HelpMode HandleUsageFlags(std::ostream& out, absl::string_view program_usage_message) { switch (GetFlagsHelpMode()) { case HelpMode::kNone: break; case HelpMode::kImportant: flags_internal::FlagsHelpImpl( out, flags_internal::GetUsageConfig().contains_help_flags, GetFlagsHelpFormat(), program_usage_message); break; case HelpMode::kShort: flags_internal::FlagsHelpImpl( out, flags_internal::GetUsageConfig().contains_helpshort_flags, GetFlagsHelpFormat(), program_usage_message); break; case HelpMode::kFull: flags_internal::FlagsHelp(out, "", GetFlagsHelpFormat(), program_usage_message); break; case HelpMode::kPackage: flags_internal::FlagsHelpImpl( out, flags_internal::GetUsageConfig().contains_helppackage_flags, GetFlagsHelpFormat(), program_usage_message); break; case HelpMode::kMatch: { std::string substr = GetFlagsHelpMatchSubstr(); if (substr.empty()) { flags_internal::FlagsHelp(out, substr, GetFlagsHelpFormat(), program_usage_message); } else { auto filter_cb = [&substr](const absl::CommandLineFlag& flag) { if (absl::StrContains(flag.Name(), substr)) return true; if (absl::StrContains(flag.Filename(), substr)) return true; if (absl::StrContains(flag.Help(), substr)) return true; return false; }; flags_internal::FlagsHelpImpl( out, filter_cb, HelpFormat::kHumanReadable, program_usage_message); } break; } case HelpMode::kVersion: if (flags_internal::GetUsageConfig().version_string) out << flags_internal::GetUsageConfig().version_string(); break; case HelpMode::kOnlyCheckArgs: break; } return GetFlagsHelpMode(); } namespace { ABSL_CONST_INIT absl::Mutex help_attributes_guard(absl::kConstInit); ABSL_CONST_INIT std::string* match_substr ABSL_GUARDED_BY(help_attributes_guard) = nullptr; ABSL_CONST_INIT HelpMode help_mode ABSL_GUARDED_BY(help_attributes_guard) = HelpMode::kNone; ABSL_CONST_INIT HelpFormat help_format ABSL_GUARDED_BY(help_attributes_guard) = HelpFormat::kHumanReadable; } std::string GetFlagsHelpMatchSubstr() { absl::MutexLock l(&help_attributes_guard); if (match_substr == nullptr) return ""; return *match_substr; } void SetFlagsHelpMatchSubstr(absl::string_view substr) { absl::MutexLock l(&help_attributes_guard); if (match_substr == nullptr) match_substr = new std::string; match_substr->assign(substr.data(), substr.size()); } HelpMode GetFlagsHelpMode() { absl::MutexLock l(&help_attributes_guard); return help_mode; } void SetFlagsHelpMode(HelpMode mode) { absl::MutexLock l(&help_attributes_guard); help_mode = mode; } HelpFormat GetFlagsHelpFormat() { absl::MutexLock l(&help_attributes_guard); return help_format; } void SetFlagsHelpFormat(HelpFormat format) { absl::MutexLock l(&help_attributes_guard); help_format = format; } bool DeduceUsageFlags(absl::string_view name, absl::string_view value) { if (absl::ConsumePrefix(&name, "help")) { if (name.empty()) { if (value.empty()) { SetFlagsHelpMode(HelpMode::kImportant); } else { SetFlagsHelpMode(HelpMode::kMatch); SetFlagsHelpMatchSubstr(value); } return true; } if (name == "match") { SetFlagsHelpMode(HelpMode::kMatch); SetFlagsHelpMatchSubstr(value); return true; } if (name == "on") { SetFlagsHelpMode(HelpMode::kMatch); SetFlagsHelpMatchSubstr(absl::StrCat("/", value, ".")); return true; } if (name == "full") { SetFlagsHelpMode(HelpMode::kFull); return true; } if (name == "short") { SetFlagsHelpMode(HelpMode::kShort); return true; } if (name == "package") { SetFlagsHelpMode(HelpMode::kPackage); return true; } return false; } if (name == "version") { SetFlagsHelpMode(HelpMode::kVersion); return true; } if (name == "only_check_args") { SetFlagsHelpMode(HelpMode::kOnlyCheckArgs); return true; } return false; } void MaybeExit(HelpMode mode) { switch (mode) { case flags_internal::HelpMode::kNone: return; case flags_internal::HelpMode::kOnlyCheckArgs: case flags_internal::HelpMode::kVersion: std::exit(0); default: std::exit(1); } } } ABSL_NAMESPACE_END }
#include "absl/flags/internal/usage.h" #include <stdint.h> #include <sstream> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/flags/config.h" #include "absl/flags/flag.h" #include "absl/flags/internal/parse.h" #include "absl/flags/internal/program_name.h" #include "absl/flags/reflection.h" #include "absl/flags/usage.h" #include "absl/flags/usage_config.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" ABSL_FLAG(int, usage_reporting_test_flag_01, 101, "usage_reporting_test_flag_01 help message"); ABSL_FLAG(bool, usage_reporting_test_flag_02, false, "usage_reporting_test_flag_02 help message"); ABSL_FLAG(double, usage_reporting_test_flag_03, 1.03, "usage_reporting_test_flag_03 help message"); ABSL_FLAG(int64_t, usage_reporting_test_flag_04, 1000000000000004L, "usage_reporting_test_flag_04 help message"); ABSL_FLAG(std::string, usage_reporting_test_flag_07, "\r\n\f\v\a\b\t ", "usage_reporting_test_flag_07 help \r\n\f\v\a\b\t "); static const char kTestUsageMessage[] = "Custom usage message"; struct UDT { UDT() = default; UDT(const UDT&) = default; UDT& operator=(const UDT&) = default; }; static bool AbslParseFlag(absl::string_view, UDT*, std::string*) { return true; } static std::string AbslUnparseFlag(const UDT&) { return "UDT{}"; } ABSL_FLAG(UDT, usage_reporting_test_flag_05, {}, "usage_reporting_test_flag_05 help message"); ABSL_FLAG( std::string, usage_reporting_test_flag_06, {}, "usage_reporting_test_flag_06 help message.\n" "\n" "Some more help.\n" "Even more long long long long long long long long long long long long " "help message."); namespace { namespace flags = absl::flags_internal; static std::string NormalizeFileName(absl::string_view fname) { #ifdef _WIN32 std::string normalized(fname); std::replace(normalized.begin(), normalized.end(), '\\', '/'); fname = normalized; #endif auto absl_pos = fname.rfind("absl/"); if (absl_pos != absl::string_view::npos) { fname = fname.substr(absl_pos); } return std::string(fname); } class UsageReportingTest : public testing::Test { protected: UsageReportingTest() { absl::FlagsUsageConfig default_config; default_config.normalize_filename = &NormalizeFileName; absl::SetFlagsUsageConfig(default_config); } ~UsageReportingTest() override { flags::SetFlagsHelpMode(flags::HelpMode::kNone); flags::SetFlagsHelpMatchSubstr(""); flags::SetFlagsHelpFormat(flags::HelpFormat::kHumanReadable); } void SetUp() override { #if ABSL_FLAGS_STRIP_NAMES GTEST_SKIP() << "This test requires flag names to be present"; #endif } private: absl::FlagSaver flag_saver_; }; using UsageReportingDeathTest = UsageReportingTest; TEST_F(UsageReportingDeathTest, TestSetProgramUsageMessage) { #if !defined(GTEST_HAS_ABSL) || !GTEST_HAS_ABSL EXPECT_EQ(absl::ProgramUsageMessage(), kTestUsageMessage); #else EXPECT_THAT(absl::ProgramUsageMessage(), ::testing::HasSubstr( "This program contains tests written using Google Test")); #endif EXPECT_DEATH_IF_SUPPORTED( absl::SetProgramUsageMessage("custom usage message"), ::testing::HasSubstr("SetProgramUsageMessage() called twice")); } TEST_F(UsageReportingTest, TestFlagHelpHRF_on_flag_01) { const auto* flag = absl::FindCommandLineFlag("usage_reporting_test_flag_01"); std::stringstream test_buf; flags::FlagHelp(test_buf, *flag, flags::HelpFormat::kHumanReadable); EXPECT_EQ( test_buf.str(), R"( --usage_reporting_test_flag_01 (usage_reporting_test_flag_01 help message); default: 101; )"); } TEST_F(UsageReportingTest, TestFlagHelpHRF_on_flag_02) { const auto* flag = absl::FindCommandLineFlag("usage_reporting_test_flag_02"); std::stringstream test_buf; flags::FlagHelp(test_buf, *flag, flags::HelpFormat::kHumanReadable); EXPECT_EQ( test_buf.str(), R"( --usage_reporting_test_flag_02 (usage_reporting_test_flag_02 help message); default: false; )"); } TEST_F(UsageReportingTest, TestFlagHelpHRF_on_flag_03) { const auto* flag = absl::FindCommandLineFlag("usage_reporting_test_flag_03"); std::stringstream test_buf; flags::FlagHelp(test_buf, *flag, flags::HelpFormat::kHumanReadable); EXPECT_EQ( test_buf.str(), R"( --usage_reporting_test_flag_03 (usage_reporting_test_flag_03 help message); default: 1.03; )"); } TEST_F(UsageReportingTest, TestFlagHelpHRF_on_flag_04) { const auto* flag = absl::FindCommandLineFlag("usage_reporting_test_flag_04"); std::stringstream test_buf; flags::FlagHelp(test_buf, *flag, flags::HelpFormat::kHumanReadable); EXPECT_EQ( test_buf.str(), R"( --usage_reporting_test_flag_04 (usage_reporting_test_flag_04 help message); default: 1000000000000004; )"); } TEST_F(UsageReportingTest, TestFlagHelpHRF_on_flag_05) { const auto* flag = absl::FindCommandLineFlag("usage_reporting_test_flag_05"); std::stringstream test_buf; flags::FlagHelp(test_buf, *flag, flags::HelpFormat::kHumanReadable); EXPECT_EQ( test_buf.str(), R"( --usage_reporting_test_flag_05 (usage_reporting_test_flag_05 help message); default: UDT{}; )"); } TEST_F(UsageReportingTest, TestFlagsHelpHRF) { std::string usage_test_flags_out = R"(usage_test: Custom usage message Flags from absl/flags/internal/usage_test.cc: --usage_reporting_test_flag_01 (usage_reporting_test_flag_01 help message); default: 101; --usage_reporting_test_flag_02 (usage_reporting_test_flag_02 help message); default: false; --usage_reporting_test_flag_03 (usage_reporting_test_flag_03 help message); default: 1.03; --usage_reporting_test_flag_04 (usage_reporting_test_flag_04 help message); default: 1000000000000004; --usage_reporting_test_flag_05 (usage_reporting_test_flag_05 help message); default: UDT{}; --usage_reporting_test_flag_06 (usage_reporting_test_flag_06 help message. Some more help. Even more long long long long long long long long long long long long help message.); default: "";)" "\n --usage_reporting_test_flag_07 (usage_reporting_test_flag_07 " "help\n\n \f\v\a\b ); default: \"\r\n\f\v\a\b\t \";\n" R"( Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"; std::stringstream test_buf_01; flags::FlagsHelp(test_buf_01, "usage_test.cc", flags::HelpFormat::kHumanReadable, kTestUsageMessage); EXPECT_EQ(test_buf_01.str(), usage_test_flags_out); std::stringstream test_buf_02; flags::FlagsHelp(test_buf_02, "flags/internal/usage_test.cc", flags::HelpFormat::kHumanReadable, kTestUsageMessage); EXPECT_EQ(test_buf_02.str(), usage_test_flags_out); std::stringstream test_buf_03; flags::FlagsHelp(test_buf_03, "usage_test", flags::HelpFormat::kHumanReadable, kTestUsageMessage); EXPECT_EQ(test_buf_03.str(), usage_test_flags_out); std::stringstream test_buf_04; flags::FlagsHelp(test_buf_04, "flags/invalid_file_name.cc", flags::HelpFormat::kHumanReadable, kTestUsageMessage); EXPECT_EQ(test_buf_04.str(), R"(usage_test: Custom usage message No flags matched. Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); std::stringstream test_buf_05; flags::FlagsHelp(test_buf_05, "", flags::HelpFormat::kHumanReadable, kTestUsageMessage); std::string test_out = test_buf_05.str(); absl::string_view test_out_str(test_out); EXPECT_TRUE( absl::StartsWith(test_out_str, "usage_test: Custom usage message")); EXPECT_TRUE(absl::StrContains( test_out_str, "Flags from absl/flags/internal/usage_test.cc:")); EXPECT_TRUE( absl::StrContains(test_out_str, "-usage_reporting_test_flag_01 ")); } TEST_F(UsageReportingTest, TestNoUsageFlags) { std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kNone); } TEST_F(UsageReportingTest, TestUsageFlag_helpshort) { flags::SetFlagsHelpMode(flags::HelpMode::kShort); std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kShort); EXPECT_EQ( test_buf.str(), R"(usage_test: Custom usage message Flags from absl/flags/internal/usage_test.cc: --usage_reporting_test_flag_01 (usage_reporting_test_flag_01 help message); default: 101; --usage_reporting_test_flag_02 (usage_reporting_test_flag_02 help message); default: false; --usage_reporting_test_flag_03 (usage_reporting_test_flag_03 help message); default: 1.03; --usage_reporting_test_flag_04 (usage_reporting_test_flag_04 help message); default: 1000000000000004; --usage_reporting_test_flag_05 (usage_reporting_test_flag_05 help message); default: UDT{}; --usage_reporting_test_flag_06 (usage_reporting_test_flag_06 help message. Some more help. Even more long long long long long long long long long long long long help message.); default: "";)" "\n --usage_reporting_test_flag_07 (usage_reporting_test_flag_07 " "help\n\n \f\v\a\b ); default: \"\r\n\f\v\a\b\t \";\n" R"( Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); } TEST_F(UsageReportingTest, TestUsageFlag_help_simple) { flags::SetFlagsHelpMode(flags::HelpMode::kImportant); std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kImportant); EXPECT_EQ( test_buf.str(), R"(usage_test: Custom usage message Flags from absl/flags/internal/usage_test.cc: --usage_reporting_test_flag_01 (usage_reporting_test_flag_01 help message); default: 101; --usage_reporting_test_flag_02 (usage_reporting_test_flag_02 help message); default: false; --usage_reporting_test_flag_03 (usage_reporting_test_flag_03 help message); default: 1.03; --usage_reporting_test_flag_04 (usage_reporting_test_flag_04 help message); default: 1000000000000004; --usage_reporting_test_flag_05 (usage_reporting_test_flag_05 help message); default: UDT{}; --usage_reporting_test_flag_06 (usage_reporting_test_flag_06 help message. Some more help. Even more long long long long long long long long long long long long help message.); default: "";)" "\n --usage_reporting_test_flag_07 (usage_reporting_test_flag_07 " "help\n\n \f\v\a\b ); default: \"\r\n\f\v\a\b\t \";\n" R"( Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); } TEST_F(UsageReportingTest, TestUsageFlag_help_one_flag) { flags::SetFlagsHelpMode(flags::HelpMode::kMatch); flags::SetFlagsHelpMatchSubstr("usage_reporting_test_flag_06"); std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kMatch); EXPECT_EQ(test_buf.str(), R"(usage_test: Custom usage message Flags from absl/flags/internal/usage_test.cc: --usage_reporting_test_flag_06 (usage_reporting_test_flag_06 help message. Some more help. Even more long long long long long long long long long long long long help message.); default: ""; Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); } TEST_F(UsageReportingTest, TestUsageFlag_help_multiple_flag) { flags::SetFlagsHelpMode(flags::HelpMode::kMatch); flags::SetFlagsHelpMatchSubstr("test_flag"); std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kMatch); EXPECT_EQ( test_buf.str(), R"(usage_test: Custom usage message Flags from absl/flags/internal/usage_test.cc: --usage_reporting_test_flag_01 (usage_reporting_test_flag_01 help message); default: 101; --usage_reporting_test_flag_02 (usage_reporting_test_flag_02 help message); default: false; --usage_reporting_test_flag_03 (usage_reporting_test_flag_03 help message); default: 1.03; --usage_reporting_test_flag_04 (usage_reporting_test_flag_04 help message); default: 1000000000000004; --usage_reporting_test_flag_05 (usage_reporting_test_flag_05 help message); default: UDT{}; --usage_reporting_test_flag_06 (usage_reporting_test_flag_06 help message. Some more help. Even more long long long long long long long long long long long long help message.); default: "";)" "\n --usage_reporting_test_flag_07 (usage_reporting_test_flag_07 " "help\n\n \f\v\a\b ); default: \"\r\n\f\v\a\b\t \";\n" R"( Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); } TEST_F(UsageReportingTest, TestUsageFlag_helppackage) { flags::SetFlagsHelpMode(flags::HelpMode::kPackage); std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kPackage); EXPECT_EQ( test_buf.str(), R"(usage_test: Custom usage message Flags from absl/flags/internal/usage_test.cc: --usage_reporting_test_flag_01 (usage_reporting_test_flag_01 help message); default: 101; --usage_reporting_test_flag_02 (usage_reporting_test_flag_02 help message); default: false; --usage_reporting_test_flag_03 (usage_reporting_test_flag_03 help message); default: 1.03; --usage_reporting_test_flag_04 (usage_reporting_test_flag_04 help message); default: 1000000000000004; --usage_reporting_test_flag_05 (usage_reporting_test_flag_05 help message); default: UDT{}; --usage_reporting_test_flag_06 (usage_reporting_test_flag_06 help message. Some more help. Even more long long long long long long long long long long long long help message.); default: "";)" "\n --usage_reporting_test_flag_07 (usage_reporting_test_flag_07 " "help\n\n \f\v\a\b ); default: \"\r\n\f\v\a\b\t \";\n" R"( Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); } TEST_F(UsageReportingTest, TestUsageFlag_version) { flags::SetFlagsHelpMode(flags::HelpMode::kVersion); std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kVersion); #ifndef NDEBUG EXPECT_EQ(test_buf.str(), "usage_test\nDebug build (NDEBUG not #defined)\n"); #else EXPECT_EQ(test_buf.str(), "usage_test\n"); #endif } TEST_F(UsageReportingTest, TestUsageFlag_only_check_args) { flags::SetFlagsHelpMode(flags::HelpMode::kOnlyCheckArgs); std::stringstream test_buf; EXPECT_EQ(flags::HandleUsageFlags(test_buf, kTestUsageMessage), flags::HelpMode::kOnlyCheckArgs); EXPECT_EQ(test_buf.str(), ""); } TEST_F(UsageReportingTest, TestUsageFlag_helpon) { flags::SetFlagsHelpMode(flags::HelpMode::kMatch); flags::SetFlagsHelpMatchSubstr("/bla-bla."); std::stringstream test_buf_01; EXPECT_EQ(flags::HandleUsageFlags(test_buf_01, kTestUsageMessage), flags::HelpMode::kMatch); EXPECT_EQ(test_buf_01.str(), R"(usage_test: Custom usage message No flags matched. Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); flags::SetFlagsHelpMatchSubstr("/usage_test."); std::stringstream test_buf_02; EXPECT_EQ(flags::HandleUsageFlags(test_buf_02, kTestUsageMessage), flags::HelpMode::kMatch); EXPECT_EQ( test_buf_02.str(), R"(usage_test: Custom usage message Flags from absl/flags/internal/usage_test.cc: --usage_reporting_test_flag_01 (usage_reporting_test_flag_01 help message); default: 101; --usage_reporting_test_flag_02 (usage_reporting_test_flag_02 help message); default: false; --usage_reporting_test_flag_03 (usage_reporting_test_flag_03 help message); default: 1.03; --usage_reporting_test_flag_04 (usage_reporting_test_flag_04 help message); default: 1000000000000004; --usage_reporting_test_flag_05 (usage_reporting_test_flag_05 help message); default: UDT{}; --usage_reporting_test_flag_06 (usage_reporting_test_flag_06 help message. Some more help. Even more long long long long long long long long long long long long help message.); default: "";)" "\n --usage_reporting_test_flag_07 (usage_reporting_test_flag_07 " "help\n\n \f\v\a\b ); default: \"\r\n\f\v\a\b\t \";\n" R"( Try --helpfull to get a list of all flags or --help=substring shows help for flags which include specified substring in either in the name, or description or path. )"); } } int main(int argc, char* argv[]) { (void)absl::GetFlag(FLAGS_undefok); flags::SetProgramInvocationName("usage_test"); #if !defined(GTEST_HAS_ABSL) || !GTEST_HAS_ABSL absl::SetProgramUsageMessage(kTestUsageMessage); #endif ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
2,504
#ifndef ABSL_FLAGS_MARSHALLING_H_ #define ABSL_FLAGS_MARSHALLING_H_ #include "absl/base/config.h" #include "absl/numeric/int128.h" #if defined(ABSL_HAVE_STD_OPTIONAL) && !defined(ABSL_USES_STD_OPTIONAL) #include <optional> #endif #include <string> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/optional.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename T> inline bool ParseFlag(absl::string_view input, T* dst, std::string* error); template <typename T> inline std::string UnparseFlag(const T& v); namespace flags_internal { bool AbslParseFlag(absl::string_view, bool*, std::string*); bool AbslParseFlag(absl::string_view, short*, std::string*); bool AbslParseFlag(absl::string_view, unsigned short*, std::string*); bool AbslParseFlag(absl::string_view, int*, std::string*); bool AbslParseFlag(absl::string_view, unsigned int*, std::string*); bool AbslParseFlag(absl::string_view, long*, std::string*); bool AbslParseFlag(absl::string_view, unsigned long*, std::string*); bool AbslParseFlag(absl::string_view, long long*, std::string*); bool AbslParseFlag(absl::string_view, unsigned long long*, std::string*); bool AbslParseFlag(absl::string_view, absl::int128*, std::string*); bool AbslParseFlag(absl::string_view, absl::uint128*, std::string*); bool AbslParseFlag(absl::string_view, float*, std::string*); bool AbslParseFlag(absl::string_view, double*, std::string*); bool AbslParseFlag(absl::string_view, std::string*, std::string*); bool AbslParseFlag(absl::string_view, std::vector<std::string>*, std::string*); template <typename T> bool AbslParseFlag(absl::string_view text, absl::optional<T>* f, std::string* err) { if (text.empty()) { *f = absl::nullopt; return true; } T value; if (!absl::ParseFlag(text, &value, err)) return false; *f = std::move(value); return true; } #if defined(ABSL_HAVE_STD_OPTIONAL) && !defined(ABSL_USES_STD_OPTIONAL) template <typename T> bool AbslParseFlag(absl::string_view text, std::optional<T>* f, std::string* err) { if (text.empty()) { *f = std::nullopt; return true; } T value; if (!absl::ParseFlag(text, &value, err)) return false; *f = std::move(value); return true; } #endif template <typename T> bool InvokeParseFlag(absl::string_view input, T* dst, std::string* err) { return AbslParseFlag(input, dst, err); } std::string AbslUnparseFlag(absl::string_view v); std::string AbslUnparseFlag(const std::vector<std::string>&); template <typename T> std::string AbslUnparseFlag(const absl::optional<T>& f) { return f.has_value() ? absl::UnparseFlag(*f) : ""; } #if defined(ABSL_HAVE_STD_OPTIONAL) && !defined(ABSL_USES_STD_OPTIONAL) template <typename T> std::string AbslUnparseFlag(const std::optional<T>& f) { return f.has_value() ? absl::UnparseFlag(*f) : ""; } #endif template <typename T> std::string Unparse(const T& v) { return AbslUnparseFlag(v); } std::string Unparse(bool v); std::string Unparse(short v); std::string Unparse(unsigned short v); std::string Unparse(int v); std::string Unparse(unsigned int v); std::string Unparse(long v); std::string Unparse(unsigned long v); std::string Unparse(long long v); std::string Unparse(unsigned long long v); std::string Unparse(absl::int128 v); std::string Unparse(absl::uint128 v); std::string Unparse(float v); std::string Unparse(double v); } template <typename T> inline bool ParseFlag(absl::string_view input, T* dst, std::string* error) { return flags_internal::InvokeParseFlag(input, dst, error); } template <typename T> inline std::string UnparseFlag(const T& v) { return flags_internal::Unparse(v); } enum class LogSeverity : int; bool AbslParseFlag(absl::string_view, absl::LogSeverity*, std::string*); std::string AbslUnparseFlag(absl::LogSeverity); ABSL_NAMESPACE_END } #endif #include "absl/flags/marshalling.h" #include <stddef.h> #include <cmath> #include <limits> #include <sstream> #include <string> #include <type_traits> #include <vector> #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/base/macros.h" #include "absl/numeric/int128.h" #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { bool AbslParseFlag(absl::string_view text, bool* dst, std::string*) { const char* kTrue[] = {"1", "t", "true", "y", "yes"}; const char* kFalse[] = {"0", "f", "false", "n", "no"}; static_assert(sizeof(kTrue) == sizeof(kFalse), "true_false_equal"); text = absl::StripAsciiWhitespace(text); for (size_t i = 0; i < ABSL_ARRAYSIZE(kTrue); ++i) { if (absl::EqualsIgnoreCase(text, kTrue[i])) { *dst = true; return true; } else if (absl::EqualsIgnoreCase(text, kFalse[i])) { *dst = false; return true; } } return false; } static int NumericBase(absl::string_view text) { if (text.empty()) return 0; size_t num_start = (text[0] == '-' || text[0] == '+') ? 1 : 0; const bool hex = (text.size() >= num_start + 2 && text[num_start] == '0' && (text[num_start + 1] == 'x' || text[num_start + 1] == 'X')); return hex ? 16 : 10; } template <typename IntType> inline bool ParseFlagImpl(absl::string_view text, IntType& dst) { text = absl::StripAsciiWhitespace(text); return absl::numbers_internal::safe_strtoi_base(text, &dst, NumericBase(text)); } bool AbslParseFlag(absl::string_view text, short* dst, std::string*) { int val; if (!ParseFlagImpl(text, val)) return false; if (static_cast<short>(val) != val) return false; *dst = static_cast<short>(val); return true; } bool AbslParseFlag(absl::string_view text, unsigned short* dst, std::string*) { unsigned int val; if (!ParseFlagImpl(text, val)) return false; if (static_cast<unsigned short>(val) != val) return false; *dst = static_cast<unsigned short>(val); return true; } bool AbslParseFlag(absl::string_view text, int* dst, std::string*) { return ParseFlagImpl(text, *dst); } bool AbslParseFlag(absl::string_view text, unsigned int* dst, std::string*) { return ParseFlagImpl(text, *dst); } bool AbslParseFlag(absl::string_view text, long* dst, std::string*) { return ParseFlagImpl(text, *dst); } bool AbslParseFlag(absl::string_view text, unsigned long* dst, std::string*) { return ParseFlagImpl(text, *dst); } bool AbslParseFlag(absl::string_view text, long long* dst, std::string*) { return ParseFlagImpl(text, *dst); } bool AbslParseFlag(absl::string_view text, unsigned long long* dst, std::string*) { return ParseFlagImpl(text, *dst); } bool AbslParseFlag(absl::string_view text, absl::int128* dst, std::string*) { text = absl::StripAsciiWhitespace(text); int base = NumericBase(text); if (!absl::numbers_internal::safe_strto128_base(text, dst, base)) { return false; } return base == 16 ? absl::SimpleHexAtoi(text, dst) : absl::SimpleAtoi(text, dst); } bool AbslParseFlag(absl::string_view text, absl::uint128* dst, std::string*) { text = absl::StripAsciiWhitespace(text); int base = NumericBase(text); if (!absl::numbers_internal::safe_strtou128_base(text, dst, base)) { return false; } return base == 16 ? absl::SimpleHexAtoi(text, dst) : absl::SimpleAtoi(text, dst); } bool AbslParseFlag(absl::string_view text, float* dst, std::string*) { return absl::SimpleAtof(text, dst); } bool AbslParseFlag(absl::string_view text, double* dst, std::string*) { return absl::SimpleAtod(text, dst); } bool AbslParseFlag(absl::string_view text, std::string* dst, std::string*) { dst->assign(text.data(), text.size()); return true; } bool AbslParseFlag(absl::string_view text, std::vector<std::string>* dst, std::string*) { if (text.empty()) { dst->clear(); return true; } *dst = absl::StrSplit(text, ',', absl::AllowEmpty()); return true; } std::string Unparse(bool v) { return v ? "true" : "false"; } std::string Unparse(short v) { return absl::StrCat(v); } std::string Unparse(unsigned short v) { return absl::StrCat(v); } std::string Unparse(int v) { return absl::StrCat(v); } std::string Unparse(unsigned int v) { return absl::StrCat(v); } std::string Unparse(long v) { return absl::StrCat(v); } std::string Unparse(unsigned long v) { return absl::StrCat(v); } std::string Unparse(long long v) { return absl::StrCat(v); } std::string Unparse(unsigned long long v) { return absl::StrCat(v); } std::string Unparse(absl::int128 v) { std::stringstream ss; ss << v; return ss.str(); } std::string Unparse(absl::uint128 v) { std::stringstream ss; ss << v; return ss.str(); } template <typename T> std::string UnparseFloatingPointVal(T v) { std::string digit10_str = absl::StrFormat("%.*g", std::numeric_limits<T>::digits10, v); if (std::isnan(v) || std::isinf(v)) return digit10_str; T roundtrip_val = 0; std::string err; if (absl::ParseFlag(digit10_str, &roundtrip_val, &err) && roundtrip_val == v) { return digit10_str; } return absl::StrFormat("%.*g", std::numeric_limits<T>::max_digits10, v); } std::string Unparse(float v) { return UnparseFloatingPointVal(v); } std::string Unparse(double v) { return UnparseFloatingPointVal(v); } std::string AbslUnparseFlag(absl::string_view v) { return std::string(v); } std::string AbslUnparseFlag(const std::vector<std::string>& v) { return absl::StrJoin(v, ","); } } bool AbslParseFlag(absl::string_view text, absl::LogSeverity* dst, std::string* err) { text = absl::StripAsciiWhitespace(text); if (text.empty()) { *err = "no value provided"; return false; } if (absl::EqualsIgnoreCase(text, "dfatal")) { *dst = absl::kLogDebugFatal; return true; } if (absl::EqualsIgnoreCase(text, "klogdebugfatal")) { *dst = absl::kLogDebugFatal; return true; } if (text.front() == 'k' || text.front() == 'K') text.remove_prefix(1); if (absl::EqualsIgnoreCase(text, "info")) { *dst = absl::LogSeverity::kInfo; return true; } if (absl::EqualsIgnoreCase(text, "warning")) { *dst = absl::LogSeverity::kWarning; return true; } if (absl::EqualsIgnoreCase(text, "error")) { *dst = absl::LogSeverity::kError; return true; } if (absl::EqualsIgnoreCase(text, "fatal")) { *dst = absl::LogSeverity::kFatal; return true; } std::underlying_type<absl::LogSeverity>::type numeric_value; if (absl::ParseFlag(text, &numeric_value, err)) { *dst = static_cast<absl::LogSeverity>(numeric_value); return true; } *err = "only integers, absl::LogSeverity enumerators, and DFATAL are accepted"; return false; } std::string AbslUnparseFlag(absl::LogSeverity v) { if (v == absl::NormalizeLogSeverity(v)) return absl::LogSeverityName(v); return absl::UnparseFlag(static_cast<int>(v)); } ABSL_NAMESPACE_END }
#include "absl/flags/marshalling.h" #include <stdint.h> #include <cmath> #include <limits> #include <string> #include <vector> #include "gtest/gtest.h" namespace { TEST(MarshallingTest, TestBoolParsing) { std::string err; bool value; EXPECT_TRUE(absl::ParseFlag("True", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("true", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("TRUE", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("Yes", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("yes", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("YES", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("t", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("T", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("y", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("Y", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("False", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("false", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("FALSE", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("No", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("no", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("NO", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("f", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("F", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("n", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("N", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_FALSE(value); EXPECT_TRUE(absl::ParseFlag(" true", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag("true ", &value, &err)); EXPECT_TRUE(value); EXPECT_TRUE(absl::ParseFlag(" true ", &value, &err)); EXPECT_TRUE(value); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2", &value, &err)); EXPECT_FALSE(absl::ParseFlag("11", &value, &err)); EXPECT_FALSE(absl::ParseFlag("tt", &value, &err)); } TEST(MarshallingTest, TestInt16Parsing) { std::string err; int16_t value; EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("-1", &value, &err)); EXPECT_EQ(value, -1); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("-18765", &value, &err)); EXPECT_EQ(value, -18765); EXPECT_TRUE(absl::ParseFlag("+3", &value, &err)); EXPECT_EQ(value, 3); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("-001", &value, &err)); EXPECT_EQ(value, -1); EXPECT_TRUE(absl::ParseFlag("0000100", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0X234", &value, &err)); EXPECT_EQ(value, 564); EXPECT_TRUE(absl::ParseFlag("-0x7FFD", &value, &err)); EXPECT_EQ(value, -32765); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("10 ", &value, &err)); EXPECT_EQ(value, 10); EXPECT_TRUE(absl::ParseFlag(" 11", &value, &err)); EXPECT_EQ(value, 11); EXPECT_TRUE(absl::ParseFlag(" 012 ", &value, &err)); EXPECT_EQ(value, 12); EXPECT_TRUE(absl::ParseFlag(" 0x22 ", &value, &err)); EXPECT_EQ(value, 34); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("40000", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); } TEST(MarshallingTest, TestUint16Parsing) { std::string err; uint16_t value; EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("+3", &value, &err)); EXPECT_EQ(value, 3); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("001", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0000100", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0X234", &value, &err)); EXPECT_EQ(value, 564); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("10 ", &value, &err)); EXPECT_EQ(value, 10); EXPECT_TRUE(absl::ParseFlag(" 11", &value, &err)); EXPECT_EQ(value, 11); EXPECT_TRUE(absl::ParseFlag(" 012 ", &value, &err)); EXPECT_EQ(value, 12); EXPECT_TRUE(absl::ParseFlag(" 0x22 ", &value, &err)); EXPECT_EQ(value, 34); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("70000", &value, &err)); EXPECT_FALSE(absl::ParseFlag("-1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); } TEST(MarshallingTest, TestInt32Parsing) { std::string err; int32_t value; EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("-1", &value, &err)); EXPECT_EQ(value, -1); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("-98765", &value, &err)); EXPECT_EQ(value, -98765); EXPECT_TRUE(absl::ParseFlag("+3", &value, &err)); EXPECT_EQ(value, 3); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("-001", &value, &err)); EXPECT_EQ(value, -1); EXPECT_TRUE(absl::ParseFlag("0000100", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0X234", &value, &err)); EXPECT_EQ(value, 564); EXPECT_TRUE(absl::ParseFlag("-0x7FFFFFFD", &value, &err)); EXPECT_EQ(value, -2147483645); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("10 ", &value, &err)); EXPECT_EQ(value, 10); EXPECT_TRUE(absl::ParseFlag(" 11", &value, &err)); EXPECT_EQ(value, 11); EXPECT_TRUE(absl::ParseFlag(" 012 ", &value, &err)); EXPECT_EQ(value, 12); EXPECT_TRUE(absl::ParseFlag(" 0x22 ", &value, &err)); EXPECT_EQ(value, 34); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("70000000000", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); } TEST(MarshallingTest, TestUint32Parsing) { std::string err; uint32_t value; EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("+3", &value, &err)); EXPECT_EQ(value, 3); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0000100", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0X234", &value, &err)); EXPECT_EQ(value, 564); EXPECT_TRUE(absl::ParseFlag("0xFFFFFFFD", &value, &err)); EXPECT_EQ(value, 4294967293); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("10 ", &value, &err)); EXPECT_EQ(value, 10); EXPECT_TRUE(absl::ParseFlag(" 11", &value, &err)); EXPECT_EQ(value, 11); EXPECT_TRUE(absl::ParseFlag(" 012 ", &value, &err)); EXPECT_EQ(value, 12); EXPECT_TRUE(absl::ParseFlag(" 0x22 ", &value, &err)); EXPECT_EQ(value, 34); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("140000000000", &value, &err)); EXPECT_FALSE(absl::ParseFlag("-1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); } TEST(MarshallingTest, TestInt64Parsing) { std::string err; int64_t value; EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("-1", &value, &err)); EXPECT_EQ(value, -1); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("-98765", &value, &err)); EXPECT_EQ(value, -98765); EXPECT_TRUE(absl::ParseFlag("+3", &value, &err)); EXPECT_EQ(value, 3); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("001", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0000100", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0XFFFAAABBBCCCDDD", &value, &err)); EXPECT_EQ(value, 1152827684197027293); EXPECT_TRUE(absl::ParseFlag("-0x7FFFFFFFFFFFFFFE", &value, &err)); EXPECT_EQ(value, -9223372036854775806); EXPECT_TRUE(absl::ParseFlag("-0x02", &value, &err)); EXPECT_EQ(value, -2); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("10 ", &value, &err)); EXPECT_EQ(value, 10); EXPECT_TRUE(absl::ParseFlag(" 11", &value, &err)); EXPECT_EQ(value, 11); EXPECT_TRUE(absl::ParseFlag(" 012 ", &value, &err)); EXPECT_EQ(value, 12); EXPECT_TRUE(absl::ParseFlag(" 0x7F ", &value, &err)); EXPECT_EQ(value, 127); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("0xFFFFFFFFFFFFFFFFFF", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); } TEST(MarshallingTest, TestUInt64Parsing) { std::string err; uint64_t value; EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("+13", &value, &err)); EXPECT_EQ(value, 13); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("001", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0000300", &value, &err)); EXPECT_EQ(value, 300); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0XFFFF", &value, &err)); EXPECT_EQ(value, 65535); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("10 ", &value, &err)); EXPECT_EQ(value, 10); EXPECT_TRUE(absl::ParseFlag(" 11", &value, &err)); EXPECT_EQ(value, 11); EXPECT_TRUE(absl::ParseFlag(" 012 ", &value, &err)); EXPECT_EQ(value, 12); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("0xFFFFFFFFFFFFFFFFFF", &value, &err)); EXPECT_FALSE(absl::ParseFlag("-1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); } TEST(MarshallingTest, TestInt128Parsing) { std::string err; absl::int128 value; EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("-1", &value, &err)); EXPECT_EQ(value, -1); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("-98765", &value, &err)); EXPECT_EQ(value, -98765); EXPECT_TRUE(absl::ParseFlag("+3", &value, &err)); EXPECT_EQ(value, 3); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("001", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0000100", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0xFFFAAABBBCCCDDD", &value, &err)); EXPECT_EQ(value, 1152827684197027293); EXPECT_TRUE(absl::ParseFlag("0xFFF0FFFFFFFFFFFFFFF", &value, &err)); EXPECT_EQ(value, absl::MakeInt128(0x000000000000fff, 0xFFFFFFFFFFFFFFF)); EXPECT_TRUE(absl::ParseFlag("-0x10000000000000000", &value, &err)); EXPECT_EQ(value, absl::MakeInt128(-1, 0)); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("16 ", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag(" 16", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag(" 0100 ", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag(" 0x7B ", &value, &err)); EXPECT_EQ(value, 123); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); } TEST(MarshallingTest, TestUint128Parsing) { std::string err; absl::uint128 value; EXPECT_TRUE(absl::ParseFlag("0", &value, &err)); EXPECT_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("123", &value, &err)); EXPECT_EQ(value, 123); EXPECT_TRUE(absl::ParseFlag("+3", &value, &err)); EXPECT_EQ(value, 3); EXPECT_TRUE(absl::ParseFlag("01", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("001", &value, &err)); EXPECT_EQ(value, 1); EXPECT_TRUE(absl::ParseFlag("0000100", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag("0x10", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag("0xFFFAAABBBCCCDDD", &value, &err)); EXPECT_EQ(value, 1152827684197027293); EXPECT_TRUE(absl::ParseFlag("0xFFF0FFFFFFFFFFFFFFF", &value, &err)); EXPECT_EQ(value, absl::MakeInt128(0x000000000000fff, 0xFFFFFFFFFFFFFFF)); EXPECT_TRUE(absl::ParseFlag("+0x31", &value, &err)); EXPECT_EQ(value, 49); EXPECT_TRUE(absl::ParseFlag("16 ", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag(" 16", &value, &err)); EXPECT_EQ(value, 16); EXPECT_TRUE(absl::ParseFlag(" 0100 ", &value, &err)); EXPECT_EQ(value, 100); EXPECT_TRUE(absl::ParseFlag(" 0x7B ", &value, &err)); EXPECT_EQ(value, 123); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("-1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2U", &value, &err)); EXPECT_FALSE(absl::ParseFlag("FFF", &value, &err)); EXPECT_FALSE(absl::ParseFlag("-0x10000000000000000", &value, &err)); } TEST(MarshallingTest, TestFloatParsing) { std::string err; float value; EXPECT_TRUE(absl::ParseFlag("1.3", &value, &err)); EXPECT_FLOAT_EQ(value, 1.3f); EXPECT_TRUE(absl::ParseFlag("-0.1", &value, &err)); EXPECT_DOUBLE_EQ(value, -0.1f); EXPECT_TRUE(absl::ParseFlag("+0.01", &value, &err)); EXPECT_DOUBLE_EQ(value, 0.01f); EXPECT_TRUE(absl::ParseFlag("1.2e3", &value, &err)); EXPECT_DOUBLE_EQ(value, 1.2e3f); EXPECT_TRUE(absl::ParseFlag("9.8765402e-37", &value, &err)); EXPECT_DOUBLE_EQ(value, 9.8765402e-37f); EXPECT_TRUE(absl::ParseFlag("0.11e+3", &value, &err)); EXPECT_DOUBLE_EQ(value, 0.11e+3f); EXPECT_TRUE(absl::ParseFlag("1.e-2300", &value, &err)); EXPECT_DOUBLE_EQ(value, 0.f); EXPECT_TRUE(absl::ParseFlag("1.e+2300", &value, &err)); EXPECT_TRUE(std::isinf(value)); EXPECT_TRUE(absl::ParseFlag("01.6", &value, &err)); EXPECT_DOUBLE_EQ(value, 1.6f); EXPECT_TRUE(absl::ParseFlag("000.0001", &value, &err)); EXPECT_DOUBLE_EQ(value, 0.0001f); EXPECT_TRUE(absl::ParseFlag("-5.1000", &value, &err)); EXPECT_DOUBLE_EQ(value, -5.1f); EXPECT_TRUE(absl::ParseFlag("NaN", &value, &err)); EXPECT_TRUE(std::isnan(value)); EXPECT_TRUE(absl::ParseFlag("Inf", &value, &err)); EXPECT_TRUE(std::isinf(value)); EXPECT_TRUE(absl::ParseFlag("0x10.23p12", &value, &err)); EXPECT_DOUBLE_EQ(value, 66096.f); EXPECT_TRUE(absl::ParseFlag("-0xF1.A3p-2", &value, &err)); EXPECT_NEAR(value, -60.4092f, 5e-5f); EXPECT_TRUE(absl::ParseFlag("+0x0.0AAp-12", &value, &err)); EXPECT_NEAR(value, 1.01328e-05f, 5e-11f); EXPECT_TRUE(absl::ParseFlag("0x.01p1", &value, &err)); EXPECT_NEAR(value, 0.0078125f, 5e-8f); EXPECT_TRUE(absl::ParseFlag("10.1 ", &value, &err)); EXPECT_DOUBLE_EQ(value, 10.1f); EXPECT_TRUE(absl::ParseFlag(" 2.34", &value, &err)); EXPECT_DOUBLE_EQ(value, 2.34f); EXPECT_TRUE(absl::ParseFlag(" 5.7 ", &value, &err)); EXPECT_DOUBLE_EQ(value, 5.7f); EXPECT_TRUE(absl::ParseFlag(" -0xE0.F3p01 ", &value, &err)); EXPECT_NEAR(value, -449.8984375f, 5e-8f); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2.3xxx", &value, &err)); EXPECT_FALSE(absl::ParseFlag("0x0.1pAA", &value, &err)); EXPECT_TRUE(absl::ParseFlag("0x0.1", &value, &err)); } TEST(MarshallingTest, TestDoubleParsing) { std::string err; double value; EXPECT_TRUE(absl::ParseFlag("1.3", &value, &err)); EXPECT_DOUBLE_EQ(value, 1.3); EXPECT_TRUE(absl::ParseFlag("-0.1", &value, &err)); EXPECT_DOUBLE_EQ(value, -0.1); EXPECT_TRUE(absl::ParseFlag("+0.01", &value, &err)); EXPECT_DOUBLE_EQ(value, 0.01); EXPECT_TRUE(absl::ParseFlag("1.2e3", &value, &err)); EXPECT_DOUBLE_EQ(value, 1.2e3); EXPECT_TRUE(absl::ParseFlag("9.00000002e-123", &value, &err)); EXPECT_DOUBLE_EQ(value, 9.00000002e-123); EXPECT_TRUE(absl::ParseFlag("0.11e+3", &value, &err)); EXPECT_DOUBLE_EQ(value, 0.11e+3); EXPECT_TRUE(absl::ParseFlag("1.e-2300", &value, &err)); EXPECT_DOUBLE_EQ(value, 0); EXPECT_TRUE(absl::ParseFlag("1.e+2300", &value, &err)); EXPECT_TRUE(std::isinf(value)); EXPECT_TRUE(absl::ParseFlag("01.6", &value, &err)); EXPECT_DOUBLE_EQ(value, 1.6); EXPECT_TRUE(absl::ParseFlag("000.0001", &value, &err)); EXPECT_DOUBLE_EQ(value, 0.0001); EXPECT_TRUE(absl::ParseFlag("-5.1000", &value, &err)); EXPECT_DOUBLE_EQ(value, -5.1); EXPECT_TRUE(absl::ParseFlag("NaN", &value, &err)); EXPECT_TRUE(std::isnan(value)); EXPECT_TRUE(absl::ParseFlag("nan", &value, &err)); EXPECT_TRUE(std::isnan(value)); EXPECT_TRUE(absl::ParseFlag("Inf", &value, &err)); EXPECT_TRUE(std::isinf(value)); EXPECT_TRUE(absl::ParseFlag("inf", &value, &err)); EXPECT_TRUE(std::isinf(value)); EXPECT_TRUE(absl::ParseFlag("0x10.23p12", &value, &err)); EXPECT_DOUBLE_EQ(value, 66096); EXPECT_TRUE(absl::ParseFlag("-0xF1.A3p-2", &value, &err)); EXPECT_NEAR(value, -60.4092, 5e-5); EXPECT_TRUE(absl::ParseFlag("+0x0.0AAp-12", &value, &err)); EXPECT_NEAR(value, 1.01328e-05, 5e-11); EXPECT_TRUE(absl::ParseFlag("0x.01p1", &value, &err)); EXPECT_NEAR(value, 0.0078125, 5e-8); EXPECT_TRUE(absl::ParseFlag("10.1 ", &value, &err)); EXPECT_DOUBLE_EQ(value, 10.1); EXPECT_TRUE(absl::ParseFlag(" 2.34", &value, &err)); EXPECT_DOUBLE_EQ(value, 2.34); EXPECT_TRUE(absl::ParseFlag(" 5.7 ", &value, &err)); EXPECT_DOUBLE_EQ(value, 5.7); EXPECT_TRUE(absl::ParseFlag(" -0xE0.F3p01 ", &value, &err)); EXPECT_NEAR(value, -449.8984375, 5e-8); EXPECT_FALSE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag(" ", &value, &err)); EXPECT_FALSE(absl::ParseFlag("--1", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\n", &value, &err)); EXPECT_FALSE(absl::ParseFlag("\t", &value, &err)); EXPECT_FALSE(absl::ParseFlag("2.3xxx", &value, &err)); EXPECT_FALSE(absl::ParseFlag("0x0.1pAA", &value, &err)); EXPECT_TRUE(absl::ParseFlag("0x0.1", &value, &err)); } TEST(MarshallingTest, TestStringParsing) { std::string err; std::string value; EXPECT_TRUE(absl::ParseFlag("", &value, &err)); EXPECT_EQ(value, ""); EXPECT_TRUE(absl::ParseFlag(" ", &value, &err)); EXPECT_EQ(value, " "); EXPECT_TRUE(absl::ParseFlag(" ", &value, &err)); EXPECT_EQ(value, " "); EXPECT_TRUE(absl::ParseFlag("\n", &value, &err)); EXPECT_EQ(value, "\n"); EXPECT_TRUE(absl::ParseFlag("\t", &value, &err)); EXPECT_EQ(value, "\t"); EXPECT_TRUE(absl::ParseFlag("asdfg", &value, &err)); EXPECT_EQ(value, "asdfg"); EXPECT_TRUE(absl::ParseFlag("asdf ghjk", &value, &err)); EXPECT_EQ(value, "asdf ghjk"); EXPECT_TRUE(absl::ParseFlag("a\nb\nc", &value, &err)); EXPECT_EQ(value, "a\nb\nc"); EXPECT_TRUE(absl::ParseFlag("asd\0fgh", &value, &err)); EXPECT_EQ(value, "asd"); EXPECT_TRUE(absl::ParseFlag("\\\\", &value, &err)); EXPECT_EQ(value, "\\\\"); } TEST(MarshallingTest, TestVectorOfStringParsing) { std::string err; std::vector<std::string> value; EXPECT_TRUE(absl::ParseFlag("", &value, &err)); EXPECT_EQ(value, std::vector<std::string>{}); EXPECT_TRUE(absl::ParseFlag("1", &value, &err)); EXPECT_EQ(value, std::vector<std::string>({"1"})); EXPECT_TRUE(absl::ParseFlag("a,b", &value, &err)); EXPECT_EQ(value, std::vector<std::string>({"a", "b"})); EXPECT_TRUE(absl::ParseFlag("a,b,c,", &value, &err)); EXPECT_EQ(value, std::vector<std::string>({"a", "b", "c", ""})); EXPECT_TRUE(absl::ParseFlag("a,,", &value, &err)); EXPECT_EQ(value, std::vector<std::string>({"a", "", ""})); EXPECT_TRUE(absl::ParseFlag(",", &value, &err)); EXPECT_EQ(value, std::vector<std::string>({"", ""})); EXPECT_TRUE(absl::ParseFlag("a, b,c ", &value, &err)); EXPECT_EQ(value, std::vector<std::string>({"a", " b", "c "})); } TEST(MarshallingTest, TestOptionalBoolParsing) { std::string err; absl::optional<bool> value; EXPECT_TRUE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(value.has_value()); EXPECT_TRUE(absl::ParseFlag("true", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_TRUE(*value); EXPECT_TRUE(absl::ParseFlag("false", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_FALSE(*value); EXPECT_FALSE(absl::ParseFlag("nullopt", &value, &err)); } TEST(MarshallingTest, TestOptionalIntParsing) { std::string err; absl::optional<int> value; EXPECT_TRUE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(value.has_value()); EXPECT_TRUE(absl::ParseFlag("10", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_EQ(*value, 10); EXPECT_TRUE(absl::ParseFlag("0x1F", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_EQ(*value, 31); EXPECT_FALSE(absl::ParseFlag("nullopt", &value, &err)); } TEST(MarshallingTest, TestOptionalDoubleParsing) { std::string err; absl::optional<double> value; EXPECT_TRUE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(value.has_value()); EXPECT_TRUE(absl::ParseFlag("1.11", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_EQ(*value, 1.11); EXPECT_TRUE(absl::ParseFlag("-0.12", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_EQ(*value, -0.12); EXPECT_FALSE(absl::ParseFlag("nullopt", &value, &err)); } TEST(MarshallingTest, TestOptionalStringParsing) { std::string err; absl::optional<std::string> value; EXPECT_TRUE(absl::ParseFlag("", &value, &err)); EXPECT_FALSE(value.has_value()); EXPECT_TRUE(absl::ParseFlag(" ", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_EQ(*value, " "); EXPECT_TRUE(absl::ParseFlag("aqswde", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_EQ(*value, "aqswde"); EXPECT_TRUE(absl::ParseFlag("nullopt", &value, &err)); EXPECT_TRUE(value.has_value()); EXPECT_EQ(*value, "nullopt"); } TEST(MarshallingTest, TestBoolUnparsing) { EXPECT_EQ(absl::UnparseFlag(true), "true"); EXPECT_EQ(absl::UnparseFlag(false), "false"); } TEST(MarshallingTest, TestInt16Unparsing) { int16_t value; value = 1; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = -1; EXPECT_EQ(absl::UnparseFlag(value), "-1"); value = 9876; EXPECT_EQ(absl::UnparseFlag(value), "9876"); value = -987; EXPECT_EQ(absl::UnparseFlag(value), "-987"); } TEST(MarshallingTest, TestUint16Unparsing) { uint16_t value; value = 1; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = 19876; EXPECT_EQ(absl::UnparseFlag(value), "19876"); } TEST(MarshallingTest, TestInt32Unparsing) { int32_t value; value = 1; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = -1; EXPECT_EQ(absl::UnparseFlag(value), "-1"); value = 12345; EXPECT_EQ(absl::UnparseFlag(value), "12345"); value = -987; EXPECT_EQ(absl::UnparseFlag(value), "-987"); } TEST(MarshallingTest, TestUint32Unparsing) { uint32_t value; value = 1; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = 1234500; EXPECT_EQ(absl::UnparseFlag(value), "1234500"); } TEST(MarshallingTest, TestInt64Unparsing) { int64_t value; value = 1; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = -1; EXPECT_EQ(absl::UnparseFlag(value), "-1"); value = 123456789L; EXPECT_EQ(absl::UnparseFlag(value), "123456789"); value = -987654321L; EXPECT_EQ(absl::UnparseFlag(value), "-987654321"); value = 0x7FFFFFFFFFFFFFFF; EXPECT_EQ(absl::UnparseFlag(value), "9223372036854775807"); value = 0xFFFFFFFFFFFFFFFF; EXPECT_EQ(absl::UnparseFlag(value), "-1"); } TEST(MarshallingTest, TestUint64Unparsing) { uint64_t value; value = 1; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = 123456789L; EXPECT_EQ(absl::UnparseFlag(value), "123456789"); value = 0xFFFFFFFFFFFFFFFF; EXPECT_EQ(absl::UnparseFlag(value), "18446744073709551615"); } TEST(MarshallingTest, TestInt128Unparsing) { absl::int128 value; value = 1; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = -1; EXPECT_EQ(absl::UnparseFlag(value), "-1"); value = 123456789L; EXPECT
2,505
#ifndef ABSL_FLAGS_INTERNAL_PROGRAM_NAME_H_ #define ABSL_FLAGS_INTERNAL_PROGRAM_NAME_H_ #include <string> #include "absl/base/config.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { std::string ProgramInvocationName(); std::string ShortProgramInvocationName(); void SetProgramInvocationName(absl::string_view prog_name_str); } ABSL_NAMESPACE_END } #endif #include "absl/flags/internal/program_name.h" #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/const_init.h" #include "absl/base/thread_annotations.h" #include "absl/flags/internal/path_util.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { ABSL_CONST_INIT static absl::Mutex program_name_guard(absl::kConstInit); ABSL_CONST_INIT static std::string* program_name ABSL_GUARDED_BY(program_name_guard) = nullptr; std::string ProgramInvocationName() { absl::MutexLock l(&program_name_guard); return program_name ? *program_name : "UNKNOWN"; } std::string ShortProgramInvocationName() { absl::MutexLock l(&program_name_guard); return program_name ? std::string(flags_internal::Basename(*program_name)) : "UNKNOWN"; } void SetProgramInvocationName(absl::string_view prog_name_str) { absl::MutexLock l(&program_name_guard); if (!program_name) program_name = new std::string(prog_name_str); else program_name->assign(prog_name_str.data(), prog_name_str.size()); } } ABSL_NAMESPACE_END }
#include "absl/flags/internal/program_name.h" #include <string> #include "gtest/gtest.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" namespace { namespace flags = absl::flags_internal; TEST(FlagsPathUtilTest, TestProgamNameInterfaces) { flags::SetProgramInvocationName("absl/flags/program_name_test"); std::string program_name = flags::ProgramInvocationName(); for (char& c : program_name) if (c == '\\') c = '/'; #if !defined(__wasm__) && !defined(__asmjs__) const std::string expect_name = "absl/flags/program_name_test"; const std::string expect_basename = "program_name_test"; #else const std::string expect_name = "this.program"; const std::string expect_basename = "this.program"; #endif EXPECT_TRUE(absl::EndsWith(program_name, expect_name)) << program_name; EXPECT_EQ(flags::ShortProgramInvocationName(), expect_basename); flags::SetProgramInvocationName("a/my_test"); EXPECT_EQ(flags::ProgramInvocationName(), "a/my_test"); EXPECT_EQ(flags::ShortProgramInvocationName(), "my_test"); absl::string_view not_null_terminated("absl/aaa/bbb"); not_null_terminated = not_null_terminated.substr(1, 10); flags::SetProgramInvocationName(not_null_terminated); EXPECT_EQ(flags::ProgramInvocationName(), "bsl/aaa/bb"); EXPECT_EQ(flags::ShortProgramInvocationName(), "bb"); } }
2,506
#ifndef ABSL_FLAGS_INTERNAL_FLAG_H_ #define ABSL_FLAGS_INTERNAL_FLAG_H_ #include <stddef.h> #include <stdint.h> #include <atomic> #include <cstring> #include <memory> #include <string> #include <type_traits> #include <typeinfo> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/optimization.h" #include "absl/base/thread_annotations.h" #include "absl/flags/commandlineflag.h" #include "absl/flags/config.h" #include "absl/flags/internal/commandlineflag.h" #include "absl/flags/internal/registry.h" #include "absl/flags/internal/sequence_lock.h" #include "absl/flags/marshalling.h" #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { template <typename T> class Flag; } template <typename T> using Flag = flags_internal::Flag<T>; template <typename T> ABSL_MUST_USE_RESULT T GetFlag(const absl::Flag<T>& flag); template <typename T> void SetFlag(absl::Flag<T>* flag, const T& v); template <typename T, typename V> void SetFlag(absl::Flag<T>* flag, const V& v); template <typename U> const CommandLineFlag& GetFlagReflectionHandle(const absl::Flag<U>& f); namespace flags_internal { enum class FlagOp { kAlloc, kDelete, kCopy, kCopyConstruct, kSizeof, kFastTypeId, kRuntimeTypeId, kParse, kUnparse, kValueOffset, }; using FlagOpFn = void* (*)(FlagOp, const void*, void*, void*); template <typename T> void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3); inline void* Alloc(FlagOpFn op) { return op(FlagOp::kAlloc, nullptr, nullptr, nullptr); } inline void Delete(FlagOpFn op, void* obj) { op(FlagOp::kDelete, nullptr, obj, nullptr); } inline void Copy(FlagOpFn op, const void* src, void* dst) { op(FlagOp::kCopy, src, dst, nullptr); } inline void CopyConstruct(FlagOpFn op, const void* src, void* dst) { op(FlagOp::kCopyConstruct, src, dst, nullptr); } inline void* Clone(FlagOpFn op, const void* obj) { void* res = flags_internal::Alloc(op); flags_internal::CopyConstruct(op, obj, res); return res; } inline bool Parse(FlagOpFn op, absl::string_view text, void* dst, std::string* error) { return op(FlagOp::kParse, &text, dst, error) != nullptr; } inline std::string Unparse(FlagOpFn op, const void* val) { std::string result; op(FlagOp::kUnparse, val, &result, nullptr); return result; } inline size_t Sizeof(FlagOpFn op) { return static_cast<size_t>(reinterpret_cast<intptr_t>( op(FlagOp::kSizeof, nullptr, nullptr, nullptr))); } inline FlagFastTypeId FastTypeId(FlagOpFn op) { return reinterpret_cast<FlagFastTypeId>( op(FlagOp::kFastTypeId, nullptr, nullptr, nullptr)); } inline const std::type_info* RuntimeTypeId(FlagOpFn op) { return reinterpret_cast<const std::type_info*>( op(FlagOp::kRuntimeTypeId, nullptr, nullptr, nullptr)); } inline ptrdiff_t ValueOffset(FlagOpFn op) { return static_cast<ptrdiff_t>(reinterpret_cast<intptr_t>( op(FlagOp::kValueOffset, nullptr, nullptr, nullptr))); } template <typename T> inline const std::type_info* GenRuntimeTypeId() { #ifdef ABSL_INTERNAL_HAS_RTTI return &typeid(T); #else return nullptr; #endif } using HelpGenFunc = std::string (*)(); template <size_t N> struct FixedCharArray { char value[N]; template <size_t... I> static constexpr FixedCharArray<N> FromLiteralString( absl::string_view str, absl::index_sequence<I...>) { return (void)str, FixedCharArray<N>({{str[I]..., '\0'}}); } }; template <typename Gen, size_t N = Gen::Value().size()> constexpr FixedCharArray<N + 1> HelpStringAsArray(int) { return FixedCharArray<N + 1>::FromLiteralString( Gen::Value(), absl::make_index_sequence<N>{}); } template <typename Gen> constexpr std::false_type HelpStringAsArray(char) { return std::false_type{}; } union FlagHelpMsg { constexpr explicit FlagHelpMsg(const char* help_msg) : literal(help_msg) {} constexpr explicit FlagHelpMsg(HelpGenFunc help_gen) : gen_func(help_gen) {} const char* literal; HelpGenFunc gen_func; }; enum class FlagHelpKind : uint8_t { kLiteral = 0, kGenFunc = 1 }; struct FlagHelpArg { FlagHelpMsg source; FlagHelpKind kind; }; extern const char kStrippedFlagHelp[]; template <typename Gen, size_t N> constexpr FlagHelpArg HelpArg(const FixedCharArray<N>& value) { return {FlagHelpMsg(value.value), FlagHelpKind::kLiteral}; } template <typename Gen> constexpr FlagHelpArg HelpArg(std::false_type) { return {FlagHelpMsg(&Gen::NonConst), FlagHelpKind::kGenFunc}; } using FlagDfltGenFunc = void (*)(void*); union FlagDefaultSrc { constexpr explicit FlagDefaultSrc(FlagDfltGenFunc gen_func_arg) : gen_func(gen_func_arg) {} #define ABSL_FLAGS_INTERNAL_DFLT_FOR_TYPE(T, name) \ T name##_value; \ constexpr explicit FlagDefaultSrc(T value) : name##_value(value) {} ABSL_FLAGS_INTERNAL_BUILTIN_TYPES(ABSL_FLAGS_INTERNAL_DFLT_FOR_TYPE) #undef ABSL_FLAGS_INTERNAL_DFLT_FOR_TYPE void* dynamic_value; FlagDfltGenFunc gen_func; }; enum class FlagDefaultKind : uint8_t { kDynamicValue = 0, kGenFunc = 1, kOneWord = 2 }; struct FlagDefaultArg { FlagDefaultSrc source; FlagDefaultKind kind; }; struct EmptyBraces {}; template <typename T> constexpr T InitDefaultValue(T t) { return t; } template <typename T> constexpr T InitDefaultValue(EmptyBraces) { return T{}; } template <typename ValueT, typename GenT, typename std::enable_if<std::is_integral<ValueT>::value, int>::type = ((void)GenT{}, 0)> constexpr FlagDefaultArg DefaultArg(int) { return {FlagDefaultSrc(GenT{}.value), FlagDefaultKind::kOneWord}; } template <typename ValueT, typename GenT> constexpr FlagDefaultArg DefaultArg(char) { return {FlagDefaultSrc(&GenT::Gen), FlagDefaultKind::kGenFunc}; } constexpr int64_t UninitializedFlagValue() { return static_cast<int64_t>(0xababababababababll); } template <typename T> using FlagUseValueAndInitBitStorage = std::integral_constant<bool, std::is_trivially_copyable<T>::value && std::is_default_constructible<T>::value && (sizeof(T) < 8)>; template <typename T> using FlagUseOneWordStorage = std::integral_constant<bool, std::is_trivially_copyable<T>::value && (sizeof(T) <= 8)>; template <class T> using FlagUseSequenceLockStorage = std::integral_constant<bool, std::is_trivially_copyable<T>::value && (sizeof(T) > 8)>; enum class FlagValueStorageKind : uint8_t { kValueAndInitBit = 0, kOneWordAtomic = 1, kSequenceLocked = 2, kAlignedBuffer = 3, }; template <typename T> static constexpr FlagValueStorageKind StorageKind() { return FlagUseValueAndInitBitStorage<T>::value ? FlagValueStorageKind::kValueAndInitBit : FlagUseOneWordStorage<T>::value ? FlagValueStorageKind::kOneWordAtomic : FlagUseSequenceLockStorage<T>::value ? FlagValueStorageKind::kSequenceLocked : FlagValueStorageKind::kAlignedBuffer; } struct FlagOneWordValue { constexpr explicit FlagOneWordValue(int64_t v) : value(v) {} std::atomic<int64_t> value; }; template <typename T> struct alignas(8) FlagValueAndInitBit { T value; uint8_t init; }; template <typename T, FlagValueStorageKind Kind = flags_internal::StorageKind<T>()> struct FlagValue; template <typename T> struct FlagValue<T, FlagValueStorageKind::kValueAndInitBit> : FlagOneWordValue { constexpr FlagValue() : FlagOneWordValue(0) {} bool Get(const SequenceLock&, T& dst) const { int64_t storage = value.load(std::memory_order_acquire); if (ABSL_PREDICT_FALSE(storage == 0)) { return false; } dst = absl::bit_cast<FlagValueAndInitBit<T>>(storage).value; return true; } }; template <typename T> struct FlagValue<T, FlagValueStorageKind::kOneWordAtomic> : FlagOneWordValue { constexpr FlagValue() : FlagOneWordValue(UninitializedFlagValue()) {} bool Get(const SequenceLock&, T& dst) const { int64_t one_word_val = value.load(std::memory_order_acquire); if (ABSL_PREDICT_FALSE(one_word_val == UninitializedFlagValue())) { return false; } std::memcpy(&dst, static_cast<const void*>(&one_word_val), sizeof(T)); return true; } }; template <typename T> struct FlagValue<T, FlagValueStorageKind::kSequenceLocked> { bool Get(const SequenceLock& lock, T& dst) const { return lock.TryRead(&dst, value_words, sizeof(T)); } static constexpr int kNumWords = flags_internal::AlignUp(sizeof(T), sizeof(uint64_t)) / sizeof(uint64_t); alignas(T) alignas( std::atomic<uint64_t>) std::atomic<uint64_t> value_words[kNumWords]; }; template <typename T> struct FlagValue<T, FlagValueStorageKind::kAlignedBuffer> { bool Get(const SequenceLock&, T&) const { return false; } alignas(T) char value[sizeof(T)]; }; using FlagCallbackFunc = void (*)(); struct FlagCallback { FlagCallbackFunc func; absl::Mutex guard; }; struct DynValueDeleter { explicit DynValueDeleter(FlagOpFn op_arg = nullptr); void operator()(void* ptr) const; FlagOpFn op; }; class FlagState; #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" #endif class FlagImpl final : public CommandLineFlag { public: constexpr FlagImpl(const char* name, const char* filename, FlagOpFn op, FlagHelpArg help, FlagValueStorageKind value_kind, FlagDefaultArg default_arg) : name_(name), filename_(filename), op_(op), help_(help.source), help_source_kind_(static_cast<uint8_t>(help.kind)), value_storage_kind_(static_cast<uint8_t>(value_kind)), def_kind_(static_cast<uint8_t>(default_arg.kind)), modified_(false), on_command_line_(false), callback_(nullptr), default_value_(default_arg.source), data_guard_{} {} int64_t ReadOneWord() const ABSL_LOCKS_EXCLUDED(*DataGuard()); bool ReadOneBool() const ABSL_LOCKS_EXCLUDED(*DataGuard()); void Read(void* dst) const override ABSL_LOCKS_EXCLUDED(*DataGuard()); void Read(bool* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) { *value = ReadOneBool(); } template <typename T, absl::enable_if_t<flags_internal::StorageKind<T>() == FlagValueStorageKind::kOneWordAtomic, int> = 0> void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) { int64_t v = ReadOneWord(); std::memcpy(value, static_cast<const void*>(&v), sizeof(T)); } template <typename T, typename std::enable_if<flags_internal::StorageKind<T>() == FlagValueStorageKind::kValueAndInitBit, int>::type = 0> void Read(T* value) const ABSL_LOCKS_EXCLUDED(*DataGuard()) { *value = absl::bit_cast<FlagValueAndInitBit<T>>(ReadOneWord()).value; } void Write(const void* src) ABSL_LOCKS_EXCLUDED(*DataGuard()); void SetCallback(const FlagCallbackFunc mutation_callback) ABSL_LOCKS_EXCLUDED(*DataGuard()); void InvokeCallback() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()); void AssertValidType(FlagFastTypeId type_id, const std::type_info* (*gen_rtti)()) const; private: template <typename T> friend class Flag; friend class FlagState; absl::Mutex* DataGuard() const ABSL_LOCK_RETURNED(reinterpret_cast<absl::Mutex*>(data_guard_)); std::unique_ptr<void, DynValueDeleter> MakeInitValue() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()); void Init(); template <typename StorageT> StorageT* OffsetValue() const; void* AlignedBufferValue() const; std::atomic<uint64_t>* AtomicBufferValue() const; std::atomic<int64_t>& OneWordValue() const; std::unique_ptr<void, DynValueDeleter> TryParse(absl::string_view value, std::string& err) const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()); void StoreValue(const void* src) ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()); void ReadSequenceLockedData(void* dst) const ABSL_LOCKS_EXCLUDED(*DataGuard()); FlagHelpKind HelpSourceKind() const { return static_cast<FlagHelpKind>(help_source_kind_); } FlagValueStorageKind ValueStorageKind() const { return static_cast<FlagValueStorageKind>(value_storage_kind_); } FlagDefaultKind DefaultKind() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()) { return static_cast<FlagDefaultKind>(def_kind_); } absl::string_view Name() const override; std::string Filename() const override; std::string Help() const override; FlagFastTypeId TypeId() const override; bool IsSpecifiedOnCommandLine() const override ABSL_LOCKS_EXCLUDED(*DataGuard()); std::string DefaultValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard()); std::string CurrentValue() const override ABSL_LOCKS_EXCLUDED(*DataGuard()); bool ValidateInputValue(absl::string_view value) const override ABSL_LOCKS_EXCLUDED(*DataGuard()); void CheckDefaultValueParsingRoundtrip() const override ABSL_LOCKS_EXCLUDED(*DataGuard()); int64_t ModificationCount() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(*DataGuard()); std::unique_ptr<FlagStateInterface> SaveState() override ABSL_LOCKS_EXCLUDED(*DataGuard()); bool RestoreState(const FlagState& flag_state) ABSL_LOCKS_EXCLUDED(*DataGuard()); bool ParseFrom(absl::string_view value, FlagSettingMode set_mode, ValueSource source, std::string& error) override ABSL_LOCKS_EXCLUDED(*DataGuard()); const char* const name_; const char* const filename_; const FlagOpFn op_; const FlagHelpMsg help_; const uint8_t help_source_kind_ : 1; const uint8_t value_storage_kind_ : 2; uint8_t : 0; uint8_t def_kind_ : 2; bool modified_ : 1 ABSL_GUARDED_BY(*DataGuard()); bool on_command_line_ : 1 ABSL_GUARDED_BY(*DataGuard()); absl::once_flag init_control_; flags_internal::SequenceLock seq_lock_; FlagCallback* callback_ ABSL_GUARDED_BY(*DataGuard()); FlagDefaultSrc default_value_; alignas(absl::Mutex) mutable char data_guard_[sizeof(absl::Mutex)]; }; #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif template <typename T> class Flag { public: constexpr Flag(const char* name, const char* filename, FlagHelpArg help, const FlagDefaultArg default_arg) : impl_(name, filename, &FlagOps<T>, help, flags_internal::StorageKind<T>(), default_arg), value_() {} absl::string_view Name() const { return impl_.Name(); } std::string Filename() const { return impl_.Filename(); } std::string Help() const { return impl_.Help(); } bool IsSpecifiedOnCommandLine() const { return impl_.IsSpecifiedOnCommandLine(); } std::string DefaultValue() const { return impl_.DefaultValue(); } std::string CurrentValue() const { return impl_.CurrentValue(); } private: template <typename, bool> friend class FlagRegistrar; friend class FlagImplPeer; T Get() const { union U { T value; U() {} ~U() { value.~T(); } }; U u; #if !defined(NDEBUG) impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>); #endif if (ABSL_PREDICT_FALSE(!value_.Get(impl_.seq_lock_, u.value))) { impl_.Read(&u.value); } return std::move(u.value); } void Set(const T& v) { impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>); impl_.Write(&v); } const CommandLineFlag& Reflect() const { return impl_; } FlagImpl impl_; FlagValue<T> value_; }; class FlagImplPeer { public: template <typename T, typename FlagType> static T InvokeGet(const FlagType& flag) { return flag.Get(); } template <typename FlagType, typename T> static void InvokeSet(FlagType& flag, const T& v) { flag.Set(v); } template <typename FlagType> static const CommandLineFlag& InvokeReflect(const FlagType& f) { return f.Reflect(); } }; template <typename T> void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3) { switch (op) { case FlagOp::kAlloc: { std::allocator<T> alloc; return std::allocator_traits<std::allocator<T>>::allocate(alloc, 1); } case FlagOp::kDelete: { T* p = static_cast<T*>(v2); p->~T(); std::allocator<T> alloc; std::allocator_traits<std::allocator<T>>::deallocate(alloc, p, 1); return nullptr; } case FlagOp::kCopy: *static_cast<T*>(v2) = *static_cast<const T*>(v1); return nullptr; case FlagOp::kCopyConstruct: new (v2) T(*static_cast<const T*>(v1)); return nullptr; case FlagOp::kSizeof: return reinterpret_cast<void*>(static_cast<uintptr_t>(sizeof(T))); case FlagOp::kFastTypeId: return const_cast<void*>(base_internal::FastTypeId<T>()); case FlagOp::kRuntimeTypeId: return const_cast<std::type_info*>(GenRuntimeTypeId<T>()); case FlagOp::kParse: { T temp(*static_cast<T*>(v2)); if (!absl::ParseFlag<T>(*static_cast<const absl::string_view*>(v1), &temp, static_cast<std::string*>(v3))) { return nullptr; } *static_cast<T*>(v2) = std::move(temp); return v2; } case FlagOp::kUnparse: *static_cast<std::string*>(v2) = absl::UnparseFlag<T>(*static_cast<const T*>(v1)); return nullptr; case FlagOp::kValueOffset: { size_t round_to = alignof(FlagValue<T>); size_t offset = (sizeof(FlagImpl) + round_to - 1) / round_to * round_to; return reinterpret_cast<void*>(offset); } } return nullptr; } struct FlagRegistrarEmpty {}; template <typename T, bool do_register> class FlagRegistrar { public: constexpr explicit FlagRegistrar(Flag<T>& flag, const char* filename) : flag_(flag) { if (do_register) flags_internal::RegisterCommandLineFlag(flag_.impl_, filename); } FlagRegistrar OnUpdate(FlagCallbackFunc cb) && { flag_.impl_.SetCallback(cb); return *this; } constexpr operator FlagRegistrarEmpty() const { return {}; } private: Flag<T>& flag_; }; } ABSL_NAMESPACE_END } #endif #include "absl/flags/internal/flag.h" #include <assert.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <array> #include <atomic> #include <memory> #include <new> #include <string> #include <typeinfo> #include "absl/base/call_once.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/dynamic_annotations.h" #include "absl/base/optimization.h" #include "absl/flags/config.h" #include "absl/flags/internal/commandlineflag.h" #include "absl/flags/usage_config.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001"; namespace { bool ShouldValidateFlagValue(FlagFastTypeId flag_type_id) { #define DONT_VALIDATE(T, _) \ if (flag_type_id == base_internal::FastTypeId<T>()) return false; ABSL_FLAGS_INTERNAL_SUPPORTED_TYPES(DONT_VALIDATE) #undef DONT_VALIDATE return true; } class MutexRelock { public: explicit MutexRelock(absl::Mutex& mu) : mu_(mu) { mu_.Unlock(); } ~MutexRelock() { mu_.Lock(); } MutexRelock(const MutexRelock&) = delete; MutexRelock& operator=(const MutexRelock&) = delete; private: absl::Mutex& mu_; }; } class FlagImpl; class FlagState : public flags_internal::FlagStateInterface { public: template <typename V> FlagState(FlagImpl& flag_impl, const V& v, bool modified, bool on_command_line, int64_t counter) : flag_impl_(flag_impl), value_(v), modified_(modified), on_command_line_(on_command_line), counter_(counter) {} ~FlagState() override { if (flag_impl_.ValueStorageKind() != FlagValueStorageKind::kAlignedBuffer && flag_impl_.ValueStorageKind() != FlagValueStorageKind::kSequenceLocked) return; flags_internal::Delete(flag_impl_.op_, value_.heap_allocated); } private: friend class FlagImpl; void Restore() const override { if (!flag_impl_.RestoreState(*this)) return; ABSL_INTERNAL_LOG(INFO, absl::StrCat("Restore saved value of ", flag_impl_.Name(), " to: ", flag_impl_.CurrentValue())); } FlagImpl& flag_impl_; union SavedValue { explicit SavedValue(void* v) : heap_allocated(v) {} explicit SavedValue(int64_t v) : one_word(v) {} void* heap_allocated; int64_t one_word; } value_; bool modified_; bool on_command_line_; int64_t counter_; }; DynValu
#include "absl/flags/flag.h" #include <string> #include "gtest/gtest.h" #include "absl/flags/reflection.h" #include "absl/time/civil_time.h" #include "absl/time/time.h" ABSL_FLAG(absl::CivilSecond, test_flag_civil_second, absl::CivilSecond(2015, 1, 2, 3, 4, 5), ""); ABSL_FLAG(absl::CivilMinute, test_flag_civil_minute, absl::CivilMinute(2015, 1, 2, 3, 4), ""); ABSL_FLAG(absl::CivilHour, test_flag_civil_hour, absl::CivilHour(2015, 1, 2, 3), ""); ABSL_FLAG(absl::CivilDay, test_flag_civil_day, absl::CivilDay(2015, 1, 2), ""); ABSL_FLAG(absl::CivilMonth, test_flag_civil_month, absl::CivilMonth(2015, 1), ""); ABSL_FLAG(absl::CivilYear, test_flag_civil_year, absl::CivilYear(2015), ""); ABSL_FLAG(absl::Duration, test_duration_flag, absl::Seconds(5), "For testing support for Duration flags"); ABSL_FLAG(absl::Time, test_time_flag, absl::InfinitePast(), "For testing support for Time flags"); namespace { bool SetFlagValue(absl::string_view flag_name, absl::string_view value) { auto* flag = absl::FindCommandLineFlag(flag_name); if (!flag) return false; std::string err; return flag->ParseFrom(value, &err); } bool GetFlagValue(absl::string_view flag_name, std::string& value) { auto* flag = absl::FindCommandLineFlag(flag_name); if (!flag) return false; value = flag->CurrentValue(); return true; } TEST(CivilTime, FlagSupport) { const absl::CivilSecond kDefaultSec(2015, 1, 2, 3, 4, 5); EXPECT_EQ(absl::CivilSecond(kDefaultSec), absl::GetFlag(FLAGS_test_flag_civil_second)); EXPECT_EQ(absl::CivilMinute(kDefaultSec), absl::GetFlag(FLAGS_test_flag_civil_minute)); EXPECT_EQ(absl::CivilHour(kDefaultSec), absl::GetFlag(FLAGS_test_flag_civil_hour)); EXPECT_EQ(absl::CivilDay(kDefaultSec), absl::GetFlag(FLAGS_test_flag_civil_day)); EXPECT_EQ(absl::CivilMonth(kDefaultSec), absl::GetFlag(FLAGS_test_flag_civil_month)); EXPECT_EQ(absl::CivilYear(kDefaultSec), absl::GetFlag(FLAGS_test_flag_civil_year)); const absl::CivilSecond kNewSec(2016, 6, 7, 8, 9, 10); absl::SetFlag(&FLAGS_test_flag_civil_second, absl::CivilSecond(kNewSec)); absl::SetFlag(&FLAGS_test_flag_civil_minute, absl::CivilMinute(kNewSec)); absl::SetFlag(&FLAGS_test_flag_civil_hour, absl::CivilHour(kNewSec)); absl::SetFlag(&FLAGS_test_flag_civil_day, absl::CivilDay(kNewSec)); absl::SetFlag(&FLAGS_test_flag_civil_month, absl::CivilMonth(kNewSec)); absl::SetFlag(&FLAGS_test_flag_civil_year, absl::CivilYear(kNewSec)); EXPECT_EQ(absl::CivilSecond(kNewSec), absl::GetFlag(FLAGS_test_flag_civil_second)); EXPECT_EQ(absl::CivilMinute(kNewSec), absl::GetFlag(FLAGS_test_flag_civil_minute)); EXPECT_EQ(absl::CivilHour(kNewSec), absl::GetFlag(FLAGS_test_flag_civil_hour)); EXPECT_EQ(absl::CivilDay(kNewSec), absl::GetFlag(FLAGS_test_flag_civil_day)); EXPECT_EQ(absl::CivilMonth(kNewSec), absl::GetFlag(FLAGS_test_flag_civil_month)); EXPECT_EQ(absl::CivilYear(kNewSec), absl::GetFlag(FLAGS_test_flag_civil_year)); } TEST(Duration, FlagSupport) { EXPECT_EQ(absl::Seconds(5), absl::GetFlag(FLAGS_test_duration_flag)); absl::SetFlag(&FLAGS_test_duration_flag, absl::Seconds(10)); EXPECT_EQ(absl::Seconds(10), absl::GetFlag(FLAGS_test_duration_flag)); EXPECT_TRUE(SetFlagValue("test_duration_flag", "20s")); EXPECT_EQ(absl::Seconds(20), absl::GetFlag(FLAGS_test_duration_flag)); std::string current_flag_value; EXPECT_TRUE(GetFlagValue("test_duration_flag", current_flag_value)); EXPECT_EQ("20s", current_flag_value); } TEST(Time, FlagSupport) { EXPECT_EQ(absl::InfinitePast(), absl::GetFlag(FLAGS_test_time_flag)); const absl::Time t = absl::FromCivil(absl::CivilSecond(2016, 1, 2, 3, 4, 5), absl::UTCTimeZone()); absl::SetFlag(&FLAGS_test_time_flag, t); EXPECT_EQ(t, absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "2016-01-02T03:04:06Z")); EXPECT_EQ(t + absl::Seconds(1), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "2016-01-02T03:04:07.0Z")); EXPECT_EQ(t + absl::Seconds(2), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "2016-01-02T03:04:08.000Z")); EXPECT_EQ(t + absl::Seconds(3), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "2016-01-02T03:04:09+00:00")); EXPECT_EQ(t + absl::Seconds(4), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "2016-01-02T03:04:05.123+00:00")); EXPECT_EQ(t + absl::Milliseconds(123), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "2016-01-02T03:04:05.123+08:00")); EXPECT_EQ(t + absl::Milliseconds(123) - absl::Hours(8), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "infinite-future")); EXPECT_EQ(absl::InfiniteFuture(), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_TRUE(SetFlagValue("test_time_flag", "infinite-past")); EXPECT_EQ(absl::InfinitePast(), absl::GetFlag(FLAGS_test_time_flag)); EXPECT_FALSE(SetFlagValue("test_time_flag", "2016-01-02T03:04:06")); EXPECT_FALSE(SetFlagValue("test_time_flag", "2016-01-02")); EXPECT_FALSE(SetFlagValue("test_time_flag", "2016-01-02Z")); EXPECT_FALSE(SetFlagValue("test_time_flag", "2016-01-02+00:00")); EXPECT_FALSE(SetFlagValue("test_time_flag", "2016-99-99T03:04:06Z")); EXPECT_TRUE(SetFlagValue("test_time_flag", "2016-01-02T03:04:05Z")); std::string current_flag_value; EXPECT_TRUE(GetFlagValue("test_time_flag", current_flag_value)); EXPECT_EQ("2016-01-02T03:04:05+00:00", current_flag_value); } }
2,507
#ifndef ABSL_PROFILING_INTERNAL_PERIODIC_SAMPLER_H_ #define ABSL_PROFILING_INTERNAL_PERIODIC_SAMPLER_H_ #include <stdint.h> #include <atomic> #include "absl/base/optimization.h" #include "absl/profiling/internal/exponential_biased.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { class PeriodicSamplerBase { public: PeriodicSamplerBase() = default; PeriodicSamplerBase(PeriodicSamplerBase&&) = default; PeriodicSamplerBase(const PeriodicSamplerBase&) = default; inline bool Sample() noexcept; inline bool SubtleMaybeSample() noexcept; bool SubtleConfirmSample() noexcept; protected: ~PeriodicSamplerBase() = default; virtual int64_t GetExponentialBiased(int period) noexcept; private: virtual int period() const noexcept = 0; uint64_t stride_ = 0; absl::profiling_internal::ExponentialBiased rng_; }; inline bool PeriodicSamplerBase::SubtleMaybeSample() noexcept { if (ABSL_PREDICT_TRUE(static_cast<int64_t>(++stride_) < 0)) { return false; } return true; } inline bool PeriodicSamplerBase::Sample() noexcept { return ABSL_PREDICT_FALSE(SubtleMaybeSample()) ? SubtleConfirmSample() : false; } template <typename Tag, int default_period = 0> class PeriodicSampler final : public PeriodicSamplerBase { public: ~PeriodicSampler() = default; int period() const noexcept final { return period_.load(std::memory_order_relaxed); } static void SetGlobalPeriod(int period) { period_.store(period, std::memory_order_relaxed); } private: static std::atomic<int> period_; }; template <typename Tag, int default_period> std::atomic<int> PeriodicSampler<Tag, default_period>::period_(default_period); } ABSL_NAMESPACE_END } #endif #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 }
2,508
#ifndef ABSL_PROFILING_INTERNAL_EXPONENTIAL_BIASED_H_ #define ABSL_PROFILING_INTERNAL_EXPONENTIAL_BIASED_H_ #include <stdint.h> #include "absl/base/config.h" #include "absl/base/macros.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { class ExponentialBiased { public: static constexpr int kPrngNumBits = 48; int64_t GetSkipCount(int64_t mean); int64_t GetStride(int64_t mean); static uint64_t NextRandom(uint64_t rnd); private: void Initialize(); uint64_t rng_{0}; double bias_{0}; bool initialized_{false}; }; inline uint64_t ExponentialBiased::NextRandom(uint64_t rnd) { const uint64_t prng_mult = uint64_t{0x5DEECE66D}; const uint64_t prng_add = 0xB; const uint64_t prng_mod_power = 48; const uint64_t prng_mod_mask = ~((~static_cast<uint64_t>(0)) << prng_mod_power); return (prng_mult * rnd + prng_add) & prng_mod_mask; } } ABSL_NAMESPACE_END } #endif #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 }
2,509
#ifndef ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_ #define ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_ #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN struct FailureSignalHandlerOptions { bool symbolize_stacktrace = true; bool use_alternate_stack = true; int alarm_on_failure_secs = 3; bool call_previous_handler = false; void (*writerfn)(const char*) = nullptr; }; void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options); namespace debugging_internal { const char* FailureSignalToString(int signo); } ABSL_NAMESPACE_END } #endif #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(); }
2,510
#ifndef ABSL_DEBUGGING_LEAK_CHECK_H_ #define ABSL_DEBUGGING_LEAK_CHECK_H_ #include <cstddef> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN bool HaveLeakSanitizer(); bool LeakCheckerIsActive(); void DoIgnoreLeak(const void* ptr); template <typename T> T* IgnoreLeak(T* ptr) { DoIgnoreLeak(ptr); return ptr; } bool FindAndReportLeaks(); class LeakCheckDisabler { public: LeakCheckDisabler(); LeakCheckDisabler(const LeakCheckDisabler&) = delete; LeakCheckDisabler& operator=(const LeakCheckDisabler&) = delete; ~LeakCheckDisabler(); }; void RegisterLivePointers(const void* ptr, size_t size); void UnRegisterLivePointers(const void* ptr, size_t size); ABSL_NAMESPACE_END } #endif #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(); } 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; } }
2,511
#ifndef ABSL_DEBUGGING_INTERNAL_SYMBOLIZE_H_ #define ABSL_DEBUGGING_INTERNAL_SYMBOLIZE_H_ #ifdef __cplusplus #include <cstddef> #include <cstdint> #include "absl/base/config.h" #include "absl/strings/string_view.h" #ifdef ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE #error ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE cannot be directly set #elif defined(__ELF__) && defined(__GLIBC__) && !defined(__native_client__) \ && !defined(__asmjs__) && !defined(__wasm__) #define ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE 1 #include <elf.h> #include <link.h> #include <functional> #include <string> namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { bool ForEachSection(int fd, const std::function<bool(absl::string_view name, const ElfW(Shdr) &)>& callback); bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, ElfW(Shdr) *out); } ABSL_NAMESPACE_END } #endif #ifdef ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE #error ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE cannot be directly set #elif defined(__APPLE__) #define ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE 1 #endif #ifdef ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE #error ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE cannot be directly set #elif defined(__EMSCRIPTEN__) #define ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE 1 #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { struct SymbolDecoratorArgs { const void *pc; ptrdiff_t relocation; int fd; char *const symbol_buf; size_t symbol_buf_size; char *const tmp_buf; size_t tmp_buf_size; void* arg; }; using SymbolDecorator = void (*)(const SymbolDecoratorArgs *); int InstallSymbolDecorator(SymbolDecorator decorator, void* arg); bool RemoveSymbolDecorator(int ticket); bool RemoveAllSymbolDecorators(); bool RegisterFileMappingHint(const void* start, const void* end, uint64_t offset, const char* filename); bool GetFileMappingHint(const void** start, const void** end, uint64_t* offset, const char** filename); } ABSL_NAMESPACE_END } #endif #include <stdbool.h> #ifdef __cplusplus extern "C" #endif bool AbslInternalGetFileMappingHint(const void** start, const void** end, uint64_t* offset, const char** filename); #endif #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); CHECK_NE(symbol, nullptr) << "TestWithReturnAddress failed"; CHECK_STREQ(symbol, "main") << "TestWithReturnAddress failed"; std::cout << "TestWithReturnAddress passed" << std::endl; #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); CHECK_NE(symbol, nullptr) << "TestWithPCInsideNonInlineFunction failed"; CHECK_STREQ(symbol, "non_inline_func") << "TestWithPCInsideNonInlineFunction failed"; std::cout << "TestWithPCInsideNonInlineFunction passed" << std::endl; #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); CHECK_NE(symbol, nullptr) << "TestWithPCInsideInlineFunction failed"; CHECK_STREQ(symbol, __FUNCTION__) << "TestWithPCInsideInlineFunction failed"; std::cout << "TestWithPCInsideInlineFunction passed" << std::endl; #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); CHECK_NE(symbol, nullptr) << "TestArmThumbOverlap failed"; CHECK_STREQ("ArmThumbOverlapArm()", symbol) << "TestArmThumbOverlap failed"; std::cout << "TestArmThumbOverlap passed" << std::endl; #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(); }
2,512
#ifndef ABSL_DEBUGGING_STACKTRACE_H_ #define ABSL_DEBUGGING_STACKTRACE_H_ #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN extern int GetStackFrames(void** result, int* sizes, int max_depth, int skip_count); extern int GetStackFramesWithContext(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames); extern int GetStackTrace(void** result, int max_depth, int skip_count); extern int GetStackTraceWithContext(void** result, int max_depth, int skip_count, const void* uc, int* min_dropped_frames); extern void SetStackUnwinder(int (*unwinder)(void** pcs, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames)); extern int DefaultStackUnwinder(void** pcs, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames); namespace debugging_internal { extern bool StackTraceWorksForTest(); } ABSL_NAMESPACE_END } #endif #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 }
2,513
#ifndef ABSL_DEBUGGING_INTERNAL_UTF8_FOR_CODE_POINT_H_ #define ABSL_DEBUGGING_INTERNAL_UTF8_FOR_CODE_POINT_H_ #include <cstdint> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { struct Utf8ForCodePoint { explicit Utf8ForCodePoint(uint64_t code_point); bool ok() const { return length != 0; } char bytes[4] = {}; uint32_t length = 0; }; } ABSL_NAMESPACE_END } #endif #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 }
2,514
#ifndef ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_ #define ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_ #include <string> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { bool Demangle(const char* mangled, char* out, size_t out_size); std::string DemangleString(const char* mangled); } ABSL_NAMESPACE_END } #endif #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_
#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];
2,515
#ifndef ABSL_DEBUGGING_INTERNAL_STACK_CONSUMPTION_H_ #define ABSL_DEBUGGING_INTERNAL_STACK_CONSUMPTION_H_ #include "absl/base/config.h" #ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION #error ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION cannot be set directly #elif !defined(__APPLE__) && !defined(_WIN32) && \ (defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || \ defined(__aarch64__) || defined(__riscv)) #define ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION 1 namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { int GetSignalHandlerStackConsumption(void (*signal_handler)(int)); } ABSL_NAMESPACE_END } #endif #endif #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
2,516
#ifndef ABSL_DEBUGGING_INTERNAL_DEMANGLE_RUST_H_ #define ABSL_DEBUGGING_INTERNAL_DEMANGLE_RUST_H_ #include <cstddef> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { bool DemangleRustSymbolEncoding(const char* mangled, char* out, size_t out_size); } ABSL_NAMESPACE_END } #endif #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" 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 (uppercase_namespace == '\0') { if (is_punycoded && !Emit("{Punycode ")) return false; } else { 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; } for (int i = 0; i < num_bytes; ++i) { const char c = Take(); if (!IsIdentifierChar(c) && (is_punycoded || (c & 0x80) == 0)) { return false; } if (!EmitChar(c)) return false; } if (uppercase_namespace != '\0') { if (!EmitChar('#')) return false; if (!EmitDisambiguator(disambiguator)) return false; } if (uppercase_namespace != '\0' || is_punycoded) { 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(ch
#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::{Punycode Eyjafjallajkull_jtb}"); } 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 }
2,517
#ifndef ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ #define ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ #include <algorithm> #include <cassert> #include <cmath> #include <cstddef> #include <cstdint> #include <cstring> #include <initializer_list> #include <iterator> #include <limits> #include <memory> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/base/options.h" #include "absl/base/port.h" #include "absl/base/prefetch.h" #include "absl/container/internal/common.h" #include "absl/container/internal/compressed_tuple.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/hash_policy_traits.h" #include "absl/container/internal/hashtable_debug_hooks.h" #include "absl/container/internal/hashtablez_sampler.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/numeric/bits.h" #include "absl/utility/utility.h" #ifdef ABSL_INTERNAL_HAVE_SSE2 #include <emmintrin.h> #endif #ifdef ABSL_INTERNAL_HAVE_SSSE3 #include <tmmintrin.h> #endif #ifdef _MSC_VER #include <intrin.h> #endif #ifdef ABSL_INTERNAL_HAVE_ARM_NEON #include <arm_neon.h> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { #ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS #error ABSL_SWISSTABLE_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_SWISSTABLE_ENABLE_GENERATIONS #endif using GenerationType = uint8_t; constexpr GenerationType SentinelEmptyGeneration() { return 0; } constexpr GenerationType NextGeneration(GenerationType generation) { return ++generation == SentinelEmptyGeneration() ? ++generation : generation; } #ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS constexpr bool SwisstableGenerationsEnabled() { return true; } constexpr size_t NumGenerationBytes() { return sizeof(GenerationType); } #else constexpr bool SwisstableGenerationsEnabled() { return false; } constexpr size_t NumGenerationBytes() { return 0; } #endif template <typename AllocType> void SwapAlloc(AllocType& lhs, AllocType& rhs, std::true_type ) { using std::swap; swap(lhs, rhs); } template <typename AllocType> void SwapAlloc(AllocType& lhs, AllocType& rhs, std::false_type ) { (void)lhs; (void)rhs; assert(lhs == rhs && "It's UB to call swap with unequal non-propagating allocators."); } template <typename AllocType> void CopyAlloc(AllocType& lhs, AllocType& rhs, std::true_type ) { lhs = rhs; } template <typename AllocType> void CopyAlloc(AllocType&, AllocType&, std::false_type ) {} template <size_t Width> class probe_seq { public: probe_seq(size_t hash, size_t mask) { assert(((mask + 1) & mask) == 0 && "not a mask"); mask_ = mask; offset_ = hash & mask_; } size_t offset() const { return offset_; } size_t offset(size_t i) const { return (offset_ + i) & mask_; } void next() { index_ += Width; offset_ += index_; offset_ &= mask_; } size_t index() const { return index_; } private: size_t mask_; size_t offset_; size_t index_ = 0; }; template <class ContainerKey, class Hash, class Eq> struct RequireUsableKey { template <class PassedKey, class... Args> std::pair< decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())), decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(), std::declval<const PassedKey&>()))>* operator()(const PassedKey&, const Args&...) const; }; template <class E, class Policy, class Hash, class Eq, class... Ts> struct IsDecomposable : std::false_type {}; template <class Policy, class Hash, class Eq, class... Ts> struct IsDecomposable< absl::void_t<decltype(Policy::apply( RequireUsableKey<typename Policy::key_type, Hash, Eq>(), std::declval<Ts>()...))>, Policy, Hash, Eq, Ts...> : std::true_type {}; template <class T> constexpr bool IsNoThrowSwappable(std::true_type = {} ) { using std::swap; return noexcept(swap(std::declval<T&>(), std::declval<T&>())); } template <class T> constexpr bool IsNoThrowSwappable(std::false_type ) { return false; } template <typename T> uint32_t TrailingZeros(T x) { ABSL_ASSUME(x != 0); return static_cast<uint32_t>(countr_zero(x)); } constexpr uint64_t kMsbs8Bytes = 0x8080808080808080ULL; template <class T, int SignificantBits, int Shift = 0> class NonIterableBitMask { public: explicit NonIterableBitMask(T mask) : mask_(mask) {} explicit operator bool() const { return this->mask_ != 0; } uint32_t LowestBitSet() const { return container_internal::TrailingZeros(mask_) >> Shift; } uint32_t HighestBitSet() const { return static_cast<uint32_t>((bit_width(mask_) - 1) >> Shift); } uint32_t TrailingZeros() const { return container_internal::TrailingZeros(mask_) >> Shift; } uint32_t LeadingZeros() const { constexpr int total_significant_bits = SignificantBits << Shift; constexpr int extra_bits = sizeof(T) * 8 - total_significant_bits; return static_cast<uint32_t>( countl_zero(static_cast<T>(mask_ << extra_bits))) >> Shift; } T mask_; }; template <class T, int SignificantBits, int Shift = 0, bool NullifyBitsOnIteration = false> class BitMask : public NonIterableBitMask<T, SignificantBits, Shift> { using Base = NonIterableBitMask<T, SignificantBits, Shift>; static_assert(std::is_unsigned<T>::value, ""); static_assert(Shift == 0 || Shift == 3, ""); static_assert(!NullifyBitsOnIteration || Shift == 3, ""); public: explicit BitMask(T mask) : Base(mask) { if (Shift == 3 && !NullifyBitsOnIteration) { assert(this->mask_ == (this->mask_ & kMsbs8Bytes)); } } using value_type = int; using iterator = BitMask; using const_iterator = BitMask; BitMask& operator++() { if (Shift == 3 && NullifyBitsOnIteration) { this->mask_ &= kMsbs8Bytes; } this->mask_ &= (this->mask_ - 1); return *this; } uint32_t operator*() const { return Base::LowestBitSet(); } BitMask begin() const { return *this; } BitMask end() const { return BitMask(0); } private: friend bool operator==(const BitMask& a, const BitMask& b) { return a.mask_ == b.mask_; } friend bool operator!=(const BitMask& a, const BitMask& b) { return a.mask_ != b.mask_; } }; using h2_t = uint8_t; enum class ctrl_t : int8_t { kEmpty = -128, kDeleted = -2, kSentinel = -1, }; static_assert( (static_cast<int8_t>(ctrl_t::kEmpty) & static_cast<int8_t>(ctrl_t::kDeleted) & static_cast<int8_t>(ctrl_t::kSentinel) & 0x80) != 0, "Special markers need to have the MSB to make checking for them efficient"); static_assert( ctrl_t::kEmpty < ctrl_t::kSentinel && ctrl_t::kDeleted < ctrl_t::kSentinel, "ctrl_t::kEmpty and ctrl_t::kDeleted must be smaller than " "ctrl_t::kSentinel to make the SIMD test of IsEmptyOrDeleted() efficient"); static_assert( ctrl_t::kSentinel == static_cast<ctrl_t>(-1), "ctrl_t::kSentinel must be -1 to elide loading it from memory into SIMD " "registers (pcmpeqd xmm, xmm)"); static_assert(ctrl_t::kEmpty == static_cast<ctrl_t>(-128), "ctrl_t::kEmpty must be -128 to make the SIMD check for its " "existence efficient (psignb xmm, xmm)"); static_assert( (~static_cast<int8_t>(ctrl_t::kEmpty) & ~static_cast<int8_t>(ctrl_t::kDeleted) & static_cast<int8_t>(ctrl_t::kSentinel) & 0x7F) != 0, "ctrl_t::kEmpty and ctrl_t::kDeleted must share an unset bit that is not " "shared by ctrl_t::kSentinel to make the scalar test for " "MaskEmptyOrDeleted() efficient"); static_assert(ctrl_t::kDeleted == static_cast<ctrl_t>(-2), "ctrl_t::kDeleted must be -2 to make the implementation of " "ConvertSpecialToEmptyAndFullToDeleted efficient"); ABSL_DLL extern const ctrl_t kEmptyGroup[32]; inline ctrl_t* EmptyGroup() { return const_cast<ctrl_t*>(kEmptyGroup + 16); } ABSL_DLL extern const ctrl_t kSooControl[17]; inline ctrl_t* SooControl() { return const_cast<ctrl_t*>(kSooControl); } inline bool IsSooControl(const ctrl_t* ctrl) { return ctrl == SooControl(); } GenerationType* EmptyGeneration(); inline bool IsEmptyGeneration(const GenerationType* generation) { return *generation == SentinelEmptyGeneration(); } bool ShouldInsertBackwardsForDebug(size_t capacity, size_t hash, const ctrl_t* ctrl); ABSL_ATTRIBUTE_ALWAYS_INLINE inline bool ShouldInsertBackwards( ABSL_ATTRIBUTE_UNUSED size_t capacity, ABSL_ATTRIBUTE_UNUSED size_t hash, ABSL_ATTRIBUTE_UNUSED const ctrl_t* ctrl) { #if defined(NDEBUG) return false; #else return ShouldInsertBackwardsForDebug(capacity, hash, ctrl); #endif } template <class Mask> ABSL_ATTRIBUTE_ALWAYS_INLINE inline auto GetInsertionOffset( Mask mask, ABSL_ATTRIBUTE_UNUSED size_t capacity, ABSL_ATTRIBUTE_UNUSED size_t hash, ABSL_ATTRIBUTE_UNUSED const ctrl_t* ctrl) { #if defined(NDEBUG) return mask.LowestBitSet(); #else return ShouldInsertBackwardsForDebug(capacity, hash, ctrl) ? mask.HighestBitSet() : mask.LowestBitSet(); #endif } inline size_t PerTableSalt(const ctrl_t* ctrl) { return reinterpret_cast<uintptr_t>(ctrl) >> 12; } inline size_t H1(size_t hash, const ctrl_t* ctrl) { return (hash >> 7) ^ PerTableSalt(ctrl); } inline h2_t H2(size_t hash) { return hash & 0x7F; } inline bool IsEmpty(ctrl_t c) { return c == ctrl_t::kEmpty; } inline bool IsFull(ctrl_t c) { return static_cast<std::underlying_type_t<ctrl_t>>(c) >= 0; } inline bool IsDeleted(ctrl_t c) { return c == ctrl_t::kDeleted; } inline bool IsEmptyOrDeleted(ctrl_t c) { return c < ctrl_t::kSentinel; } #ifdef ABSL_INTERNAL_HAVE_SSE2 inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) { #if defined(__GNUC__) && !defined(__clang__) if (std::is_unsigned<char>::value) { const __m128i mask = _mm_set1_epi8(0x80); const __m128i diff = _mm_subs_epi8(b, a); return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask); } #endif return _mm_cmpgt_epi8(a, b); } struct GroupSse2Impl { static constexpr size_t kWidth = 16; explicit GroupSse2Impl(const ctrl_t* pos) { ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos)); } BitMask<uint16_t, kWidth> Match(h2_t hash) const { auto match = _mm_set1_epi8(static_cast<char>(hash)); BitMask<uint16_t, kWidth> result = BitMask<uint16_t, kWidth>(0); result = BitMask<uint16_t, kWidth>( static_cast<uint16_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl)))); return result; } NonIterableBitMask<uint16_t, kWidth> MaskEmpty() const { #ifdef ABSL_INTERNAL_HAVE_SSSE3 return NonIterableBitMask<uint16_t, kWidth>( static_cast<uint16_t>(_mm_movemask_epi8(_mm_sign_epi8(ctrl, ctrl)))); #else auto match = _mm_set1_epi8(static_cast<char>(ctrl_t::kEmpty)); return NonIterableBitMask<uint16_t, kWidth>( static_cast<uint16_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl)))); #endif } BitMask<uint16_t, kWidth> MaskFull() const { return BitMask<uint16_t, kWidth>( static_cast<uint16_t>(_mm_movemask_epi8(ctrl) ^ 0xffff)); } auto MaskNonFull() const { return BitMask<uint16_t, kWidth>( static_cast<uint16_t>(_mm_movemask_epi8(ctrl))); } NonIterableBitMask<uint16_t, kWidth> MaskEmptyOrDeleted() const { auto special = _mm_set1_epi8(static_cast<char>(ctrl_t::kSentinel)); return NonIterableBitMask<uint16_t, kWidth>(static_cast<uint16_t>( _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)))); } uint32_t CountLeadingEmptyOrDeleted() const { auto special = _mm_set1_epi8(static_cast<char>(ctrl_t::kSentinel)); return TrailingZeros(static_cast<uint32_t>( _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1)); } void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const { auto msbs = _mm_set1_epi8(static_cast<char>(-128)); auto x126 = _mm_set1_epi8(126); #ifdef ABSL_INTERNAL_HAVE_SSSE3 auto res = _mm_or_si128(_mm_shuffle_epi8(x126, ctrl), msbs); #else auto zero = _mm_setzero_si128(); auto special_mask = _mm_cmpgt_epi8_fixed(zero, ctrl); auto res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126)); #endif _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), res); } __m128i ctrl; }; #endif #if defined(ABSL_INTERNAL_HAVE_ARM_NEON) && defined(ABSL_IS_LITTLE_ENDIAN) struct GroupAArch64Impl { static constexpr size_t kWidth = 8; explicit GroupAArch64Impl(const ctrl_t* pos) { ctrl = vld1_u8(reinterpret_cast<const uint8_t*>(pos)); } auto Match(h2_t hash) const { uint8x8_t dup = vdup_n_u8(hash); auto mask = vceq_u8(ctrl, dup); return BitMask<uint64_t, kWidth, 3, true>( vget_lane_u64(vreinterpret_u64_u8(mask), 0)); } NonIterableBitMask<uint64_t, kWidth, 3> MaskEmpty() const { uint64_t mask = vget_lane_u64(vreinterpret_u64_u8(vceq_s8( vdup_n_s8(static_cast<int8_t>(ctrl_t::kEmpty)), vreinterpret_s8_u8(ctrl))), 0); return NonIterableBitMask<uint64_t, kWidth, 3>(mask); } auto MaskFull() const { uint64_t mask = vget_lane_u64( vreinterpret_u64_u8(vcge_s8(vreinterpret_s8_u8(ctrl), vdup_n_s8(static_cast<int8_t>(0)))), 0); return BitMask<uint64_t, kWidth, 3, true>(mask); } auto MaskNonFull() const { uint64_t mask = vget_lane_u64( vreinterpret_u64_u8(vclt_s8(vreinterpret_s8_u8(ctrl), vdup_n_s8(static_cast<int8_t>(0)))), 0); return BitMask<uint64_t, kWidth, 3, true>(mask); } NonIterableBitMask<uint64_t, kWidth, 3> MaskEmptyOrDeleted() const { uint64_t mask = vget_lane_u64(vreinterpret_u64_u8(vcgt_s8( vdup_n_s8(static_cast<int8_t>(ctrl_t::kSentinel)), vreinterpret_s8_u8(ctrl))),
#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" 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, ResizeReduceSmallTable
2,518
#ifndef ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_ #define ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_ #include <atomic> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <vector> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/per_thread_tls.h" #include "absl/base/optimization.h" #include "absl/base/thread_annotations.h" #include "absl/profiling/internal/sample_recorder.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { struct HashtablezInfo : public profiling_internal::Sample<HashtablezInfo> { HashtablezInfo(); ~HashtablezInfo(); HashtablezInfo(const HashtablezInfo&) = delete; HashtablezInfo& operator=(const HashtablezInfo&) = delete; void PrepareForSampling(int64_t stride, size_t inline_element_size_value, size_t key_size, size_t value_size, uint16_t soo_capacity_value) ABSL_EXCLUSIVE_LOCKS_REQUIRED(init_mu); std::atomic<size_t> capacity; std::atomic<size_t> size; std::atomic<size_t> num_erases; std::atomic<size_t> num_rehashes; std::atomic<size_t> max_probe_length; std::atomic<size_t> total_probe_length; std::atomic<size_t> hashes_bitwise_or; std::atomic<size_t> hashes_bitwise_and; std::atomic<size_t> hashes_bitwise_xor; std::atomic<size_t> max_reserve; static constexpr int kMaxStackDepth = 64; absl::Time create_time; int32_t depth; uint16_t soo_capacity; void* stack[kMaxStackDepth]; size_t inline_element_size; size_t key_size; size_t value_size; }; void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length); void RecordReservationSlow(HashtablezInfo* info, size_t target_capacity); void RecordClearedReservationSlow(HashtablezInfo* info); void RecordStorageChangedSlow(HashtablezInfo* info, size_t size, size_t capacity); void RecordInsertSlow(HashtablezInfo* info, size_t hash, size_t distance_from_desired); void RecordEraseSlow(HashtablezInfo* info); struct SamplingState { int64_t next_sample; int64_t sample_stride; }; HashtablezInfo* SampleSlow(SamplingState& next_sample, size_t inline_element_size, size_t key_size, size_t value_size, uint16_t soo_capacity); void UnsampleSlow(HashtablezInfo* info); #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) #error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set #endif #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) class HashtablezInfoHandle { public: explicit HashtablezInfoHandle() : info_(nullptr) {} explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {} void Unregister() { if (ABSL_PREDICT_TRUE(info_ == nullptr)) return; UnsampleSlow(info_); } inline bool IsSampled() const { return ABSL_PREDICT_FALSE(info_ != nullptr); } inline void RecordStorageChanged(size_t size, size_t capacity) { if (ABSL_PREDICT_TRUE(info_ == nullptr)) return; RecordStorageChangedSlow(info_, size, capacity); } inline void RecordRehash(size_t total_probe_length) { if (ABSL_PREDICT_TRUE(info_ == nullptr)) return; RecordRehashSlow(info_, total_probe_length); } inline void RecordReservation(size_t target_capacity) { if (ABSL_PREDICT_TRUE(info_ == nullptr)) return; RecordReservationSlow(info_, target_capacity); } inline void RecordClearedReservation() { if (ABSL_PREDICT_TRUE(info_ == nullptr)) return; RecordClearedReservationSlow(info_); } inline void RecordInsert(size_t hash, size_t distance_from_desired) { if (ABSL_PREDICT_TRUE(info_ == nullptr)) return; RecordInsertSlow(info_, hash, distance_from_desired); } inline void RecordErase() { if (ABSL_PREDICT_TRUE(info_ == nullptr)) return; RecordEraseSlow(info_); } friend inline void swap(HashtablezInfoHandle& lhs, HashtablezInfoHandle& rhs) { std::swap(lhs.info_, rhs.info_); } private: friend class HashtablezInfoHandlePeer; HashtablezInfo* info_; }; #else class HashtablezInfoHandle { public: explicit HashtablezInfoHandle() = default; explicit HashtablezInfoHandle(std::nullptr_t) {} inline void Unregister() {} inline bool IsSampled() const { return false; } inline void RecordStorageChanged(size_t , size_t ) {} inline void RecordRehash(size_t ) {} inline void RecordReservation(size_t ) {} inline void RecordClearedReservation() {} inline void RecordInsert(size_t , size_t ) {} inline void RecordErase() {} friend inline void swap(HashtablezInfoHandle& , HashtablezInfoHandle& ) {} }; #endif #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) extern ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample; #endif inline HashtablezInfoHandle Sample( ABSL_ATTRIBUTE_UNUSED size_t inline_element_size, ABSL_ATTRIBUTE_UNUSED size_t key_size, ABSL_ATTRIBUTE_UNUSED size_t value_size, ABSL_ATTRIBUTE_UNUSED uint16_t soo_capacity) { #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) if (ABSL_PREDICT_TRUE(--global_next_sample.next_sample > 0)) { return HashtablezInfoHandle(nullptr); } return HashtablezInfoHandle(SampleSlow(global_next_sample, inline_element_size, key_size, value_size, soo_capacity)); #else return HashtablezInfoHandle(nullptr); #endif } using HashtablezSampler = ::absl::profiling_internal::SampleRecorder<HashtablezInfo>; HashtablezSampler& GlobalHashtablezSampler(); using HashtablezConfigListener = void (*)(); void SetHashtablezConfigListener(HashtablezConfigListener l); bool IsHashtablezEnabled(); void SetHashtablezEnabled(bool enabled); void SetHashtablezEnabledInternal(bool enabled); int32_t GetHashtablezSampleParameter(); void SetHashtablezSampleParameter(int32_t rate); void SetHashtablezSampleParameterInternal(int32_t rate); size_t GetHashtablezMaxSamples(); void SetHashtablezMaxSamples(size_t max); void SetHashtablezMaxSamplesInternal(size_t max); extern "C" bool ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)(); } ABSL_NAMESPACE_END } #endif #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 }
2,519
#ifndef ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_ #define ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_ #include <cstdlib> #include <ostream> #include "absl/types/compare.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace test_internal { class BaseCountedInstance { public: explicit BaseCountedInstance(int x) : value_(x) { ++num_instances_; ++num_live_instances_; } BaseCountedInstance(const BaseCountedInstance& x) : value_(x.value_), is_live_(x.is_live_) { ++num_instances_; if (is_live_) ++num_live_instances_; ++num_copies_; } BaseCountedInstance(BaseCountedInstance&& x) : value_(x.value_), is_live_(x.is_live_) { x.is_live_ = false; ++num_instances_; ++num_moves_; } ~BaseCountedInstance() { --num_instances_; if (is_live_) --num_live_instances_; } BaseCountedInstance& operator=(const BaseCountedInstance& x) { value_ = x.value_; if (is_live_) --num_live_instances_; is_live_ = x.is_live_; if (is_live_) ++num_live_instances_; ++num_copies_; return *this; } BaseCountedInstance& operator=(BaseCountedInstance&& x) { value_ = x.value_; if (is_live_) --num_live_instances_; is_live_ = x.is_live_; x.is_live_ = false; ++num_moves_; return *this; } bool operator==(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ == x.value_; } bool operator!=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ != x.value_; } bool operator<(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ < x.value_; } bool operator>(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ > x.value_; } bool operator<=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ <= x.value_; } bool operator>=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ >= x.value_; } absl::weak_ordering compare(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ < x.value_ ? absl::weak_ordering::less : value_ == x.value_ ? absl::weak_ordering::equivalent : absl::weak_ordering::greater; } int value() const { if (!is_live_) std::abort(); return value_; } friend std::ostream& operator<<(std::ostream& o, const BaseCountedInstance& v) { return o << "[value:" << v.value() << "]"; } static void SwapImpl( BaseCountedInstance& lhs, BaseCountedInstance& rhs) { using std::swap; swap(lhs.value_, rhs.value_); swap(lhs.is_live_, rhs.is_live_); ++BaseCountedInstance::num_swaps_; } private: friend class InstanceTracker; int value_; bool is_live_ = true; static int num_instances_; static int num_live_instances_; static int num_moves_; static int num_copies_; static int num_swaps_; static int num_comparisons_; }; class InstanceTracker { public: InstanceTracker() : start_instances_(BaseCountedInstance::num_instances_), start_live_instances_(BaseCountedInstance::num_live_instances_) { ResetCopiesMovesSwaps(); } ~InstanceTracker() { if (instances() != 0) std::abort(); if (live_instances() != 0) std::abort(); } int instances() const { return BaseCountedInstance::num_instances_ - start_instances_; } int live_instances() const { return BaseCountedInstance::num_live_instances_ - start_live_instances_; } int moves() const { return BaseCountedInstance::num_moves_ - start_moves_; } int copies() const { return BaseCountedInstance::num_copies_ - start_copies_; } int swaps() const { return BaseCountedInstance::num_swaps_ - start_swaps_; } int comparisons() const { return BaseCountedInstance::num_comparisons_ - start_comparisons_; } void ResetCopiesMovesSwaps() { start_moves_ = BaseCountedInstance::num_moves_; start_copies_ = BaseCountedInstance::num_copies_; start_swaps_ = BaseCountedInstance::num_swaps_; start_comparisons_ = BaseCountedInstance::num_comparisons_; } private: int start_instances_; int start_live_instances_; int start_moves_; int start_copies_; int start_swaps_; int start_comparisons_; }; class CopyableOnlyInstance : public BaseCountedInstance { public: explicit CopyableOnlyInstance(int x) : BaseCountedInstance(x) {} CopyableOnlyInstance(const CopyableOnlyInstance& rhs) = default; CopyableOnlyInstance& operator=(const CopyableOnlyInstance& rhs) = default; friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } static bool supports_move() { return false; } }; class CopyableMovableInstance : public BaseCountedInstance { public: explicit CopyableMovableInstance(int x) : BaseCountedInstance(x) {} CopyableMovableInstance(const CopyableMovableInstance& rhs) = default; CopyableMovableInstance(CopyableMovableInstance&& rhs) = default; CopyableMovableInstance& operator=(const CopyableMovableInstance& rhs) = default; CopyableMovableInstance& operator=(CopyableMovableInstance&& rhs) = default; friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } static bool supports_move() { return true; } }; class MovableOnlyInstance : public BaseCountedInstance { public: explicit MovableOnlyInstance(int x) : BaseCountedInstance(x) {} MovableOnlyInstance(MovableOnlyInstance&& other) = default; MovableOnlyInstance& operator=(MovableOnlyInstance&& other) = default; friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } static bool supports_move() { return true; } }; } ABSL_NAMESPACE_END } #endif #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()); } }
2,520
#ifndef ABSL_BASE_LOG_SEVERITY_H_ #define ABSL_BASE_LOG_SEVERITY_H_ #include <array> #include <ostream> #include "absl/base/attributes.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN enum class LogSeverity : int { kInfo = 0, kWarning = 1, kError = 2, kFatal = 3, }; constexpr std::array<absl::LogSeverity, 4> LogSeverities() { return {{absl::LogSeverity::kInfo, absl::LogSeverity::kWarning, absl::LogSeverity::kError, absl::LogSeverity::kFatal}}; } #ifdef NDEBUG static constexpr absl::LogSeverity kLogDebugFatal = absl::LogSeverity::kError; #else static constexpr absl::LogSeverity kLogDebugFatal = absl::LogSeverity::kFatal; #endif constexpr const char* LogSeverityName(absl::LogSeverity s) { switch (s) { case absl::LogSeverity::kInfo: return "INFO"; case absl::LogSeverity::kWarning: return "WARNING"; case absl::LogSeverity::kError: return "ERROR"; case absl::LogSeverity::kFatal: return "FATAL"; } return "UNKNOWN"; } constexpr absl::LogSeverity NormalizeLogSeverity(absl::LogSeverity s) { absl::LogSeverity n = s; if (n < absl::LogSeverity::kInfo) n = absl::LogSeverity::kInfo; if (n > absl::LogSeverity::kFatal) n = absl::LogSeverity::kError; return n; } constexpr absl::LogSeverity NormalizeLogSeverity(int s) { return absl::NormalizeLogSeverity(static_cast<absl::LogSeverity>(s)); } std::ostream& operator<<(std::ostream& os, absl::LogSeverity s); enum class LogSeverityAtLeast : int { kInfo = static_cast<int>(absl::LogSeverity::kInfo), kWarning = static_cast<int>(absl::LogSeverity::kWarning), kError = static_cast<int>(absl::LogSeverity::kError), kFatal = static_cast<int>(absl::LogSeverity::kFatal), kInfinity = 1000, }; std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtLeast s); enum class LogSeverityAtMost : int { kNegativeInfinity = -1000, kInfo = static_cast<int>(absl::LogSeverity::kInfo), kWarning = static_cast<int>(absl::LogSeverity::kWarning), kError = static_cast<int>(absl::LogSeverity::kError), kFatal = static_cast<int>(absl::LogSeverity::kFatal), }; std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtMost s); #define COMPOP(op1, op2, T) \ constexpr bool operator op1(absl::T lhs, absl::LogSeverity rhs) { \ return static_cast<absl::LogSeverity>(lhs) op1 rhs; \ } \ constexpr bool operator op2(absl::LogSeverity lhs, absl::T rhs) { \ return lhs op2 static_cast<absl::LogSeverity>(rhs); \ } COMPOP(>, <, LogSeverityAtLeast) COMPOP(<=, >=, LogSeverityAtLeast) COMPOP(<, >, LogSeverityAtMost) COMPOP(>=, <=, LogSeverityAtMost) #undef COMPOP ABSL_NAMESPACE_END } #endif #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")); } }
2,521
#ifndef ABSL_BASE_INTERNAL_STRERROR_H_ #define ABSL_BASE_INTERNAL_STRERROR_H_ #include <string> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { std::string StrError(int errnum); } ABSL_NAMESPACE_END } #endif #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)); } }
2,522
#ifndef ABSL_BASE_INTERNAL_EXCEPTION_SAFETY_TESTING_H_ #define ABSL_BASE_INTERNAL_EXCEPTION_SAFETY_TESTING_H_ #include "absl/base/config.h" #ifdef ABSL_HAVE_EXCEPTIONS #include <cstddef> #include <cstdint> #include <functional> #include <initializer_list> #include <iosfwd> #include <string> #include <tuple> #include <unordered_map> #include "gtest/gtest.h" #include "absl/base/internal/pretty_function.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "absl/utility/utility.h" namespace testing { enum class TypeSpec; enum class AllocSpec; constexpr TypeSpec operator|(TypeSpec a, TypeSpec b) { using T = absl::underlying_type_t<TypeSpec>; return static_cast<TypeSpec>(static_cast<T>(a) | static_cast<T>(b)); } constexpr TypeSpec operator&(TypeSpec a, TypeSpec b) { using T = absl::underlying_type_t<TypeSpec>; return static_cast<TypeSpec>(static_cast<T>(a) & static_cast<T>(b)); } constexpr AllocSpec operator|(AllocSpec a, AllocSpec b) { using T = absl::underlying_type_t<AllocSpec>; return static_cast<AllocSpec>(static_cast<T>(a) | static_cast<T>(b)); } constexpr AllocSpec operator&(AllocSpec a, AllocSpec b) { using T = absl::underlying_type_t<AllocSpec>; return static_cast<AllocSpec>(static_cast<T>(a) & static_cast<T>(b)); } namespace exceptions_internal { std::string GetSpecString(TypeSpec); std::string GetSpecString(AllocSpec); struct NoThrowTag {}; struct StrongGuaranteeTagType {}; class TestException { public: explicit TestException(absl::string_view msg) : msg_(msg) {} virtual ~TestException() {} virtual const char* what() const noexcept { return msg_.c_str(); } private: std::string msg_; }; class TestBadAllocException : public std::bad_alloc, public TestException { public: explicit TestBadAllocException(absl::string_view msg) : TestException(msg) {} using TestException::what; }; extern int countdown; inline void SetCountdown(int i = 0) { countdown = i; } inline void UnsetCountdown() { SetCountdown(-1); } void MaybeThrow(absl::string_view msg, bool throw_bad_alloc = false); testing::AssertionResult FailureMessage(const TestException& e, int countdown) noexcept; struct TrackedAddress { bool is_alive; std::string description; }; class ConstructorTracker { public: explicit ConstructorTracker(int count) : countdown_(count) { assert(current_tracker_instance_ == nullptr); current_tracker_instance_ = this; } ~ConstructorTracker() { assert(current_tracker_instance_ == this); current_tracker_instance_ = nullptr; for (auto& it : address_map_) { void* address = it.first; TrackedAddress& tracked_address = it.second; if (tracked_address.is_alive) { ADD_FAILURE() << ErrorMessage(address, tracked_address.description, countdown_, "Object was not destroyed."); } } } static void ObjectConstructed(void* address, std::string description) { if (!CurrentlyTracking()) return; TrackedAddress& tracked_address = current_tracker_instance_->address_map_[address]; if (tracked_address.is_alive) { ADD_FAILURE() << ErrorMessage( address, tracked_address.description, current_tracker_instance_->countdown_, "Object was re-constructed. Current object was constructed by " + description); } tracked_address = {true, std::move(description)}; } static void ObjectDestructed(void* address) { if (!CurrentlyTracking()) return; auto it = current_tracker_instance_->address_map_.find(address); if (it == current_tracker_instance_->address_map_.end()) return; TrackedAddress& tracked_address = it->second; if (!tracked_address.is_alive) { ADD_FAILURE() << ErrorMessage(address, tracked_address.description, current_tracker_instance_->countdown_, "Object was re-destroyed."); } tracked_address.is_alive = false; } private: static bool CurrentlyTracking() { return current_tracker_instance_ != nullptr; } static std::string ErrorMessage(void* address, const std::string& address_description, int countdown, const std::string& error_description) { return absl::Substitute( "With coundtown at $0:\n" " $1\n" " Object originally constructed by $2\n" " Object address: $3\n", countdown, error_description, address_description, address); } std::unordered_map<void*, TrackedAddress> address_map_; int countdown_; static ConstructorTracker* current_tracker_instance_; }; class TrackedObject { public: TrackedObject(const TrackedObject&) = delete; TrackedObject(TrackedObject&&) = delete; protected: explicit TrackedObject(std::string description) { ConstructorTracker::ObjectConstructed(this, std::move(description)); } ~TrackedObject() noexcept { ConstructorTracker::ObjectDestructed(this); } }; } extern exceptions_internal::NoThrowTag nothrow_ctor; extern exceptions_internal::StrongGuaranteeTagType strong_guarantee; class ThrowingBool { public: ThrowingBool(bool b) noexcept : b_(b) {} operator bool() const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return b_; } private: bool b_; }; enum class TypeSpec { kEverythingThrows = 0, kNoThrowCopy = 1, kNoThrowMove = 1 << 1, kNoThrowNew = 1 << 2, }; template <TypeSpec Spec = TypeSpec::kEverythingThrows> class ThrowingValue : private exceptions_internal::TrackedObject { static constexpr bool IsSpecified(TypeSpec spec) { return static_cast<bool>(Spec & spec); } static constexpr int kDefaultValue = 0; static constexpr int kBadValue = 938550620; public: ThrowingValue() : TrackedObject(GetInstanceString(kDefaultValue)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ = kDefaultValue; } ThrowingValue(const ThrowingValue& other) noexcept( IsSpecified(TypeSpec::kNoThrowCopy)) : TrackedObject(GetInstanceString(other.dummy_)) { if (!IsSpecified(TypeSpec::kNoThrowCopy)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); } dummy_ = other.dummy_; } ThrowingValue(ThrowingValue&& other) noexcept( IsSpecified(TypeSpec::kNoThrowMove)) : TrackedObject(GetInstanceString(other.dummy_)) { if (!IsSpecified(TypeSpec::kNoThrowMove)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); } dummy_ = other.dummy_; } explicit ThrowingValue(int i) : TrackedObject(GetInstanceString(i)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ = i; } ThrowingValue(int i, exceptions_internal::NoThrowTag) noexcept : TrackedObject(GetInstanceString(i)), dummy_(i) {} ~ThrowingValue() noexcept = default; ThrowingValue& operator=(const ThrowingValue& other) noexcept( IsSpecified(TypeSpec::kNoThrowCopy)) { dummy_ = kBadValue; if (!IsSpecified(TypeSpec::kNoThrowCopy)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); } dummy_ = other.dummy_; return *this; } ThrowingValue& operator=(ThrowingValue&& other) noexcept( IsSpecified(TypeSpec::kNoThrowMove)) { dummy_ = kBadValue; if (!IsSpecified(TypeSpec::kNoThrowMove)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); } dummy_ = other.dummy_; return *this; } ThrowingValue operator+(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ + other.dummy_, nothrow_ctor); } ThrowingValue operator+() const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_, nothrow_ctor); } ThrowingValue operator-(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ - other.dummy_, nothrow_ctor); } ThrowingValue operator-() const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(-dummy_, nothrow_ctor); } ThrowingValue& operator++() { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); ++dummy_; return *this; } ThrowingValue operator++(int) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); auto out = ThrowingValue(dummy_, nothrow_ctor); ++dummy_; return out; } ThrowingValue& operator--() { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); --dummy_; return *this; } ThrowingValue operator--(int) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); auto out = ThrowingValue(dummy_, nothrow_ctor); --dummy_; return out; } ThrowingValue operator*(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ * other.dummy_, nothrow_ctor); } ThrowingValue operator/(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ / other.dummy_, nothrow_ctor); } ThrowingValue operator%(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ % other.dummy_, nothrow_ctor); } ThrowingValue operator<<(int shift) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ << shift, nothrow_ctor); } ThrowingValue operator>>(int shift) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ >> shift, nothrow_ctor); } friend ThrowingBool operator==(const ThrowingValue& a, const ThrowingValue& b) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return a.dummy_ == b.dummy_; } friend ThrowingBool operator!=(const ThrowingValue& a, const ThrowingValue& b) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return a.dummy_ != b.dummy_; } friend ThrowingBool operator<(const ThrowingValue& a, const ThrowingValue& b) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return a.dummy_ < b.dummy_; } friend ThrowingBool operator<=(const ThrowingValue& a, const ThrowingValue& b) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return a.dummy_ <= b.dummy_; } friend ThrowingBool operator>(const ThrowingValue& a, const ThrowingValue& b) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return a.dummy_ > b.dummy_; } friend ThrowingBool operator>=(const ThrowingValue& a, const ThrowingValue& b) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return a.dummy_ >= b.dummy_; } ThrowingBool operator!() const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return !dummy_; } ThrowingBool operator&&(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return dummy_ && other.dummy_; } ThrowingBool operator||(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return dummy_ || other.dummy_; } ThrowingValue operator~() const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(~dummy_, nothrow_ctor); } ThrowingValue operator&(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ & other.dummy_, nothrow_ctor); } ThrowingValue operator|(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ | other.dummy_, nothrow_ctor); } ThrowingValue operator^(const ThrowingValue& other) const { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return ThrowingValue(dummy_ ^ other.dummy_, nothrow_ctor); } ThrowingValue& operator+=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ += other.dummy_; return *this; } ThrowingValue& operator-=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ -= other.dummy_; return *this; } ThrowingValue& operator*=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ *= other.dummy_; return *this; } ThrowingValue& operator/=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ /= other.dummy_; return *this; } ThrowingValue& operator%=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ %= other.dummy_; return *this; } ThrowingValue& operator&=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ &= other.dummy_; return *this; } ThrowingValue& operator|=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ |= other.dummy_; return *this; } ThrowingValue& operator^=(const ThrowingValue& other) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ ^= other.dummy_; return *this; } ThrowingValue& operator<<=(int shift) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ <<= shift; return *this; } ThrowingValue& operator>>=(int shift) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ >>= shift; return *this; } void operator&() const = delete; friend std::ostream& operator<<(std::ostream& os, const ThrowingValue& tv) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return os << GetInstanceString(tv.dummy_); } friend std::istream& operator>>(std::istream& is, const ThrowingValue&) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); return is; } static void* operator new(size_t s) noexcept( IsSpecified(TypeSpec::kNoThrowNew)) { if (!IsSpecified(TypeSpec::kNoThrowNew)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true); } return ::operator new(s); } static void* operator new[](size_t s) noexcept( IsSpecified(TypeSpec::kNoThrowNew)) { if (!IsSpecified(TypeSpec::kNoThrowNew)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true); } return ::operator new[](s); } template <typename... Args> static void* operator new(size_t s, Args&&... args) noexcept( IsSpecified(TypeSpec::kNoThrowNew)) { if (!IsSpecified(TypeSpec::kNoThrowNew)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true); } return ::operator new(s, std::forward<Args>(args)...); } template <typename... Args> static void* operator new[](size_t s, Args&&... args) noexcept( IsSpecified(TypeSpec::kNoThrowNew)) { if (!IsSpecified(TypeSpec::kNoThrowNew)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true); } return ::operator new[](s, std::forward<Args>(args)...); } void operator delete(void* p) noexcept { ::operator delete(p); } template <typename... Args> void operator delete(void* p, Args&&... args) noexcept { ::operator delete(p, std::forward<Args>(args)...); } void operator delete[](void* p) noexcept { return ::operator delete[](p); } template <typename... Args> void operator delete[](void* p, Args&&... args) noexcept { return ::operator delete[](p, std::forward<Args>(args)...); } int& Get() noexcept { return dummy_; } const int& Get() const noexcept { return dummy_; } private: static std::string GetInstanceString(int dummy) { return absl::StrCat("ThrowingValue<", exceptions_internal::GetSpecString(Spec), ">(", dummy, ")"); } int dummy_; }; template <TypeSpec Spec, typename T> void operator,(const ThrowingValue<Spec>&, T&&) = delete; template <TypeSpec Spec, typename T> void operator,(T&&, const ThrowingValue<Spec>&) = delete; enum class AllocSpec { kEverythingThrows = 0, kNoThrowAllocate = 1, }; template <typename T, AllocSpec Spec = AllocSpec::kEverythingThrows> class ThrowingAllocator : private exceptions_internal::TrackedObject { static constexpr bool IsSpecified(AllocSpec spec) { return static_cast<bool>(Spec & spec); } public: using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using void_pointer = void*; using const_void_pointer = const void*; using value_type = T; using size_type = size_t; using difference_type = ptrdiff_t; using is_nothrow = std::integral_constant<bool, Spec == AllocSpec::kNoThrowAllocate>; using propagate_on_container_copy_assignment = std::true_type; using propagate_on_container_move_assignment = std::true_type; using propagate_on_container_swap = std::true_type; using is_always_equal = std::false_type; ThrowingAllocator() : TrackedObject(GetInstanceString(next_id_)) { exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION); dummy_ = std::make_shared<const int>(next_id_++); } template <typename U> ThrowingAllocator(const ThrowingAllocator<U, Spec>& other) noexcept : TrackedObject(GetInstanceString(*other.State())), dummy_(other.State()) {} ThrowingAllocator(const ThrowingAllocator& other) noexcept : TrackedObject(GetInstanceString(*other.State())), dummy_(other.State()) {} template <typename U> ThrowingAllocator(ThrowingAllocator<U, Spec>&& other) noexcept : TrackedObject(GetInstanceString(*other.State())), dummy_(std::move(other.State())) {} ThrowingAllocator(ThrowingAllocator&& other) noexcept : TrackedObject(GetInstanceString(*other.State())), dummy_(std::move(other.State())) {} ~ThrowingAllocator() noexcept = default; ThrowingAllocator& operator=(const ThrowingAllocator& other) noexcept { dummy_ = other.State(); return *this; } template <typename U> ThrowingAllocator& operator=( const ThrowingAllocator<U, Spec>& other) noexcept { dummy_ = other.State(); return *this; } template <typename U> ThrowingAllocator& operator=(ThrowingAllocator<U, Spec>&& other) noexcept { dummy_ = std::move(other.State()); return *this; } template <typename U> struct rebind { using other = ThrowingAllocator<U, Spec>; }; pointer allocate(size_type n) noexcept( IsSpecified(AllocSpec::kNoThrowAllocate)) { ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION); return static_cast<pointer>(::operator new(n * sizeof(T))); } pointer allocate(size_type n, const_void_pointer) noexcept( IsSpecified(AllocSpec::kNoThrowAllocate)) { return allocate(n); } void deallocate(pointer ptr, size_type) noexcept { ReadState(); ::operator delete(static_cast<void*>(ptr)); } template <typename U, typename... Args> void construct(U* ptr, Args&&... args) noexcept( IsSpecified(AllocSpec::kNoThrowAllocate)) { ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION); ::new (static_cast<void*>(ptr)) U(std::forward<Args>(args)...); } template <typename U> void destroy(U* p) noexcept { ReadState(); p->~U(); } size_type max_size() const noexcept { return (std::numeric_limits<difference_type>::max)() / sizeof(value_type); } ThrowingAllocator select_on_container_copy_construction() noexcept( IsSpecified(AllocSpec::kNoThrowAllocate)) { ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION); return *this; } template <typename U> bool operator==(const ThrowingAllocator<U, Spec>& other) const noexcept { return dummy_ == other.dummy_; } template <typename U> bool operator!=(const ThrowingAllocator<U, Spec>& other) const noexcept { return dummy_ != other.dummy_; } template <typename, AllocSpec> friend class ThrowingAllocator; private: static std::string GetInstanceString(int dummy) { return absl::StrCat("ThrowingAllocator<", exceptions_internal::GetSpecString(Spec), ">(", dummy, ")"); } const std::shared_ptr<const int>& State() const { return dummy_; } std::shared_ptr<const int>& State() { return dummy_; } void ReadState() { if (*dummy_ < 0) std::abort(); } void ReadStateAndMaybeThrow(absl::string_view msg) const { if (!IsSpecified(AllocSpec::kNoThrowAllocate)) { exceptions_internal::MaybeThrow( absl::Substitute("Allocator id $0 threw from $1", *dummy_, msg)); } } static int next_id_; std::shared_ptr<const int> dummy_; }; template <typename T, AllocSpec Spec> int ThrowingAllocator<T, Spec>::next_id_ = 0; template <typename T, typename... Args> void TestThrowingCtor(Args&&... args) { struct Cleanup { ~Cleanup() { exceptions_internal::UnsetCountdown(); } } c; for (int count = 0;; ++count) { exceptions_internal::ConstructorTracker ct(count); exceptions_internal::SetCountdown(count); try { T temp(std::forward<Args>(args)...); static_cast<void>(temp); break; } catch (const exceptions_internal::TestException&) { } } } template <typename Operation> testing::AssertionResult TestNothrowOp(const Operation& operation) { struct Cleanup { Cleanup() { exceptions_internal::SetCountdown(); } ~Cleanup() { exceptions_internal::UnsetCountdown(); } } c; try { operation(); return testing::AssertionSuccess(); } catch (const exceptions_internal::TestException&) { return testing::AssertionFailure() << "TestException thrown during call to operation() when nothrow " "guarantee was expected."; } catch (...) { return testing::AssertionFailure() << "Unknown exception thrown during call to operation() when " "nothrow guarantee was expected."; } } namespace exceptions_internal { struct UninitializedT {}; template <typename T> class DefaultFactory { public: explicit DefaultFactory(const T& t) : t_(t) {} std::unique_ptr<T> operator()() const { return absl::make_unique<T>(t_); } private: T t_; }; template <size_t LazyContractsCount, typename LazyFactory, typename LazyOperation> using EnableIfTestable = typename absl::enable_if_t< LazyContractsCount != 0 && !std::is_same<LazyFactory, UninitializedT>::value && !std::is_same<LazyOperation, UninitializedT>::value>; template <typename Factory = UninitializedT, typename Operation = UninitializedT, typename... Contracts> class ExceptionSafetyTestBuilder; } exceptions_internal::ExceptionSafetyTestBuilder<> MakeExceptionSafetyTester(); namespace exceptions_internal { template <typename T> struct IsUniquePtr : std::false_type {}; template <typename T, typename D> struct IsUniquePtr<std::unique_ptr<T, D>> : std::true_type {}; template <typename Factory> struct FactoryPtrTypeHelper { using type = decltype(std::declval<const Factory&>()()); static_assert(IsUniquePtr<type>::value, "Factories must return a unique_ptr"); }; template <typename Factory> using FactoryPtrType = typename FactoryPtrTypeHelper<Factory>::type; template <typename Factory> using FactoryElementType = typename FactoryPtrType<Factory>::element_type; template <typename T> class ExceptionSafetyTest { using Factory = std::function<std::unique_ptr<T>()>; using Operation = std::function<void(T*)>; using Contract = std::function<AssertionResult(T*)>; public: template <typename... Contracts> explicit ExceptionSafetyTest(const Factory& f, const Operation& op, const Contracts&... contracts) : factory_(f), operation_(op), contracts_{WrapContract(contracts)...} {} AssertionResult Test() const { for (int count = 0;; ++count) { exceptions_internal::ConstructorTracker ct(count); for (const auto& contract : contracts_) { auto t_ptr = factory_(); try { SetCountdown(count); operation_(t_ptr.get()); UnsetCountdown(); return AssertionSuccess(); } catch (const exceptions_internal::TestException& e) { if (!contract(t_ptr.get())) { return AssertionFailure() << e.what() << " failed contract check"; } } } } } private: template <typename ContractFn> Contract WrapContract(const ContractFn& contract) { return [contract](T* t_ptr) { return AssertionResult(contract(t_ptr)); }; } Contract WrapContract(StrongGuaranteeTagType) { return [this](T* t_ptr) { return AssertionResult(*factory_() == *t_ptr); }; } Factory factory_; Operation operation_; std::vector<Contract> contracts_; }; template <typename Factory, typename Operation, typename... Contracts> class ExceptionSafetyTestBuilder { public: /* * Returns a new ExceptionSafetyTestBuilder with an included T factory based * on the provided T instance. The existing factory will not be included in * the newly created tes
#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
2,523
#ifndef ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_ #define ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_ #ifndef _WIN32 #include <pthread.h> #include <unistd.h> #endif #include <atomic> #include <cstdint> #include "absl/base/config.h" #include "absl/base/internal/per_thread_tls.h" #include "absl/base/optimization.h" namespace absl { ABSL_NAMESPACE_BEGIN struct SynchLocksHeld; struct SynchWaitParams; namespace base_internal { class SpinLock; struct ThreadIdentity; struct PerThreadSynch { static constexpr int kLowZeroBits = 8; static constexpr int kAlignment = 1 << kLowZeroBits; ThreadIdentity* thread_identity() { return reinterpret_cast<ThreadIdentity*>(this); } PerThreadSynch* next; PerThreadSynch* skip; bool may_skip; bool wake; bool cond_waiter; bool maybe_unlocking; bool suppress_fatal_errors; int priority; enum State { kAvailable, kQueued }; std::atomic<State> state; SynchWaitParams* waitp; intptr_t readers; int64_t next_priority_read_cycles; SynchLocksHeld* all_locks; }; struct ThreadIdentity { PerThreadSynch per_thread_synch; struct WaiterState { alignas(void*) char data[256]; } waiter_state; std::atomic<int>* blocked_count_ptr; std::atomic<int> ticker; std::atomic<int> wait_start; std::atomic<bool> is_idle; ThreadIdentity* next; }; ThreadIdentity* CurrentThreadIdentityIfPresent(); using ThreadIdentityReclaimerFunction = void (*)(void*); void SetCurrentThreadIdentity(ThreadIdentity* identity, ThreadIdentityReclaimerFunction reclaimer); void ClearCurrentThreadIdentity(); #ifdef ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC #error ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC cannot be directly set #else #define ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC 0 #endif #ifdef ABSL_THREAD_IDENTITY_MODE_USE_TLS #error ABSL_THREAD_IDENTITY_MODE_USE_TLS cannot be directly set #else #define ABSL_THREAD_IDENTITY_MODE_USE_TLS 1 #endif #ifdef ABSL_THREAD_IDENTITY_MODE_USE_CPP11 #error ABSL_THREAD_IDENTITY_MODE_USE_CPP11 cannot be directly set #else #define ABSL_THREAD_IDENTITY_MODE_USE_CPP11 2 #endif #ifdef ABSL_THREAD_IDENTITY_MODE #error ABSL_THREAD_IDENTITY_MODE cannot be directly set #elif defined(ABSL_FORCE_THREAD_IDENTITY_MODE) #define ABSL_THREAD_IDENTITY_MODE ABSL_FORCE_THREAD_IDENTITY_MODE #elif defined(_WIN32) && !defined(__MINGW32__) #define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11 #elif defined(__APPLE__) && defined(ABSL_HAVE_THREAD_LOCAL) #define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11 #elif ABSL_PER_THREAD_TLS && defined(__GOOGLE_GRTE_VERSION__) && \ (__GOOGLE_GRTE_VERSION__ >= 20140228L) #define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_TLS #else #define ABSL_THREAD_IDENTITY_MODE \ ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC #endif #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \ ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11 #if ABSL_PER_THREAD_TLS ABSL_CONST_INIT extern ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity* thread_identity_ptr; #elif defined(ABSL_HAVE_THREAD_LOCAL) ABSL_CONST_INIT extern thread_local ThreadIdentity* thread_identity_ptr; #else #error Thread-local storage not detected on this platform #endif #if !defined(__APPLE__) && !defined(ABSL_BUILD_DLL) && \ !defined(ABSL_CONSUME_DLL) #define ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT 1 #endif #ifdef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT inline ThreadIdentity* CurrentThreadIdentityIfPresent() { return thread_identity_ptr; } #endif #elif ABSL_THREAD_IDENTITY_MODE != \ ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC #error Unknown ABSL_THREAD_IDENTITY_MODE #endif } ABSL_NAMESPACE_END } #endif #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 }
2,524
#ifndef ABSL_BASE_INTERNAL_POISON_H_ #define ABSL_BASE_INTERNAL_POISON_H_ #include <atomic> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { extern std::atomic<void*> poison_data; inline void* get_poisoned_pointer() { return poison_data.load(std::memory_order_relaxed); } } ABSL_NAMESPACE_END } #endif #include "absl/base/internal/poison.h" #include <atomic> #include <cstdint> #include <cstdlib> #include "absl/base/attributes.h" #include "absl/base/config.h" #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) && !defined(SGX_SIM) #include <sys/mman.h> #elif defined(_MSC_VER) #include <windows.h> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { constexpr size_t kPageSize = 1 << 12; alignas(kPageSize) static char poison_page[kPageSize]; } std::atomic<void*> poison_data = {&poison_page}; namespace { #if defined(ABSL_HAVE_ADDRESS_SANITIZER) void PoisonBlock(void* data) { ASAN_POISON_MEMORY_REGION(data, kPageSize); } #elif defined(ABSL_HAVE_MEMORY_SANITIZER) void PoisonBlock(void* data) { __msan_poison(data, kPageSize); } #elif defined(ABSL_HAVE_MMAP) void PoisonBlock(void* data) { mprotect(data, kPageSize, PROT_NONE); } #elif defined(_MSC_VER) void PoisonBlock(void* data) { DWORD old_mode = 0; VirtualProtect(data, kPageSize, PAGE_NOACCESS, &old_mode); } #else void PoisonBlock(void* data) { constexpr uint64_t kBadPtr = 0xBAD0BAD0BAD0BAD0; poison_data = reinterpret_cast<void*>(static_cast<uintptr_t>(kBadPtr)); } #endif void* InitializePoisonedPointer() { PoisonBlock(&poison_page); return &poison_page; } } ABSL_ATTRIBUTE_UNUSED void* force_initialize = InitializePoisonedPointer(); } 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 void* poisoned_ptr = get_poisoned_pointer(); EXPECT_DEATH_IF_SUPPORTED(std::cout << *static_cast<int*>(poisoned_ptr), ""); } } } ABSL_NAMESPACE_END }
2,525
#ifndef ABSL_BASE_INTERNAL_LOW_LEVEL_ALLOC_H_ #define ABSL_BASE_INTERNAL_LOW_LEVEL_ALLOC_H_ #include <sys/types.h> #include <cstdint> #include "absl/base/attributes.h" #include "absl/base/config.h" #ifdef ABSL_LOW_LEVEL_ALLOC_MISSING #error ABSL_LOW_LEVEL_ALLOC_MISSING cannot be directly set #elif !defined(ABSL_HAVE_MMAP) && !defined(_WIN32) #define ABSL_LOW_LEVEL_ALLOC_MISSING 1 #endif #ifdef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING #error ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING cannot be directly set #elif defined(_WIN32) || defined(__asmjs__) || defined(__wasm__) || \ defined(__hexagon__) #define ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING 1 #endif #include <cstddef> #include "absl/base/port.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { class LowLevelAlloc { public: struct Arena; static void *Alloc(size_t request) ABSL_ATTRIBUTE_SECTION(malloc_hook); static void *AllocWithArena(size_t request, Arena *arena) ABSL_ATTRIBUTE_SECTION(malloc_hook); static void Free(void *s) ABSL_ATTRIBUTE_SECTION(malloc_hook); enum { kCallMallocHook = 0x0001, #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING kAsyncSignalSafe = 0x0002, #endif }; static Arena *NewArena(uint32_t flags); static bool DeleteArena(Arena *arena); static Arena *DefaultArena(); private: LowLevelAlloc(); }; } ABSL_NAMESPACE_END } #endif #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; }
2,526
#ifndef ABSL_BASE_INTERNAL_RAW_LOGGING_H_ #define ABSL_BASE_INTERNAL_RAW_LOGGING_H_ #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/atomic_hook.h" #include "absl/base/log_severity.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/base/port.h" #define ABSL_RAW_LOG(severity, ...) \ do { \ constexpr const char* absl_raw_log_internal_basename = \ ::absl::raw_log_internal::Basename(__FILE__, sizeof(__FILE__) - 1); \ ::absl::raw_log_internal::RawLog(ABSL_RAW_LOG_INTERNAL_##severity, \ absl_raw_log_internal_basename, __LINE__, \ __VA_ARGS__); \ ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_##severity; \ } while (0) #define ABSL_RAW_CHECK(condition, message) \ do { \ if (ABSL_PREDICT_FALSE(!(condition))) { \ ABSL_RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \ } \ } while (0) #define ABSL_INTERNAL_LOG(severity, message) \ do { \ constexpr const char* absl_raw_log_internal_filename = __FILE__; \ ::absl::raw_log_internal::internal_log_function( \ ABSL_RAW_LOG_INTERNAL_##severity, absl_raw_log_internal_filename, \ __LINE__, message); \ ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_##severity; \ } while (0) #define ABSL_INTERNAL_CHECK(condition, message) \ do { \ if (ABSL_PREDICT_FALSE(!(condition))) { \ std::string death_message = "Check " #condition " failed: "; \ death_message += std::string(message); \ ABSL_INTERNAL_LOG(FATAL, death_message); \ } \ } while (0) #ifndef NDEBUG #define ABSL_RAW_DLOG(severity, ...) ABSL_RAW_LOG(severity, __VA_ARGS__) #define ABSL_RAW_DCHECK(condition, message) ABSL_RAW_CHECK(condition, message) #else #define ABSL_RAW_DLOG(severity, ...) \ while (false) ABSL_RAW_LOG(severity, __VA_ARGS__) #define ABSL_RAW_DCHECK(condition, message) \ while (false) ABSL_RAW_CHECK(condition, message) #endif #define ABSL_RAW_LOG_INTERNAL_INFO ::absl::LogSeverity::kInfo #define ABSL_RAW_LOG_INTERNAL_WARNING ::absl::LogSeverity::kWarning #define ABSL_RAW_LOG_INTERNAL_ERROR ::absl::LogSeverity::kError #define ABSL_RAW_LOG_INTERNAL_FATAL ::absl::LogSeverity::kFatal #define ABSL_RAW_LOG_INTERNAL_DFATAL ::absl::kLogDebugFatal #define ABSL_RAW_LOG_INTERNAL_LEVEL(severity) \ ::absl::NormalizeLogSeverity(severity) #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_INFO #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_WARNING #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_ERROR #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_FATAL ABSL_UNREACHABLE() #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_DFATAL #define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_LEVEL(severity) namespace absl { ABSL_NAMESPACE_BEGIN namespace raw_log_internal { void RawLog(absl::LogSeverity severity, const char* file, int line, const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5); void AsyncSignalSafeWriteError(const char* s, size_t len); constexpr const char* Basename(const char* fname, int offset) { return offset == 0 || fname[offset - 1] == '/' || fname[offset - 1] == '\\' ? fname + offset : Basename(fname, offset - 1); } bool RawLoggingFullySupported(); using LogFilterAndPrefixHook = bool (*)(absl::LogSeverity severity, const char* file, int line, char** buf, int* buf_size); using AbortHook = void (*)(const char* file, int line, const char* buf_start, const char* prefix_end, const char* buf_end); using InternalLogFunction = void (*)(absl::LogSeverity severity, const char* file, int line, const std::string& message); ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL extern base_internal::AtomicHook< InternalLogFunction> internal_log_function; void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func); void RegisterAbortHook(AbortHook func); void RegisterInternalLogFunction(InternalLogFunction func); } ABSL_NAMESPACE_END } #endif #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, strlen(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, 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); } }
2,527
#ifndef ABSL_BASE_INTERNAL_THROW_DELEGATE_H_ #define ABSL_BASE_INTERNAL_THROW_DELEGATE_H_ #include <string> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { [[noreturn]] void ThrowStdLogicError(const std::string& what_arg); [[noreturn]] void ThrowStdLogicError(const char* what_arg); [[noreturn]] void ThrowStdInvalidArgument(const std::string& what_arg); [[noreturn]] void ThrowStdInvalidArgument(const char* what_arg); [[noreturn]] void ThrowStdDomainError(const std::string& what_arg); [[noreturn]] void ThrowStdDomainError(const char* what_arg); [[noreturn]] void ThrowStdLengthError(const std::string& what_arg); [[noreturn]] void ThrowStdLengthError(const char* what_arg); [[noreturn]] void ThrowStdOutOfRange(const std::string& what_arg); [[noreturn]] void ThrowStdOutOfRange(const char* what_arg); [[noreturn]] void ThrowStdRuntimeError(const std::string& what_arg); [[noreturn]] void ThrowStdRuntimeError(const char* what_arg); [[noreturn]] void ThrowStdRangeError(const std::string& what_arg); [[noreturn]] void ThrowStdRangeError(const char* what_arg); [[noreturn]] void ThrowStdOverflowError(const std::string& what_arg); [[noreturn]] void ThrowStdOverflowError(const char* what_arg); [[noreturn]] void ThrowStdUnderflowError(const std::string& what_arg); [[noreturn]] void ThrowStdUnderflowError(const char* what_arg); [[noreturn]] void ThrowStdBadFunctionCall(); [[noreturn]] void ThrowStdBadAlloc(); } ABSL_NAMESPACE_END } #endif #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); } }
2,528
#ifndef ABSL_BASE_INTERNAL_SYSINFO_H_ #define ABSL_BASE_INTERNAL_SYSINFO_H_ #ifndef _WIN32 #include <sys/types.h> #endif #include <cstdint> #include "absl/base/config.h" #include "absl/base/port.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { double NominalCPUFrequency(); int NumCPUs(); #ifdef _WIN32 using pid_t = uint32_t; #endif pid_t GetTID(); pid_t GetCachedTID(); } ABSL_NAMESPACE_END } #endif #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 #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); } #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 }
2,529
#ifndef ABSL_BASE_INTERNAL_SCOPED_SET_ENV_H_ #define ABSL_BASE_INTERNAL_SCOPED_SET_ENV_H_ #include <string> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { class ScopedSetEnv { public: ScopedSetEnv(const char* var_name, const char* new_value); ~ScopedSetEnv(); private: std::string var_name_; std::string old_value_; bool was_unset_; }; } ABSL_NAMESPACE_END } #endif #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"); } }
2,530
#ifndef ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_ #define ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_ #include <cmath> #include <cstdint> #include <istream> #include <limits> #include <type_traits> #include "absl/base/config.h" #include "absl/random/internal/fast_uniform_bits.h" #include "absl/random/internal/generate_real.h" #include "absl/random/internal/iostream_state_saver.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { class ABSL_DLL gaussian_distribution_base { public: template <typename URBG> inline double zignor(URBG& g); private: friend class TableGenerator; template <typename URBG> inline double zignor_fallback(URBG& g, bool neg); static constexpr double kR = 3.442619855899; static constexpr double kRInv = 0.29047645161474317; static constexpr double kV = 9.91256303526217e-3; static constexpr uint64_t kMask = 0x07f; struct Tables { double x[kMask + 2]; double f[kMask + 2]; }; static const Tables zg_; random_internal::FastUniformBits<uint64_t> fast_u64_; }; } template <typename RealType = double> class gaussian_distribution : random_internal::gaussian_distribution_base { public: using result_type = RealType; class param_type { public: using distribution_type = gaussian_distribution; explicit param_type(result_type mean = 0, result_type stddev = 1) : mean_(mean), stddev_(stddev) {} result_type mean() const { return mean_; } result_type stddev() const { return stddev_; } friend bool operator==(const param_type& a, const param_type& b) { return a.mean_ == b.mean_ && a.stddev_ == b.stddev_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: result_type mean_; result_type stddev_; static_assert( std::is_floating_point<RealType>::value, "Class-template absl::gaussian_distribution<> must be parameterized " "using a floating-point type."); }; gaussian_distribution() : gaussian_distribution(0) {} explicit gaussian_distribution(result_type mean, result_type stddev = 1) : param_(mean, stddev) {} explicit gaussian_distribution(const param_type& p) : param_(p) {} void reset() {} template <typename URBG> result_type operator()(URBG& g) { return (*this)(g, param_); } template <typename URBG> result_type operator()(URBG& g, const param_type& p); param_type param() const { return param_; } void param(const param_type& p) { param_ = p; } result_type(min)() const { return -std::numeric_limits<result_type>::infinity(); } result_type(max)() const { return std::numeric_limits<result_type>::infinity(); } result_type mean() const { return param_.mean(); } result_type stddev() const { return param_.stddev(); } friend bool operator==(const gaussian_distribution& a, const gaussian_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const gaussian_distribution& a, const gaussian_distribution& b) { return a.param_ != b.param_; } private: param_type param_; }; template <typename RealType> template <typename URBG> typename gaussian_distribution<RealType>::result_type gaussian_distribution<RealType>::operator()( URBG& g, const param_type& p) { return p.mean() + p.stddev() * static_cast<result_type>(zignor(g)); } template <typename CharT, typename Traits, typename RealType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const gaussian_distribution<RealType>& x) { auto saver = random_internal::make_ostream_state_saver(os); os.precision(random_internal::stream_precision_helper<RealType>::kPrecision); os << x.mean() << os.fill() << x.stddev(); return os; } template <typename CharT, typename Traits, typename RealType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, gaussian_distribution<RealType>& x) { using result_type = typename gaussian_distribution<RealType>::result_type; using param_type = typename gaussian_distribution<RealType>::param_type; auto saver = random_internal::make_istream_state_saver(is); auto mean = random_internal::read_floating_point<result_type>(is); if (is.fail()) return is; auto stddev = random_internal::read_floating_point<result_type>(is); if (!is.fail()) { x.param(param_type(mean, stddev)); } return is; } namespace random_internal { template <typename URBG> inline double gaussian_distribution_base::zignor_fallback(URBG& g, bool neg) { using random_internal::GeneratePositiveTag; using random_internal::GenerateRealFromBits; double x, y; do { x = kRInv * std::log(GenerateRealFromBits<double, GeneratePositiveTag, false>( fast_u64_(g))); y = -std::log( GenerateRealFromBits<double, GeneratePositiveTag, false>(fast_u64_(g))); } while ((y + y) < (x * x)); return neg ? (x - kR) : (kR - x); } template <typename URBG> inline double gaussian_distribution_base::zignor( URBG& g) { using random_internal::GeneratePositiveTag; using random_internal::GenerateRealFromBits; using random_internal::GenerateSignedTag; while (true) { uint64_t bits = fast_u64_(g); int i = static_cast<int>(bits & kMask); double j = GenerateRealFromBits<double, GenerateSignedTag, false>( bits); const double x = j * zg_.x[i]; if (std::abs(x) < zg_.x[i + 1]) { return x; } if (i == 0) { return zignor_fallback(g, j < 0); } double v = GenerateRealFromBits<double, GeneratePositiveTag, false>( fast_u64_(g)); if ((zg_.f[i + 1] + v * (zg_.f[i] - zg_.f[i + 1])) < std::exp(-0.5 * x * x)) { return x; } } } } ABSL_NAMESPACE_END } #endif #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()); } } }
2,531
#ifndef ABSL_RANDOM_SEED_SEQUENCES_H_ #define ABSL_RANDOM_SEED_SEQUENCES_H_ #include <iterator> #include <random> #include "absl/base/config.h" #include "absl/base/nullability.h" #include "absl/random/internal/salted_seed_seq.h" #include "absl/random/internal/seed_material.h" #include "absl/random/seed_gen_exception.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN using SeedSeq = random_internal::SaltedSeedSeq<std::seed_seq>; template <typename URBG> SeedSeq CreateSeedSeqFrom(URBG* urbg) { SeedSeq::result_type seed_material[random_internal::kEntropyBlocksNeeded]; if (!random_internal::ReadSeedMaterialFromURBG( urbg, absl::MakeSpan(seed_material))) { random_internal::ThrowSeedGenException(); } return SeedSeq(std::begin(seed_material), std::end(seed_material)); } SeedSeq MakeSeedSeq(); ABSL_NAMESPACE_END } #endif #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>(); } }
2,532
#ifndef ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_ #define ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_ #include <cassert> #include <cmath> #include <istream> #include <limits> #include <numeric> #include <type_traits> #include <utility> #include <vector> #include "absl/random/bernoulli_distribution.h" #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/uniform_int_distribution.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename IntType = int> class discrete_distribution { public: using result_type = IntType; class param_type { public: using distribution_type = discrete_distribution; param_type() { init(); } template <typename InputIterator> explicit param_type(InputIterator begin, InputIterator end) : p_(begin, end) { init(); } explicit param_type(std::initializer_list<double> weights) : p_(weights) { init(); } template <class UnaryOperation> explicit param_type(size_t nw, double xmin, double xmax, UnaryOperation fw) { if (nw > 0) { p_.reserve(nw); double delta = (xmax - xmin) / static_cast<double>(nw); assert(delta > 0); double t = delta * 0.5; for (size_t i = 0; i < nw; ++i) { p_.push_back(fw(xmin + i * delta + t)); } } init(); } const std::vector<double>& probabilities() const { return p_; } size_t n() const { return p_.size() - 1; } friend bool operator==(const param_type& a, const param_type& b) { return a.probabilities() == b.probabilities(); } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class discrete_distribution; void init(); std::vector<double> p_; std::vector<std::pair<double, size_t>> q_; static_assert(std::is_integral<result_type>::value, "Class-template absl::discrete_distribution<> must be " "parameterized using an integral type."); }; discrete_distribution() : param_() {} explicit discrete_distribution(const param_type& p) : param_(p) {} template <typename InputIterator> explicit discrete_distribution(InputIterator begin, InputIterator end) : param_(begin, end) {} explicit discrete_distribution(std::initializer_list<double> weights) : param_(weights) {} template <class UnaryOperation> explicit discrete_distribution(size_t nw, double xmin, double xmax, UnaryOperation fw) : param_(nw, xmin, xmax, std::move(fw)) {} void reset() {} template <typename URBG> result_type operator()(URBG& g) { return (*this)(g, param_); } template <typename URBG> result_type operator()(URBG& g, const param_type& p); const param_type& param() const { return param_; } void param(const param_type& p) { param_ = p; } result_type(min)() const { return 0; } result_type(max)() const { return static_cast<result_type>(param_.n()); } const std::vector<double>& probabilities() const { return param_.probabilities(); } friend bool operator==(const discrete_distribution& a, const discrete_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const discrete_distribution& a, const discrete_distribution& b) { return a.param_ != b.param_; } private: param_type param_; }; namespace random_internal { std::vector<std::pair<double, size_t>> InitDiscreteDistribution( std::vector<double>* probabilities); } template <typename IntType> void discrete_distribution<IntType>::param_type::init() { if (p_.empty()) { p_.push_back(1.0); q_.emplace_back(1.0, 0); } else { assert(n() <= (std::numeric_limits<IntType>::max)()); q_ = random_internal::InitDiscreteDistribution(&p_); } } template <typename IntType> template <typename URBG> typename discrete_distribution<IntType>::result_type discrete_distribution<IntType>::operator()( URBG& g, const param_type& p) { const auto idx = absl::uniform_int_distribution<result_type>(0, p.n())(g); const auto& q = p.q_[idx]; const bool selected = absl::bernoulli_distribution(q.first)(g); return selected ? idx : static_cast<result_type>(q.second); } template <typename CharT, typename Traits, typename IntType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const discrete_distribution<IntType>& x) { auto saver = random_internal::make_ostream_state_saver(os); const auto& probabilities = x.param().probabilities(); os << probabilities.size(); os.precision(random_internal::stream_precision_helper<double>::kPrecision); for (const auto& p : probabilities) { os << os.fill() << p; } return os; } template <typename CharT, typename Traits, typename IntType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, discrete_distribution<IntType>& x) { using param_type = typename discrete_distribution<IntType>::param_type; auto saver = random_internal::make_istream_state_saver(is); size_t n; std::vector<double> p; is >> n; if (is.fail()) return is; if (n > 0) { p.reserve(n); for (IntType i = 0; i < n && !is.fail(); ++i) { auto tmp = random_internal::read_floating_point<double>(is); if (is.fail()) return is; p.push_back(tmp); } } x.param(param_type(p.begin(), p.end())); return is; } ABSL_NAMESPACE_END } #endif #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)); } }
2,533
#ifndef ABSL_RANDOM_INTERNAL_RANDEN_HWAES_H_ #define ABSL_RANDOM_INTERNAL_RANDEN_HWAES_H_ #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { class RandenHwAes { public: static void Generate(const void* keys, void* state_void); static void Absorb(const void* seed_void, void* state_void); static const void* GetKeys(); }; bool HasRandenHwAesImplementation(); } ABSL_NAMESPACE_END } #endif #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(); }
2,534
#ifndef ABSL_RANDOM_INTERNAL_CHI_SQUARE_H_ #define ABSL_RANDOM_INTERNAL_CHI_SQUARE_H_ #include <cassert> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { constexpr const char kChiSquared[] = "chi-squared"; template <typename Iterator> double ChiSquareWithExpected(Iterator begin, Iterator end, double expected) { assert(expected >= 10); double chi_square = 0; for (auto it = begin; it != end; it++) { double d = static_cast<double>(*it) - expected; chi_square += d * d; } chi_square = chi_square / expected; return chi_square; } template <typename Iterator, typename Expected> double ChiSquare(Iterator it, Iterator end, Expected eit, Expected eend) { double chi_square = 0; for (; it != end && eit != eend; ++it, ++eit) { if (*it > 0) { assert(*eit > 0); } double e = static_cast<double>(*eit); double d = static_cast<double>(*it - *eit); if (d != 0) { assert(e > 0); chi_square += (d * d) / e; } } assert(it == end && eit == eend); return chi_square; } double ChiSquareValue(int dof, double p); double ChiSquarePValue(double chi_square, int dof); } ABSL_NAMESPACE_END } #endif #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); } }
2,535
#ifndef ABSL_RANDOM_INTERNAL_SEED_MATERIAL_H_ #define ABSL_RANDOM_INTERNAL_SEED_MATERIAL_H_ #include <cassert> #include <cstdint> #include <cstdlib> #include <string> #include <vector> #include "absl/base/attributes.h" #include "absl/random/internal/fast_uniform_bits.h" #include "absl/types/optional.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { constexpr size_t SeedBitsToBlocks(size_t seed_size) { return (seed_size + 31) / 32; } constexpr size_t kEntropyBitsNeeded = 256; constexpr size_t kEntropyBlocksNeeded = random_internal::SeedBitsToBlocks(kEntropyBitsNeeded); static_assert(kEntropyBlocksNeeded > 0, "Entropy used to seed URBGs must be nonzero."); ABSL_MUST_USE_RESULT bool ReadSeedMaterialFromOSEntropy(absl::Span<uint32_t> values); template <typename URBG> ABSL_MUST_USE_RESULT bool ReadSeedMaterialFromURBG( URBG* urbg, absl::Span<uint32_t> values) { random_internal::FastUniformBits<uint32_t> distr; assert(urbg != nullptr && values.data() != nullptr); if (urbg == nullptr || values.data() == nullptr) { return false; } for (uint32_t& seed_value : values) { seed_value = distr(*urbg); } return true; } void MixIntoSeedMaterial(absl::Span<const uint32_t> sequence, absl::Span<uint32_t> seed_material); absl::optional<uint32_t> GetSaltMaterial(); } ABSL_NAMESPACE_END } #endif #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()); } } }
2,536
#ifndef ABSL_RANDOM_INTERNAL_NANOBENCHMARK_H_ #define ABSL_RANDOM_INTERNAL_NANOBENCHMARK_H_ #include <stddef.h> #include <stdint.h> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal_nanobenchmark { using FuncInput = size_t; using FuncOutput = uint64_t; using Func = FuncOutput (*)(const void*, FuncInput); struct Params { static constexpr size_t kTimerSamples = 256; size_t precision_divisor = 1024; size_t subset_ratio = 2; double seconds_per_eval = 4E-3; size_t min_samples_per_eval = 7; size_t min_mode_samples = 64; double target_rel_mad = 0.002; size_t max_evals = 9; size_t max_measure_retries = 2; bool verbose = true; }; struct Result { FuncInput input; float ticks; float variability; }; void PinThreadToCPU(const int cpu = -1); double InvariantTicksPerSecond(); size_t Measure(const Func func, const void* arg, const FuncInput* inputs, const size_t num_inputs, Result* results, const Params& p = Params()); template <class Closure> static FuncOutput CallClosure(const void* f, const FuncInput input) { return (*reinterpret_cast<const Closure*>(f))(input); } template <class Closure> static inline size_t MeasureClosure(const Closure& closure, const FuncInput* inputs, const size_t num_inputs, Result* results, const Params& p = Params()) { return Measure(reinterpret_cast<Func>(&CallClosure<Closure>), reinterpret_cast<const void*>(&closure), inputs, num_inputs, results, p); } } ABSL_NAMESPACE_END } #endif #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)
#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; }
2,537
#ifndef ABSL_RANDOM_INTERNAL_POOL_URBG_H_ #define ABSL_RANDOM_INTERNAL_POOL_URBG_H_ #include <cinttypes> #include <limits> #include "absl/random/internal/traits.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename T> class RandenPool { public: using result_type = T; static_assert(std::is_unsigned<result_type>::value, "RandenPool template argument must be a built-in unsigned " "integer type"); static constexpr result_type(min)() { return (std::numeric_limits<result_type>::min)(); } static constexpr result_type(max)() { return (std::numeric_limits<result_type>::max)(); } RandenPool() {} inline result_type operator()() { return Generate(); } static void Fill(absl::Span<result_type> data); protected: static result_type Generate(); }; extern template class RandenPool<uint8_t>; extern template class RandenPool<uint16_t>; extern template class RandenPool<uint32_t>; extern template class RandenPool<uint64_t>; template <typename T, size_t kBufferSize> class PoolURBG { using unsigned_type = typename make_unsigned_bits<T>::type; using PoolType = RandenPool<unsigned_type>; using SpanType = absl::Span<unsigned_type>; static constexpr size_t kInitialBuffer = kBufferSize + 1; static constexpr size_t kHalfBuffer = kBufferSize / 2; public: using result_type = T; static_assert(std::is_unsigned<result_type>::value, "PoolURBG must be parameterized by an unsigned integer type"); static_assert(kBufferSize > 1, "PoolURBG must be parameterized by a buffer-size > 1"); static_assert(kBufferSize <= 256, "PoolURBG must be parameterized by a buffer-size <= 256"); static constexpr result_type(min)() { return (std::numeric_limits<result_type>::min)(); } static constexpr result_type(max)() { return (std::numeric_limits<result_type>::max)(); } PoolURBG() : next_(kInitialBuffer) {} PoolURBG(const PoolURBG&) : next_(kInitialBuffer) {} const PoolURBG& operator=(const PoolURBG&) { next_ = kInitialBuffer; return *this; } PoolURBG(PoolURBG&&) = default; PoolURBG& operator=(PoolURBG&&) = default; inline result_type operator()() { if (next_ >= kBufferSize) { next_ = (kBufferSize > 2 && next_ > kBufferSize) ? kHalfBuffer : 0; PoolType::Fill(SpanType(reinterpret_cast<unsigned_type*>(state_ + next_), kBufferSize - next_)); } return state_[next_++]; } private: size_t next_; result_type state_[kBufferSize]; }; } ABSL_NAMESPACE_END } #endif #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); } }
2,538
#ifndef ABSL_RANDOM_INTERNAL_RANDEN_SLOW_H_ #define ABSL_RANDOM_INTERNAL_RANDEN_SLOW_H_ #include <cstddef> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { class RandenSlow { public: static void Generate(const void* keys, void* state_void); static void Absorb(const void* seed_void, void* state_void); static const void* GetKeys(); }; } ABSL_NAMESPACE_END } #endif #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))); } }
2,539
#ifndef ABSL_RANDOM_INTERNAL_DISTRIBUTION_TEST_UTIL_H_ #define ABSL_RANDOM_INTERNAL_DISTRIBUTION_TEST_UTIL_H_ #include <cstddef> #include <iostream> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { struct DistributionMoments { size_t n = 0; double mean = 0.0; double variance = 0.0; double skewness = 0.0; double kurtosis = 0.0; }; DistributionMoments ComputeDistributionMoments( absl::Span<const double> data_points); std::ostream& operator<<(std::ostream& os, const DistributionMoments& moments); double ZScore(double expected_mean, const DistributionMoments& moments); double RequiredSuccessProbability(double p_fail, int num_trials); double MaxErrorTolerance(double acceptance_probability); double erfinv(double x); double beta(double p, double q); double InverseNormalSurvival(double x); bool Near(absl::string_view msg, double actual, double expected, double bound); double BetaIncomplete(double x, double p, double q); double BetaIncompleteInv(double p, double q, double alpha); } ABSL_NAMESPACE_END } #endif #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); } }
2,540
#ifndef ABSL_RANDOM_INTERNAL_RANDEN_H_ #define ABSL_RANDOM_INTERNAL_RANDEN_H_ #include <cstddef> #include "absl/random/internal/platform.h" #include "absl/random/internal/randen_hwaes.h" #include "absl/random/internal/randen_slow.h" #include "absl/random/internal/randen_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { class Randen { public: static constexpr size_t kStateBytes = RandenTraits::kStateBytes; static constexpr size_t kCapacityBytes = RandenTraits::kCapacityBytes; static constexpr size_t kSeedBytes = RandenTraits::kSeedBytes; ~Randen() = default; Randen(); inline void Generate(void* state) const { #if ABSL_RANDOM_INTERNAL_AES_DISPATCH if (has_crypto_) { RandenHwAes::Generate(keys_, state); } else { RandenSlow::Generate(keys_, state); } #elif ABSL_HAVE_ACCELERATED_AES RandenHwAes::Generate(keys_, state); #else RandenSlow::Generate(keys_, state); #endif } inline void Absorb(const void* seed, void* state) const { #if ABSL_RANDOM_INTERNAL_AES_DISPATCH if (has_crypto_) { RandenHwAes::Absorb(seed, state); } else { RandenSlow::Absorb(seed, state); } #elif ABSL_HAVE_ACCELERATED_AES RandenHwAes::Absorb(seed, state); #else RandenSlow::Absorb(seed, state); #endif } private: const void* keys_; #if ABSL_RANDOM_INTERNAL_AES_DISPATCH bool has_crypto_; #endif }; } ABSL_NAMESPACE_END } #endif #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))); } }
2,541
#ifndef ABSL_CRC_INTERNAL_CRC32C_H_ #define ABSL_CRC_INTERNAL_CRC32C_H_ #include "absl/base/config.h" #include "absl/crc/crc32c.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace crc_internal { crc32c_t UnextendCrc32cByZeroes(crc32c_t initial_crc, size_t length); } ABSL_NAMESPACE_END } #endif #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"); } }
2,542
#ifndef ABSL_CRC_INTERNAL_CRC_CORD_STATE_H_ #define ABSL_CRC_INTERNAL_CRC_CORD_STATE_H_ #include <atomic> #include <cstddef> #include <deque> #include "absl/base/config.h" #include "absl/crc/crc32c.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace crc_internal { class CrcCordState { public: CrcCordState(); CrcCordState(const CrcCordState&); CrcCordState(CrcCordState&&); ~CrcCordState(); CrcCordState& operator=(const CrcCordState&); CrcCordState& operator=(CrcCordState&&); struct PrefixCrc { PrefixCrc() = default; PrefixCrc(size_t length_arg, absl::crc32c_t crc_arg) : length(length_arg), crc(crc_arg) {} size_t length = 0; absl::crc32c_t crc = absl::crc32c_t{0}; }; struct Rep { PrefixCrc removed_prefix; std::deque<PrefixCrc> prefix_crc; }; const Rep& rep() const { return refcounted_rep_->rep; } Rep* mutable_rep() { if (refcounted_rep_->count.load(std::memory_order_acquire) != 1) { RefcountedRep* copy = new RefcountedRep; copy->rep = refcounted_rep_->rep; Unref(refcounted_rep_); refcounted_rep_ = copy; } return &refcounted_rep_->rep; } absl::crc32c_t Checksum() const; bool IsNormalized() const { return rep().removed_prefix.length == 0; } void Normalize(); size_t NumChunks() const { return rep().prefix_crc.size(); } PrefixCrc NormalizedPrefixCrcAtNthChunk(size_t n) const; void Poison(); private: struct RefcountedRep { std::atomic<int32_t> count{1}; Rep rep; }; static RefcountedRep* RefSharedEmptyRep(); static void Ref(RefcountedRep* r) { assert(r != nullptr); r->count.fetch_add(1, std::memory_order_relaxed); } static void Unref(RefcountedRep* r) { assert(r != nullptr); if (r->count.fetch_sub(1, std::memory_order_acq_rel) == 1) { delete r; } } RefcountedRep* refcounted_rep_; }; } ABSL_NAMESPACE_END } #endif #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); } }
2,543
#ifndef ABSL_LOG_DIE_IF_NULL_H_ #define ABSL_LOG_DIE_IF_NULL_H_ #include <stdint.h> #include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/optimization.h" #define ABSL_DIE_IF_NULL(val) \ ::absl::log_internal::DieIfNull(__FILE__, __LINE__, #val, (val)) namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { ABSL_ATTRIBUTE_NORETURN ABSL_ATTRIBUTE_NOINLINE void DieBecauseNull( const char* file, int line, const char* exprtext); template <typename T> ABSL_MUST_USE_RESULT T DieIfNull(const char* file, int line, const char* exprtext, T&& t) { if (ABSL_PREDICT_FALSE(t == nullptr)) { DieBecauseNull(file, line, exprtext); } return std::forward<T>(t); } } ABSL_NAMESPACE_END } #endif #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); } }
2,544
#ifndef ABSL_LOG_LOG_ENTRY_H_ #define ABSL_LOG_LOG_ENTRY_H_ #include <cstddef> #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/log/internal/config.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { class LogEntryTestPeer; class LogMessage; } class LogEntry final { public: using tid_t = log_internal::Tid; static constexpr int kNoVerbosityLevel = -1; static constexpr int kNoVerboseLevel = -1; LogEntry(const LogEntry&) = delete; LogEntry& operator=(const LogEntry&) = delete; absl::string_view source_filename() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return full_filename_; } absl::string_view source_basename() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return base_filename_; } int source_line() const { return line_; } bool prefix() const { return prefix_; } absl::LogSeverity log_severity() const { return severity_; } int verbosity() const { return verbose_level_; } absl::Time timestamp() const { return timestamp_; } tid_t tid() const { return tid_; } absl::string_view text_message_with_prefix_and_newline() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return absl::string_view( text_message_with_prefix_and_newline_and_nul_.data(), text_message_with_prefix_and_newline_and_nul_.size() - 1); } absl::string_view text_message_with_prefix() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return absl::string_view( text_message_with_prefix_and_newline_and_nul_.data(), text_message_with_prefix_and_newline_and_nul_.size() - 2); } absl::string_view text_message_with_newline() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return absl::string_view( text_message_with_prefix_and_newline_and_nul_.data() + prefix_len_, text_message_with_prefix_and_newline_and_nul_.size() - prefix_len_ - 1); } absl::string_view text_message() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return absl::string_view( text_message_with_prefix_and_newline_and_nul_.data() + prefix_len_, text_message_with_prefix_and_newline_and_nul_.size() - prefix_len_ - 2); } const char* text_message_with_prefix_and_newline_c_str() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return text_message_with_prefix_and_newline_and_nul_.data(); } absl::string_view encoded_message() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return encoding_; } absl::string_view stacktrace() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return stacktrace_; } private: LogEntry() = default; absl::string_view full_filename_; absl::string_view base_filename_; int line_; bool prefix_; absl::LogSeverity severity_; int verbose_level_; absl::Time timestamp_; tid_t tid_; absl::Span<const char> text_message_with_prefix_and_newline_and_nul_; size_t prefix_len_; absl::string_view encoding_; std::string stacktrace_; friend class log_internal::LogEntryTestPeer; friend class log_internal::LogMessage; }; ABSL_NAMESPACE_END } #endif #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")); } }
2,545
#ifndef ABSL_LOG_INTERNAL_GLOBALS_H_ #define ABSL_LOG_INTERNAL_GLOBALS_H_ #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { bool IsInitialized(); void SetInitialized(); void WriteToStderr(absl::string_view message, absl::LogSeverity severity); void SetTimeZone(absl::TimeZone tz); const absl::TimeZone* TimeZone(); bool ShouldSymbolizeLogStackTrace(); void EnableSymbolizeLogStackTrace(bool on_off); int MaxFramesInLogStackTrace(); void SetMaxFramesInLogStackTrace(int max_num_frames); bool ExitOnDFatal(); void SetExitOnDFatal(bool on_off); bool SuppressSigabortTrace(); bool SetSuppressSigabortTrace(bool on_off); } ABSL_NAMESPACE_END } #endif #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); } 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 }
2,546
#ifndef ABSL_LOG_INTERNAL_FLAGS_H_ #define ABSL_LOG_INTERNAL_FLAGS_H_ #include <string> #include "absl/flags/declare.h" ABSL_DECLARE_FLAG(int, stderrthreshold); ABSL_DECLARE_FLAG(int, minloglevel); ABSL_DECLARE_FLAG(std::string, log_backtrace_at); ABSL_DECLARE_FLAG(bool, log_prefix); ABSL_DECLARE_FLAG(int, v); ABSL_DECLARE_FLAG(std::string, vmodule); #endif #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(); } }
2,547
#ifndef ABSL_LOG_SCOPED_MOCK_LOG_H_ #define ABSL_LOG_SCOPED_MOCK_LOG_H_ #include <atomic> #include <string> #include "gmock/gmock.h" #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/log/log_entry.h" #include "absl/log/log_sink.h" namespace absl { ABSL_NAMESPACE_BEGIN enum class MockLogDefault { kIgnoreUnexpected, kDisallowUnexpected }; class ScopedMockLog final { public: explicit ScopedMockLog( MockLogDefault default_exp = MockLogDefault::kIgnoreUnexpected); ScopedMockLog(const ScopedMockLog&) = delete; ScopedMockLog& operator=(const ScopedMockLog&) = delete; ~ScopedMockLog(); void StartCapturingLogs(); void StopCapturingLogs(); absl::LogSink& UseAsLocalSink(); MOCK_METHOD(void, Log, (absl::LogSeverity severity, const std::string& file_path, const std::string& message)); MOCK_METHOD(void, Send, (const absl::LogEntry&)); MOCK_METHOD(void, Flush, ()); private: class ForwardingSink final : public absl::LogSink { public: explicit ForwardingSink(ScopedMockLog* sml) : sml_(sml) {} ForwardingSink(const ForwardingSink&) = delete; ForwardingSink& operator=(const ForwardingSink&) = delete; void Send(const absl::LogEntry& entry) override { sml_->Send(entry); } void Flush() override { sml_->Flush(); } private: ScopedMockLog* sml_; }; ForwardingSink sink_; bool is_capturing_logs_; std::atomic<bool> is_triggered_; }; ABSL_NAMESPACE_END } #endif #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"; } }
2,548
#ifndef ABSL_LOG_LOG_SINK_H_ #define ABSL_LOG_LOG_SINK_H_ #include "absl/base/config.h" #include "absl/log/log_entry.h" namespace absl { ABSL_NAMESPACE_BEGIN class LogSink { public: virtual ~LogSink() = default; virtual void Send(const absl::LogEntry& entry) = 0; virtual void Flush() {} protected: LogSink() = default; LogSink(const LogSink&) = default; LogSink& operator=(const LogSink&) = default; private: virtual void KeyFunction() const final; }; ABSL_NAMESPACE_END } #endif #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()); } }
2,549
#ifndef ABSL_LOG_INTERNAL_FNMATCH_H_ #define ABSL_LOG_INTERNAL_FNMATCH_H_ #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); } ABSL_NAMESPACE_END } #endif #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()); } }
2,550
#ifndef ABSL_LOG_INTERNAL_LOG_FORMAT_H_ #define ABSL_LOG_INTERNAL_LOG_FORMAT_H_ #include <stddef.h> #include <string> #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/log/internal/config.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 { enum class PrefixFormat { kNotRaw, kRaw, }; 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); 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); } ABSL_NAMESPACE_END } #endif #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(EqualsProto(R"pb()pb"))))); 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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( AnyOf(EqualsProto(R"pb(value { str: "-nan" })pb"), EqualsProto(R"pb(value { str: "nan" })pb"), EqualsProto(R"pb(value { 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( AnyOf(EqualsProto(R"pb(value { str: "-nan" })pb"), EqualsProto(R"pb(value { str: "nan" })pb"), EqualsProto(R"pb(value { 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(AnyOf( EqualsProto(R"pb(value { str: "0xdeadbeef" })pb"), EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto( R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { 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(EqualsProto(R"pb(value { str: "77" })pb"))))); test_sink.StartCapturingLogs(); LOG(INFO) << p << 77; } struct PointMultipleAppend
2,551
#ifndef ABSL_STRINGS_CORD_H_ #define ABSL_STRINGS_CORD_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <iosfwd> #include <iterator> #include <string> #include <type_traits> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/internal/per_thread_tls.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/base/port.h" #include "absl/container/inlined_vector.h" #include "absl/crc/internal/crc_cord_state.h" #include "absl/functional/function_ref.h" #include "absl/meta/type_traits.h" #include "absl/strings/cord_analysis.h" #include "absl/strings/cord_buffer.h" #include "absl/strings/internal/cord_data_edge.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" #include "absl/strings/internal/cord_rep_btree_reader.h" #include "absl/strings/internal/cord_rep_crc.h" #include "absl/strings/internal/cordz_functions.h" #include "absl/strings/internal/cordz_info.h" #include "absl/strings/internal/cordz_statistics.h" #include "absl/strings/internal/cordz_update_scope.h" #include "absl/strings/internal/cordz_update_tracker.h" #include "absl/strings/internal/resize_uninitialized.h" #include "absl/strings/internal/string_constant.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" namespace absl { ABSL_NAMESPACE_BEGIN class Cord; class CordTestPeer; template <typename Releaser> Cord MakeCordFromExternal(absl::string_view, Releaser&&); void CopyCordToString(const Cord& src, absl::Nonnull<std::string*> dst); void AppendCordToString(const Cord& src, absl::Nonnull<std::string*> dst); enum class CordMemoryAccounting { kTotal, kTotalMorePrecise, kFairShare, }; class Cord { private: template <typename T> using EnableIfString = absl::enable_if_t<std::is_same<T, std::string>::value, int>; public: constexpr Cord() noexcept; Cord(const Cord& src); Cord(Cord&& src) noexcept; Cord& operator=(const Cord& x); Cord& operator=(Cord&& x) noexcept; explicit Cord(absl::string_view src); Cord& operator=(absl::string_view src); template <typename T, EnableIfString<T> = 0> explicit Cord(T&& src); template <typename T, EnableIfString<T> = 0> Cord& operator=(T&& src); ~Cord() { if (contents_.is_tree()) DestroyCordSlow(); } template <typename Releaser> friend Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser); ABSL_ATTRIBUTE_REINITIALIZES void Clear(); void Append(const Cord& src); void Append(Cord&& src); void Append(absl::string_view src); template <typename T, EnableIfString<T> = 0> void Append(T&& src); void Append(CordBuffer buffer); CordBuffer GetAppendBuffer(size_t capacity, size_t min_capacity = 16); CordBuffer GetCustomAppendBuffer(size_t block_size, size_t capacity, size_t min_capacity = 16); void Prepend(const Cord& src); void Prepend(absl::string_view src); template <typename T, EnableIfString<T> = 0> void Prepend(T&& src); void Prepend(CordBuffer buffer); void RemovePrefix(size_t n); void RemoveSuffix(size_t n); Cord Subcord(size_t pos, size_t new_size) const; void swap(Cord& other) noexcept; friend void swap(Cord& x, Cord& y) noexcept { x.swap(y); } size_t size() const; bool empty() const; size_t EstimatedMemoryUsage(CordMemoryAccounting accounting_method = CordMemoryAccounting::kTotal) const; int Compare(absl::string_view rhs) const; int Compare(const Cord& rhs) const; bool StartsWith(const Cord& rhs) const; bool StartsWith(absl::string_view rhs) const; bool EndsWith(absl::string_view rhs) const; bool EndsWith(const Cord& rhs) const; bool Contains(absl::string_view rhs) const; bool Contains(const Cord& rhs) const; explicit operator std::string() const; friend void CopyCordToString(const Cord& src, absl::Nonnull<std::string*> dst); friend void AppendCordToString(const Cord& src, absl::Nonnull<std::string*> dst); class CharIterator; class ChunkIterator { public: using iterator_category = std::input_iterator_tag; using value_type = absl::string_view; using difference_type = ptrdiff_t; using pointer = absl::Nonnull<const value_type*>; using reference = value_type; ChunkIterator() = default; ChunkIterator& operator++(); ChunkIterator operator++(int); bool operator==(const ChunkIterator& other) const; bool operator!=(const ChunkIterator& other) const; reference operator*() const; pointer operator->() const; friend class Cord; friend class CharIterator; private: using CordRep = absl::cord_internal::CordRep; using CordRepBtree = absl::cord_internal::CordRepBtree; using CordRepBtreeReader = absl::cord_internal::CordRepBtreeReader; explicit ChunkIterator(absl::Nonnull<cord_internal::CordRep*> tree); explicit ChunkIterator(absl::Nonnull<const Cord*> cord); void InitTree(absl::Nonnull<cord_internal::CordRep*> tree); void RemoveChunkPrefix(size_t n); Cord AdvanceAndReadBytes(size_t n); void AdvanceBytes(size_t n); ChunkIterator& AdvanceBtree(); void AdvanceBytesBtree(size_t n); absl::string_view current_chunk_; absl::Nullable<absl::cord_internal::CordRep*> current_leaf_ = nullptr; size_t bytes_remaining_ = 0; CordRepBtreeReader btree_reader_; }; ChunkIterator chunk_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND; ChunkIterator chunk_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND; class ChunkRange { public: using value_type = absl::string_view; using reference = value_type&; using const_reference = const value_type&; using iterator = ChunkIterator; using const_iterator = ChunkIterator; explicit ChunkRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {} ChunkIterator begin() const; ChunkIterator end() const; private: absl::Nonnull<const Cord*> cord_; }; ChunkRange Chunks() const ABSL_ATTRIBUTE_LIFETIME_BOUND; class CharIterator { public: using iterator_category = std::input_iterator_tag; using value_type = char; using difference_type = ptrdiff_t; using pointer = absl::Nonnull<const char*>; using reference = const char&; CharIterator() = default; CharIterator& operator++(); CharIterator operator++(int); bool operator==(const CharIterator& other) const; bool operator!=(const CharIterator& other) const; reference operator*() const; pointer operator->() const; friend Cord; private: explicit CharIterator(absl::Nonnull<const Cord*> cord) : chunk_iterator_(cord) {} ChunkIterator chunk_iterator_; }; static Cord AdvanceAndRead(absl::Nonnull<CharIterator*> it, size_t n_bytes); static void Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes); static absl::string_view ChunkRemaining(const CharIterator& it); CharIterator char_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND; CharIterator char_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND; class CharRange { public: using value_type = char; using reference = value_type&; using const_reference = const value_type&; using iterator = CharIterator; using const_iterator = CharIterator; explicit CharRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {} CharIterator begin() const; CharIterator end() const; private: absl::Nonnull<const Cord*> cord_; }; CharRange Chars() const ABSL_ATTRIBUTE_LIFETIME_BOUND; char operator[](size_t i) const; absl::optional<absl::string_view> TryFlat() const ABSL_ATTRIBUTE_LIFETIME_BOUND; absl::string_view Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND; CharIterator Find(absl::string_view needle) const; CharIterator Find(const absl::Cord& needle) const; friend void AbslFormatFlush(absl::Nonnull<absl::Cord*> cord, absl::string_view part) { cord->Append(part); } template <typename Sink> friend void AbslStringify(Sink& sink, const absl::Cord& cord) { for (absl::string_view chunk : cord.Chunks()) { sink.Append(chunk); } }
#include "absl/strings/cord.h" #include <algorithm> #include <array> #include <cassert> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstring> #include <iostream> #include <iterator> #include <limits> #include <random> #include <set> #include <sstream> #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/internal/endian.h" #include "absl/base/macros.h" #include "absl/base/no_destructor.h" #include "absl/base/options.h" #include "absl/container/fixed_array.h" #include "absl/functional/function_ref.h" #include "absl/hash/hash.h" #include "absl/hash/hash_testing.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/random/random.h" #include "absl/strings/cord_buffer.h" #include "absl/strings/cord_test_helpers.h" #include "absl/strings/cordz_test_helpers.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_crc.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/internal/cordz_statistics.h" #include "absl/strings/internal/cordz_update_tracker.h" #include "absl/strings/internal/string_constant.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" static constexpr auto FLAT = absl::cord_internal::FLAT; static constexpr auto MAX_FLAT_TAG = absl::cord_internal::MAX_FLAT_TAG; typedef std::mt19937_64 RandomEngine; using absl::cord_internal::CordRep; using absl::cord_internal::CordRepBtree; using absl::cord_internal::CordRepConcat; using absl::cord_internal::CordRepCrc; using absl::cord_internal::CordRepExternal; using absl::cord_internal::CordRepFlat; using absl::cord_internal::CordRepSubstring; using absl::cord_internal::CordzUpdateTracker; using absl::cord_internal::kFlatOverhead; using absl::cord_internal::kMaxFlatLength; using ::testing::ElementsAre; using ::testing::Le; static std::string RandomLowercaseString(RandomEngine* rng); static std::string RandomLowercaseString(RandomEngine* rng, size_t length); static int GetUniformRandomUpTo(RandomEngine* rng, int upper_bound) { if (upper_bound > 0) { std::uniform_int_distribution<int> uniform(0, upper_bound - 1); return uniform(*rng); } else { return 0; } } static size_t GetUniformRandomUpTo(RandomEngine* rng, size_t upper_bound) { if (upper_bound > 0) { std::uniform_int_distribution<size_t> uniform(0, upper_bound - 1); return uniform(*rng); } else { return 0; } } static int32_t GenerateSkewedRandom(RandomEngine* rng, int max_log) { const uint32_t base = (*rng)() % (max_log + 1); const uint32_t mask = ((base < 32) ? (1u << base) : 0u) - 1u; return (*rng)() & mask; } static std::string RandomLowercaseString(RandomEngine* rng) { int length; std::bernoulli_distribution one_in_1k(0.001); std::bernoulli_distribution one_in_10k(0.0001); if (one_in_10k(*rng)) { length = GetUniformRandomUpTo(rng, 1048576); } else if (one_in_1k(*rng)) { length = GetUniformRandomUpTo(rng, 10000); } else { length = GenerateSkewedRandom(rng, 10); } return RandomLowercaseString(rng, length); } static std::string RandomLowercaseString(RandomEngine* rng, size_t length) { std::string result(length, '\0'); std::uniform_int_distribution<int> chars('a', 'z'); std::generate(result.begin(), result.end(), [&]() { return static_cast<char>(chars(*rng)); }); return result; } static void DoNothing(absl::string_view , void* ) {} static void DeleteExternalString(absl::string_view data, void* arg) { std::string* s = reinterpret_cast<std::string*>(arg); EXPECT_EQ(data, *s); delete s; } static void AddExternalMemory(absl::string_view s, absl::Cord* dst) { std::string* str = new std::string(s.data(), s.size()); dst->Append(absl::MakeCordFromExternal(*str, [str](absl::string_view data) { DeleteExternalString(data, str); })); } static void DumpGrowth() { absl::Cord str; for (int i = 0; i < 1000; i++) { char c = 'a' + i % 26; str.Append(absl::string_view(&c, 1)); } } static size_t AppendWithFragments(const std::string& s, RandomEngine* rng, absl::Cord* cord) { size_t j = 0; const size_t max_size = s.size() / 5; size_t min_size = max_size; while (j < s.size()) { size_t N = 1 + GetUniformRandomUpTo(rng, max_size); if (N > (s.size() - j)) { N = s.size() - j; } if (N < min_size) { min_size = N; } std::bernoulli_distribution coin_flip(0.5); if (coin_flip(*rng)) { AddExternalMemory(absl::string_view(s.data() + j, N), cord); } else { cord->Append(absl::string_view(s.data() + j, N)); } j += N; } return min_size; } static void AddNewStringBlock(const std::string& str, absl::Cord* dst) { char* data = new char[str.size()]; memcpy(data, str.data(), str.size()); dst->Append(absl::MakeCordFromExternal( absl::string_view(data, str.size()), [](absl::string_view s) { delete[] s.data(); })); } static absl::Cord MakeComposite() { absl::Cord cord; cord.Append("the"); AddExternalMemory(" quick brown", &cord); AddExternalMemory(" fox jumped", &cord); absl::Cord full(" over"); AddExternalMemory(" the lazy", &full); AddNewStringBlock(" dog slept the whole day away", &full); absl::Cord substring = full.Subcord(0, 18); substring.Append(std::string(1000, '.')); cord.Append(substring); cord = cord.Subcord(0, cord.size() - 998); return cord; } namespace absl { ABSL_NAMESPACE_BEGIN class CordTestPeer { public: static void ForEachChunk( const Cord& c, absl::FunctionRef<void(absl::string_view)> callback) { c.ForEachChunk(callback); } static bool IsTree(const Cord& c) { return c.contents_.is_tree(); } static CordRep* Tree(const Cord& c) { return c.contents_.tree(); } static cord_internal::CordzInfo* GetCordzInfo(const Cord& c) { return c.contents_.cordz_info(); } static Cord MakeSubstring(Cord src, size_t offset, size_t length) { CHECK(src.contents_.is_tree()) << "Can not be inlined"; CHECK(!src.ExpectedChecksum().has_value()) << "Can not be hardened"; Cord cord; auto* tree = cord_internal::SkipCrcNode(src.contents_.tree()); auto* rep = CordRepSubstring::Create(CordRep::Ref(tree), offset, length); cord.contents_.EmplaceTree(rep, CordzUpdateTracker::kSubCord); return cord; } }; ABSL_NAMESPACE_END } class CordTest : public testing::TestWithParam<bool > { public: bool UseCrc() const { return GetParam(); } void MaybeHarden(absl::Cord& c) { if (UseCrc()) { c.SetExpectedChecksum(1); } } absl::Cord MaybeHardened(absl::Cord c) { MaybeHarden(c); return c; } static std::string ToString(testing::TestParamInfo<bool> useCrc) { if (useCrc.param) { return "BtreeHardened"; } else { return "Btree"; } } }; INSTANTIATE_TEST_SUITE_P(WithParam, CordTest, testing::Bool(), CordTest::ToString); TEST(CordRepFlat, AllFlatCapacities) { static_assert(absl::cord_internal::kFlatOverhead < 32, ""); static_assert(absl::cord_internal::kMinFlatSize == 32, ""); static_assert(absl::cord_internal::kMaxLargeFlatSize == 256 << 10, ""); EXPECT_EQ(absl::cord_internal::TagToAllocatedSize(FLAT), 32); EXPECT_EQ(absl::cord_internal::TagToAllocatedSize(MAX_FLAT_TAG), 256 << 10); size_t last_size = 0; for (int tag = FLAT; tag <= MAX_FLAT_TAG; ++tag) { size_t size = absl::cord_internal::TagToAllocatedSize(tag); ASSERT_GT(size, last_size); ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size); last_size = size; } for (size_t size = 32; size <= 512; size += 8) { ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size); uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size); ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size); } for (size_t size = 512; size <= 8192; size += 64) { ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size); uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size); ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size); } for (size_t size = 8192; size <= 256 * 1024; size += 4 * 1024) { ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size); uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size); ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size); } } TEST(CordRepFlat, MaxFlatSize) { CordRepFlat* flat = CordRepFlat::New(kMaxFlatLength); EXPECT_EQ(flat->Capacity(), kMaxFlatLength); CordRep::Unref(flat); flat = CordRepFlat::New(kMaxFlatLength * 4); EXPECT_EQ(flat->Capacity(), kMaxFlatLength); CordRep::Unref(flat); } TEST(CordRepFlat, MaxLargeFlatSize) { const size_t size = 256 * 1024 - kFlatOverhead; CordRepFlat* flat = CordRepFlat::New(CordRepFlat::Large(), size); EXPECT_GE(flat->Capacity(), size); CordRep::Unref(flat); } TEST(CordRepFlat, AllFlatSizes) { const size_t kMaxSize = 256 * 1024; for (size_t size = 32; size <= kMaxSize; size *=2) { const size_t length = size - kFlatOverhead - 1; CordRepFlat* flat = CordRepFlat::New(CordRepFlat::Large(), length); EXPECT_GE(flat->Capacity(), length); memset(flat->Data(), 0xCD, flat->Capacity()); CordRep::Unref(flat); } } TEST_P(CordTest, AllFlatSizes) { using absl::strings_internal::CordTestAccess; for (size_t s = 0; s < CordTestAccess::MaxFlatLength(); s++) { std::string src; while (src.size() < s) { src.push_back('a' + (src.size() % 26)); } absl::Cord dst(src); MaybeHarden(dst); EXPECT_EQ(std::string(dst), src) << s; } } TEST_P(CordTest, GigabyteCordFromExternal) { const size_t one_gig = 1024U * 1024U * 1024U; size_t max_size = 2 * one_gig; if (sizeof(max_size) > 4) max_size = 128 * one_gig; size_t length = 128 * 1024; char* data = new char[length]; absl::Cord from = absl::MakeCordFromExternal( absl::string_view(data, length), [](absl::string_view sv) { delete[] sv.data(); }); absl::Cord c; c.Append(from); while (c.size() < max_size) { c.Append(c); c.Append(from); c.Append(from); c.Append(from); c.Append(from); MaybeHarden(c); } for (int i = 0; i < 1024; ++i) { c.Append(from); } LOG(INFO) << "Made a Cord with " << c.size() << " bytes!"; } static absl::Cord MakeExternalCord(int size) { char* buffer = new char[size]; memset(buffer, 'x', size); absl::Cord cord; cord.Append(absl::MakeCordFromExternal( absl::string_view(buffer, size), [](absl::string_view s) { delete[] s.data(); })); return cord; } extern bool my_unique_true_boolean; bool my_unique_true_boolean = true; TEST_P(CordTest, Assignment) { absl::Cord x(absl::string_view("hi there")); absl::Cord y(x); MaybeHarden(y); ASSERT_EQ(x.ExpectedChecksum(), absl::nullopt); ASSERT_EQ(std::string(x), "hi there"); ASSERT_EQ(std::string(y), "hi there"); ASSERT_TRUE(x == y); ASSERT_TRUE(x <= y); ASSERT_TRUE(y <= x); x = absl::string_view("foo"); ASSERT_EQ(std::string(x), "foo"); ASSERT_EQ(std::string(y), "hi there"); ASSERT_TRUE(x < y); ASSERT_TRUE(y > x); ASSERT_TRUE(x != y); ASSERT_TRUE(x <= y); ASSERT_TRUE(y >= x); x = "foo"; ASSERT_EQ(x, "foo"); std::vector<std::pair<absl::string_view, absl::string_view>> test_string_pairs = {{"hi there", "foo"}, {"loooooong coooooord", "short cord"}, {"short cord", "loooooong coooooord"}, {"loooooong coooooord1", "loooooong coooooord2"}}; for (std::pair<absl::string_view, absl::string_view> test_strings : test_string_pairs) { absl::Cord tmp(test_strings.first); absl::Cord z(std::move(tmp)); ASSERT_EQ(std::string(z), test_strings.first); tmp = test_strings.second; z = std::move(tmp); ASSERT_EQ(std::string(z), test_strings.second); } { absl::Cord my_small_cord("foo"); absl::Cord my_big_cord("loooooong coooooord"); absl::Cord* my_small_alias = my_unique_true_boolean ? &my_small_cord : &my_big_cord; absl::Cord* my_big_alias = !my_unique_true_boolean ? &my_small_cord : &my_big_cord; *my_small_alias = std::move(my_small_cord); *my_big_alias = std::move(my_big_cord); } } TEST_P(CordTest, StartsEndsWith) { absl::Cord x(absl::string_view("abcde")); MaybeHarden(x); absl::Cord empty(""); ASSERT_TRUE(x.StartsWith(absl::Cord("abcde"))); ASSERT_TRUE(x.StartsWith(absl::Cord("abc"))); ASSERT_TRUE(x.StartsWith(absl::Cord(""))); ASSERT_TRUE(empty.StartsWith(absl::Cord(""))); ASSERT_TRUE(x.EndsWith(absl::Cord("abcde"))); ASSERT_TRUE(x.EndsWith(absl::Cord("cde"))); ASSERT_TRUE(x.EndsWith(absl::Cord(""))); ASSERT_TRUE(empty.EndsWith(absl::Cord(""))); ASSERT_TRUE(!x.StartsWith(absl::Cord("xyz"))); ASSERT_TRUE(!empty.StartsWith(absl::Cord("xyz"))); ASSERT_TRUE(!x.EndsWith(absl::Cord("xyz"))); ASSERT_TRUE(!empty.EndsWith(absl::Cord("xyz"))); ASSERT_TRUE(x.StartsWith("abcde")); ASSERT_TRUE(x.StartsWith("abc")); ASSERT_TRUE(x.StartsWith("")); ASSERT_TRUE(empty.StartsWith("")); ASSERT_TRUE(x.EndsWith("abcde")); ASSERT_TRUE(x.EndsWith("cde")); ASSERT_TRUE(x.EndsWith("")); ASSERT_TRUE(empty.EndsWith("")); ASSERT_TRUE(!x.StartsWith("xyz")); ASSERT_TRUE(!empty.StartsWith("xyz")); ASSERT_TRUE(!x.EndsWith("xyz")); ASSERT_TRUE(!empty.EndsWith("xyz")); } TEST_P(CordTest, Contains) { auto flat_haystack = absl::Cord("this is a flat cord"); auto fragmented_haystack = absl::MakeFragmentedCord( {"this", " ", "is", " ", "a", " ", "fragmented", " ", "cord"}); EXPECT_TRUE(flat_haystack.Contains("")); EXPECT_TRUE(fragmented_haystack.Contains("")); EXPECT_TRUE(flat_haystack.Contains(absl::Cord(""))); EXPECT_TRUE(fragmented_haystack.Contains(absl::Cord(""))); EXPECT_TRUE(absl::Cord("").Contains("")); EXPECT_TRUE(absl::Cord("").Contains(absl::Cord(""))); EXPECT_FALSE(absl::Cord("").Contains(flat_haystack)); EXPECT_FALSE(absl::Cord("").Contains(fragmented_haystack)); EXPECT_FALSE(flat_haystack.Contains("z")); EXPECT_FALSE(fragmented_haystack.Contains("z")); EXPECT_FALSE(flat_haystack.Contains(absl::Cord("z"))); EXPECT_FALSE(fragmented_haystack.Contains(absl::Cord("z"))); EXPECT_FALSE(flat_haystack.Contains("is an")); EXPECT_FALSE(fragmented_haystack.Contains("is an")); EXPECT_FALSE(flat_haystack.Contains(absl::Cord("is an"))); EXPECT_FALSE(fragmented_haystack.Contains(absl::Cord("is an"))); EXPECT_FALSE( flat_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "an"}))); EXPECT_FALSE(fragmented_haystack.Contains( absl::MakeFragmentedCord({"is", " ", "an"}))); EXPECT_TRUE(flat_haystack.Contains("is a")); EXPECT_TRUE(fragmented_haystack.Contains("is a")); EXPECT_TRUE(flat_haystack.Contains(absl::Cord("is a"))); EXPECT_TRUE(fragmented_haystack.Contains(absl::Cord("is a"))); EXPECT_TRUE( flat_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "a"}))); EXPECT_TRUE( fragmented_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "a"}))); } TEST_P(CordTest, Find) { auto flat_haystack = absl::Cord("this is a flat cord"); auto fragmented_haystack = absl::MakeFragmentedCord( {"this", " ", "is", " ", "a", " ", "fragmented", " ", "cord"}); auto empty_haystack = absl::Cord(""); EXPECT_EQ(flat_haystack.Find(""), flat_haystack.char_begin()); EXPECT_EQ(fragmented_haystack.Find(""), fragmented_haystack.char_begin()); EXPECT_EQ(flat_haystack.Find(absl::Cord("")), flat_haystack.char_begin()); EXPECT_EQ(fragmented_haystack.Find(absl::Cord("")), fragmented_haystack.char_begin()); EXPECT_EQ(empty_haystack.Find(""), empty_haystack.char_begin()); EXPECT_EQ(empty_haystack.Find(absl::Cord("")), empty_haystack.char_begin()); EXPECT_EQ(empty_haystack.Find(flat_haystack), empty_haystack.char_end()); EXPECT_EQ(empty_haystack.Find(fragmented_haystack), empty_haystack.char_end()); EXPECT_EQ(flat_haystack.Find("z"), flat_haystack.char_end()); EXPECT_EQ(fragmented_haystack.Find("z"), fragmented_haystack.char_end()); EXPECT_EQ(flat_haystack.Find(absl::Cord("z")), flat_haystack.char_end()); EXPECT_EQ(fragmented_haystack.Find(absl::Cord("z")), fragmented_haystack.char_end()); EXPECT_EQ(flat_haystack.Find("is an"), flat_haystack.char_end()); EXPECT_EQ(fragmented_haystack.Find("is an"), fragmented_haystack.char_end()); EXPECT_EQ(flat_haystack.Find(absl::Cord("is an")), flat_haystack.char_end()); EXPECT_EQ(fragmented_haystack.Find(absl::Cord("is an")), fragmented_haystack.char_end()); EXPECT_EQ(flat_haystack.Find(absl::MakeFragmentedCord({"is", " ", "an"})), flat_haystack.char_end()); EXPECT_EQ( fragmented_haystack.Find(absl::MakeFragmentedCord({"is", " ", "an"})), fragmented_haystack.char_end()); EXPECT_EQ(flat_haystack.Find("is a"), std::next(flat_haystack.char_begin(), 5)); EXPECT_EQ(fragmented_haystack.Find("is a"), std::next(fragmented_haystack.char_begin(), 5)); EXPECT_EQ(flat_haystack.Find(absl::Cord("is a")), std::next(flat_haystack.char_begin(), 5)); EXPECT_EQ(fragmented_haystack.Find(absl::Cord("is a")), std::next(fragmented_haystack.char_begin(), 5)); EXPECT_EQ(flat_haystack.Find(absl::MakeFragmentedCord({"is", " ", "a"})), std::next(flat_haystack.char_begin(), 5)); EXPECT_EQ( fragmented_haystack.Find(absl::MakeFragmentedCord({"is", " ", "a"})), std::next(fragmented_haystack.char_begin(), 5)); } TEST_P(CordTest, Subcord) { RandomEngine rng(GTEST_FLAG_GET(random_seed)); const std::string s = RandomLowercaseString(&rng, 1024); absl::Cord a; AppendWithFragments(s, &rng, &a); MaybeHarden(a); ASSERT_EQ(s, std::string(a)); std::set<size_t> positions; for (int i = 0; i <= 32; ++i) { positions.insert(i); positions.insert(i * 32 - 1); positions.insert(i * 32); positions.insert(i * 32 + 1); positions.insert(a.size() - i); } positions.insert(237); positions.insert(732); for (size_t pos : positions) { if (pos > a.size()) continue; for (size_t end_pos : positions) { if (end_pos < pos || end_pos > a.size()) continue; absl::Cord sa = a.Subcord(pos, end_pos - pos); ASSERT_EQ(absl::string_view(s).substr(pos, end_pos - pos), std::string(sa)) << a; if (pos != 0 || end_pos != a.size()) { ASSERT_EQ(sa.ExpectedChecksum(), absl::nullopt); } } } const std::string sh = "short"; absl::Cord c(sh); for (size_t pos = 0; pos <= sh.size(); ++pos) { for (size_t n = 0; n <= sh.size() - pos; ++n) { absl::Cord sc = c.Subcord(pos, n); ASSERT_EQ(sh.substr(pos, n), std::string(sc)) << c; } } absl::Cord sa = a.Subcord(0, a.size()); std::string ss = s.substr(0, s.size()); while (sa.size() > 1) { sa = sa.Subcord(1, sa.size() - 2); ss = ss.substr(1, ss.size() - 2); ASSERT_EQ(ss, std::string(sa)) << a; if (HasFailure()) break; } sa = a.Subcord(0, a.size() + 1); EXPECT_EQ(s, std::string(sa)); sa = a.Subcord(a.size() + 1, 0); EXPECT_TRUE(sa.empty()); sa = a.Subcord(a.size() + 1, 1); EXPECT_TRUE(sa.empty()); } TEST_P(CordTest, Swap) { absl::string_view a("Dexter"); absl::string_view b("Mandark"); absl::Cord x(a); absl::Cord y(b); MaybeHarden(x); swap(x, y); if (UseCrc()) { ASSERT_EQ(x.ExpectedChecksum(), absl::nullopt); ASSERT_EQ(y.ExpectedChecksum(), 1); } ASSERT_EQ(x, absl::Cord(b)); ASSERT_EQ(y, absl::Cord(a)); x.swap(y); if (UseCrc()) { ASSERT_EQ(x.ExpectedChecksum(), 1); ASSERT_EQ(y.ExpectedChecksum(), absl::nullopt); } ASSERT_EQ(x, absl::Cord(a)); ASSERT_EQ(y, absl::Cord(b)); } static void VerifyCopyToString(const absl::Cord& cord) { std::string initially_empty; absl::CopyCordToString(cord, &initially_empty); EXPECT_EQ(initially_empty, cord); constexpr size_t kInitialLength = 1024; std::string has_initial_contents(kInitialLength, 'x'); const char* address_before_copy = has_initial_contents.data(); absl::CopyCordToString(cord, &has_initial_contents); EXPECT_EQ(has_initial_contents, cord); if (cord.size() <= kInitialLength) { EXPECT_EQ(has_initial_contents.data(), address_before_copy) << "CopyCordToString allocated new string storage; " "has_initial_contents = \"" << has_initial_contents << "\""; } } TEST_P(CordTest, CopyToString) { VerifyCopyToString(absl::Cord()); VerifyCopyToString(MaybeHardened(absl::Cord("small cord"))); VerifyCopyToString(MaybeHardened( absl::MakeFragmentedCord({"fragmented ", "cord ", "to ", "test ", "copying ", "to ", "a ", "string."}))); } static void VerifyAppendCordToString(const absl::Cord& cord) { std::string initially_empty; absl::AppendCordToString(cord, &initially_empty); EXPECT_EQ(initially_empty, cord); const absl::string_view kInitialContents = "initial contents."; std::string expected_after_append = absl::StrCat(kInitialContents, std::string(cord)); std::string no_reserve(kInitialContents); absl::AppendCordToString(cord, &no_reserve); EXPECT_EQ(no_reserve, expected_after_append); std::string has_reserved_capacity(kInitialContents); has_reserved_capacity.reserve(has_reserved_capacity.size() + cord.size()); const char* address_before_copy = has_reserved_capacity.data(); absl::AppendCordToString(cord, &has_reserved_capacity); EXPECT_EQ(has_reserved_capacity, expected_after_append); EXPECT_EQ(has_reserved_capacity.data(), address_before_copy) << "AppendCordToString allocated new string storage; " "has_reserved_capacity = \"" << has_reserved_capacity << "\""; } TEST_P(CordTest, AppendToString) { VerifyAppendCordToString(absl::Cord()); VerifyAppendCordToString(MaybeHardened(absl::Cord("small cord"))); VerifyAppendCordToString(MaybeHardened( absl::MakeFragmentedCord({"fragmented ", "cord ", "to ", "test ", "appending ", "to ", "a ", "string."}))); } TEST_P(CordTest, AppendEmptyBuffer) { absl::Cord cord; cord.Append(absl::CordBuffer()); cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000)); } TEST_P(CordTest, AppendEmptyBufferToFlat) { absl::Cord cord(std::string(2000, 'x')); cord.Append(absl::CordBuffer()); cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000)); } TEST_P(CordTest, AppendEmptyBufferToTree) { absl::Cord cord(std::string(2000, 'x')); cord.Append(std::string(2000, 'y')); cord.Append(absl::CordBuffer()); cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000)); } TEST_P(CordTest, AppendSmallBuffer) { absl::Cord cord; absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3); ASSERT_THAT(buffer.capacity(), Le(15)); memcpy(buffer.data(), "Abc", 3); buffer.SetLength(3); cord.Append(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); buffer = absl::CordBuffer::CreateWithDefaultLimit(3); memcpy(buffer.data(), "defgh", 5); buffer.SetLength(5); cord.Append(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); EXPECT_THAT(cord.Chunks(), ElementsAre("Abcdefgh")); } TEST_P(CordTest, AppendAndPrependBufferArePrecise) { std::string test_data(absl::cord_internal::kMaxFlatLength * 10, 'x'); absl::Cord cord1(test_data); absl::Cord cord2(test_data); const size_t size1 = cord1.EstimatedMemoryUsage(); const size_t size2 = cord2.EstimatedMemoryUsage(); absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3); memcpy(buffer.data(), "Abc", 3); buffer.SetLength(3); cord1.Append(std::move(buffer)); buffer = absl::CordBuffer::CreateWithDefaultLimit(3); memcpy(buffer.data(), "Abc", 3); buffer.SetLength(3); cord2.Prepend(std::move(buffer)); #ifndef NDEBUG constexpr size_t kMaxDelta = 128 + 32; #else constexpr size_t kMaxDelta = 128 + 32 + 256; #endif EXPECT_LE(cord1.EstimatedMemoryUsage() - size1, kMaxDelta); EXPECT_LE(cord2.EstimatedMemoryUsage() - size2, kMaxDelta); EXPECT_EQ(cord1, absl::StrCat(test_data, "Abc")); EXPECT_EQ(cord2, absl::StrCat("Abc", test_data)); } TEST_P(CordTest, PrependSmallBuffer) { absl::Cord cord; absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3); ASSERT_THAT(buffer.capacity(), Le(15)); memcpy(buffer.data(), "Abc", 3); buffer.SetLength(3); cord.Prepend(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); buffer = absl::CordBuffer::CreateWithDefaultLimit(3); memcpy(buffer.data(), "defgh", 5); buffer.SetLength(5); cord.Prepend(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); EXPECT_THAT(cord.Chunks(), ElementsAre("defghAbc")); } TEST_P(CordTest, AppendLargeBuffer) { absl::Cord cord; std::string s1(700, '1'); absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(s1.size()); memcpy(buffer.data(), s1.data(), s1.size()); buffer.SetLength(s1.size()); cord.Append(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); std::string s2(1000, '2'); buffer = absl::CordBuffer::CreateWithDefaultLimit(s2.size()); memcpy(buffer.data(), s2.data(), s2.size()); buffer.SetLength(s2.size()); cord.Append(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); EXPECT_THAT(cord.Chunks(), ElementsAre(s1, s2)); } TEST_P(CordTest, PrependLargeBuffer) { absl::Cord cord; std::string s1(700, '1'); absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(s1.size()); memcpy(buffer.data(), s1.data(), s1.size()); buffer.SetLength(s1.size()); cord.Prepend(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); std::string s2(1000, '2'); buffer = absl::CordBuffer::CreateWithDefaultLimit(s2.size()); memcpy(buffer.data(), s2.data(), s2.size()); buffer.SetLength(s2.size()); cord.Prepend(std::move(buffer)); EXPECT_EQ(buffer.length(), 0); EXPECT_GT(buffer.capacity(), 0); EXPECT_THAT(cord.Chunks(), ElementsAre(s2, s1)); } class CordAppendBufferTest : public testing::TestWithParam<bool> { public: size_t is_default() const { return GetParam(); } static std::string ToString(testing::TestParamInfo<bool> param) { return param.param ? "DefaultLimit" : "CustomLimit"; } size_t limit() const { return is_default() ? absl::CordBuffer::kDefaultLimit : absl::CordBuffer::kCustomLimit; } size_t maximum_payload() const { return is_default() ? absl::CordBuffer::MaximumPayload() : absl::CordBuffer::MaximumPayload(limit()); } absl::CordBuffer GetAppendBuffer(absl::Cord& cord, size_t capacity, size_t min_capacity = 16) { return is_default() ? cord.GetAppendBuffer(capacity, min_capacity) : cord.GetCustomAppendBuffer(limit(), capacity, min_capacity); } }; INSTANTIATE_TEST_SUITE_P(WithParam, CordAppendBufferTest, testing::Bool(), CordAppendBufferTest::ToString); TEST_P(CordAppendBufferTest, GetAppendBufferOnEmptyCord) { absl::Cord cord; absl::CordBuffer buffer = GetAppendBuffer(cord, 1000); EXPECT_GE(buffer.capacity(), 1000); EXPECT_EQ(buffer.length(), 0); } TEST_P(CordAppendBufferTest, GetAppendBufferOnInlinedCord) { static constexpr int kInlinedSize = sizeof(absl::CordBuffer) - 1; for (int size : {6, kInlinedSize - 3, kInlinedSize - 2, 1000}) { absl::Cord cord("Abc"); absl::CordBuffer buffer = GetAppendBuffer(cord, size, 1); EXPECT_GE(buffer.capacity(), 3 + size); EXPECT_EQ(buffer.length(), 3); EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc"); EXPECT_TRUE(cord.empty()); } } TEST_P(CordAppendBufferTest, GetAppendBufferOnInlinedCordCapacityCloseToMax) { for (size_t dist_from_max = 0; dist_from_max <= 4; ++dist_from_max) { absl::Cord cord("Abc"); size_t size = std::numeric_limits<size_t>::max() - dist_from_max; absl::CordBuffer buffer = GetAppendBuffer(cord, size, 1); EXPECT_GE(buffer.capacity(), maximum_payload()); EXPECT_EQ(buffer.length(), 3); EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc"); EXPECT_TRUE(cord.empty()); } } TEST_P(CordAppendBufferTest, GetAppend
2,552
#ifndef ABSL_STRINGS_SUBSTITUTE_H_ #define ABSL_STRINGS_SUBSTITUTE_H_ #include <cstring> #include <string> #include <type_traits> #include <vector> #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/base/port.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/internal/stringify_sink.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace substitute_internal { class Arg { public: Arg(absl::Nullable<const char*> value) : piece_(absl::NullSafeStringView(value)) {} template <typename Allocator> Arg( const std::basic_string<char, std::char_traits<char>, Allocator>& value) noexcept : piece_(value) {} Arg(absl::string_view value) : piece_(value) {} Arg(char value) : piece_(scratch_, 1) { scratch_[0] = value; } Arg(short value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(unsigned short value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(int value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(unsigned int value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(long value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(unsigned long value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(long long value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(unsigned long long value) : piece_(scratch_, static_cast<size_t>( numbers_internal::FastIntToBuffer(value, scratch_) - scratch_)) {} Arg(float value) : piece_(scratch_, numbers_internal::SixDigitsToBuffer(value, scratch_)) { } Arg(double value) : piece_(scratch_, numbers_internal::SixDigitsToBuffer(value, scratch_)) { } Arg(bool value) : piece_(value ? "true" : "false") {} template <typename T, typename = typename std::enable_if< HasAbslStringify<T>::value>::type> Arg( const T& v, strings_internal::StringifySink&& sink = {}) : piece_(strings_internal::ExtractStringification(sink, v)) {} Arg(Hex hex); Arg(Dec dec); template <typename T, absl::enable_if_t< std::is_class<T>::value && (std::is_same<T, std::vector<bool>::reference>::value || std::is_same<T, std::vector<bool>::const_reference>::value)>* = nullptr> Arg(T value) : Arg(static_cast<bool>(value)) {} Arg( absl::Nullable<const void*> value); template <typename T, typename = typename std::enable_if< std::is_enum<T>{} && !std::is_convertible<T, int>{} && !HasAbslStringify<T>::value>::type> Arg(T value) : Arg(static_cast<typename std::underlying_type<T>::type>(value)) {} Arg(const Arg&) = delete; Arg& operator=(const Arg&) = delete; absl::string_view piece() const { return piece_; } private: absl::string_view piece_; char scratch_[numbers_internal::kFastToBufferSize]; }; void SubstituteAndAppendArray( absl::Nonnull<std::string*> output, absl::string_view format, absl::Nullable<const absl::string_view*> args_array, size_t num_args); #if defined(ABSL_BAD_CALL_IF) constexpr int CalculateOneBit(absl::Nonnull<const char*> format) { return (*format < '0' || *format > '9') ? (*format == '$' ? 0 : -1) : (1 << (*format - '0')); } constexpr const char* SkipNumber(absl::Nonnull<const char*> format) { return !*format ? format : (format + 1); } constexpr int PlaceholderBitmask(absl::Nonnull<const char*> format) { return !*format ? 0 : *format != '$' ? PlaceholderBitmask(format + 1) : (CalculateOneBit(format + 1) | PlaceholderBitmask(SkipNumber(format + 1))); } #endif } inline void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::string_view format) { substitute_internal::SubstituteAndAppendArray(output, format, nullptr, 0); } inline void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0) { const absl::string_view args[] = {a0.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1) { const absl::string_view args[] = {a0.piece(), a1.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2) { const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3) { const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(), a3.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4) { const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(), a3.piece(), a4.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5) { const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(), a3.piece(), a4.piece(), a5.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6) { const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(), a3.piece(), a4.piece(), a5.piece(), a6.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7) { const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(), a3.piece(), a4.piece(), a5.piece(), a6.piece(), a7.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7, const substitute_internal::Arg& a8) { const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(), a3.piece(), a4.piece(), a5.piece(), a6.piece(), a7.piece(), a8.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } inline void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7, const substitute_internal::Arg& a8, const substitute_internal::Arg& a9) { const absl::string_view args[] = { a0.piece(), a1.piece(), a2.piece(), a3.piece(), a4.piece(), a5.piece(), a6.piece(), a7.piece(), a8.piece(), a9.piece()}; substitute_internal::SubstituteAndAppendArray(output, format, args, ABSL_ARRAYSIZE(args)); } #if defined(ABSL_BAD_CALL_IF) void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 0, "There were no substitution arguments " "but this format string either has a $[0-9] in it or contains " "an unescaped $ character (use $$ instead)"); void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0) ABSL_BAD_CALL_IF(substitute_internal::PlaceholderBitmask(format) != 1, "There was 1 substitution argument given, but " "this format string is missing its $0, contains " "one of $1-$9, or contains an unescaped $ character (use " "$$ instead)"); void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 3, "There were 2 substitution arguments given, but this format string is " "missing its $0/$1, contains one of $2-$9, or contains an " "unescaped $ character (use $$ instead)"); void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 7, "There were 3 substitution arguments given, but " "this format string is missing its $0/$1/$2, contains one of " "$3-$9, or contains an unescaped $ character (use $$ instead)"); void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 15, "There were 4 substitution arguments given, but " "this format string is missing its $0-$3, contains one of " "$4-$9, or contains an unescaped $ character (use $$ instead)"); void SubstituteAndAppend(absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 31, "There were 5 substitution arguments given, but " "this format string is missing its $0-$4, contains one of " "$5-$9, or contains an unescaped $ character (use $$ instead)"); void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 63, "There were 6 substitution arguments given, but " "this format string is missing its $0-$5, contains one of " "$6-$9, or contains an unescaped $ character (use $$ instead)"); void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 127, "There were 7 substitution arguments given, but " "this format string is missing its $0-$6, contains one of " "$7-$9, or contains an unescaped $ character (use $$ instead)"); void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 255, "There were 8 substitution arguments given, but " "this format string is missing its $0-$7, contains one of " "$8-$9, or contains an unescaped $ character (use $$ instead)"); void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7, const substitute_internal::Arg& a8) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 511, "There were 9 substitution arguments given, but " "this format string is missing its $0-$8, contains a $9, or " "contains an unescaped $ character (use $$ instead)"); void SubstituteAndAppend( absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7, const substitute_internal::Arg& a8, const substitute_internal::Arg& a9) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 1023, "There were 10 substitution arguments given, but this " "format string either doesn't contain all of $0 through $9 or " "contains an unescaped $ character (use $$ instead)"); #endif ABSL_MUST_USE_RESULT inline std::string Substitute(absl::string_view format) { std::string result; SubstituteAndAppend(&result, format); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0) { std::string result; SubstituteAndAppend(&result, format, a0); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1) { std::string result; SubstituteAndAppend(&result, format, a0, a1); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2, a3); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6, a7); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7, const substitute_internal::Arg& a8) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6, a7, a8); return result; } ABSL_MUST_USE_RESULT inline std::string Substitute( absl::string_view format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5, const substitute_internal::Arg& a6, const substitute_internal::Arg& a7, const substitute_internal::Arg& a8, const substitute_internal::Arg& a9) { std::string result; SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return result; } #if defined(ABSL_BAD_CALL_IF) std::string Substitute(absl::Nonnull<const char*> format) ABSL_BAD_CALL_IF(substitute_internal::PlaceholderBitmask(format) != 0, "There were no substitution arguments " "but this format string either has a $[0-9] in it or " "contains an unescaped $ character (use $$ instead)"); std::string Substitute(absl::Nonnull<const char*> format, const substitute_internal::Arg& a0) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 1, "There was 1 substitution argument given, but " "this format string is missing its $0, contains one of $1-$9, " "or contains an unescaped $ character (use $$ instead)"); std::string Substitute(absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 3, "There were 2 substitution arguments given, but " "this format string is missing its $0/$1, contains one of " "$2-$9, or contains an unescaped $ character (use $$ instead)"); std::string Substitute(absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 7, "There were 3 substitution arguments given, but " "this format string is missing its $0/$1/$2, contains one of " "$3-$9, or contains an unescaped $ character (use $$ instead)"); std::string Substitute(absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 15, "There were 4 substitution arguments given, but " "this format string is missing its $0-$3, contains one of " "$4-$9, or contains an unescaped $ character (use $$ instead)"); std::string Substitute(absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4) ABSL_BAD_CALL_IF( substitute_internal::PlaceholderBitmask(format) != 31, "There were 5 substitution arguments given, but " "this format string is missing its $0-$4, contains one of " "$5-$9, or contains an unescaped $ character (use $$ instead)"); std::string Substitute(absl::Nonnull<const char*> format, const substitute_internal::Arg& a0, const substitute_internal::Arg& a1, const substitute_internal::Arg& a2, const substitute_internal::Arg& a3, const substitute_internal::Arg& a4, const substitute_internal::Arg& a5) ABSL_BAD_CALL_IF( substitute_
#include "absl/strings/substitute.h" #include <cstdint> #include <cstring> #include <string> #include <vector> #include "gtest/gtest.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace { struct MyStruct { template <typename Sink> friend void AbslStringify(Sink& sink, const MyStruct& s) { sink.Append("MyStruct{.value = "); sink.Append(absl::StrCat(s.value)); sink.Append("}"); } int value; }; TEST(SubstituteTest, Substitute) { EXPECT_EQ("Hello, world!", absl::Substitute("$0, $1!", "Hello", "world")); EXPECT_EQ("123 0.2 0.1 foo true false x", absl::Substitute("$0 $1 $2 $3 $4 $5 $6", 123, 0.2, 0.1f, std::string("foo"), true, false, 'x')); EXPECT_EQ( "-32767 65535 " "-1234567890 3234567890 " "-1234567890 3234567890 " "-1234567890123456789 9234567890123456789", absl::Substitute( "$0 $1 $2 $3 $4 $5 $6 $7", static_cast<short>(-32767), static_cast<unsigned short>(65535), -1234567890, 3234567890U, -1234567890L, 3234567890UL, -int64_t{1234567890123456789}, uint64_t{9234567890123456789u})); EXPECT_EQ("0 1 f ffff0ffff 0123456789abcdef", absl::Substitute("$0$1$2$3$4 $5", absl::Hex(0), absl::Hex(1, absl::kSpacePad2), absl::Hex(0xf, absl::kSpacePad2), absl::Hex(int16_t{-1}, absl::kSpacePad5), absl::Hex(int16_t{-1}, absl::kZeroPad5), absl::Hex(0x123456789abcdef, absl::kZeroPad16))); EXPECT_EQ("0 115 -1-0001 81985529216486895", absl::Substitute("$0$1$2$3$4 $5", absl::Dec(0), absl::Dec(1, absl::kSpacePad2), absl::Dec(0xf, absl::kSpacePad2), absl::Dec(int16_t{-1}, absl::kSpacePad5), absl::Dec(int16_t{-1}, absl::kZeroPad5), absl::Dec(0x123456789abcdef, absl::kZeroPad16))); const int* int_p = reinterpret_cast<const int*>(0x12345); std::string str = absl::Substitute("$0", int_p); EXPECT_EQ(absl::StrCat("0x", absl::Hex(int_p)), str); volatile int vol = 237; volatile int* volatile volptr = &vol; str = absl::Substitute("$0", volptr); EXPECT_EQ("true", str); const uint64_t* null_p = nullptr; str = absl::Substitute("$0", null_p); EXPECT_EQ("NULL", str); const char* char_p = "print me"; str = absl::Substitute("$0", char_p); EXPECT_EQ("print me", str); char char_buf[16]; strncpy(char_buf, "print me too", sizeof(char_buf)); str = absl::Substitute("$0", char_buf); EXPECT_EQ("print me too", str); char_p = nullptr; str = absl::Substitute("$0", char_p); EXPECT_EQ("", str); EXPECT_EQ("b, a, c, b", absl::Substitute("$1, $0, $2, $1", "a", "b", "c")); EXPECT_EQ("$", absl::Substitute("$$")); EXPECT_EQ("$1", absl::Substitute("$$1")); EXPECT_EQ("a", absl::Substitute("$0", "a")); EXPECT_EQ("a b", absl::Substitute("$0 $1", "a", "b")); EXPECT_EQ("a b c", absl::Substitute("$0 $1 $2", "a", "b", "c")); EXPECT_EQ("a b c d", absl::Substitute("$0 $1 $2 $3", "a", "b", "c", "d")); EXPECT_EQ("a b c d e", absl::Substitute("$0 $1 $2 $3 $4", "a", "b", "c", "d", "e")); EXPECT_EQ("a b c d e f", absl::Substitute("$0 $1 $2 $3 $4 $5", "a", "b", "c", "d", "e", "f")); EXPECT_EQ("a b c d e f g", absl::Substitute("$0 $1 $2 $3 $4 $5 $6", "a", "b", "c", "d", "e", "f", "g")); EXPECT_EQ("a b c d e f g h", absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7", "a", "b", "c", "d", "e", "f", "g", "h")); EXPECT_EQ("a b c d e f g h i", absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7 $8", "a", "b", "c", "d", "e", "f", "g", "h", "i")); EXPECT_EQ("a b c d e f g h i j", absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7 $8 $9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j")); EXPECT_EQ("a b c d e f g h i j b0", absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j")); const char* null_cstring = nullptr; EXPECT_EQ("Text: ''", absl::Substitute("Text: '$0'", null_cstring)); MyStruct s1 = MyStruct{17}; MyStruct s2 = MyStruct{1043}; EXPECT_EQ("MyStruct{.value = 17}, MyStruct{.value = 1043}", absl::Substitute("$0, $1", s1, s2)); } TEST(SubstituteTest, SubstituteAndAppend) { std::string str = "Hello"; absl::SubstituteAndAppend(&str, ", $0!", "world"); EXPECT_EQ("Hello, world!", str); str.clear(); absl::SubstituteAndAppend(&str, "$0", "a"); EXPECT_EQ("a", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1", "a", "b"); EXPECT_EQ("a b", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2", "a", "b", "c"); EXPECT_EQ("a b c", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2 $3", "a", "b", "c", "d"); EXPECT_EQ("a b c d", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4", "a", "b", "c", "d", "e"); EXPECT_EQ("a b c d e", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5", "a", "b", "c", "d", "e", "f"); EXPECT_EQ("a b c d e f", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6", "a", "b", "c", "d", "e", "f", "g"); EXPECT_EQ("a b c d e f g", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6 $7", "a", "b", "c", "d", "e", "f", "g", "h"); EXPECT_EQ("a b c d e f g h", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6 $7 $8", "a", "b", "c", "d", "e", "f", "g", "h", "i"); EXPECT_EQ("a b c d e f g h i", str); str.clear(); absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6 $7 $8 $9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); EXPECT_EQ("a b c d e f g h i j", str); str.clear(); MyStruct s1 = MyStruct{17}; MyStruct s2 = MyStruct{1043}; absl::SubstituteAndAppend(&str, "$0, $1", s1, s2); EXPECT_EQ("MyStruct{.value = 17}, MyStruct{.value = 1043}", str); } TEST(SubstituteTest, VectorBoolRef) { std::vector<bool> v = {true, false}; const auto& cv = v; EXPECT_EQ("true false true false", absl::Substitute("$0 $1 $2 $3", v[0], v[1], cv[0], cv[1])); std::string str = "Logic be like: "; absl::SubstituteAndAppend(&str, "$0 $1 $2 $3", v[0], v[1], cv[0], cv[1]); EXPECT_EQ("Logic be like: true false true false", str); } TEST(SubstituteTest, Enums) { enum UnscopedEnum { kEnum0 = 0, kEnum1 = 1 }; EXPECT_EQ("0 1", absl::Substitute("$0 $1", UnscopedEnum::kEnum0, UnscopedEnum::kEnum1)); enum class ScopedEnum { kEnum0 = 0, kEnum1 = 1 }; EXPECT_EQ("0 1", absl::Substitute("$0 $1", ScopedEnum::kEnum0, ScopedEnum::kEnum1)); enum class ScopedEnumInt32 : int32_t { kEnum0 = 989, kEnum1 = INT32_MIN }; EXPECT_EQ("989 -2147483648", absl::Substitute("$0 $1", ScopedEnumInt32::kEnum0, ScopedEnumInt32::kEnum1)); enum class ScopedEnumUInt32 : uint32_t { kEnum0 = 1, kEnum1 = UINT32_MAX }; EXPECT_EQ("1 4294967295", absl::Substitute("$0 $1", ScopedEnumUInt32::kEnum0, ScopedEnumUInt32::kEnum1)); enum class ScopedEnumInt64 : int64_t { kEnum0 = -1, kEnum1 = 42949672950 }; EXPECT_EQ("-1 42949672950", absl::Substitute("$0 $1", ScopedEnumInt64::kEnum0, ScopedEnumInt64::kEnum1)); enum class ScopedEnumUInt64 : uint64_t { kEnum0 = 1, kEnum1 = 42949672950 }; EXPECT_EQ("1 42949672950", absl::Substitute("$0 $1", ScopedEnumUInt64::kEnum0, ScopedEnumUInt64::kEnum1)); enum class ScopedEnumChar : signed char { kEnum0 = -1, kEnum1 = 1 }; EXPECT_EQ("-1 1", absl::Substitute("$0 $1", ScopedEnumChar::kEnum0, ScopedEnumChar::kEnum1)); enum class ScopedEnumUChar : unsigned char { kEnum0 = 0, kEnum1 = 1, kEnumMax = 255 }; EXPECT_EQ("0 1 255", absl::Substitute("$0 $1 $2", ScopedEnumUChar::kEnum0, ScopedEnumUChar::kEnum1, ScopedEnumUChar::kEnumMax)); enum class ScopedEnumInt16 : int16_t { kEnum0 = -100, kEnum1 = 10000 }; EXPECT_EQ("-100 10000", absl::Substitute("$0 $1", ScopedEnumInt16::kEnum0, ScopedEnumInt16::kEnum1)); enum class ScopedEnumUInt16 : uint16_t { kEnum0 = 0, kEnum1 = 10000 }; EXPECT_EQ("0 10000", absl::Substitute("$0 $1", ScopedEnumUInt16::kEnum0, ScopedEnumUInt16::kEnum1)); } enum class EnumWithStringify { Many = 0, Choices = 1 }; template <typename Sink> void AbslStringify(Sink& sink, EnumWithStringify e) { sink.Append(e == EnumWithStringify::Many ? "Many" : "Choices"); } TEST(SubstituteTest, AbslStringifyWithEnum) { const auto e = EnumWithStringify::Choices; EXPECT_EQ(absl::Substitute("$0", e), "Choices"); } #if GTEST_HAS_DEATH_TEST TEST(SubstituteDeathTest, SubstituteDeath) { EXPECT_DEBUG_DEATH( static_cast<void>(absl::Substitute(absl::string_view("-$2"), "a", "b")), "Invalid absl::Substitute\\(\\) format string: asked for \"\\$2\", " "but only 2 args were given."); EXPECT_DEBUG_DEATH( static_cast<void>(absl::Substitute(absl::string_view("-$z-"))), "Invalid absl::Substitute\\(\\) format string: \"-\\$z-\""); EXPECT_DEBUG_DEATH( static_cast<void>(absl::Substitute(absl::string_view("-$"))), "Invalid absl::Substitute\\(\\) format string: \"-\\$\""); } #endif }
2,553
#ifndef ABSL_STRINGS_MATCH_H_ #define ABSL_STRINGS_MATCH_H_ #include <cstring> #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN inline bool StrContains(absl::string_view haystack, absl::string_view needle) noexcept { return haystack.find(needle, 0) != haystack.npos; } inline bool StrContains(absl::string_view haystack, char needle) noexcept { return haystack.find(needle) != haystack.npos; } inline bool StartsWith(absl::string_view text, absl::string_view prefix) noexcept { return prefix.empty() || (text.size() >= prefix.size() && memcmp(text.data(), prefix.data(), prefix.size()) == 0); } inline bool EndsWith(absl::string_view text, absl::string_view suffix) noexcept { return suffix.empty() || (text.size() >= suffix.size() && memcmp(text.data() + (text.size() - suffix.size()), suffix.data(), suffix.size()) == 0); } bool StrContainsIgnoreCase(absl::string_view haystack, absl::string_view needle) noexcept; bool StrContainsIgnoreCase(absl::string_view haystack, char needle) noexcept; bool EqualsIgnoreCase(absl::string_view piece1, absl::string_view piece2) noexcept; bool StartsWithIgnoreCase(absl::string_view text, absl::string_view prefix) noexcept; bool EndsWithIgnoreCase(absl::string_view text, absl::string_view suffix) noexcept; absl::string_view FindLongestCommonPrefix(absl::string_view a, absl::string_view b); absl::string_view FindLongestCommonSuffix(absl::string_view a, absl::string_view b); ABSL_NAMESPACE_END } #endif #include "absl/strings/match.h" #include <algorithm> #include <cstdint> #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/optimization.h" #include "absl/numeric/bits.h" #include "absl/strings/ascii.h" #include "absl/strings/internal/memutil.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN bool EqualsIgnoreCase(absl::string_view piece1, absl::string_view piece2) noexcept { return (piece1.size() == piece2.size() && 0 == absl::strings_internal::memcasecmp(piece1.data(), piece2.data(), piece1.size())); } bool StrContainsIgnoreCase(absl::string_view haystack, absl::string_view needle) noexcept { while (haystack.size() >= needle.size()) { if (StartsWithIgnoreCase(haystack, needle)) return true; haystack.remove_prefix(1); } return false; } bool StrContainsIgnoreCase(absl::string_view haystack, char needle) noexcept { char upper_needle = absl::ascii_toupper(static_cast<unsigned char>(needle)); char lower_needle = absl::ascii_tolower(static_cast<unsigned char>(needle)); if (upper_needle == lower_needle) { return StrContains(haystack, needle); } else { const char both_cstr[3] = {lower_needle, upper_needle, '\0'}; return haystack.find_first_of(both_cstr) != absl::string_view::npos; } } bool StartsWithIgnoreCase(absl::string_view text, absl::string_view prefix) noexcept { return (text.size() >= prefix.size()) && EqualsIgnoreCase(text.substr(0, prefix.size()), prefix); } bool EndsWithIgnoreCase(absl::string_view text, absl::string_view suffix) noexcept { return (text.size() >= suffix.size()) && EqualsIgnoreCase(text.substr(text.size() - suffix.size()), suffix); } absl::string_view FindLongestCommonPrefix(absl::string_view a, absl::string_view b) { const absl::string_view::size_type limit = std::min(a.size(), b.size()); const char* const pa = a.data(); const char* const pb = b.data(); absl::string_view::size_type count = (unsigned) 0; if (ABSL_PREDICT_FALSE(limit < 8)) { while (ABSL_PREDICT_TRUE(count + 2 <= limit)) { uint16_t xor_bytes = absl::little_endian::Load16(pa + count) ^ absl::little_endian::Load16(pb + count); if (ABSL_PREDICT_FALSE(xor_bytes != 0)) { if (ABSL_PREDICT_TRUE((xor_bytes & 0xff) == 0)) ++count; return absl::string_view(pa, count); } count += 2; } if (ABSL_PREDICT_TRUE(count != limit)) { if (ABSL_PREDICT_TRUE(pa[count] == pb[count])) ++count; } return absl::string_view(pa, count); } do { uint64_t xor_bytes = absl::little_endian::Load64(pa + count) ^ absl::little_endian::Load64(pb + count); if (ABSL_PREDICT_FALSE(xor_bytes != 0)) { count += static_cast<uint64_t>(absl::countr_zero(xor_bytes) >> 3); return absl::string_view(pa, count); } count += 8; } while (ABSL_PREDICT_TRUE(count + 8 < limit)); count = limit - 8; uint64_t xor_bytes = absl::little_endian::Load64(pa + count) ^ absl::little_endian::Load64(pb + count); if (ABSL_PREDICT_TRUE(xor_bytes != 0)) { count += static_cast<uint64_t>(absl::countr_zero(xor_bytes) >> 3); return absl::string_view(pa, count); } return absl::string_view(pa, limit); } absl::string_view FindLongestCommonSuffix(absl::string_view a, absl::string_view b) { const absl::string_view::size_type limit = std::min(a.size(), b.size()); if (limit == 0) return absl::string_view(); const char* pa = a.data() + a.size() - 1; const char* pb = b.data() + b.size() - 1; absl::string_view::size_type count = (unsigned) 0; while (count < limit && *pa == *pb) { --pa; --pb; ++count; } return absl::string_view(++pa, count); } ABSL_NAMESPACE_END }
#include "absl/strings/match.h" #include <string> #include "gtest/gtest.h" #include "absl/strings/string_view.h" namespace { TEST(MatchTest, StartsWith) { const std::string s1("123\0abc", 7); const absl::string_view a("foobar"); const absl::string_view b(s1); const absl::string_view e; EXPECT_TRUE(absl::StartsWith(a, a)); EXPECT_TRUE(absl::StartsWith(a, "foo")); EXPECT_TRUE(absl::StartsWith(a, e)); EXPECT_TRUE(absl::StartsWith(b, s1)); EXPECT_TRUE(absl::StartsWith(b, b)); EXPECT_TRUE(absl::StartsWith(b, e)); EXPECT_TRUE(absl::StartsWith(e, "")); EXPECT_FALSE(absl::StartsWith(a, b)); EXPECT_FALSE(absl::StartsWith(b, a)); EXPECT_FALSE(absl::StartsWith(e, a)); } TEST(MatchTest, EndsWith) { const std::string s1("123\0abc", 7); const absl::string_view a("foobar"); const absl::string_view b(s1); const absl::string_view e; EXPECT_TRUE(absl::EndsWith(a, a)); EXPECT_TRUE(absl::EndsWith(a, "bar")); EXPECT_TRUE(absl::EndsWith(a, e)); EXPECT_TRUE(absl::EndsWith(b, s1)); EXPECT_TRUE(absl::EndsWith(b, b)); EXPECT_TRUE(absl::EndsWith(b, e)); EXPECT_TRUE(absl::EndsWith(e, "")); EXPECT_FALSE(absl::EndsWith(a, b)); EXPECT_FALSE(absl::EndsWith(b, a)); EXPECT_FALSE(absl::EndsWith(e, a)); } TEST(MatchTest, Contains) { absl::string_view a("abcdefg"); absl::string_view b("abcd"); absl::string_view c("efg"); absl::string_view d("gh"); EXPECT_TRUE(absl::StrContains(a, a)); EXPECT_TRUE(absl::StrContains(a, b)); EXPECT_TRUE(absl::StrContains(a, c)); EXPECT_FALSE(absl::StrContains(a, d)); EXPECT_TRUE(absl::StrContains("", "")); EXPECT_TRUE(absl::StrContains("abc", "")); EXPECT_FALSE(absl::StrContains("", "a")); } TEST(MatchTest, ContainsChar) { absl::string_view a("abcdefg"); absl::string_view b("abcd"); EXPECT_TRUE(absl::StrContains(a, 'a')); EXPECT_TRUE(absl::StrContains(a, 'b')); EXPECT_TRUE(absl::StrContains(a, 'e')); EXPECT_FALSE(absl::StrContains(a, 'h')); EXPECT_TRUE(absl::StrContains(b, 'a')); EXPECT_TRUE(absl::StrContains(b, 'b')); EXPECT_FALSE(absl::StrContains(b, 'e')); EXPECT_FALSE(absl::StrContains(b, 'h')); EXPECT_FALSE(absl::StrContains("", 'a')); EXPECT_FALSE(absl::StrContains("", 'a')); } TEST(MatchTest, ContainsNull) { const std::string s = "foo"; const char* cs = "foo"; const absl::string_view sv("foo"); const absl::string_view sv2("foo\0bar", 4); EXPECT_EQ(s, "foo"); EXPECT_EQ(sv, "foo"); EXPECT_NE(sv2, "foo"); EXPECT_TRUE(absl::EndsWith(s, sv)); EXPECT_TRUE(absl::StartsWith(cs, sv)); EXPECT_TRUE(absl::StrContains(cs, sv)); EXPECT_FALSE(absl::StrContains(cs, sv2)); } TEST(MatchTest, EqualsIgnoreCase) { std::string text = "the"; absl::string_view data(text); EXPECT_TRUE(absl::EqualsIgnoreCase(data, "The")); EXPECT_TRUE(absl::EqualsIgnoreCase(data, "THE")); EXPECT_TRUE(absl::EqualsIgnoreCase(data, "the")); EXPECT_FALSE(absl::EqualsIgnoreCase(data, "Quick")); EXPECT_FALSE(absl::EqualsIgnoreCase(data, "then")); } TEST(MatchTest, StartsWithIgnoreCase) { EXPECT_TRUE(absl::StartsWithIgnoreCase("foo", "foo")); EXPECT_TRUE(absl::StartsWithIgnoreCase("foo", "Fo")); EXPECT_TRUE(absl::StartsWithIgnoreCase("foo", "")); EXPECT_FALSE(absl::StartsWithIgnoreCase("foo", "fooo")); EXPECT_FALSE(absl::StartsWithIgnoreCase("", "fo")); } TEST(MatchTest, EndsWithIgnoreCase) { EXPECT_TRUE(absl::EndsWithIgnoreCase("foo", "foo")); EXPECT_TRUE(absl::EndsWithIgnoreCase("foo", "Oo")); EXPECT_TRUE(absl::EndsWithIgnoreCase("foo", "")); EXPECT_FALSE(absl::EndsWithIgnoreCase("foo", "fooo")); EXPECT_FALSE(absl::EndsWithIgnoreCase("", "fo")); } TEST(MatchTest, ContainsIgnoreCase) { EXPECT_TRUE(absl::StrContainsIgnoreCase("foo", "foo")); EXPECT_TRUE(absl::StrContainsIgnoreCase("FOO", "Foo")); EXPECT_TRUE(absl::StrContainsIgnoreCase("--FOO", "Foo")); EXPECT_TRUE(absl::StrContainsIgnoreCase("FOO--", "Foo")); EXPECT_FALSE(absl::StrContainsIgnoreCase("BAR", "Foo")); EXPECT_FALSE(absl::StrContainsIgnoreCase("BAR", "Foo")); EXPECT_TRUE(absl::StrContainsIgnoreCase("123456", "123456")); EXPECT_TRUE(absl::StrContainsIgnoreCase("123456", "234")); EXPECT_TRUE(absl::StrContainsIgnoreCase("", "")); EXPECT_TRUE(absl::StrContainsIgnoreCase("abc", "")); EXPECT_FALSE(absl::StrContainsIgnoreCase("", "a")); } TEST(MatchTest, ContainsCharIgnoreCase) { absl::string_view a("AaBCdefg!"); absl::string_view b("AaBCd!"); EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'a')); EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'A')); EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'b')); EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'B')); EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'e')); EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'E')); EXPECT_FALSE(absl::StrContainsIgnoreCase(a, 'h')); EXPECT_FALSE(absl::StrContainsIgnoreCase(a, 'H')); EXPECT_TRUE(absl::StrContainsIgnoreCase(a, '!')); EXPECT_FALSE(absl::StrContainsIgnoreCase(a, '?')); EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'a')); EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'A')); EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'b')); EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'B')); EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'e')); EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'E')); EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'h')); EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'H')); EXPECT_TRUE(absl::StrContainsIgnoreCase(b, '!')); EXPECT_FALSE(absl::StrContainsIgnoreCase(b, '?')); EXPECT_FALSE(absl::StrContainsIgnoreCase("", 'a')); EXPECT_FALSE(absl::StrContainsIgnoreCase("", 'A')); EXPECT_FALSE(absl::StrContainsIgnoreCase("", '0')); } TEST(MatchTest, FindLongestCommonPrefix) { EXPECT_EQ(absl::FindLongestCommonPrefix("", ""), ""); EXPECT_EQ(absl::FindLongestCommonPrefix("", "abc"), ""); EXPECT_EQ(absl::FindLongestCommonPrefix("abc", ""), ""); EXPECT_EQ(absl::FindLongestCommonPrefix("ab", "abc"), "ab"); EXPECT_EQ(absl::FindLongestCommonPrefix("abc", "ab"), "ab"); EXPECT_EQ(absl::FindLongestCommonPrefix("abc", "abd"), "ab"); EXPECT_EQ(absl::FindLongestCommonPrefix("abc", "abcd"), "abc"); EXPECT_EQ(absl::FindLongestCommonPrefix("abcd", "abcd"), "abcd"); EXPECT_EQ(absl::FindLongestCommonPrefix("abcd", "efgh"), ""); EXPECT_EQ(absl::FindLongestCommonPrefix( absl::string_view("1234 abcdef").substr(5, 5), absl::string_view("5678 abcdef").substr(5, 3)), "abc"); } TEST(MatchTest, FindLongestCommonPrefixLoad16Mismatch) { const std::string x1 = "abcdefgh"; const std::string x2 = "abcde_"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcde"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcde"); } TEST(MatchTest, FindLongestCommonPrefixLoad16MatchesNoLast) { const std::string x1 = "abcdef"; const std::string x2 = "abcdef"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcdef"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcdef"); } TEST(MatchTest, FindLongestCommonPrefixLoad16MatchesLastCharMismatches) { const std::string x1 = "abcdefg"; const std::string x2 = "abcdef_h"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcdef"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcdef"); } TEST(MatchTest, FindLongestCommonPrefixLoad16MatchesLastMatches) { const std::string x1 = "abcde"; const std::string x2 = "abcdefgh"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcde"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcde"); } TEST(MatchTest, FindLongestCommonPrefixSize8Load64Mismatches) { const std::string x1 = "abcdefghijk"; const std::string x2 = "abcde_g_"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcde"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcde"); } TEST(MatchTest, FindLongestCommonPrefixSize8Load64Matches) { const std::string x1 = "abcdefgh"; const std::string x2 = "abcdefgh"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcdefgh"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcdefgh"); } TEST(MatchTest, FindLongestCommonPrefixSize15Load64Mismatches) { const std::string x1 = "012345670123456"; const std::string x2 = "0123456701_34_6"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "0123456701"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "0123456701"); } TEST(MatchTest, FindLongestCommonPrefixSize15Load64Matches) { const std::string x1 = "012345670123456"; const std::string x2 = "0123456701234567"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "012345670123456"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "012345670123456"); } TEST(MatchTest, FindLongestCommonPrefixSizeFirstByteOfLast8BytesMismatch) { const std::string x1 = "012345670123456701234567"; const std::string x2 = "0123456701234567_1234567"; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "0123456701234567"); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "0123456701234567"); } TEST(MatchTest, FindLongestCommonPrefixLargeLastCharMismatches) { const std::string x1(300, 'x'); std::string x2 = x1; x2.back() = '#'; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), std::string(299, 'x')); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), std::string(299, 'x')); } TEST(MatchTest, FindLongestCommonPrefixLargeFullMatch) { const std::string x1(300, 'x'); const std::string x2 = x1; EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), std::string(300, 'x')); EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), std::string(300, 'x')); } TEST(MatchTest, FindLongestCommonSuffix) { EXPECT_EQ(absl::FindLongestCommonSuffix("", ""), ""); EXPECT_EQ(absl::FindLongestCommonSuffix("", "abc"), ""); EXPECT_EQ(absl::FindLongestCommonSuffix("abc", ""), ""); EXPECT_EQ(absl::FindLongestCommonSuffix("bc", "abc"), "bc"); EXPECT_EQ(absl::FindLongestCommonSuffix("abc", "bc"), "bc"); EXPECT_EQ(absl::FindLongestCommonSuffix("abc", "dbc"), "bc"); EXPECT_EQ(absl::FindLongestCommonSuffix("bcd", "abcd"), "bcd"); EXPECT_EQ(absl::FindLongestCommonSuffix("abcd", "abcd"), "abcd"); EXPECT_EQ(absl::FindLongestCommonSuffix("abcd", "efgh"), ""); EXPECT_EQ(absl::FindLongestCommonSuffix( absl::string_view("1234 abcdef").substr(5, 5), absl::string_view("5678 abcdef").substr(7, 3)), "cde"); } }
2,554
#ifndef ABSL_STRINGS_CHARCONV_H_ #define ABSL_STRINGS_CHARCONV_H_ #include <system_error> #include "absl/base/config.h" #include "absl/base/nullability.h" namespace absl { ABSL_NAMESPACE_BEGIN enum class chars_format { scientific = 1, fixed = 2, hex = 4, general = fixed | scientific, }; struct from_chars_result { absl::Nonnull<const char*> ptr; std::errc ec; }; absl::from_chars_result from_chars(absl::Nonnull<const char*> first, absl::Nonnull<const char*> last, double& value, chars_format fmt = chars_format::general); absl::from_chars_result from_chars(absl::Nonnull<const char*> first, absl::Nonnull<const char*> last, float& value, chars_format fmt = chars_format::general); inline constexpr chars_format operator&(chars_format lhs, chars_format rhs) { return static_cast<chars_format>(static_cast<int>(lhs) & static_cast<int>(rhs)); } inline constexpr chars_format operator|(chars_format lhs, chars_format rhs) { return static_cast<chars_format>(static_cast<int>(lhs) | static_cast<int>(rhs)); } inline constexpr chars_format operator^(chars_format lhs, chars_format rhs) { return static_cast<chars_format>(static_cast<int>(lhs) ^ static_cast<int>(rhs)); } inline constexpr chars_format operator~(chars_format arg) { return static_cast<chars_format>(~static_cast<int>(arg)); } inline chars_format& operator&=(chars_format& lhs, chars_format rhs) { lhs = lhs & rhs; return lhs; } inline chars_format& operator|=(chars_format& lhs, chars_format rhs) { lhs = lhs | rhs; return lhs; } inline chars_format& operator^=(chars_format& lhs, chars_format rhs) { lhs = lhs ^ rhs; return lhs; } ABSL_NAMESPACE_END } #endif #include "absl/strings/charconv.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <limits> #include <system_error> #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/nullability.h" #include "absl/numeric/bits.h" #include "absl/numeric/int128.h" #include "absl/strings/internal/charconv_bigint.h" #include "absl/strings/internal/charconv_parse.h" #ifdef ABSL_BIT_PACK_FLOATS #error ABSL_BIT_PACK_FLOATS cannot be directly set #elif defined(__x86_64__) || defined(_M_X64) #define ABSL_BIT_PACK_FLOATS 1 #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace { template <typename FloatType> struct FloatTraits; template <> struct FloatTraits<double> { using mantissa_t = uint64_t; static constexpr int kTargetBits = 64; static constexpr int kTargetExponentBits = 11; static constexpr int kTargetMantissaBits = 53; static constexpr int kMaxExponent = 971; static constexpr int kMinNormalExponent = -1074; static constexpr int kExponentBias = 1023; static constexpr int kEiselLemireShift = 9; static constexpr uint64_t kEiselLemireMask = uint64_t{0x1FF}; static constexpr int kEiselLemireMinInclusiveExp10 = -324 - 18; static constexpr int kEiselLemireMaxExclusiveExp10 = 309; static double MakeNan(absl::Nonnull<const char*> tagp) { #if ABSL_HAVE_BUILTIN(__builtin_nan) return __builtin_nan(tagp); #else using namespace std; return nan(tagp); #endif } static double Make(mantissa_t mantissa, int exponent, bool sign) { #ifndef ABSL_BIT_PACK_FLOATS using namespace std; return sign ? -ldexp(mantissa, exponent) : ldexp(mantissa, exponent); #else constexpr uint64_t kMantissaMask = (uint64_t{1} << (kTargetMantissaBits - 1)) - 1; uint64_t dbl = static_cast<uint64_t>(sign) << 63; if (mantissa > kMantissaMask) { dbl += static_cast<uint64_t>(exponent + 1023 + kTargetMantissaBits - 1) << 52; mantissa &= kMantissaMask; } else { assert(exponent == kMinNormalExponent); } dbl += mantissa; return absl::bit_cast<double>(dbl); #endif } }; template <> struct FloatTraits<float> { using mantissa_t = uint32_t; static constexpr int kTargetBits = 32; static constexpr int kTargetExponentBits = 8; static constexpr int kTargetMantissaBits = 24; static constexpr int kMaxExponent = 104; static constexpr int kMinNormalExponent = -149; static constexpr int kExponentBias = 127; static constexpr int kEiselLemireShift = 38; static constexpr uint64_t kEiselLemireMask = uint64_t{0x3FFFFFFFFF}; static constexpr int kEiselLemireMinInclusiveExp10 = -46 - 18; static constexpr int kEiselLemireMaxExclusiveExp10 = 39; static float MakeNan(absl::Nonnull<const char*> tagp) { #if ABSL_HAVE_BUILTIN(__builtin_nanf) return __builtin_nanf(tagp); #else using namespace std; return std::nanf(tagp); #endif } static float Make(mantissa_t mantissa, int exponent, bool sign) { #ifndef ABSL_BIT_PACK_FLOATS using namespace std; return sign ? -ldexpf(mantissa, exponent) : ldexpf(mantissa, exponent); #else constexpr uint32_t kMantissaMask = (uint32_t{1} << (kTargetMantissaBits - 1)) - 1; uint32_t flt = static_cast<uint32_t>(sign) << 31; if (mantissa > kMantissaMask) { flt += static_cast<uint32_t>(exponent + 127 + kTargetMantissaBits - 1) << 23; mantissa &= kMantissaMask; } else { assert(exponent == kMinNormalExponent); } flt += mantissa; return absl::bit_cast<float>(flt); #endif } }; extern const uint64_t kPower10MantissaHighTable[]; extern const uint64_t kPower10MantissaLowTable[]; constexpr int kPower10TableMinInclusive = -342; constexpr int kPower10TableMaxExclusive = 309; uint64_t Power10Mantissa(int n) { return kPower10MantissaHighTable[n - kPower10TableMinInclusive]; } int Power10Exponent(int n) { return (217706 * n >> 16) - 63; } bool Power10Overflow(int n) { return n >= kPower10TableMaxExclusive; } bool Power10Underflow(int n) { return n < kPower10TableMinInclusive; } bool Power10Exact(int n) { return n >= 0 && n <= 27; } constexpr int kOverflow = 99999; constexpr int kUnderflow = -99999; struct CalculatedFloat { uint64_t mantissa = 0; int exponent = 0; }; int BitWidth(uint128 value) { if (Uint128High64(value) == 0) { return static_cast<int>(bit_width(Uint128Low64(value))); } return 128 - countl_zero(Uint128High64(value)); } template <typename FloatType> int NormalizedShiftSize(int mantissa_width, int binary_exponent) { const int normal_shift = mantissa_width - FloatTraits<FloatType>::kTargetMantissaBits; const int minimum_shift = FloatTraits<FloatType>::kMinNormalExponent - binary_exponent; return std::max(normal_shift, minimum_shift); } int TruncateToBitWidth(int bit_width, absl::Nonnull<uint128*> value) { const int current_bit_width = BitWidth(*value); const int shift = current_bit_width - bit_width; *value >>= shift; return shift; } template <typename FloatType> bool HandleEdgeCase(const strings_internal::ParsedFloat& input, bool negative, absl::Nonnull<FloatType*> value) { if (input.type == strings_internal::FloatType::kNan) { constexpr ptrdiff_t kNanBufferSize = 128; #if (defined(__GNUC__) && !defined(__clang__)) || \ (defined(__clang__) && __clang_major__ < 7) volatile char n_char_sequence[kNanBufferSize]; #else char n_char_sequence[kNanBufferSize]; #endif if (input.subrange_begin == nullptr) { n_char_sequence[0] = '\0'; } else { ptrdiff_t nan_size = input.subrange_end - input.subrange_begin; nan_size = std::min(nan_size, kNanBufferSize - 1); std::copy_n(input.subrange_begin, nan_size, n_char_sequence); n_char_sequence[nan_size] = '\0'; } char* nan_argument = const_cast<char*>(n_char_sequence); *value = negative ? -FloatTraits<FloatType>::MakeNan(nan_argument) : FloatTraits<FloatType>::MakeNan(nan_argument); return true; } if (input.type == strings_internal::FloatType::kInfinity) { *value = negative ? -std::numeric_limits<FloatType>::infinity() : std::numeric_limits<FloatType>::infinity(); return true; } if (input.mantissa == 0) { *value = negative ? -0.0 : 0.0; return true; } return false; } template <typename FloatType> void EncodeResult(const CalculatedFloat& calculated, bool negative, absl::Nonnull<absl::from_chars_result*> result, absl::Nonnull<FloatType*> value) { if (calculated.exponent == kOverflow) { result->ec = std::errc::result_out_of_range; *value = negative ? -std::numeric_limits<FloatType>::max() : std::numeric_limits<FloatType>::max(); return; } else if (calculated.mantissa == 0 || calculated.exponent == kUnderflow) { result->ec = std::errc::result_out_of_range; *value = negative ? -0.0 : 0.0; return; } *value = FloatTraits<FloatType>::Make( static_cast<typename FloatTraits<FloatType>::mantissa_t>( calculated.mantissa), calculated.exponent, negative); } uint64_t ShiftRightAndRound(uint128 value, int shift, bool input_exact, absl::Nonnull<bool*> output_exact) { if (shift <= 0) { *output_exact = input_exact; return static_cast<uint64_t>(value << -shift); } if (shift >= 128) { *output_exact = true; return 0; } *output_exact = true; const uint128 shift_mask = (uint128(1) << shift) - 1; const uint128 halfway_point = uint128(1) << (shift - 1); const uint128 shifted_bits = value & shift_mask; value >>= shift; if (shifted_bits > halfway_point) { return static_cast<uint64_t>(value + 1); } if (shifted_bits == halfway_point) { if ((value & 1) == 1 || !input_exact) { ++value; } return static_cast<uint64_t>(value); } if (!input_exact && shifted_bits == halfway_point - 1) { *output_exact = false; } return static_cast<uint64_t>(value); } bool MustRoundUp(uint64_t guess_mantissa, int guess_exponent, const strings_internal::ParsedFloat& parsed_decimal) { absl::strings_internal::BigUnsigned<84> exact_mantissa; int exact_exponent = exact_mantissa.ReadFloatMantissa(parsed_decimal, 768); guess_mantissa = guess_mantissa * 2 + 1; guess_exponent -= 1; absl::strings_internal::BigUnsigned<84>& lhs = exact_mantissa; int comparison; if (exact_exponent >= 0) { lhs.MultiplyByFiveToTheNth(exact_exponent); absl::strings_internal::BigUnsigned<84> rhs(guess_mantissa); if (exact_exponent > guess_exponent) { lhs.ShiftLeft(exact_exponent - guess_exponent); } else { rhs.ShiftLeft(guess_exponent - exact_exponent); } comparison = Compare(lhs, rhs); } else { absl::strings_internal::BigUnsigned<84> rhs = absl::strings_internal::BigUnsigned<84>::FiveToTheNth(-exact_exponent); rhs.MultiplyBy(guess_mantissa); if (exact_exponent > guess_exponent) { lhs.ShiftLeft(exact_exponent - guess_exponent); } else { rhs.ShiftLeft(guess_exponent - exact_exponent); } comparison = Compare(lhs, rhs); } if (comparison < 0) { return false; } else if (comparison > 0) { return true; } else { return (guess_mantissa & 2) == 2; } } template <typename FloatType> CalculatedFloat CalculatedFloatFromRawValues(uint64_t mantissa, int exponent) { CalculatedFloat result; if (mantissa == uint64_t{1} << FloatTraits<FloatType>::kTargetMantissaBits) { mantissa >>= 1; exponent += 1; } if (exponent > FloatTraits<FloatType>::kMaxExponent) { result.exponent = kOverflow; } else if (mantissa == 0) { result.exponent = kUnderflow; } else { result.exponent = exponent; result.mantissa = mantissa; } return result; } template <typename FloatType> CalculatedFloat CalculateFromParsedHexadecimal( const strings_internal::ParsedFloat& parsed_hex) { uint64_t mantissa = parsed_hex.mantissa; int exponent = parsed_hex.exponent; int mantissa_width = static_cast<int>(bit_width(mantissa)); const int shift = NormalizedShiftSize<FloatType>(mantissa_width, exponent); bool result_exact; exponent += shift; mantissa = ShiftRightAndRound(mantissa, shift, true, &result_exact); return CalculatedFloatFromRawValues<FloatType>(mantissa, exponent); } template <typename FloatType> CalculatedFloat CalculateFromParsedDecimal( const strings_internal::ParsedFloat& parsed_decimal) { CalculatedFloat result; if (Power10Underflow(parsed_decimal.exponent)) { result.exponent = kUnderflow; return result; } else if (Power10Overflow(parsed_decimal.exponent)) { result.exponent = kOverflow; return result; } uint128 wide_binary_mantissa = parsed_decimal.mantissa; wide_binary_mantissa *= Power10Mantissa(parsed_decimal.exponent); int binary_exponent = Power10Exponent(parsed_decimal.exponent); bool mantissa_exact; int mantissa_width; if (parsed_decimal.subrange_begin) { mantissa_width = 58; mantissa_exact = false; binary_exponent += TruncateToBitWidth(mantissa_width, &wide_binary_mantissa); } else if (!Power10Exact(parsed_decimal.exponent)) { mantissa_width = 63; mantissa_exact = false; binary_exponent += TruncateToBitWidth(mantissa_width, &wide_binary_mantissa); } else { mantissa_width = BitWidth(wide_binary_mantissa); mantissa_exact = true; } const int shift = NormalizedShiftSize<FloatType>(mantissa_width, binary_exponent); bool result_exact; binary_exponent += shift; uint64_t binary_mantissa = ShiftRightAndRound(wide_binary_mantissa, shift, mantissa_exact, &result_exact); if (!result_exact) {
#include "absl/strings/charconv.h" #include <cfloat> #include <cmath> #include <cstdlib> #include <functional> #include <limits> #include <string> #include <system_error> #include "gtest/gtest.h" #include "absl/strings/internal/pow10_helper.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #ifdef _MSC_FULL_VER #define ABSL_COMPILER_DOES_EXACT_ROUNDING 0 #define ABSL_STRTOD_HANDLES_NAN_CORRECTLY 0 #else #define ABSL_COMPILER_DOES_EXACT_ROUNDING 1 #define ABSL_STRTOD_HANDLES_NAN_CORRECTLY 1 #endif namespace { using absl::strings_internal::Pow10; #if ABSL_COMPILER_DOES_EXACT_ROUNDING void TestDoubleParse(absl::string_view str, double expected_number) { SCOPED_TRACE(str); double actual_number = 0.0; absl::from_chars_result result = absl::from_chars(str.data(), str.data() + str.length(), actual_number); EXPECT_EQ(result.ec, std::errc()); EXPECT_EQ(result.ptr, str.data() + str.length()); EXPECT_EQ(actual_number, expected_number); } void TestFloatParse(absl::string_view str, float expected_number) { SCOPED_TRACE(str); float actual_number = 0.0; absl::from_chars_result result = absl::from_chars(str.data(), str.data() + str.length(), actual_number); EXPECT_EQ(result.ec, std::errc()); EXPECT_EQ(result.ptr, str.data() + str.length()); EXPECT_EQ(actual_number, expected_number); } #define FROM_CHARS_TEST_DOUBLE(number) \ { \ TestDoubleParse(#number, number); \ TestDoubleParse("-" #number, -number); \ } #define FROM_CHARS_TEST_FLOAT(number) \ { \ TestFloatParse(#number, number##f); \ TestFloatParse("-" #number, -number##f); \ } TEST(FromChars, NearRoundingCases) { FROM_CHARS_TEST_DOUBLE(5.e125); FROM_CHARS_TEST_DOUBLE(69.e267); FROM_CHARS_TEST_DOUBLE(999.e-026); FROM_CHARS_TEST_DOUBLE(7861.e-034); FROM_CHARS_TEST_DOUBLE(75569.e-254); FROM_CHARS_TEST_DOUBLE(928609.e-261); FROM_CHARS_TEST_DOUBLE(9210917.e080); FROM_CHARS_TEST_DOUBLE(84863171.e114); FROM_CHARS_TEST_DOUBLE(653777767.e273); FROM_CHARS_TEST_DOUBLE(5232604057.e-298); FROM_CHARS_TEST_DOUBLE(27235667517.e-109); FROM_CHARS_TEST_DOUBLE(653532977297.e-123); FROM_CHARS_TEST_DOUBLE(3142213164987.e-294); FROM_CHARS_TEST_DOUBLE(46202199371337.e-072); FROM_CHARS_TEST_DOUBLE(231010996856685.e-073); FROM_CHARS_TEST_DOUBLE(9324754620109615.e212); FROM_CHARS_TEST_DOUBLE(78459735791271921.e049); FROM_CHARS_TEST_DOUBLE(272104041512242479.e200); FROM_CHARS_TEST_DOUBLE(6802601037806061975.e198); FROM_CHARS_TEST_DOUBLE(20505426358836677347.e-221); FROM_CHARS_TEST_DOUBLE(836168422905420598437.e-234); FROM_CHARS_TEST_DOUBLE(4891559871276714924261.e222); FROM_CHARS_TEST_FLOAT(5.e-20); FROM_CHARS_TEST_FLOAT(67.e14); FROM_CHARS_TEST_FLOAT(985.e15); FROM_CHARS_TEST_FLOAT(7693.e-42); FROM_CHARS_TEST_FLOAT(55895.e-16); FROM_CHARS_TEST_FLOAT(996622.e-44); FROM_CHARS_TEST_FLOAT(7038531.e-32); FROM_CHARS_TEST_FLOAT(60419369.e-46); FROM_CHARS_TEST_FLOAT(702990899.e-20); FROM_CHARS_TEST_FLOAT(6930161142.e-48); FROM_CHARS_TEST_FLOAT(25933168707.e-13); FROM_CHARS_TEST_FLOAT(596428896559.e20); FROM_CHARS_TEST_DOUBLE(9.e-265); FROM_CHARS_TEST_DOUBLE(85.e-037); FROM_CHARS_TEST_DOUBLE(623.e100); FROM_CHARS_TEST_DOUBLE(3571.e263); FROM_CHARS_TEST_DOUBLE(81661.e153); FROM_CHARS_TEST_DOUBLE(920657.e-023); FROM_CHARS_TEST_DOUBLE(4603285.e-024); FROM_CHARS_TEST_DOUBLE(87575437.e-309); FROM_CHARS_TEST_DOUBLE(245540327.e122); FROM_CHARS_TEST_DOUBLE(6138508175.e120); FROM_CHARS_TEST_DOUBLE(83356057653.e193); FROM_CHARS_TEST_DOUBLE(619534293513.e124); FROM_CHARS_TEST_DOUBLE(2335141086879.e218); FROM_CHARS_TEST_DOUBLE(36167929443327.e-159); FROM_CHARS_TEST_DOUBLE(609610927149051.e-255); FROM_CHARS_TEST_DOUBLE(3743626360493413.e-165); FROM_CHARS_TEST_DOUBLE(94080055902682397.e-242); FROM_CHARS_TEST_DOUBLE(899810892172646163.e283); FROM_CHARS_TEST_DOUBLE(7120190517612959703.e120); FROM_CHARS_TEST_DOUBLE(25188282901709339043.e-252); FROM_CHARS_TEST_DOUBLE(308984926168550152811.e-052); FROM_CHARS_TEST_DOUBLE(6372891218502368041059.e064); FROM_CHARS_TEST_FLOAT(3.e-23); FROM_CHARS_TEST_FLOAT(57.e18); FROM_CHARS_TEST_FLOAT(789.e-35); FROM_CHARS_TEST_FLOAT(2539.e-18); FROM_CHARS_TEST_FLOAT(76173.e28); FROM_CHARS_TEST_FLOAT(887745.e-11); FROM_CHARS_TEST_FLOAT(5382571.e-37); FROM_CHARS_TEST_FLOAT(82381273.e-35); FROM_CHARS_TEST_FLOAT(750486563.e-38); FROM_CHARS_TEST_FLOAT(3752432815.e-39); FROM_CHARS_TEST_FLOAT(75224575729.e-45); FROM_CHARS_TEST_FLOAT(459926601011.e15); } #undef FROM_CHARS_TEST_DOUBLE #undef FROM_CHARS_TEST_FLOAT #endif float ToFloat(absl::string_view s) { float f; absl::from_chars(s.data(), s.data() + s.size(), f); return f; } double ToDouble(absl::string_view s) { double d; absl::from_chars(s.data(), s.data() + s.size(), d); return d; } TEST(FromChars, NearRoundingCasesExplicit) { EXPECT_EQ(ToDouble("5.e125"), ldexp(6653062250012735, 365)); EXPECT_EQ(ToDouble("69.e267"), ldexp(4705683757438170, 841)); EXPECT_EQ(ToDouble("999.e-026"), ldexp(6798841691080350, -129)); EXPECT_EQ(ToDouble("7861.e-034"), ldexp(8975675289889240, -153)); EXPECT_EQ(ToDouble("75569.e-254"), ldexp(6091718967192243, -880)); EXPECT_EQ(ToDouble("928609.e-261"), ldexp(7849264900213743, -900)); EXPECT_EQ(ToDouble("9210917.e080"), ldexp(8341110837370930, 236)); EXPECT_EQ(ToDouble("84863171.e114"), ldexp(4625202867375927, 353)); EXPECT_EQ(ToDouble("653777767.e273"), ldexp(5068902999763073, 884)); EXPECT_EQ(ToDouble("5232604057.e-298"), ldexp(5741343011915040, -1010)); EXPECT_EQ(ToDouble("27235667517.e-109"), ldexp(6707124626673586, -380)); EXPECT_EQ(ToDouble("653532977297.e-123"), ldexp(7078246407265384, -422)); EXPECT_EQ(ToDouble("3142213164987.e-294"), ldexp(8219991337640559, -988)); EXPECT_EQ(ToDouble("46202199371337.e-072"), ldexp(5224462102115359, -246)); EXPECT_EQ(ToDouble("231010996856685.e-073"), ldexp(5224462102115359, -247)); EXPECT_EQ(ToDouble("9324754620109615.e212"), ldexp(5539753864394442, 705)); EXPECT_EQ(ToDouble("78459735791271921.e049"), ldexp(8388176519442766, 166)); EXPECT_EQ(ToDouble("272104041512242479.e200"), ldexp(5554409530847367, 670)); EXPECT_EQ(ToDouble("6802601037806061975.e198"), ldexp(5554409530847367, 668)); EXPECT_EQ(ToDouble("20505426358836677347.e-221"), ldexp(4524032052079546, -722)); EXPECT_EQ(ToDouble("836168422905420598437.e-234"), ldexp(5070963299887562, -760)); EXPECT_EQ(ToDouble("4891559871276714924261.e222"), ldexp(6452687840519111, 757)); EXPECT_EQ(ToFloat("5.e-20"), ldexpf(15474250, -88)); EXPECT_EQ(ToFloat("67.e14"), ldexpf(12479722, 29)); EXPECT_EQ(ToFloat("985.e15"), ldexpf(14333636, 36)); EXPECT_EQ(ToFloat("7693.e-42"), ldexpf(10979816, -150)); EXPECT_EQ(ToFloat("55895.e-16"), ldexpf(12888509, -61)); EXPECT_EQ(ToFloat("996622.e-44"), ldexpf(14224264, -150)); EXPECT_EQ(ToFloat("7038531.e-32"), ldexpf(11420669, -107)); EXPECT_EQ(ToFloat("60419369.e-46"), ldexpf(8623340, -150)); EXPECT_EQ(ToFloat("702990899.e-20"), ldexpf(16209866, -61)); EXPECT_EQ(ToFloat("6930161142.e-48"), ldexpf(9891056, -150)); EXPECT_EQ(ToFloat("25933168707.e-13"), ldexpf(11138211, -32)); EXPECT_EQ(ToFloat("596428896559.e20"), ldexpf(12333860, 82)); EXPECT_EQ(ToDouble("9.e-265"), ldexp(8168427841980010, -930)); EXPECT_EQ(ToDouble("85.e-037"), ldexp(6360455125664090, -169)); EXPECT_EQ(ToDouble("623.e100"), ldexp(6263531988747231, 289)); EXPECT_EQ(ToDouble("3571.e263"), ldexp(6234526311072170, 833)); EXPECT_EQ(ToDouble("81661.e153"), ldexp(6696636728760206, 472)); EXPECT_EQ(ToDouble("920657.e-023"), ldexp(5975405561110124, -109)); EXPECT_EQ(ToDouble("4603285.e-024"), ldexp(5975405561110124, -110)); EXPECT_EQ(ToDouble("87575437.e-309"), ldexp(8452160731874668, -1053)); EXPECT_EQ(ToDouble("245540327.e122"), ldexp(4985336549131723, 381)); EXPECT_EQ(ToDouble("6138508175.e120"), ldexp(4985336549131723, 379)); EXPECT_EQ(ToDouble("83356057653.e193"), ldexp(5986732817132056, 625)); EXPECT_EQ(ToDouble("619534293513.e124"), ldexp(4798406992060657, 399)); EXPECT_EQ(ToDouble("2335141086879.e218"), ldexp(5419088166961646, 713)); EXPECT_EQ(ToDouble("36167929443327.e-159"), ldexp(8135819834632444, -536)); EXPECT_EQ(ToDouble("609610927149051.e-255"), ldexp(4576664294594737, -850)); EXPECT_EQ(ToDouble("3743626360493413.e-165"), ldexp(6898586531774201, -549)); EXPECT_EQ(ToDouble("94080055902682397.e-242"), ldexp(6273271706052298, -800)); EXPECT_EQ(ToDouble("899810892172646163.e283"), ldexp(7563892574477827, 947)); EXPECT_EQ(ToDouble("7120190517612959703.e120"), ldexp(5385467232557565, 409)); EXPECT_EQ(ToDouble("25188282901709339043.e-252"), ldexp(5635662608542340, -825)); EXPECT_EQ(ToDouble("308984926168550152811.e-052"), ldexp(5644774693823803, -157)); EXPECT_EQ(ToDouble("6372891218502368041059.e064"), ldexp(4616868614322430, 233)); EXPECT_EQ(ToFloat("3.e-23"), ldexpf(9507380, -98)); EXPECT_EQ(ToFloat("57.e18"), ldexpf(12960300, 42)); EXPECT_EQ(ToFloat("789.e-35"), ldexpf(10739312, -130)); EXPECT_EQ(ToFloat("2539.e-18"), ldexpf(11990089, -72)); EXPECT_EQ(ToFloat("76173.e28"), ldexpf(9845130, 86)); EXPECT_EQ(ToFloat("887745.e-11"), ldexpf(9760860, -40)); EXPECT_EQ(ToFloat("5382571.e-37"), ldexpf(11447463, -124)); EXPECT_EQ(ToFloat("82381273.e-35"), ldexpf(8554961, -113)); EXPECT_EQ(ToFloat("750486563.e-38"), ldexpf(9975678, -120)); EXPECT_EQ(ToFloat("3752432815.e-39"), ldexpf(9975678, -121)); EXPECT_EQ(ToFloat("75224575729.e-45"), ldexpf(13105970, -137)); EXPECT_EQ(ToFloat("459926601011.e15"), ldexpf(12466336, 65)); } template <typename FloatType> void TestHalfwayValue(const std::string& mantissa, int exponent, FloatType expected_low, FloatType expected_high, FloatType expected_half) { std::string low_rep = mantissa; low_rep[low_rep.size() - 1] -= 1; absl::StrAppend(&low_rep, std::string(1000, '9'), "e", exponent); FloatType actual_low = 0; absl::from_chars(low_rep.data(), low_rep.data() + low_rep.size(), actual_low); EXPECT_EQ(expected_low, actual_low); std::string high_rep = absl::StrCat(mantissa, std::string(1000, '0'), "1e", exponent); FloatType actual_high = 0; absl::from_chars(high_rep.data(), high_rep.data() + high_rep.size(), actual_high); EXPECT_EQ(expected_high, actual_high); std::string halfway_rep = absl::StrCat(mantissa, "e", exponent); FloatType actual_half = 0; absl::from_chars(halfway_rep.data(), halfway_rep.data() + halfway_rep.size(), actual_half); EXPECT_EQ(expected_half, actual_half); } TEST(FromChars, DoubleRounding) { const double zero = 0.0; const double first_subnormal = nextafter(zero, 1.0); const double second_subnormal = nextafter(first_subnormal, 1.0); const double first_normal = DBL_MIN; const double last_subnormal = nextafter(first_normal, 0.0); const double second_normal = nextafter(first_normal, 1.0); const double last_normal = DBL_MAX; const double penultimate_normal = nextafter(last_normal, 0.0); TestHalfwayValue( "2." "470328229206232720882843964341106861825299013071623822127928412503377536" "351043759326499181808179961898982823477228588654633283551779698981993873" "980053909390631503565951557022639229085839244910518443593180284993653615" "250031937045767824921936562366986365848075700158576926990370631192827955" "855133292783433840935197801553124659726357957462276646527282722005637400" "648549997709659947045402082816622623785739345073633900796776193057750674" "017632467360096895134053553745851666113422376667860416215968046191446729" "184030053005753084904876539171138659164623952491262365388187963623937328" "042389101867234849766823508986338858792562830275599565752445550725518931" "369083625477918694866799496832404970582102851318545139621383772282614543" "7693412532098591327667236328125", -324, zero, first_subnormal, zero); TestHalfwayValue( "7." "410984687618698162648531893023320585475897039214871466383785237510132609" "053131277979497545424539885696948470431685765963899850655339096945981621" "940161728171894510697854671067917687257517734731555330779540854980960845" "750095811137303474765809687100959097544227100475730780971111893578483867" "565399878350301522805593404659373979179073872386829939581848166016912201" "945649993128979841136206248449867871357218035220901702390328579173252022" "052897402080290685402160661237554998340267130003581248647904138574340187" "552090159017259254714629617513415977493871857473787096164563890871811984" "127167305601704549300470526959016576377688490826798697257336652176556794" "107250876433756084600398490497214911746308553955635418864151316847843631" "3080237596295773983001708984375", -324, first_subnormal, second_subnormal, second_subnormal); TestHalfwayValue( "2." "225073858507201136057409796709131975934819546351645648023426109724822222" "021076945516529523908135087914149158913039621106870086438694594645527657" "207407820621743379988141063267329253552286881372149012981122451451889849" "057222307285255133155755015914397476397983411801999323962548289017107081" "850690630666655994938275772572015763062690663332647565300009245888316433" "037779791869612049497390377829704905051080609940730262937128958950003583" "799967207254304360284078895771796150945516748243471030702609144621572289" "880258182545180325707018860872113128079512233426288368622321503775666622" "503982534335974568884423900265498198385487948292206894721689831099698365" "846814022854243330660339850886445804001034933970427567186443383770486037" "86162277173854562306587467901408672332763671875", -308, last_subnormal, first_normal, first_normal); TestHalfwayValue( "2." "225073858507201630123055637955676152503612414573018013083228724049586647" "606759446192036794116886953213985520549032000903434781884412325572184367" "563347617020518175998922941393629966742598285899994830148971433555578567" "693279306015978183162142425067962460785295885199272493577688320732492479" "924816869232247165964934329258783950102250973957579510571600738343645738" "494324192997092179207389919761694314131497173265255020084997973676783743" "155205818804439163810572367791175177756227497413804253387084478193655533" "073867420834526162513029462022730109054820067654020201547112002028139700" "141575259123440177362244273712468151750189745559978653234255886219611516" "335924167958029604477064946470184777360934300451421683607013647479513962" "13837722826145437693412532098591327667236328125", -308, first_normal, second_normal, first_normal); TestHalfwayValue( "1." "797693134862315608353258760581052985162070023416521662616611746258695532" "672923265745300992879465492467506314903358770175220871059269879629062776" "047355692132901909191523941804762171253349609463563872612866401980290377" "995141836029815117562837277714038305214839639239356331336428021390916694" "57927874464075218944", 308, penultimate_normal, last_normal, penultimate_normal); } TEST(FromChars, FloatRounding) { const float zero = 0.0; const float first_subnormal = nextafterf(zero, 1.0); const float second_subnormal = nextafterf(first_subnormal, 1.0); const float first_normal = FLT_MIN; const float last_subnormal = nextafterf(first_normal, 0.0); const float second_normal = nextafterf(first_normal, 1.0); const float last_normal = FLT_MAX; const float penultimate_normal = nextafterf(last_normal, 0.0); TestHalfwayValue( "7." "006492321624085354618647916449580656401309709382578858785341419448955413" "42930300743319094181060791015625", -46, zero, first_subnormal, zero); TestHalfwayValue( "2." "101947696487225606385594374934874196920392912814773657635602425834686624" "028790902229957282543182373046875", -45, first_subnormal, second_subnormal, second_subnormal); TestHalfwayValue( "1." "175494280757364291727882991035766513322858992758990427682963118425003064" "9651730385585324256680905818939208984375", -38, last_subnormal, first_normal, first_normal); TestHalfwayValue( "1." "175494420887210724209590083408724842314472120785184615334540294131831453" "9442813071445925743319094181060791015625", -38, first_normal, second_normal, first_normal); TestHalfwayValue("3.40282336497324057985868971510891282432", 38, penultimate_normal, last_normal, penultimate_normal); } TEST(FromChars, Underflow) { double d; float f; absl::from_chars_result result; std::string negative_underflow = "-1e-1000"; const char* begin = negative_underflow.data(); const char* end = begin + negative_underflow.size(); d = 100.0; result = absl::from_chars(begin, end, d); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_TRUE(std::signbit(d)); EXPECT_GE(d, -std::numeric_limits<double>::min()); f = 100.0; result = absl::from_chars(begin, end, f); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_TRUE(std::signbit(f)); EXPECT_GE(f, -std::numeric_limits<float>::min()); std::string positive_underflow = "1e-1000"; begin = positive_underflow.data(); end = begin + positive_underflow.size(); d = -100.0; result = absl::from_chars(begin, end, d); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_FALSE(std::signbit(d)); EXPECT_LE(d, std::numeric_limits<double>::min()); f = -100.0; result = absl::from_chars(begin, end, f); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_FALSE(std::signbit(f)); EXPECT_LE(f, std::numeric_limits<float>::min()); } TEST(FromChars, Overflow) { double d; float f; absl::from_chars_result result; std::string negative_overflow = "-1e1000"; const char* begin = negative_overflow.data(); const char* end = begin + negative_overflow.size(); d = 100.0; result = absl::from_chars(begin, end, d); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_TRUE(std::signbit(d)); EXPECT_EQ(d, -std::numeric_limits<double>::max()); f = 100.0; result = absl::from_chars(begin, end, f); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_TRUE(std::signbit(f)); EXPECT_EQ(f, -std::numeric_limits<float>::max()); std::string positive_overflow = "1e1000"; begin = positive_overflow.data(); end = begin + positive_overflow.size(); d = -100.0; result = absl::from_chars(begin, end, d); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_FALSE(std::signbit(d)); EXPECT_EQ(d, std::numeric_limits<double>::max()); f = -100.0; result = absl::from_chars(begin, end, f); EXPECT_EQ(result.ptr, end); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_FALSE(std::signbit(f)); EXPECT_EQ(f, std::numeric_limits<float>::max()); } TEST(FromChars, RegressionTestsFromFuzzer) { absl::string_view src = "0x21900000p00000000099"; float f; auto result = absl::from_chars(src.data(), src.data() + src.size(), f); EXPECT_EQ(result.ec, std::errc::result_out_of_range); } TEST(FromChars, ReturnValuePtr) { double d; absl::from_chars_result result; std::string normal = "3.14@#$%@#$%"; result = absl::from_chars(normal.data(), normal.data() + normal.size(), d); EXPECT_EQ(result.ec, std::errc()); EXPECT_EQ(result.ptr - normal.data(), 4); std::string overflow = "1e1000@#$%@#$%"; result = absl::from_chars(overflow.data(), overflow.data() + overflow.size(), d); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_EQ(result.ptr - overflow.data(), 6); std::string garbage = "#$%@#$%"; result = absl::from_chars(garbage.data(), garbage.data() + garbage.size(), d); EXPECT_EQ(result.ec, std::errc::invalid_argument); EXPECT_EQ(result.ptr - garbage.data(), 0); } TEST(FromChars, TestVersusStrtod) { for (int mantissa = 1000000; mantissa <= 9999999; mantissa += 501) { for (int exponent = -300; exponent < 300; ++exponent) { std::string candidate = absl::StrCat(mantissa, "e", exponent); double strtod_value = strtod(candidate.c_str(), nullptr); double absl_value = 0; absl::from_chars(candidate.data(), candidate.data() + candidate.size(), absl_value); ASSERT_EQ(strtod_value, absl_value) << candidate; } } } TEST(FromChars, TestVersusStrtof) { for (int mantissa = 1000000; mantissa <= 9999999; mantissa += 501) { for (int exponent = -43; exponent < 32; ++exponent) { std::string candidate = absl::StrCat(mantissa, "e", exponent); float strtod_value = strtof(candidate.c_str(), nullptr); float absl_value = 0; absl::from_chars(candidate.data(), candidate.data() + candidate.size(), absl_value); ASSERT_EQ(strtod_value, absl_value) << candidate; } } } template <typename Float> bool Identical(Float a, Float b) { return 0 == memcmp(&a, &b, sizeof(Float)); } TEST(FromChars, NaNDoubles) { for (std::string n_char_sequence : {"", "1", "2", "3", "fff", "FFF", "200000", "400000", "4000000000000", "8000000000000", "abc123", "legal_but_unexpected", "99999999999999999999999", "_"}) { std::string input = absl::StrCat("nan(", n_char_sequence, ")"); SCOPED_TRACE(input); double from_chars_double; absl::from_chars(input.data(), input.data() + input.size(), from_chars_double); double std_nan_double = std::nan(n_char_sequence.c_str()); EXPECT_TRUE(Identical(from_chars_double, std_nan_double)); #if ABSL_STRTOD_HANDLES_NAN_CORRECTLY double strtod_double = strtod(input.c_str(), nullptr); EXPECT_TRUE(Identical(from_chars_double, strtod_double)); #endif std::string negative_input = "-" + input; double negative_from_chars_double; absl::from_chars(negative_input.data(), negative_input.data() + negative_input.size(), negative_from_chars_double); EXPECT_TRUE(std::signbit(negative_from_chars_double)); EXPECT_FALSE(Identical(negative_from_chars_double, from_chars_double)); from_chars_double = std::copysign(from_chars_double, -1.0); EXPECT_TRUE(Identical(negative_from_chars_double, from_chars_double)); } } TEST(FromChars, NaNFloats) { for (std::string n_char_sequence : {"", "1", "2", "3", "fff", "FFF", "200000", "400000", "4000000000000", "8000000000000", "abc123", "legal_but_unexpected", "99999999999999999999999", "_"}) { std::string input = absl::StrCat("nan(", n_char_sequence, ")"); SCOPED_TRACE(input); float from_chars_float; absl::from_chars(input.data(), input.data() + input.size(), from_chars_float); float std_nan_float = std::nanf(n_char_sequence.c_str()); EXPECT_TRUE(Identical(from_chars_float, std_nan_float)); #if ABSL_STRTOD_HANDLES_NAN_CORRECTLY float strtof_float = strtof(input.c_str(), nullptr); EXPECT_TRUE(Identical(from_chars_float, strtof_float)); #endif std::string negative_input = "-" + input; float negative_from_chars_float; absl::from_chars(negative_input.data(), negative_input.data() + negative_input.size(), negative_from_chars_float); EXPECT_TRUE(std::signbit(negative_from_chars_float)); EXPECT_FALSE(Identical(negative_from_chars_float, from_chars_float)); from_chars_float = std::copysign(from_chars_float, -1.0f); EXPECT_TRUE(Identical(negative_from_chars_float, from_chars_float)); } } int NextStep(int step) { return step + (step >> 2) + 1; } template <typename Float> void TestOverflowAndUnderflow( const std::function<std::string(int)>& input_generator, const std::function<Float(int)>& expected_generator, int lower_bound, int upper_bound) { int index, step; for (index = lower_bound, step = 1; index < upper_bound; index += step, step = NextStep(step)) { std::string input = input_generator(index); SCOPED_TRACE(input); Float expected = expected_generator(index); Float actual; auto result = absl::from_chars(input.data(), input.data() + input.size(), actual); EXPECT_EQ(result.ec, std::errc()); EXPECT_EQ(expected, actual) << absl::StrFormat("%a vs %a", expected, actual); } for (index = upper_bound, step = 1; index > lower_bound; index -= step, step = NextStep(step)) { std::string input = input_generator(index); SCOPED_TRACE(input); Float expected = expected_generator(index); Float actual; auto result = absl::from_chars(input.data(), input.data() + input.size(), actual); EXPECT_EQ(result.ec, std::errc()); EXPECT_EQ(expected, actual) << absl::StrFormat("%a vs %a", expected, actual); } for (index = lower_bound - 1, step = 1; index > -1000000; index -= step, step = NextStep(step)) { std::string input = input_generator(index); SCOPED_TRACE(input); Float actual; auto result = absl::from_chars(input.data(), input.data() + input.size(), actual); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_LT(actual, 1.0); } for (index = upper_bound + 1, step = 1; index < 1000000; index += step, step = NextStep(step)) { std::string input = input_generator(index); SCOPED_TRACE(input); Float actual; auto result = absl::from_chars(input.data(), input.data() + input.size(), actual); EXPECT_EQ(result.ec, std::errc::result_out_of_range); EXPECT_GT(actual, 1.0); } } TEST(FromChars, HexdecimalDoubleLimits) { auto input_gen = [](int index) { return absl::StrCat("0x1.0p", index); }; auto expected_gen = [](int index) { return std::ldexp(1.0, index); }; TestOverflowAndUnderflow<doub
2,555
#ifndef ABSL_STRINGS_ASCII_H_ #define ABSL_STRINGS_ASCII_H_ #include <algorithm> #include <cstddef> #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/nullability.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace ascii_internal { ABSL_DLL extern const unsigned char kPropertyBits[256]; ABSL_DLL extern const char kToUpper[256]; ABSL_DLL extern const char kToLower[256]; } inline bool ascii_isalpha(unsigned char c) { return (ascii_internal::kPropertyBits[c] & 0x01) != 0; } inline bool ascii_isalnum(unsigned char c) { return (ascii_internal::kPropertyBits[c] & 0x04) != 0; } inline bool ascii_isspace(unsigned char c) { return (ascii_internal::kPropertyBits[c] & 0x08) != 0; } inline bool ascii_ispunct(unsigned char c) { return (ascii_internal::kPropertyBits[c] & 0x10) != 0; } inline bool ascii_isblank(unsigned char c) { return (ascii_internal::kPropertyBits[c] & 0x20) != 0; } inline bool ascii_iscntrl(unsigned char c) { return (ascii_internal::kPropertyBits[c] & 0x40) != 0; } inline bool ascii_isxdigit(unsigned char c) { return (ascii_internal::kPropertyBits[c] & 0x80) != 0; } inline bool ascii_isdigit(unsigned char c) { return c >= '0' && c <= '9'; } inline bool ascii_isprint(unsigned char c) { return c >= 32 && c < 127; } inline bool ascii_isgraph(unsigned char c) { return c > 32 && c < 127; } inline bool ascii_isupper(unsigned char c) { return c >= 'A' && c <= 'Z'; } inline bool ascii_islower(unsigned char c) { return c >= 'a' && c <= 'z'; } inline bool ascii_isascii(unsigned char c) { return c < 128; } inline char ascii_tolower(unsigned char c) { return ascii_internal::kToLower[c]; } void AsciiStrToLower(absl::Nonnull<std::string*> s); ABSL_MUST_USE_RESULT inline std::string AsciiStrToLower(absl::string_view s) { std::string result(s); absl::AsciiStrToLower(&result); return result; } inline char ascii_toupper(unsigned char c) { return ascii_internal::kToUpper[c]; } void AsciiStrToUpper(absl::Nonnull<std::string*> s); ABSL_MUST_USE_RESULT inline std::string AsciiStrToUpper(absl::string_view s) { std::string result(s); absl::AsciiStrToUpper(&result); return result; } ABSL_MUST_USE_RESULT inline absl::string_view StripLeadingAsciiWhitespace( absl::string_view str) { auto it = std::find_if_not(str.begin(), str.end(), absl::ascii_isspace); return str.substr(static_cast<size_t>(it - str.begin())); } inline void StripLeadingAsciiWhitespace(absl::Nonnull<std::string*> str) { auto it = std::find_if_not(str->begin(), str->end(), absl::ascii_isspace); str->erase(str->begin(), it); } ABSL_MUST_USE_RESULT inline absl::string_view StripTrailingAsciiWhitespace( absl::string_view str) { auto it = std::find_if_not(str.rbegin(), str.rend(), absl::ascii_isspace); return str.substr(0, static_cast<size_t>(str.rend() - it)); } inline void StripTrailingAsciiWhitespace(absl::Nonnull<std::string*> str) { auto it = std::find_if_not(str->rbegin(), str->rend(), absl::ascii_isspace); str->erase(static_cast<size_t>(str->rend() - it)); } ABSL_MUST_USE_RESULT inline absl::string_view StripAsciiWhitespace( absl::string_view str) { return StripTrailingAsciiWhitespace(StripLeadingAsciiWhitespace(str)); } inline void StripAsciiWhitespace(absl::Nonnull<std::string*> str) { StripTrailingAsciiWhitespace(str); StripLeadingAsciiWhitespace(str); } void RemoveExtraAsciiWhitespace(absl::Nonnull<std::string*> str); ABSL_NAMESPACE_END } #endif #include "absl/strings/ascii.h" #include <climits> #include <cstddef> #include <cstring> #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace ascii_internal { ABSL_DLL const unsigned char kPropertyBits[256] = { 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x68, 0x48, 0x48, 0x48, 0x48, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x28, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x40, }; ABSL_DLL const char kToLower[256] = { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27', '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f', '\x40', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f', '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', '\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f', '\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87', '\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e', '\x8f', '\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97', '\x98', '\x99', '\x9a', '\x9b', '\x9c', '\x9d', '\x9e', '\x9f', '\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7', '\xa8', '\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf', '\xb0', '\xb1', '\xb2', '\xb3', '\xb4', '\xb5', '\xb6', '\xb7', '\xb8', '\xb9', '\xba', '\xbb', '\xbc', '\xbd', '\xbe', '\xbf', '\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7', '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf', '\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff', }; ABSL_DLL const char kToUpper[256] = { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27', '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f', '\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47', '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f', '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57', '\x58', '\x59', '\x5a', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f', '\x60', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f', '\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87', '\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e', '\x8f', '\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97', '\x98', '\x99', '\x9a', '\x9b', '\x9c', '\x9d', '\x9e', '\x9f', '\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7', '\xa8', '\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf', '\xb0', '\xb1', '\xb2', '\xb3', '\xb4', '\xb5', '\xb6', '\xb7', '\xb8', '\xb9', '\xba', '\xbb', '\xbc', '\xbd', '\xbe', '\xbf', '\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7', '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf', '\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7', '\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff', }; template <bool ToUpper> constexpr bool AsciiInAZRange(unsigned char c) { constexpr unsigned char sub = (ToUpper ? 'a' : 'A') - SCHAR_MIN; constexpr signed char threshold = SCHAR_MIN + 26; unsigned char u = c - sub; return static_cast<signed char>(u) < threshold; } template <bool ToUpper> ABSL_ATTRIBUTE_ALWAYS_INLINE inline constexpr void AsciiStrCaseFoldImpl( absl::Nonnull<char*> p, size_t size) { constexpr unsigned char kAsciiCaseBitFlip = 'a' ^ 'A'; for (size_t i = 0; i < size; ++i) { unsigned char v = static_cast<unsigned char>(p[i]); v ^= AsciiInAZRange<ToUpper>(v) ? kAsciiCaseBitFlip : 0; p[i] = static_cast<char>(v); } } constexpr size_t kCaseFoldThreshold = 16; template <bool ToUpper> ABSL_ATTRIBUTE_NOINLINE constexpr void AsciiStrCaseFoldLong( absl::Nonnull<char*> p, size_t size) { ABSL_ASSUME(size >= kCaseFoldThreshold); AsciiStrCaseFoldImpl<ToUpper>(p, size); } template <bool ToUpper> constexpr void AsciiStrCaseFold(absl::Nonnull<char*> p, size_t size) { size < kCaseFoldThreshold ? AsciiStrCaseFoldImpl<ToUpper>(p, size) : AsciiStrCaseFoldLong<ToUpper>(p, size); } static constexpr size_t ValidateAsciiCasefold() { constexpr size_t num_chars = 1 + CHAR_MAX - CHAR_MIN; size_t incorrect_index = 0; char lowered[num_chars] = {}; char uppered[num_chars] = {}; for (unsigned int i = 0; i < num_chars; ++i) { uppered[i] = lowered[i] = static_cast<char>(i); } AsciiStrCaseFold<false>(&lowered[0], num_chars); AsciiStrCaseFold<true>(&uppered[0], num_chars); for (size_t i = 0; i < num_chars; ++i) { const char ch = static_cast<char>(i), ch_upper = ('a' <= ch && ch <= 'z' ? 'A' + (ch - 'a') : ch), ch_lower = ('A' <= ch && ch <= 'Z' ? 'a' + (ch - 'A') : ch); if (uppered[i] != ch_upper || lowered[i] != ch_lower) { incorrect_index = i > 0 ? i : num_chars; break; } } return incorrect_index; } static_assert(ValidateAsciiCasefold() == 0, "error in case conversion"); } void AsciiStrToLower(absl::Nonnull<std::string*> s) { return ascii_internal::AsciiStrCaseFold<false>(&(*s)[0], s->size()); } void AsciiStrToUpper(absl::Nonnull<std::string*> s) { return ascii_internal::AsciiStrCaseFold<true>(&(*s)[0], s->size()); } void RemoveExtraAsciiWhitespace(absl::Nonnull<std::string*> str) { auto stripped = StripAsciiWhitespace(*str); if (stripped.empty()) { str->clear(); return; } auto input_it = stripped.begin(); auto input_end = stripped.end(); auto output_it = &(*str)[0]; bool is_ws = false; for (; input_it < input_end; ++input_it) { if (is_ws) { is_ws = absl::ascii_isspace(static_cast<unsigned char>(*input_it)); if (is_ws) --output_it; } else { is_ws = absl::ascii_isspace(static_cast<unsigned char>(*input_it)); } *output_it = *input_it; ++output_it; } str->erase(static_cast<size_t>(output_it - &(*str)[0])); } ABSL_NAMESPACE_END }
#include "absl/strings/ascii.h" #include <algorithm> #include <cctype> #include <clocale> #include <cstring> #include <string> #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/strings/string_view.h" namespace { TEST(AsciiIsFoo, All) { for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) EXPECT_TRUE(absl::ascii_isalpha(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isalpha(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if ((c >= '0' && c <= '9')) EXPECT_TRUE(absl::ascii_isdigit(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isdigit(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (absl::ascii_isalpha(c) || absl::ascii_isdigit(c)) EXPECT_TRUE(absl::ascii_isalnum(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isalnum(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (i != '\0' && strchr(" \r\n\t\v\f", i)) EXPECT_TRUE(absl::ascii_isspace(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isspace(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (i >= 32 && i < 127) EXPECT_TRUE(absl::ascii_isprint(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isprint(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (absl::ascii_isprint(c) && !absl::ascii_isspace(c) && !absl::ascii_isalnum(c)) { EXPECT_TRUE(absl::ascii_ispunct(c)) << ": failed on " << c; } else { EXPECT_TRUE(!absl::ascii_ispunct(c)) << ": failed on " << c; } } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (i == ' ' || i == '\t') EXPECT_TRUE(absl::ascii_isblank(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isblank(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (i < 32 || i == 127) EXPECT_TRUE(absl::ascii_iscntrl(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_iscntrl(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (absl::ascii_isdigit(c) || (i >= 'A' && i <= 'F') || (i >= 'a' && i <= 'f')) { EXPECT_TRUE(absl::ascii_isxdigit(c)) << ": failed on " << c; } else { EXPECT_TRUE(!absl::ascii_isxdigit(c)) << ": failed on " << c; } } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (i > 32 && i < 127) EXPECT_TRUE(absl::ascii_isgraph(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isgraph(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (i >= 'A' && i <= 'Z') EXPECT_TRUE(absl::ascii_isupper(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_isupper(c)) << ": failed on " << c; } for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (i >= 'a' && i <= 'z') EXPECT_TRUE(absl::ascii_islower(c)) << ": failed on " << c; else EXPECT_TRUE(!absl::ascii_islower(c)) << ": failed on " << c; } for (unsigned char c = 0; c < 128; c++) { EXPECT_TRUE(absl::ascii_isascii(c)) << ": failed on " << c; } for (int i = 128; i < 256; i++) { const auto c = static_cast<unsigned char>(i); EXPECT_TRUE(!absl::ascii_isascii(c)) << ": failed on " << c; } } TEST(AsciiIsFoo, SameAsIsFoo) { #ifndef __ANDROID__ const char* old_locale = setlocale(LC_CTYPE, "C"); ASSERT_TRUE(old_locale != nullptr); #endif for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); EXPECT_EQ(isalpha(c) != 0, absl::ascii_isalpha(c)) << c; EXPECT_EQ(isdigit(c) != 0, absl::ascii_isdigit(c)) << c; EXPECT_EQ(isalnum(c) != 0, absl::ascii_isalnum(c)) << c; EXPECT_EQ(isspace(c) != 0, absl::ascii_isspace(c)) << c; EXPECT_EQ(ispunct(c) != 0, absl::ascii_ispunct(c)) << c; EXPECT_EQ(isblank(c) != 0, absl::ascii_isblank(c)) << c; EXPECT_EQ(iscntrl(c) != 0, absl::ascii_iscntrl(c)) << c; EXPECT_EQ(isxdigit(c) != 0, absl::ascii_isxdigit(c)) << c; EXPECT_EQ(isprint(c) != 0, absl::ascii_isprint(c)) << c; EXPECT_EQ(isgraph(c) != 0, absl::ascii_isgraph(c)) << c; EXPECT_EQ(isupper(c) != 0, absl::ascii_isupper(c)) << c; EXPECT_EQ(islower(c) != 0, absl::ascii_islower(c)) << c; EXPECT_EQ(isascii(c) != 0, absl::ascii_isascii(c)) << c; } #ifndef __ANDROID__ ASSERT_TRUE(setlocale(LC_CTYPE, old_locale)); #endif } TEST(AsciiToFoo, All) { #ifndef __ANDROID__ const char* old_locale = setlocale(LC_CTYPE, "C"); ASSERT_TRUE(old_locale != nullptr); #endif for (int i = 0; i < 256; i++) { const auto c = static_cast<unsigned char>(i); if (absl::ascii_islower(c)) EXPECT_EQ(absl::ascii_toupper(c), 'A' + (i - 'a')) << c; else EXPECT_EQ(absl::ascii_toupper(c), static_cast<char>(i)) << c; if (absl::ascii_isupper(c)) EXPECT_EQ(absl::ascii_tolower(c), 'a' + (i - 'A')) << c; else EXPECT_EQ(absl::ascii_tolower(c), static_cast<char>(i)) << c; EXPECT_EQ(static_cast<char>(tolower(i)), absl::ascii_tolower(c)) << c; EXPECT_EQ(static_cast<char>(toupper(i)), absl::ascii_toupper(c)) << c; } #ifndef __ANDROID__ ASSERT_TRUE(setlocale(LC_CTYPE, old_locale)); #endif } TEST(AsciiStrTo, Lower) { const char buf[] = "ABCDEF"; const std::string str("GHIJKL"); const std::string str2("MNOPQR"); const absl::string_view sp(str2); const std::string long_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ1!a"); std::string mutable_str("_`?@[{AMNOPQRSTUVWXYZ"); EXPECT_EQ("abcdef", absl::AsciiStrToLower(buf)); EXPECT_EQ("ghijkl", absl::AsciiStrToLower(str)); EXPECT_EQ("mnopqr", absl::AsciiStrToLower(sp)); EXPECT_EQ("abcdefghijklmnopqrstuvwxyz1!a", absl::AsciiStrToLower(long_str)); absl::AsciiStrToLower(&mutable_str); EXPECT_EQ("_`?@[{amnopqrstuvwxyz", mutable_str); char mutable_buf[] = "Mutable"; std::transform(mutable_buf, mutable_buf + strlen(mutable_buf), mutable_buf, absl::ascii_tolower); EXPECT_STREQ("mutable", mutable_buf); } TEST(AsciiStrTo, Upper) { const char buf[] = "abcdef"; const std::string str("ghijkl"); const std::string str2("_`?@[{amnopqrstuvwxyz"); const absl::string_view sp(str2); const std::string long_str("abcdefghijklmnopqrstuvwxyz1!A"); EXPECT_EQ("ABCDEF", absl::AsciiStrToUpper(buf)); EXPECT_EQ("GHIJKL", absl::AsciiStrToUpper(str)); EXPECT_EQ("_`?@[{AMNOPQRSTUVWXYZ", absl::AsciiStrToUpper(sp)); EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1!A", absl::AsciiStrToUpper(long_str)); char mutable_buf[] = "Mutable"; std::transform(mutable_buf, mutable_buf + strlen(mutable_buf), mutable_buf, absl::ascii_toupper); EXPECT_STREQ("MUTABLE", mutable_buf); } TEST(StripLeadingAsciiWhitespace, FromStringView) { EXPECT_EQ(absl::string_view{}, absl::StripLeadingAsciiWhitespace(absl::string_view{})); EXPECT_EQ("foo", absl::StripLeadingAsciiWhitespace({"foo"})); EXPECT_EQ("foo", absl::StripLeadingAsciiWhitespace({"\t \n\f\r\n\vfoo"})); EXPECT_EQ("foo foo\n ", absl::StripLeadingAsciiWhitespace({"\t \n\f\r\n\vfoo foo\n "})); EXPECT_EQ(absl::string_view{}, absl::StripLeadingAsciiWhitespace( {"\t \n\f\r\v\n\t \n\f\r\v\n"})); } TEST(StripLeadingAsciiWhitespace, InPlace) { std::string str; absl::StripLeadingAsciiWhitespace(&str); EXPECT_EQ("", str); str = "foo"; absl::StripLeadingAsciiWhitespace(&str); EXPECT_EQ("foo", str); str = "\t \n\f\r\n\vfoo"; absl::StripLeadingAsciiWhitespace(&str); EXPECT_EQ("foo", str); str = "\t \n\f\r\n\vfoo foo\n "; absl::StripLeadingAsciiWhitespace(&str); EXPECT_EQ("foo foo\n ", str); str = "\t \n\f\r\v\n\t \n\f\r\v\n"; absl::StripLeadingAsciiWhitespace(&str); EXPECT_EQ(absl::string_view{}, str); } TEST(StripTrailingAsciiWhitespace, FromStringView) { EXPECT_EQ(absl::string_view{}, absl::StripTrailingAsciiWhitespace(absl::string_view{})); EXPECT_EQ("foo", absl::StripTrailingAsciiWhitespace({"foo"})); EXPECT_EQ("foo", absl::StripTrailingAsciiWhitespace({"foo\t \n\f\r\n\v"})); EXPECT_EQ(" \nfoo foo", absl::StripTrailingAsciiWhitespace({" \nfoo foo\t \n\f\r\n\v"})); EXPECT_EQ(absl::string_view{}, absl::StripTrailingAsciiWhitespace( {"\t \n\f\r\v\n\t \n\f\r\v\n"})); } TEST(StripTrailingAsciiWhitespace, InPlace) { std::string str; absl::StripTrailingAsciiWhitespace(&str); EXPECT_EQ("", str); str = "foo"; absl::StripTrailingAsciiWhitespace(&str); EXPECT_EQ("foo", str); str = "foo\t \n\f\r\n\v"; absl::StripTrailingAsciiWhitespace(&str); EXPECT_EQ("foo", str); str = " \nfoo foo\t \n\f\r\n\v"; absl::StripTrailingAsciiWhitespace(&str); EXPECT_EQ(" \nfoo foo", str); str = "\t \n\f\r\v\n\t \n\f\r\v\n"; absl::StripTrailingAsciiWhitespace(&str); EXPECT_EQ(absl::string_view{}, str); } TEST(StripAsciiWhitespace, FromStringView) { EXPECT_EQ(absl::string_view{}, absl::StripAsciiWhitespace(absl::string_view{})); EXPECT_EQ("foo", absl::StripAsciiWhitespace({"foo"})); EXPECT_EQ("foo", absl::StripAsciiWhitespace({"\t \n\f\r\n\vfoo\t \n\f\r\n\v"})); EXPECT_EQ("foo foo", absl::StripAsciiWhitespace( {"\t \n\f\r\n\vfoo foo\t \n\f\r\n\v"})); EXPECT_EQ(absl::string_view{}, absl::StripAsciiWhitespace({"\t \n\f\r\v\n\t \n\f\r\v\n"})); } TEST(StripAsciiWhitespace, InPlace) { std::string str; absl::StripAsciiWhitespace(&str); EXPECT_EQ("", str); str = "foo"; absl::StripAsciiWhitespace(&str); EXPECT_EQ("foo", str); str = "\t \n\f\r\n\vfoo\t \n\f\r\n\v"; absl::StripAsciiWhitespace(&str); EXPECT_EQ("foo", str); str = "\t \n\f\r\n\vfoo foo\t \n\f\r\n\v"; absl::StripAsciiWhitespace(&str); EXPECT_EQ("foo foo", str); str = "\t \n\f\r\v\n\t \n\f\r\v\n"; absl::StripAsciiWhitespace(&str); EXPECT_EQ(absl::string_view{}, str); } TEST(RemoveExtraAsciiWhitespace, InPlace) { const char* inputs[] = {"No extra space", " Leading whitespace", "Trailing whitespace ", " Leading and trailing ", " Whitespace \t in\v middle ", "'Eeeeep! \n Newlines!\n", "nospaces", "", "\n\t a\t\n\nb \t\n"}; const char* outputs[] = { "No extra space", "Leading whitespace", "Trailing whitespace", "Leading and trailing", "Whitespace in middle", "'Eeeeep! Newlines!", "nospaces", "", "a\nb", }; const int NUM_TESTS = ABSL_ARRAYSIZE(inputs); for (int i = 0; i < NUM_TESTS; i++) { std::string s(inputs[i]); absl::RemoveExtraAsciiWhitespace(&s); EXPECT_EQ(outputs[i], s); } } }
2,556
#ifndef ABSL_STRINGS_INTERNAL_ESCAPING_H_ #define ABSL_STRINGS_INTERNAL_ESCAPING_H_ #include <cassert> #include "absl/strings/internal/resize_uninitialized.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { ABSL_CONST_INIT extern const char kBase64Chars[]; ABSL_CONST_INIT extern const char kWebSafeBase64Chars[]; size_t CalculateBase64EscapedLenInternal(size_t input_len, bool do_padding); size_t Base64EscapeInternal(const unsigned char* src, size_t szsrc, char* dest, size_t szdest, const char* base64, bool do_padding); template <typename String> void Base64EscapeInternal(const unsigned char* src, size_t szsrc, String* dest, bool do_padding, const char* base64_chars) { const size_t calc_escaped_size = CalculateBase64EscapedLenInternal(szsrc, do_padding); STLStringResizeUninitialized(dest, calc_escaped_size); const size_t escaped_len = Base64EscapeInternal( src, szsrc, &(*dest)[0], dest->size(), base64_chars, do_padding); assert(calc_escaped_size == escaped_len); dest->erase(escaped_len); } } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/escaping.h" #include <limits> #include "absl/base/internal/endian.h" #include "absl/base/internal/raw_logging.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { ABSL_CONST_INIT const char kBase64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; ABSL_CONST_INIT const char kWebSafeBase64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; size_t CalculateBase64EscapedLenInternal(size_t input_len, bool do_padding) { constexpr size_t kMaxSize = (std::numeric_limits<size_t>::max() - 1) / 4 * 3; ABSL_INTERNAL_CHECK(input_len <= kMaxSize, "CalculateBase64EscapedLenInternal() overflow"); size_t len = (input_len / 3) * 4; if (input_len % 3 == 0) { } else if (input_len % 3 == 1) { len += 2; if (do_padding) { len += 2; } } else { len += 3; if (do_padding) { len += 1; } } return len; } size_t Base64EscapeInternal(const unsigned char* src, size_t szsrc, char* dest, size_t szdest, const char* base64, bool do_padding) { static const char kPad64 = '='; if (szsrc * 4 > szdest * 3) return 0; char* cur_dest = dest; const unsigned char* cur_src = src; char* const limit_dest = dest + szdest; const unsigned char* const limit_src = src + szsrc; if (szsrc >= 3) { while (cur_src < limit_src - 3) { uint32_t in = absl::big_endian::Load32(cur_src) >> 8; cur_dest[0] = base64[in >> 18]; in &= 0x3FFFF; cur_dest[1] = base64[in >> 12]; in &= 0xFFF; cur_dest[2] = base64[in >> 6]; in &= 0x3F; cur_dest[3] = base64[in]; cur_dest += 4; cur_src += 3; } } szdest = static_cast<size_t>(limit_dest - cur_dest); szsrc = static_cast<size_t>(limit_src - cur_src); switch (szsrc) { case 0: break; case 1: { if (szdest < 2) return 0; uint32_t in = cur_src[0]; cur_dest[0] = base64[in >> 2]; in &= 0x3; cur_dest[1] = base64[in << 4]; cur_dest += 2; szdest -= 2; if (do_padding) { if (szdest < 2) return 0; cur_dest[0] = kPad64; cur_dest[1] = kPad64; cur_dest += 2; szdest -= 2; } break; } case 2: { if (szdest < 3) return 0; uint32_t in = absl::big_endian::Load16(cur_src); cur_dest[0] = base64[in >> 10]; in &= 0x3FF; cur_dest[1] = base64[in >> 4]; in &= 0x00F; cur_dest[2] = base64[in << 2]; cur_dest += 3; szdest -= 3; if (do_padding) { if (szdest < 1) return 0; cur_dest[0] = kPad64; cur_dest += 1; szdest -= 1; } break; } case 3: { if (szdest < 4) return 0; uint32_t in = (uint32_t{cur_src[0]} << 16) + absl::big_endian::Load16(cur_src + 1); cur_dest[0] = base64[in >> 18]; in &= 0x3FFFF; cur_dest[1] = base64[in >> 12]; in &= 0xFFF; cur_dest[2] = base64[in >> 6]; in &= 0x3F; cur_dest[3] = base64[in]; cur_dest += 4; szdest -= 4; break; } default: ABSL_RAW_LOG(FATAL, "Logic problem? szsrc = %zu", szsrc); break; } return static_cast<size_t>(cur_dest - dest); } } ABSL_NAMESPACE_END }
#include "absl/strings/escaping.h" #include <array> #include <cstddef> #include <cstdio> #include <cstring> #include <initializer_list> #include <memory> #include <string> #include <vector> #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/strings/str_cat.h" #include "absl/strings/internal/escaping_test_common.h" #include "absl/strings/string_view.h" namespace { struct epair { std::string escaped; std::string unescaped; }; TEST(CEscape, EscapeAndUnescape) { const std::string inputs[] = { std::string("foo\nxx\r\b\0023"), std::string(""), std::string("abc"), std::string("\1chad_rules"), std::string("\1arnar_drools"), std::string("xxxx\r\t'\"\\"), std::string("\0xx\0", 4), std::string("\x01\x31"), std::string("abc\xb\x42\141bc"), std::string("123\1\x31\x32\x33"), std::string("\xc1\xca\x1b\x62\x19o\xcc\x04"), std::string( "\\\"\xe8\xb0\xb7\xe6\xad\x8c\\\" is Google\\\'s Chinese name"), }; for (int kind = 0; kind < 4; kind++) { for (const std::string& original : inputs) { std::string escaped; switch (kind) { case 0: escaped = absl::CEscape(original); break; case 1: escaped = absl::CHexEscape(original); break; case 2: escaped = absl::Utf8SafeCEscape(original); break; case 3: escaped = absl::Utf8SafeCHexEscape(original); break; } std::string unescaped_str; EXPECT_TRUE(absl::CUnescape(escaped, &unescaped_str)); EXPECT_EQ(unescaped_str, original); unescaped_str.erase(); std::string error; EXPECT_TRUE(absl::CUnescape(escaped, &unescaped_str, &error)); EXPECT_EQ(error, ""); std::string s = escaped; EXPECT_TRUE(absl::CUnescape(s, &s)); ASSERT_EQ(s, original); } } for (int char0 = 0; char0 < 256; char0++) { for (int char1 = 0; char1 < 256; char1++) { char chars[2]; chars[0] = char0; chars[1] = char1; std::string s(chars, 2); std::string escaped = absl::CHexEscape(s); std::string unescaped; EXPECT_TRUE(absl::CUnescape(escaped, &unescaped)); EXPECT_EQ(s, unescaped); } } } TEST(CEscape, BasicEscaping) { epair oct_values[] = { {"foo\\rbar\\nbaz\\t", "foo\rbar\nbaz\t"}, {"\\'full of \\\"sound\\\" and \\\"fury\\\"\\'", "'full of \"sound\" and \"fury\"'"}, {"signi\\\\fying\\\\ nothing\\\\", "signi\\fying\\ nothing\\"}, {"\\010\\t\\n\\013\\014\\r", "\010\011\012\013\014\015"} }; epair hex_values[] = { {"ubik\\rubik\\nubik\\t", "ubik\rubik\nubik\t"}, {"I\\\'ve just seen a \\\"face\\\"", "I've just seen a \"face\""}, {"hel\\\\ter\\\\skel\\\\ter\\\\", "hel\\ter\\skel\\ter\\"}, {"\\x08\\t\\n\\x0b\\x0c\\r", "\010\011\012\013\014\015"} }; epair utf8_oct_values[] = { {"\xe8\xb0\xb7\xe6\xad\x8c\\r\xe8\xb0\xb7\xe6\xad\x8c\\nbaz\\t", "\xe8\xb0\xb7\xe6\xad\x8c\r\xe8\xb0\xb7\xe6\xad\x8c\nbaz\t"}, {"\\\"\xe8\xb0\xb7\xe6\xad\x8c\\\" is Google\\\'s Chinese name", "\"\xe8\xb0\xb7\xe6\xad\x8c\" is Google\'s Chinese name"}, {"\xe3\x83\xa1\xe3\x83\xbc\xe3\x83\xab\\\\are\\\\Japanese\\\\chars\\\\", "\xe3\x83\xa1\xe3\x83\xbc\xe3\x83\xab\\are\\Japanese\\chars\\"}, {"\xed\x81\xac\xeb\xa1\xac\\010\\t\\n\\013\\014\\r", "\xed\x81\xac\xeb\xa1\xac\010\011\012\013\014\015"} }; epair utf8_hex_values[] = { {"\x20\xe4\xbd\xa0\\t\xe5\xa5\xbd,\\r!\\n", "\x20\xe4\xbd\xa0\t\xe5\xa5\xbd,\r!\n"}, {"\xe8\xa9\xa6\xe9\xa8\x93\\\' means \\\"test\\\"", "\xe8\xa9\xa6\xe9\xa8\x93\' means \"test\""}, {"\\\\\xe6\x88\x91\\\\:\\\\\xe6\x9d\xa8\xe6\xac\xa2\\\\", "\\\xe6\x88\x91\\:\\\xe6\x9d\xa8\xe6\xac\xa2\\"}, {"\xed\x81\xac\xeb\xa1\xac\\x08\\t\\n\\x0b\\x0c\\r", "\xed\x81\xac\xeb\xa1\xac\010\011\012\013\014\015"} }; for (const epair& val : oct_values) { std::string escaped = absl::CEscape(val.unescaped); EXPECT_EQ(escaped, val.escaped); } for (const epair& val : hex_values) { std::string escaped = absl::CHexEscape(val.unescaped); EXPECT_EQ(escaped, val.escaped); } for (const epair& val : utf8_oct_values) { std::string escaped = absl::Utf8SafeCEscape(val.unescaped); EXPECT_EQ(escaped, val.escaped); } for (const epair& val : utf8_hex_values) { std::string escaped = absl::Utf8SafeCHexEscape(val.unescaped); EXPECT_EQ(escaped, val.escaped); } } TEST(Unescape, BasicFunction) { epair tests[] = {{"", ""}, {"\\u0030", "0"}, {"\\u00A3", "\xC2\xA3"}, {"\\u22FD", "\xE2\x8B\xBD"}, {"\\U00010000", "\xF0\x90\x80\x80"}, {"\\U0010FFFD", "\xF4\x8F\xBF\xBD"}}; for (const epair& val : tests) { std::string out; EXPECT_TRUE(absl::CUnescape(val.escaped, &out)); EXPECT_EQ(out, val.unescaped); } std::string bad[] = {"\\u1", "\\U1", "\\Uffffff", "\\U00110000", "\\uD835", "\\U0000DD04", "\\777", "\\xABCD"}; for (const std::string& e : bad) { std::string error; std::string out; EXPECT_FALSE(absl::CUnescape(e, &out, &error)); EXPECT_FALSE(error.empty()); out.erase(); EXPECT_FALSE(absl::CUnescape(e, &out)); } } class CUnescapeTest : public testing::Test { protected: static const char kStringWithMultipleOctalNulls[]; static const char kStringWithMultipleHexNulls[]; static const char kStringWithMultipleUnicodeNulls[]; std::string result_string_; }; const char CUnescapeTest::kStringWithMultipleOctalNulls[] = "\\0\\n" "0\\n" "\\00\\12" "\\000"; const char CUnescapeTest::kStringWithMultipleHexNulls[] = "\\x0\\n" "0\\n" "\\x00\\xa" "\\x000"; const char CUnescapeTest::kStringWithMultipleUnicodeNulls[] = "\\u0000\\n" "0\\n" "\\U00000000"; TEST_F(CUnescapeTest, Unescapes1CharOctalNull) { std::string original_string = "\\0"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, Unescapes2CharOctalNull) { std::string original_string = "\\00"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, Unescapes3CharOctalNull) { std::string original_string = "\\000"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, Unescapes1CharHexNull) { std::string original_string = "\\x0"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, Unescapes2CharHexNull) { std::string original_string = "\\x00"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, Unescapes3CharHexNull) { std::string original_string = "\\x000"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, Unescapes4CharUnicodeNull) { std::string original_string = "\\u0000"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, Unescapes8CharUnicodeNull) { std::string original_string = "\\U00000000"; EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0", 1), result_string_); } TEST_F(CUnescapeTest, UnescapesMultipleOctalNulls) { std::string original_string(kStringWithMultipleOctalNulls); EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0\n" "0\n" "\0\n" "\0", 7), result_string_); } TEST_F(CUnescapeTest, UnescapesMultipleHexNulls) { std::string original_string(kStringWithMultipleHexNulls); EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0\n" "0\n" "\0\n" "\0", 7), result_string_); } TEST_F(CUnescapeTest, UnescapesMultipleUnicodeNulls) { std::string original_string(kStringWithMultipleUnicodeNulls); EXPECT_TRUE(absl::CUnescape(original_string, &result_string_)); EXPECT_EQ(std::string("\0\n" "0\n" "\0", 5), result_string_); } static struct { absl::string_view plaintext; absl::string_view cyphertext; } const base64_tests[] = { {{"", 0}, {"", 0}}, {{nullptr, 0}, {"", 0}}, {{"\000", 1}, "AA=="}, {{"\001", 1}, "AQ=="}, {{"\002", 1}, "Ag=="}, {{"\004", 1}, "BA=="}, {{"\010", 1}, "CA=="}, {{"\020", 1}, "EA=="}, {{"\040", 1}, "IA=="}, {{"\100", 1}, "QA=="}, {{"\200", 1}, "gA=="}, {{"\377", 1}, "/w=="}, {{"\376", 1}, "/g=="}, {{"\375", 1}, "/Q=="}, {{"\373", 1}, "+w=="}, {{"\367", 1}, "9w=="}, {{"\357", 1}, "7w=="}, {{"\337", 1}, "3w=="}, {{"\277", 1}, "vw=="}, {{"\177", 1}, "fw=="}, {{"\000\000", 2}, "AAA="}, {{"\000\001", 2}, "AAE="}, {{"\000\002", 2}, "AAI="}, {{"\000\004", 2}, "AAQ="}, {{"\000\010", 2}, "AAg="}, {{"\000\020", 2}, "ABA="}, {{"\000\040", 2}, "ACA="}, {{"\000\100", 2}, "AEA="}, {{"\000\200", 2}, "AIA="}, {{"\001\000", 2}, "AQA="}, {{"\002\000", 2}, "AgA="}, {{"\004\000", 2}, "BAA="}, {{"\010\000", 2}, "CAA="}, {{"\020\000", 2}, "EAA="}, {{"\040\000", 2}, "IAA="}, {{"\100\000", 2}, "QAA="}, {{"\200\000", 2}, "gAA="}, {{"\377\377", 2}, " {{"\377\376", 2}, " {{"\377\375", 2}, " {{"\377\373", 2}, " {{"\377\367", 2}, " {{"\377\357", 2}, "/+8="}, {{"\377\337", 2}, "/98="}, {{"\377\277", 2}, "/78="}, {{"\377\177", 2}, "/38="}, {{"\376\377", 2}, "/v8="}, {{"\375\377", 2}, "/f8="}, {{"\373\377", 2}, "+/8="}, {{"\367\377", 2}, "9/8="}, {{"\357\377", 2}, "7/8="}, {{"\337\377", 2}, "3/8="}, {{"\277\377", 2}, "v/8="}, {{"\177\377", 2}, "f/8="}, {{"\000\000\000", 3}, "AAAA"}, {{"\000\000\001", 3}, "AAAB"}, {{"\000\000\002", 3}, "AAAC"}, {{"\000\000\004", 3}, "AAAE"}, {{"\000\000\010", 3}, "AAAI"}, {{"\000\000\020", 3}, "AAAQ"}, {{"\000\000\040", 3}, "AAAg"}, {{"\000\000\100", 3}, "AABA"}, {{"\000\000\200", 3}, "AACA"}, {{"\000\001\000", 3}, "AAEA"}, {{"\000\002\000", 3}, "AAIA"}, {{"\000\004\000", 3}, "AAQA"}, {{"\000\010\000", 3}, "AAgA"}, {{"\000\020\000", 3}, "ABAA"}, {{"\000\040\000", 3}, "ACAA"}, {{"\000\100\000", 3}, "AEAA"}, {{"\000\200\000", 3}, "AIAA"}, {{"\001\000\000", 3}, "AQAA"}, {{"\002\000\000", 3}, "AgAA"}, {{"\004\000\000", 3}, "BAAA"}, {{"\010\000\000", 3}, "CAAA"}, {{"\020\000\000", 3}, "EAAA"}, {{"\040\000\000", 3}, "IAAA"}, {{"\100\000\000", 3}, "QAAA"}, {{"\200\000\000", 3}, "gAAA"}, {{"\377\377\377", 3}, " {{"\377\377\376", 3}, " {{"\377\377\375", 3}, " {{"\377\377\373", 3}, " {{"\377\377\367", 3}, " {{"\377\377\357", 3}, " {{"\377\377\337", 3}, " {{"\377\377\277", 3}, " {{"\377\377\177", 3}, " {{"\377\376\377", 3}, " {{"\377\375\377", 3}, " {{"\377\373\377", 3}, " {{"\377\367\377", 3}, " {{"\377\357\377", 3}, "/+ {{"\377\337\377", 3}, "/9 {{"\377\277\377", 3}, "/7 {{"\377\177\377", 3}, "/3 {{"\376\377\377", 3}, "/v {{"\375\377\377", 3}, "/f {{"\373\377\377", 3}, "+ {{"\367\377\377", 3}, "9 {{"\357\377\377", 3}, "7 {{"\337\377\377", 3}, "3 {{"\277\377\377", 3}, "v {{"\177\377\377", 3}, "f {{"\243\361", 2}, "o/E="}, {{"\024\167", 2}, "FHc="}, {{"\313\252", 2}, "y6o="}, {{"\046\041", 2}, "JiE="}, {{"\145\236", 2}, "ZZ4="}, {{"\254\325", 2}, "rNU="}, {{"\061\330", 2}, "Mdg="}, {{"\245\032", 2}, "pRo="}, {{"\006\000", 2}, "BgA="}, {{"\375\131", 2}, "/Vk="}, {{"\303\210", 2}, "w4g="}, {{"\040\037", 2}, "IB8="}, {{"\261\372", 2}, "sfo="}, {{"\335\014", 2}, "3Qw="}, {{"\233\217", 2}, "m48="}, {{"\373\056", 2}, "+y4="}, {{"\247\232", 2}, "p5o="}, {{"\107\053", 2}, "Rys="}, {{"\204\077", 2}, "hD8="}, {{"\276\211", 2}, "vok="}, {{"\313\110", 2}, "y0g="}, {{"\363\376", 2}, "8/4="}, {{"\251\234", 2}, "qZw="}, {{"\103\262", 2}, "Q7I="}, {{"\142\312", 2}, "Yso="}, {{"\067\211", 2}, "N4k="}, {{"\220\001", 2}, "kAE="}, {{"\152\240", 2}, "aqA="}, {{"\367\061", 2}, "9zE="}, {{"\133\255", 2}, "W60="}, {{"\176\035", 2}, "fh0="}, {{"\032\231", 2}, "Gpk="}, {{"\013\007\144", 3}, "Cwdk"}, {{"\030\112\106", 3}, "GEpG"}, {{"\047\325\046", 3}, "J9Um"}, {{"\310\160\022", 3}, "yHAS"}, {{"\131\100\237", 3}, "WUCf"}, {{"\064\342\134", 3}, "NOJc"}, {{"\010\177\004", 3}, "CH8E"}, {{"\345\147\205", 3}, "5WeF"}, {{"\300\343\360", 3}, "wOPw"}, {{"\061\240\201", 3}, "MaCB"}, {{"\225\333\044", 3}, "ldsk"}, {{"\215\137\352", 3}, "jV/q"}, {{"\371\147\160", 3}, "+Wdw"}, {{"\030\320\051", 3}, "GNAp"}, {{"\044\174\241", 3}, "JHyh"}, {{"\260\127\037", 3}, "sFcf"}, {{"\111\045\033", 3}, "SSUb"}, {{"\202\114\107", 3}, "gkxH"}, {{"\057\371\042", 3}, "L/ki"}, {{"\223\247\244", 3}, "k6ek"}, {{"\047\216\144", 3}, "J45k"}, {{"\203\070\327", 3}, "gzjX"}, {{"\247\140\072", 3}, "p2A6"}, {{"\124\115\116", 3}, "VE1O"}, {{"\157\162\050", 3}, "b3Io"}, {{"\357\223\004", 3}, "75ME"}, {{"\052\117\156", 3}, "Kk9u"}, {{"\347\154\000", 3}, "52wA"}, {{"\303\012\142", 3}, "wwpi"}, {{"\060\035\362", 3}, "MB3y"}, {{"\130\226\361", 3}, "WJbx"}, {{"\173\013\071", 3}, "ews5"}, {{"\336\004\027", 3}, "3gQX"}, {{"\357\366\234", 3}, "7/ac"}, {{"\353\304\111", 3}, "68RJ"}, {{"\024\264\131", 3}, "FLRZ"}, {{"\075\114\251", 3}, "PUyp"}, {{"\315\031\225", 3}, "zRmV"}, {{"\154\201\276", 3}, "bIG+"}, {{"\200\066\072", 3}, "gDY6"}, {{"\142\350\267", 3}, "Yui3"}, {{"\033\000\166", 3}, "GwB2"}, {{"\210\055\077", 3}, "iC0/"}, {{"\341\037\124", 3}, "4R9U"}, {{"\161\103\152", 3}, "cUNq"}, {{"\270\142\131", 3}, "uGJZ"}, {{"\337\076\074", 3}, "3z48"}, {{"\375\106\362", 3}, "/Uby"}, {{"\227\301\127", 3}, "l8FX"}, {{"\340\002\234", 3}, "4AKc"}, {{"\121\064\033", 3}, "UTQb"}, {{"\157\134\143", 3}, "b1xj"}, {{"\247\055\327", 3}, "py3X"}, {{"\340\142\005", 3}, "4GIF"}, {{"\060\260\143", 3}, "MLBj"}, {{"\075\203\170", 3}, "PYN4"}, {{"\143\160\016", 3}, "Y3AO"}, {{"\313\013\063", 3}, "ywsz"}, {{"\174\236\135", 3}, "fJ5d"}, {{"\103\047\026", 3}, "QycW"}, {{"\365\005\343", 3}, "9QXj"}, {{"\271\160\223", 3}, "uXCT"}, {{"\362\255\172", 3}, "8q16"}, {{"\113\012\015", 3}, "SwoN"}, {{"", 0}, {"", 0}}, {"a", "YQ=="}, {"ab", "YWI="}, {"abc", "YWJj"}, {"abcd", "YWJjZA=="}, {"abcde", "YWJjZGU="}, {"abcdef", "YWJjZGVm"}, {"abcdefg", "YWJjZGVmZw=="}, {"abcdefgh", "YWJjZGVmZ2g="}, {"abcdefghi", "YWJjZGVmZ2hp"}, {"abcdefghij", "YWJjZGVmZ2hpag=="}, {"abcdefghijk", "YWJjZGVmZ2hpams="}, {"abcdefghijkl", "YWJjZGVmZ2hpamts"}, {"abcdefghijklm", "YWJjZGVmZ2hpamtsbQ=="}, {"abcdefghijklmn", "YWJjZGVmZ2hpamtsbW4="}, {"abcdefghijklmno", "YWJjZGVmZ2hpamtsbW5v"}, {"abcdefghijklmnop", "YWJjZGVmZ2hpamtsbW5vcA=="}, {"abcdefghijklmnopq", "YWJjZGVmZ2hpamtsbW5vcHE="}, {"abcdefghijklmnopqr", "YWJjZGVmZ2hpamtsbW5vcHFy"}, {"abcdefghijklmnopqrs", "YWJjZGVmZ2hpamtsbW5vcHFycw=="}, {"abcdefghijklmnopqrst", "YWJjZGVmZ2hpamtsbW5vcHFyc3Q="}, {"abcdefghijklmnopqrstu", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1"}, {"abcdefghijklmnopqrstuv", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dg=="}, {"abcdefghijklmnopqrstuvw", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnc="}, {"abcdefghijklmnopqrstuvwx", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4"}, {"abcdefghijklmnopqrstuvwxy", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eQ=="}, {"abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo="}, }; template <typename StringType> void TestEscapeAndUnescape() { for (const auto& tc : base64_tests) { StringType encoded("this junk should be ignored"); absl::Base64Escape(tc.plaintext, &encoded); EXPECT_EQ(encoded, tc.cyphertext); EXPECT_EQ(absl::Base64Escape(tc.plaintext), tc.cyphertext); StringType decoded("this junk should be ignored"); EXPECT_TRUE(absl::Base64Unescape(encoded, &decoded)); EXPECT_EQ(decoded, tc.plaintext); StringType websafe_with_padding(tc.cyphertext); for (unsigned int c = 0; c < websafe_with_padding.size(); ++c) { if ('+' == websafe_with_padding[c]) websafe_with_padding[c] = '-'; if ('/' == websafe_with_padding[c]) websafe_with_padding[c] = '_'; } StringType websafe(websafe_with_padding); for (unsigned int c = 0; c < websafe.size(); ++c) { if ('=' == websafe[c]) { websafe.resize(c); break; } } encoded = "this junk should be ignored"; absl::WebSafeBase64Escape(tc.plaintext, &encoded); EXPECT_EQ(encoded, websafe); EXPECT_EQ(absl::WebSafeBase64Escape(tc.plaintext), websafe); decoded = "this junk should be ignored"; EXPECT_TRUE(absl::WebSafeBase64Unescape(websafe, &decoded)); EXPECT_EQ(decoded, tc.plaintext); } for (const auto& tc : absl::strings_internal::base64_strings()) { StringType buffer; absl::WebSafeBase64Escape(tc.plaintext, &buffer); EXPECT_EQ(tc.cyphertext, buffer); EXPECT_EQ(absl::WebSafeBase64Escape(tc.plaintext), tc.cyphertext); } { absl::string_view data_set[] = {"ab-/", absl::string_view("\0bcd", 4), absl::string_view("abc.\0", 5)}; for (absl::string_view bad_data : data_set) { StringType buf; EXPECT_FALSE(absl::Base64Unescape(bad_data, &buf)); EXPECT_FALSE(absl::WebSafeBase64Unescape(bad_data, &buf)); EXPECT_TRUE(buf.empty()); } } } TEST(Base64, EscapeAndUnescape) { TestEscapeAndUnescape<std::string>(); } TEST(Base64, Padding) { std::initializer_list<absl::string_view> good_padding = { "YQ", "YQ==", "YQ=.", "YQ.=", "YQ..", }; for (absl::string_view b64 : good_padding) { std::string decoded; EXPECT_TRUE(absl::Base64Unescape(b64, &decoded)); EXPECT_EQ(decoded, "a"); std::string websafe_decoded; EXPECT_TRUE(absl::WebSafeBase64Unescape(b64, &websafe_decoded)); EXPECT_EQ(websafe_decoded, "a"); } std::initializer_list<absl::string_view> bad_padding = { "YQ=", "YQ.", "YQ===", "YQ==.", "YQ=.=", "YQ=..", "YQ.==", "YQ.=.", "YQ..=", "YQ...", "YQ====", "YQ....", "YQ=====", "YQ.....", }; for (absl::string_view b64 : bad_padding) { std::string decoded; EXPECT_FALSE(absl::Base64Unescape(b64, &decoded)); std::string websafe_decoded; EXPECT_FALSE(absl::WebSafeBase64Unescape(b64, &websafe_decoded)); } } TEST(Base64, DISABLED_HugeData) { const size_t kSize = size_t(3) * 1000 * 1000 * 1000; static_assert(kSize % 3 == 0, "kSize must be divisible by 3"); const std::string huge(kSize, 'x'); std::string escaped; absl::Base64Escape(huge, &escaped); std::string expected_encoding; expected_encoding.reserve(kSize / 3 * 4); for (size_t i = 0; i < kSize / 3; ++i) { expected_encoding.append("eHh4"); } EXPECT_EQ(expected_encoding, escaped); std::string unescaped; EXPECT_TRUE(absl::Base64Unescape(escaped, &unescaped)); EXPECT_EQ(huge, unescaped); } TEST(Escaping, HexStringToBytesBackToHex) { std::string bytes, hex; constexpr absl::string_view kTestHexLower = "1c2f0032f40123456789abcdef"; constexpr absl::string_view kTestHexUpper = "1C2F0032F40123456789ABCDEF"; constexpr absl::string_view kTestBytes = absl::string_view( "\x1c\x2f\x00\x32\xf4\x01\x23\x45\x67\x89\xab\xcd\xef", 13); EXPECT_TRUE(absl::HexStringToBytes(kTestHexLower, &bytes)); EXPECT_EQ(bytes, kTestBytes); EXPECT_TRUE(absl::HexStringToBytes(kTestHexUpper, &bytes)); EXPECT_EQ(bytes, kTestBytes); hex = absl::BytesToHexString(kTestBytes); EXPECT_EQ(hex, kTestHexLower); bytes = std::string(kTestHexUpper); (void)absl::HexStringToBytes(bytes, &bytes); EXPECT_FALSE(absl::HexStringToBytes("1c2f003", &bytes)); EXPECT_FALSE(absl::HexStringToBytes("1c2f00ft", &bytes)); bytes = "abc"; EXPECT_TRUE(absl::HexStringToBytes("", &bytes)); EXPECT_EQ("", bytes); } TEST(HexAndBack, HexStringToBytes_and_BytesToHexString) { std::string hex_mixed = "0123456789abcdefABCDEF"; std::string bytes_expected = "\x01\x23\x45\x67\x89\xab\xcd\xef\xAB\xCD\xEF"; std::string hex_only_lower = "0123456789abcdefabcdef"; std::string bytes_result = absl::HexStringToBytes(hex_mixed); EXPECT_EQ(bytes_expected, bytes_result); std::string prefix_valid = hex_mixed + "?"; std::string prefix_valid_result = absl::HexStringToBytes( absl::string_view(prefix_valid.data(), prefix_valid.size() - 1)); EXPECT_EQ(bytes_expected, prefix_valid_result); std::string infix_valid = "?" + hex_mixed + "???"; std::string infix_valid_result = absl::HexStringToBytes( absl::string_view(infix_valid.data() + 1, hex_mixed.size())); EXPECT_EQ(bytes_expected, infix_valid_result); std::string hex_result = absl::BytesToHexString(bytes_expected); EXPECT_EQ(hex_only_lower, hex_result); } }
2,557
#ifndef ABSL_STRINGS_CORD_BUFFER_H_ #define ABSL_STRINGS_CORD_BUFFER_H_ #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include "absl/base/config.h" #include "absl/base/macros.h" #include "absl/numeric/bits.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN class Cord; class CordBufferTestPeer; class CordBuffer { public: static constexpr size_t kDefaultLimit = cord_internal::kMaxFlatLength; static constexpr size_t kCustomLimit = 64U << 10; CordBuffer() = default; ~CordBuffer(); CordBuffer(CordBuffer&& rhs) noexcept; CordBuffer& operator=(CordBuffer&&) noexcept; CordBuffer(const CordBuffer&) = delete; CordBuffer& operator=(const CordBuffer&) = delete; static constexpr size_t MaximumPayload(); static constexpr size_t MaximumPayload(size_t block_size); static CordBuffer CreateWithDefaultLimit(size_t capacity); static CordBuffer CreateWithCustomLimit(size_t block_size, size_t capacity); absl::Span<char> available(); absl::Span<char> available_up_to(size_t size); char* data(); const char* data() const; size_t length() const; size_t capacity() const; void IncreaseLengthBy(size_t n); void SetLength(size_t length); private: static_assert(kCustomLimit <= cord_internal::kMaxLargeFlatSize, ""); static constexpr size_t kMaxPageSlop = 128; static constexpr size_t kOverhead = cord_internal::kFlatOverhead; using CordRepFlat = cord_internal::CordRepFlat; struct Rep { static constexpr size_t kInlineCapacity = sizeof(intptr_t) * 2 - 1; Rep() : short_rep{} {} explicit Rep(cord_internal::CordRepFlat* rep) : long_rep{rep} { assert(rep != nullptr); } bool is_short() const { constexpr size_t offset = offsetof(Short, raw_size); return (reinterpret_cast<const char*>(this)[offset] & 1) != 0; } absl::Span<char> short_available() { const size_t length = short_length(); return absl::Span<char>(short_rep.data + length, kInlineCapacity - length); } absl::Span<char> long_available() const { assert(!is_short()); const size_t length = long_rep.rep->length; return absl::Span<char>(long_rep.rep->Data() + length, long_rep.rep->Capacity() - length); } size_t short_length() const { assert(is_short()); return static_cast<size_t>(short_rep.raw_size >> 1); } void set_short_length(size_t length) { short_rep.raw_size = static_cast<char>((length << 1) + 1); } void add_short_length(size_t n) { assert(is_short()); short_rep.raw_size += static_cast<char>(n << 1); } char* data() { assert(is_short()); return short_rep.data; } const char* data() const { assert(is_short()); return short_rep.data; } cord_internal::CordRepFlat* rep() const { assert(!is_short()); return long_rep.rep; } #if defined(ABSL_IS_BIG_ENDIAN) struct Long { explicit Long(cord_internal::CordRepFlat* rep_arg) : rep(rep_arg) {} void* padding; cord_internal::CordRepFlat* rep; }; struct Short { char data[sizeof(Long) - 1]; char raw_size = 1; }; #else struct Long { explicit Long(cord_internal::CordRepFlat* rep_arg) : rep(rep_arg) {} cord_internal::CordRepFlat* rep; void* padding; }; struct Short { char raw_size = 1; char data[sizeof(Long) - 1]; }; #endif union { Long long_rep; Short short_rep; }; }; static bool IsPow2(size_t size) { return absl::has_single_bit(size); } static size_t Log2Floor(size_t size) { return static_cast<size_t>(absl::bit_width(size) - 1); } static size_t Log2Ceil(size_t size) { return static_cast<size_t>(absl::bit_width(size - 1)); } template <typename... AllocationHints> static CordBuffer CreateWithCustomLimitImpl(size_t block_size, size_t capacity, AllocationHints... hints); cord_internal::CordRep* ConsumeValue(absl::string_view& short_value) { cord_internal::CordRep* rep = nullptr; if (rep_.is_short()) { short_value = absl::string_view(rep_.data(), rep_.short_length()); } else { rep = rep_.rep(); } rep_.set_short_length(0); return rep; } explicit CordBuffer(cord_internal::CordRepFlat* rep) : rep_(rep) { assert(rep != nullptr); } Rep rep_; friend class Cord; friend class CordBufferTestPeer; }; inline constexpr size_t CordBuffer::MaximumPayload() { return cord_internal::kMaxFlatLength; } inline constexpr size_t CordBuffer::MaximumPayload(size_t block_size) { return (std::min)(kCustomLimit, block_size) - cord_internal::kFlatOverhead; } inline CordBuffer CordBuffer::CreateWithDefaultLimit(size_t capacity) { if (capacity > Rep::kInlineCapacity) { auto* rep = cord_internal::CordRepFlat::New(capacity); rep->length = 0; return CordBuffer(rep); } return CordBuffer(); } template <typename... AllocationHints> inline CordBuffer CordBuffer::CreateWithCustomLimitImpl( size_t block_size, size_t capacity, AllocationHints... hints) { assert(IsPow2(block_size)); capacity = (std::min)(capacity, kCustomLimit); block_size = (std::min)(block_size, kCustomLimit); if (capacity + kOverhead >= block_size) { capacity = block_size; } else if (capacity <= kDefaultLimit) { capacity = capacity + kOverhead; } else if (!IsPow2(capacity)) { const size_t rounded_up = size_t{1} << Log2Ceil(capacity); const size_t slop = rounded_up - capacity; if (slop >= kOverhead && slop <= kMaxPageSlop + kOverhead) { capacity = rounded_up; } else { const size_t rounded_down = size_t{1} << Log2Floor(capacity); capacity = rounded_down; } } const size_t length = capacity - kOverhead; auto* rep = CordRepFlat::New(CordRepFlat::Large(), length, hints...); rep->length = 0; return CordBuffer(rep); } inline CordBuffer CordBuffer::CreateWithCustomLimit(size_t block_size, size_t capacity) { return CreateWithCustomLimitImpl(block_size, capacity); } inline CordBuffer::~CordBuffer() { if (!rep_.is_short()) { cord_internal::CordRepFlat::Delete(rep_.rep()); } } inline CordBuffer::CordBuffer(CordBuffer&& rhs) noexcept : rep_(rhs.rep_) { rhs.rep_.set_short_length(0); } inline CordBuffer& CordBuffer::operator=(CordBuffer&& rhs) noexcept { if (!rep_.is_short()) cord_internal::CordRepFlat::Delete(rep_.rep()); rep_ = rhs.rep_; rhs.rep_.set_short_length(0); return *this; } inline absl::Span<char> CordBuffer::available() { return rep_.is_short() ? rep_.short_available() : rep_.long_available(); } inline absl::Span<char> CordBuffer::available_up_to(size_t size) { return available().subspan(0, size); } inline char* CordBuffer::data() { return rep_.is_short() ? rep_.data() : rep_.rep()->Data(); } inline const char* CordBuffer::data() const { return rep_.is_short() ? rep_.data() : rep_.rep()->Data(); } inline size_t CordBuffer::capacity() const { return rep_.is_short() ? Rep::kInlineCapacity : rep_.rep()->Capacity(); } inline size_t CordBuffer::length() const { return rep_.is_short() ? rep_.short_length() : rep_.rep()->length; } inline void CordBuffer::SetLength(size_t length) { ABSL_HARDENING_ASSERT(length <= capacity()); if (rep_.is_short()) { rep_.set_short_length(length); } else { rep_.rep()->length = length; } } inline void CordBuffer::IncreaseLengthBy(size_t n) { ABSL_HARDENING_ASSERT(n <= capacity() && length() + n <= capacity()); if (rep_.is_short()) { rep_.add_short_length(n); } else { rep_.rep()->length += n; } } ABSL_NAMESPACE_END } #endif #include "absl/strings/cord_buffer.h" #include <cstddef> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr size_t CordBuffer::kDefaultLimit; constexpr size_t CordBuffer::kCustomLimit; #endif ABSL_NAMESPACE_END }
#include "absl/strings/cord_buffer.h" #include <algorithm> #include <cstring> #include <limits> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/internal/cord_rep_test_util.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" using testing::Eq; using testing::Ge; using testing::Le; using testing::Ne; namespace absl { ABSL_NAMESPACE_BEGIN class CordBufferTestPeer { public: static cord_internal::CordRep* ConsumeValue(CordBuffer& buffer, absl::string_view& short_value) { return buffer.ConsumeValue(short_value); } }; namespace { using ::absl::cordrep_testing::CordToString; constexpr size_t kInlinedSize = sizeof(CordBuffer) - 1; constexpr size_t kDefaultLimit = CordBuffer::kDefaultLimit; constexpr size_t kCustomLimit = CordBuffer::kCustomLimit; constexpr size_t kMaxFlatSize = cord_internal::kMaxFlatSize; constexpr size_t kMaxFlatLength = cord_internal::kMaxFlatLength; constexpr size_t kFlatOverhead = cord_internal::kFlatOverhead; constexpr size_t k8KiB = 8 << 10; constexpr size_t k16KiB = 16 << 10; constexpr size_t k64KiB = 64 << 10; constexpr size_t k1MB = 1 << 20; class CordBufferTest : public testing::TestWithParam<size_t> {}; INSTANTIATE_TEST_SUITE_P(MediumSize, CordBufferTest, testing::Values(1, kInlinedSize - 1, kInlinedSize, kInlinedSize + 1, kDefaultLimit - 1, kDefaultLimit)); TEST_P(CordBufferTest, MaximumPayload) { EXPECT_THAT(CordBuffer::MaximumPayload(), Eq(kMaxFlatLength)); EXPECT_THAT(CordBuffer::MaximumPayload(512), Eq(512 - kFlatOverhead)); EXPECT_THAT(CordBuffer::MaximumPayload(k64KiB), Eq(k64KiB - kFlatOverhead)); EXPECT_THAT(CordBuffer::MaximumPayload(k1MB), Eq(k64KiB - kFlatOverhead)); } TEST(CordBufferTest, ConstructDefault) { CordBuffer buffer; EXPECT_THAT(buffer.capacity(), Eq(sizeof(CordBuffer) - 1)); EXPECT_THAT(buffer.length(), Eq(0)); EXPECT_THAT(buffer.data(), Ne(nullptr)); EXPECT_THAT(buffer.available().data(), Eq(buffer.data())); EXPECT_THAT(buffer.available().size(), Eq(buffer.capacity())); memset(buffer.data(), 0xCD, buffer.capacity()); } TEST(CordBufferTest, CreateSsoWithDefaultLimit) { CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(3); EXPECT_THAT(buffer.capacity(), Ge(3)); EXPECT_THAT(buffer.capacity(), Le(sizeof(CordBuffer))); EXPECT_THAT(buffer.length(), Eq(0)); memset(buffer.data(), 0xCD, buffer.capacity()); memcpy(buffer.data(), "Abc", 3); buffer.SetLength(3); EXPECT_THAT(buffer.length(), Eq(3)); absl::string_view short_value; EXPECT_THAT(CordBufferTestPeer::ConsumeValue(buffer, short_value), Eq(nullptr)); EXPECT_THAT(absl::string_view(buffer.data(), 3), Eq("Abc")); EXPECT_THAT(short_value, Eq("Abc")); } TEST_P(CordBufferTest, Available) { const size_t requested = GetParam(); CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested); EXPECT_THAT(buffer.available().data(), Eq(buffer.data())); EXPECT_THAT(buffer.available().size(), Eq(buffer.capacity())); buffer.SetLength(2); EXPECT_THAT(buffer.available().data(), Eq(buffer.data() + 2)); EXPECT_THAT(buffer.available().size(), Eq(buffer.capacity() - 2)); } TEST_P(CordBufferTest, IncreaseLengthBy) { const size_t requested = GetParam(); CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested); buffer.IncreaseLengthBy(2); EXPECT_THAT(buffer.length(), Eq(2)); buffer.IncreaseLengthBy(5); EXPECT_THAT(buffer.length(), Eq(7)); } TEST_P(CordBufferTest, AvailableUpTo) { const size_t requested = GetParam(); CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested); size_t expected_up_to = std::min<size_t>(3, buffer.capacity()); EXPECT_THAT(buffer.available_up_to(3).data(), Eq(buffer.data())); EXPECT_THAT(buffer.available_up_to(3).size(), Eq(expected_up_to)); buffer.SetLength(2); expected_up_to = std::min<size_t>(3, buffer.capacity() - 2); EXPECT_THAT(buffer.available_up_to(3).data(), Eq(buffer.data() + 2)); EXPECT_THAT(buffer.available_up_to(3).size(), Eq(expected_up_to)); } size_t MaxCapacityFor(size_t block_size, size_t requested) { requested = (std::min)(requested, cord_internal::kMaxLargeFlatSize); return block_size - kFlatOverhead; } TEST_P(CordBufferTest, CreateWithDefaultLimit) { const size_t requested = GetParam(); CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested); EXPECT_THAT(buffer.capacity(), Ge(requested)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(kMaxFlatSize, requested))); EXPECT_THAT(buffer.length(), Eq(0)); memset(buffer.data(), 0xCD, buffer.capacity()); std::string data(requested - 1, 'x'); memcpy(buffer.data(), data.c_str(), requested); buffer.SetLength(requested); EXPECT_THAT(buffer.length(), Eq(requested)); EXPECT_THAT(absl::string_view(buffer.data()), Eq(data)); } TEST(CordBufferTest, CreateWithDefaultLimitAskingFor2GB) { constexpr size_t k2GiB = 1U << 31; CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(k2GiB); EXPECT_THAT(buffer.capacity(), Le(2 * CordBuffer::kDefaultLimit)); EXPECT_THAT(buffer.length(), Eq(0)); EXPECT_THAT(buffer.data(), Ne(nullptr)); memset(buffer.data(), 0xCD, buffer.capacity()); } TEST_P(CordBufferTest, MoveConstruct) { const size_t requested = GetParam(); CordBuffer from = CordBuffer::CreateWithDefaultLimit(requested); const size_t capacity = from.capacity(); memcpy(from.data(), "Abc", 4); from.SetLength(4); CordBuffer to(std::move(from)); EXPECT_THAT(to.capacity(), Eq(capacity)); EXPECT_THAT(to.length(), Eq(4)); EXPECT_THAT(absl::string_view(to.data()), Eq("Abc")); EXPECT_THAT(from.length(), Eq(0)); } TEST_P(CordBufferTest, MoveAssign) { const size_t requested = GetParam(); CordBuffer from = CordBuffer::CreateWithDefaultLimit(requested); const size_t capacity = from.capacity(); memcpy(from.data(), "Abc", 4); from.SetLength(4); CordBuffer to; to = std::move(from); EXPECT_THAT(to.capacity(), Eq(capacity)); EXPECT_THAT(to.length(), Eq(4)); EXPECT_THAT(absl::string_view(to.data()), Eq("Abc")); EXPECT_THAT(from.length(), Eq(0)); } TEST_P(CordBufferTest, ConsumeValue) { const size_t requested = GetParam(); CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested); memcpy(buffer.data(), "Abc", 4); buffer.SetLength(3); absl::string_view short_value; if (cord_internal::CordRep* rep = CordBufferTestPeer::ConsumeValue(buffer, short_value)) { EXPECT_THAT(CordToString(rep), Eq("Abc")); cord_internal::CordRep::Unref(rep); } else { EXPECT_THAT(short_value, Eq("Abc")); } EXPECT_THAT(buffer.length(), Eq(0)); } TEST_P(CordBufferTest, CreateWithCustomLimitWithinDefaultLimit) { const size_t requested = GetParam(); CordBuffer buffer = CordBuffer::CreateWithCustomLimit(kMaxFlatSize, requested); EXPECT_THAT(buffer.capacity(), Ge(requested)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(kMaxFlatSize, requested))); EXPECT_THAT(buffer.length(), Eq(0)); memset(buffer.data(), 0xCD, buffer.capacity()); std::string data(requested - 1, 'x'); memcpy(buffer.data(), data.c_str(), requested); buffer.SetLength(requested); EXPECT_THAT(buffer.length(), Eq(requested)); EXPECT_THAT(absl::string_view(buffer.data()), Eq(data)); } TEST(CordLargeBufferTest, CreateAtOrBelowDefaultLimit) { CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k64KiB, kDefaultLimit); EXPECT_THAT(buffer.capacity(), Ge(kDefaultLimit)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(kMaxFlatSize, kDefaultLimit))); buffer = CordBuffer::CreateWithCustomLimit(k64KiB, 3178); EXPECT_THAT(buffer.capacity(), Ge(3178)); } TEST(CordLargeBufferTest, CreateWithCustomLimit) { ASSERT_THAT((kMaxFlatSize & (kMaxFlatSize - 1)) == 0, "Must be power of 2"); for (size_t size = kMaxFlatSize; size <= kCustomLimit; size *= 2) { CordBuffer buffer = CordBuffer::CreateWithCustomLimit(size, size); size_t expected = size - kFlatOverhead; ASSERT_THAT(buffer.capacity(), Ge(expected)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(size, expected))); } } TEST(CordLargeBufferTest, CreateWithTooLargeLimit) { CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k64KiB, k1MB); ASSERT_THAT(buffer.capacity(), Ge(k64KiB - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(k64KiB, k1MB))); } TEST(CordLargeBufferTest, CreateWithHugeValueForOverFlowHardening) { for (size_t dist_from_max = 0; dist_from_max <= 32; ++dist_from_max) { size_t capacity = std::numeric_limits<size_t>::max() - dist_from_max; CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(capacity); ASSERT_THAT(buffer.capacity(), Ge(kDefaultLimit)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(kMaxFlatSize, capacity))); for (size_t limit = kMaxFlatSize; limit <= kCustomLimit; limit *= 2) { CordBuffer buffer = CordBuffer::CreateWithCustomLimit(limit, capacity); ASSERT_THAT(buffer.capacity(), Ge(limit - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(limit, capacity))); } } } TEST(CordLargeBufferTest, CreateWithSmallLimit) { CordBuffer buffer = CordBuffer::CreateWithCustomLimit(512, 1024); ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 1024))); buffer = CordBuffer::CreateWithCustomLimit(512, 512); ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 512))); buffer = CordBuffer::CreateWithCustomLimit(512, 511); ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 511))); buffer = CordBuffer::CreateWithCustomLimit(512, 498); ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 498))); } TEST(CordLargeBufferTest, CreateWasteFull) { const size_t requested = (15 << 10); CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k16KiB, requested); ASSERT_THAT(buffer.capacity(), Ge(k8KiB - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(k8KiB, requested))); } TEST(CordLargeBufferTest, CreateSmallSlop) { const size_t requested = k16KiB - 2 * kFlatOverhead; CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k16KiB, requested); ASSERT_THAT(buffer.capacity(), Ge(k16KiB - kFlatOverhead)); EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(k16KiB, requested))); } } ABSL_NAMESPACE_END }
2,558
#ifndef ABSL_STRINGS_STR_CAT_H_ #define ABSL_STRINGS_STR_CAT_H_ #include <algorithm> #include <array> #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include <initializer_list> #include <limits> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/port.h" #include "absl/meta/type_traits.h" #include "absl/strings/has_absl_stringify.h" #include "absl/strings/internal/resize_uninitialized.h" #include "absl/strings/internal/stringify_sink.h" #include "absl/strings/numbers.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { template <size_t max_size> struct AlphaNumBuffer { std::array<char, max_size> data; size_t size; }; } enum PadSpec : uint8_t { kNoPad = 1, kZeroPad2, kZeroPad3, kZeroPad4, kZeroPad5, kZeroPad6, kZeroPad7, kZeroPad8, kZeroPad9, kZeroPad10, kZeroPad11, kZeroPad12, kZeroPad13, kZeroPad14, kZeroPad15, kZeroPad16, kZeroPad17, kZeroPad18, kZeroPad19, kZeroPad20, kSpacePad2 = kZeroPad2 + 64, kSpacePad3, kSpacePad4, kSpacePad5, kSpacePad6, kSpacePad7, kSpacePad8, kSpacePad9, kSpacePad10, kSpacePad11, kSpacePad12, kSpacePad13, kSpacePad14, kSpacePad15, kSpacePad16, kSpacePad17, kSpacePad18, kSpacePad19, kSpacePad20, }; struct Hex { uint64_t value; uint8_t width; char fill; template <typename Int> explicit Hex( Int v, PadSpec spec = absl::kNoPad, typename std::enable_if<sizeof(Int) == 1 && !std::is_pointer<Int>::value>::type* = nullptr) : Hex(spec, static_cast<uint8_t>(v)) {} template <typename Int> explicit Hex( Int v, PadSpec spec = absl::kNoPad, typename std::enable_if<sizeof(Int) == 2 && !std::is_pointer<Int>::value>::type* = nullptr) : Hex(spec, static_cast<uint16_t>(v)) {} template <typename Int> explicit Hex( Int v, PadSpec spec = absl::kNoPad, typename std::enable_if<sizeof(Int) == 4 && !std::is_pointer<Int>::value>::type* = nullptr) : Hex(spec, static_cast<uint32_t>(v)) {} template <typename Int> explicit Hex( Int v, PadSpec spec = absl::kNoPad, typename std::enable_if<sizeof(Int) == 8 && !std::is_pointer<Int>::value>::type* = nullptr) : Hex(spec, static_cast<uint64_t>(v)) {} template <typename Pointee> explicit Hex(absl::Nullable<Pointee*> v, PadSpec spec = absl::kNoPad) : Hex(spec, reinterpret_cast<uintptr_t>(v)) {} template <typename S> friend void AbslStringify(S& sink, Hex hex) { static_assert( numbers_internal::kFastToBufferSize >= 32, "This function only works when output buffer >= 32 bytes long"); char buffer[numbers_internal::kFastToBufferSize]; char* const end = &buffer[numbers_internal::kFastToBufferSize]; auto real_width = absl::numbers_internal::FastHexToBufferZeroPad16(hex.value, end - 16); if (real_width >= hex.width) { sink.Append(absl::string_view(end - real_width, real_width)); } else { std::memset(end - 32, hex.fill, 16); std::memset(end - real_width - 16, hex.fill, 16); sink.Append(absl::string_view(end - hex.width, hex.width)); } } private: Hex(PadSpec spec, uint64_t v) : value(v), width(spec == absl::kNoPad ? 1 : spec >= absl::kSpacePad2 ? spec - absl::kSpacePad2 + 2 : spec - absl::kZeroPad2 + 2), fill(spec >= absl::kSpacePad2 ? ' ' : '0') {} }; struct Dec { uint64_t value; uint8_t width; char fill; bool neg; template <typename Int> explicit Dec(Int v, PadSpec spec = absl::kNoPad, typename std::enable_if<(sizeof(Int) <= 8)>::type* = nullptr) : value(v >= 0 ? static_cast<uint64_t>(v) : uint64_t{0} - static_cast<uint64_t>(v)), width(spec == absl::kNoPad ? 1 : spec >= absl::kSpacePad2 ? spec - absl::kSpacePad2 + 2 : spec - absl::kZeroPad2 + 2), fill(spec >= absl::kSpacePad2 ? ' ' : '0'), neg(v < 0) {} template <typename S> friend void AbslStringify(S& sink, Dec dec) { assert(dec.width <= numbers_internal::kFastToBufferSize); char buffer[numbers_internal::kFastToBufferSize]; char* const end = &buffer[numbers_internal::kFastToBufferSize]; char* const minfill = end - dec.width; char* writer = end; uint64_t val = dec.value; while (val > 9) { *--writer = '0' + (val % 10); val /= 10; } *--writer = '0' + static_cast<char>(val); if (dec.neg) *--writer = '-'; ptrdiff_t fillers = writer - minfill; if (fillers > 0) { bool add_sign_again = false; if (dec.neg && dec.fill == '0') { ++writer; add_sign_again = true; } writer -= fillers; std::fill_n(writer, fillers, dec.fill); if (add_sign_again) *--writer = '-'; } sink.Append(absl::string_view(writer, static_cast<size_t>(end - writer))); } }; class AlphaNum { public: template <typename T> AlphaNum(std::initializer_list<T>) = delete; AlphaNum(int x) : piece_(digits_, static_cast<size_t>( numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0])) {} AlphaNum(unsigned int x) : piece_(digits_, static_cast<size_t>( numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0])) {} AlphaNum(long x) : piece_(digits_, static_cast<size_t>( numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0])) {} AlphaNum(unsigned long x) : piece_(digits_, static_cast<size_t>( numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0])) {} AlphaNum(long long x) : piece_(digits_, static_cast<size_t>( numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0])) {} AlphaNum(unsigned long long x) : piece_(digits_, static_cast<size_t>( numbers_internal::FastIntToBuffer(x, digits_) - &digits_[0])) {} AlphaNum(float f) : piece_(digits_, numbers_internal::SixDigitsToBuffer(f, digits_)) {} AlphaNum(double f) : piece_(digits_, numbers_internal::SixDigitsToBuffer(f, digits_)) {} template <size_t size> AlphaNum( const strings_internal::AlphaNumBuffer<size>& buf ABSL_ATTRIBUTE_LIFETIME_BOUND) : piece_(&buf.data[0], buf.size) {} AlphaNum(absl::Nullable<const char*> c_str ABSL_ATTRIBUTE_LIFETIME_BOUND) : piece_(NullSafeStringView(c_str)) {} AlphaNum(absl::string_view pc ABSL_ATTRIBUTE_LIFETIME_BOUND) : piece_(pc) {} template <typename T, typename = typename std::enable_if< HasAbslStringify<T>::value>::type> AlphaNum( const T& v ABSL_ATTRIBUTE_LIFETIME_BOUND, strings_internal::StringifySink&& sink ABSL_ATTRIBUTE_LIFETIME_BOUND = {}) : piece_(strings_internal::ExtractStringification(sink, v)) {} template <typename Allocator> AlphaNum( const std::basic_string<char, std::char_traits<char>, Allocator>& str ABSL_ATTRIBUTE_LIFETIME_BOUND) : piece_(str) {} AlphaNum(char c) = delete; AlphaNum(const AlphaNum&) = delete; AlphaNum& operator=(const AlphaNum&) = delete; absl::string_view::size_type size() const { return piece_.size(); } absl::Nullable<const char*> data() const { return piece_.data(); } absl::string_view Piece() const { return piece_; } template <typename T, typename = typename std::enable_if< std::is_enum<T>{} && std::is_convertible<T, int>{} && !HasAbslStringify<T>::value>::type> AlphaNum(T e) : AlphaNum(+e) {} template <typename T, typename std::enable_if<std::is_enum<T>{} && !std::is_convertible<T, int>{} && !HasAbslStringify<T>::value, char*>::type = nullptr> AlphaNum(T e) : AlphaNum(+static_cast<typename std::underlying_type<T>::type>(e)) {} template < typename T, typename std::enable_if< std::is_class<T>::value && (std::is_same<T, std::vector<bool>::reference>::value || std::is_same<T, std::vector<bool>::const_reference>::value)>::type* = nullptr> AlphaNum(T e) : AlphaNum(static_cast<bool>(e)) {} private: absl::string_view piece_; char digits_[numbers_internal::kFastToBufferSize]; }; namespace strings_internal { std::string CatPieces(std::initializer_list<absl::string_view> pieces); void AppendPieces(absl::Nonnull<std::string*> dest, std::initializer_list<absl::string_view> pieces); template <typename Integer> std::string IntegerToString(Integer i) { constexpr size_t kMaxDigits10 = 22; std::string result; strings_internal::STLStringResizeUninitialized(&result, kMaxDigits10); char* start = &result[0]; char* end = numbers_internal::FastIntToBuffer(i, start); auto size = static_cast<size_t>(end - start); assert((size < result.size()) && "StrCat(Integer) does not fit into kMaxDigits10"); result.erase(size); return result; } template <typename Float> std::string FloatToString(Float f) { std::string result; strings_internal::STLStringResizeUninitialized( &result, numbers_internal::kSixDigitsToBufferSize); char* start = &result[0]; result.erase(numbers_internal::SixDigitsToBuffer(f, start)); return result; } inline std::string SingleArgStrCat(int x) { return IntegerToString(x); } inline std::string SingleArgStrCat(unsigned int x) { return IntegerToString(x); } inline std::string SingleArgStrCat(long x) { return IntegerToString(x); } inline std::string SingleArgStrCat(unsigned long x) { return IntegerToString(x); } inline std::string SingleArgStrCat(long long x) { return IntegerToString(x); } inline std::string SingleArgStrCat(unsigned long long x) { return IntegerToString(x); } inline std::string SingleArgStrCat(float x) { return FloatToString(x); } inline std::string SingleArgStrCat(double x) { return FloatToString(x); } #ifdef _LIBCPP_VERSION #define ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE true #else #define ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE false #endif template <typename T, typename = std::enable_if_t< ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE && std::is_arithmetic<T>{} && !std::is_same<T, char>{}>> using EnableIfFastCase = T; #undef ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE } ABSL_MUST_USE_RESULT inline std::string StrCat() { return std::string(); } template <typename T> ABSL_MUST_USE_RESULT inline std::string StrCat( strings_internal::EnableIfFastCase<T> a) { return strings_internal::SingleArgStrCat(a); } ABSL_MUST_USE_RESULT inline std::string StrCat(const AlphaNum& a) { return std::string(a.data(), a.size()); } ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b); ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c); ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d); template <typename... AV> ABSL_MUST_USE_RESULT inline std::string StrCat( const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AV&... args) { return strings_internal::CatPieces( {a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(), static_cast<const AlphaNum&>(args).Piece()...}); } inline void StrAppend(absl::Nonnull<std::string*>) {} void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a); void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a, const AlphaNum& b); void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c); void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d); template <typename... AV> inline void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AV&... args) { strings_internal::AppendPieces( dest, {a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(), static_cast<const AlphaNum&>(args).Piece()...}); } inline strings_internal::AlphaNumBuffer< numbers_internal::kSixDigitsToBufferSize> SixDigits(double d) { strings_internal::AlphaNumBuffer<numbers_internal::kSixDigitsToBufferSize> result; result.size = numbers_internal::SixDigitsToBuffer(d, &result.data[0]); return result; } ABSL_NAMESPACE_END } #endif #include "absl/strings/str_cat.h" #include <assert.h> #include <cstddef> #include <cstdint> #include <cstring> #include <initializer_list> #include <limits> #include <string> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/nullability.h" #include "absl/strings/internal/resize_uninitialized.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { inline absl::Nonnull<char*> Append(absl::Nonnull<char*> out, const AlphaNum& x) { char* after = out + x.size(); if (x.size() != 0) { memcpy(out, x.data(), x.size()); } return after; } inline void STLStringAppendUninitializedAmortized(std::string* dest, size_t to_append) { strings_internal::AppendUninitializedTraits<std::string>::Append(dest, to_append); } } std::string StrCat(const AlphaNum& a, const AlphaNum& b) { std::string result; constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()}; const uint64_t result_size = static_cast<uint64_t>(a.size()) + static_cast<uint64_t>(b.size()); ABSL_INTERNAL_CHECK(result_size <= kMaxSize, "size_t overflow"); absl::strings_internal::STLStringResizeUninitialized( &result, static_cast<size_t>(result_size)); char* const begin = &result[0]; char* out = begin; out = Append(out, a); out = Append(out, b); assert(out == begin + result.size()); return result; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c) { std::string result; constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()}; const uint64_t result_size = static_cast<uint64_t>(a.size()) + static_cast<uint64_t>(b.size()) + static_cast<uint64_t>(c.size()); ABSL_INTERNAL_CHECK(result_size <= kMaxSize, "size_t overflow"); strings_internal::STLStringResizeUninitialized( &result, static_cast<size_t>(result_size)); char* const begin = &result[0]; char* out = begin; out = Append(out, a); out = Append(out, b); out = Append(out, c); assert(out == begin + result.size()); return result; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d) { std::string result; constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()}; const uint64_t result_size = static_cast<uint64_t>(a.size()) + static_cast<uint64_t>(b.size()) + static_cast<uint64_t>(c.size()) + static_cast<uint64_t>(d.size()); ABSL_INTERNAL_CHECK(result_size <= kMaxSize, "size_t overflow"); strings_internal::STLStringResizeUninitialized( &result, static_cast<size_t>(result_size)); char* const begin = &result[0]; char* out = begin; out = Append(out, a); out = Append(out, b); out = Append(out, c); out = Append(out, d); assert(out == begin + result.size()); return result; } namespace strings_internal { std::string CatPieces(std::initializer_list<absl::string_view> pieces) { std::string result; constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()}; uint64_t total_size = 0; for (absl::string_view piece : pieces) { total_size += piece.size(); } ABSL_INTERNAL_CHECK(total_size <= kMaxSize, "size_t overflow"); strings_internal::STLStringResizeUninitialized( &result, static_cast<size_t>(total_size)); char* const begin = &result[0]; char* out = begin; for (absl::string_view piece : pieces) { const size_t this_size = piece.size(); if (this_size != 0) { memcpy(out, piece.data(), this_size); out += this_size; } } assert(out == begin + result.size()); return result; } #define ASSERT_NO_OVERLAP(dest, src) \ assert(((src).size() == 0) || \ (uintptr_t((src).data() - (dest).data()) > uintptr_t((dest).size()))) void AppendPieces(absl::Nonnull<std::string*> dest, std::initializer_list<absl::string_view> pieces) { size_t old_size = dest->size(); size_t to_append = 0; for (absl::string_view piece : pieces) { ASSERT_NO_OVERLAP(*dest, piece); to_append += piece.size(); } STLStringAppendUninitializedAmortized(dest, to_append); char* const begin = &(*dest)[0]; char* out = begin + old_size; for (absl::string_view piece : pieces) { const size_t this_size = piece.size(); if (this_size != 0) { memcpy(out, piece.data(), this_size); out += this_size; } } assert(out == begin + dest->size()); } } void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a) { ASSERT_NO_OVERLAP(*dest, a); std::string::size_type old_size = dest->size(); STLStringAppendUninitializedAmortized(dest, a.size()); char* const begin = &(*dest)[0]; char* out = begin + old_size; out = Append(out, a); assert(out == begin + dest->size()); } void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a, const AlphaNum& b) { ASSERT_NO_OVERLAP(*dest, a); ASSERT_NO_OVERLAP(*dest, b); std::string::size_type old_size = dest->size(); STLStringAppendUninitializedAmortized(dest, a.size() + b.size()); char* const begin = &(*dest)[0]; char* out = begin + old_size; out = Append(out, a); out = Append(out, b); assert(out == begin + dest->size()); } void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c) { ASSERT_NO_OVERLAP(*dest, a); ASSERT_NO_OVERLAP(*dest, b); ASSERT_NO_OVERLAP(*dest, c); std::string::size_type old_size = dest->size(); STLStringAppendUninitializedAmortized(dest, a.size() + b.size() + c.size()); char* const begin = &(*dest)[0]; char* out = begin + old_size; out = Append(out, a); out = Append(out, b); out = Append(out, c); assert(out == begin + dest->size()); } void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d) { ASSERT_NO_OVERLAP(*dest, a); ASSERT_NO_OVERLAP(*dest, b); ASSERT_NO_OVERLAP(*dest, c); ASSERT_NO_OVERLAP(*dest, d); std::string::size_type old_size = dest->size(); STLStringAppendUninitializedAmortized( dest, a.size() + b.size() + c.size() + d.size()); char* const begin = &(*dest)[0]; char* out = begin + old_size; out = Append(out, a); out = Append(out, b); out = Append(out, c); out = Append(out, d); assert(out == begin + dest->size()); } ABSL_NAMESPACE_END }
#include "absl/strings/str_cat.h" #include <cstddef> #include <cstdint> #include <cstdlib> #include <limits> #include <string> #include <vector> #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #ifdef __ANDROID__ #define ABSL_EXPECT_DEBUG_DEATH(statement, regex) \ EXPECT_DEBUG_DEATH(statement, ".*") #else #define ABSL_EXPECT_DEBUG_DEATH(statement, regex) \ EXPECT_DEBUG_DEATH(statement, regex) #endif namespace { TEST(StrCat, Ints) { const short s = -1; const uint16_t us = 2; const int i = -3; const unsigned int ui = 4; const long l = -5; const unsigned long ul = 6; const long long ll = -7; const unsigned long long ull = 8; const ptrdiff_t ptrdiff = -9; const size_t size = 10; const intptr_t intptr = -12; const uintptr_t uintptr = 13; std::string answer; answer = absl::StrCat(s, us); EXPECT_EQ(answer, "-12"); answer = absl::StrCat(i, ui); EXPECT_EQ(answer, "-34"); answer = absl::StrCat(l, ul); EXPECT_EQ(answer, "-56"); answer = absl::StrCat(ll, ull); EXPECT_EQ(answer, "-78"); answer = absl::StrCat(ptrdiff, size); EXPECT_EQ(answer, "-910"); answer = absl::StrCat(ptrdiff, intptr); EXPECT_EQ(answer, "-9-12"); answer = absl::StrCat(uintptr, 0); EXPECT_EQ(answer, "130"); } TEST(StrCat, Enums) { enum SmallNumbers { One = 1, Ten = 10 } e = Ten; EXPECT_EQ("10", absl::StrCat(e)); EXPECT_EQ("-5", absl::StrCat(SmallNumbers(-5))); enum class Option { Boxers = 1, Briefs = -1 }; EXPECT_EQ("-1", absl::StrCat(Option::Briefs)); enum class Airplane : uint64_t { Airbus = 1, Boeing = 1000, Canary = 10000000000 }; EXPECT_EQ("10000000000", absl::StrCat(Airplane::Canary)); enum class TwoGig : int32_t { TwoToTheZero = 1, TwoToTheSixteenth = 1 << 16, TwoToTheThirtyFirst = INT32_MIN }; EXPECT_EQ("65536", absl::StrCat(TwoGig::TwoToTheSixteenth)); EXPECT_EQ("-2147483648", absl::StrCat(TwoGig::TwoToTheThirtyFirst)); EXPECT_EQ("-1", absl::StrCat(static_cast<TwoGig>(-1))); enum class FourGig : uint32_t { TwoToTheZero = 1, TwoToTheSixteenth = 1 << 16, TwoToTheThirtyFirst = 1U << 31 }; EXPECT_EQ("65536", absl::StrCat(FourGig::TwoToTheSixteenth)); EXPECT_EQ("2147483648", absl::StrCat(FourGig::TwoToTheThirtyFirst)); EXPECT_EQ("4294967295", absl::StrCat(static_cast<FourGig>(-1))); EXPECT_EQ("10000000000", absl::StrCat(Airplane::Canary)); } TEST(StrCat, Basics) { std::string result; std::string strs[] = {"Hello", "Cruel", "World"}; std::string stdstrs[] = { "std::Hello", "std::Cruel", "std::World" }; absl::string_view pieces[] = {"Hello", "Cruel", "World"}; const char* c_strs[] = { "Hello", "Cruel", "World" }; int32_t i32s[] = {'H', 'C', 'W'}; uint64_t ui64s[] = {12345678910LL, 10987654321LL}; EXPECT_EQ(absl::StrCat(), ""); result = absl::StrCat(false, true, 2, 3); EXPECT_EQ(result, "0123"); result = absl::StrCat(-1); EXPECT_EQ(result, "-1"); result = absl::StrCat(absl::SixDigits(0.5)); EXPECT_EQ(result, "0.5"); result = absl::StrCat(strs[1], pieces[2]); EXPECT_EQ(result, "CruelWorld"); result = absl::StrCat(stdstrs[1], " ", stdstrs[2]); EXPECT_EQ(result, "std::Cruel std::World"); result = absl::StrCat(strs[0], ", ", pieces[2]); EXPECT_EQ(result, "Hello, World"); result = absl::StrCat(strs[0], ", ", strs[1], " ", strs[2], "!"); EXPECT_EQ(result, "Hello, Cruel World!"); result = absl::StrCat(pieces[0], ", ", pieces[1], " ", pieces[2]); EXPECT_EQ(result, "Hello, Cruel World"); result = absl::StrCat(c_strs[0], ", ", c_strs[1], " ", c_strs[2]); EXPECT_EQ(result, "Hello, Cruel World"); result = absl::StrCat("ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!"); EXPECT_EQ(result, "ASCII 72, 67 87!"); result = absl::StrCat(ui64s[0], ", ", ui64s[1], "!"); EXPECT_EQ(result, "12345678910, 10987654321!"); std::string one = "1"; result = absl::StrCat("And a ", one.size(), " and a ", &result[2] - &result[0], " and a ", one, " 2 3 4", "!"); EXPECT_EQ(result, "And a 1 and a 2 and a 1 2 3 4!"); result = absl::StrCat("To output a char by ASCII/numeric value, use +: ", '!' + 0); EXPECT_EQ(result, "To output a char by ASCII/numeric value, use +: 33"); float f = 100000.5; result = absl::StrCat("A hundred K and a half is ", absl::SixDigits(f)); EXPECT_EQ(result, "A hundred K and a half is 100000"); f = 100001.5; result = absl::StrCat("A hundred K and one and a half is ", absl::SixDigits(f)); EXPECT_EQ(result, "A hundred K and one and a half is 100002"); double d = 100000.5; d *= d; result = absl::StrCat("A hundred K and a half squared is ", absl::SixDigits(d)); EXPECT_EQ(result, "A hundred K and a half squared is 1.00001e+10"); result = absl::StrCat(1, 2, 333, 4444, 55555, 666666, 7777777, 88888888, 999999999); EXPECT_EQ(result, "12333444455555666666777777788888888999999999"); } TEST(StrCat, CornerCases) { std::string result; result = absl::StrCat(""); EXPECT_EQ(result, ""); result = absl::StrCat("", ""); EXPECT_EQ(result, ""); result = absl::StrCat("", "", ""); EXPECT_EQ(result, ""); result = absl::StrCat("", "", "", ""); EXPECT_EQ(result, ""); result = absl::StrCat("", "", "", "", ""); EXPECT_EQ(result, ""); } TEST(StrCat, NullConstCharPtr) { const char* null = nullptr; EXPECT_EQ(absl::StrCat("mon", null, "key"), "monkey"); } template <typename T> struct Mallocator { typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; size_type max_size() const { return size_t(std::numeric_limits<size_type>::max()) / sizeof(value_type); } template <typename U> struct rebind { typedef Mallocator<U> other; }; Mallocator() = default; template <class U> Mallocator(const Mallocator<U>&) {} T* allocate(size_t n) { return static_cast<T*>(std::malloc(n * sizeof(T))); } void deallocate(T* p, size_t) { std::free(p); } }; template <typename T, typename U> bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; } template <typename T, typename U> bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; } TEST(StrCat, CustomAllocator) { using mstring = std::basic_string<char, std::char_traits<char>, Mallocator<char>>; const mstring str1("PARACHUTE OFF A BLIMP INTO MOSCONE!!"); const mstring str2("Read this book about coffee tables"); std::string result = absl::StrCat(str1, str2); EXPECT_EQ(result, "PARACHUTE OFF A BLIMP INTO MOSCONE!!" "Read this book about coffee tables"); } TEST(StrCat, MaxArgs) { std::string result; result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a"); EXPECT_EQ(result, "123456789a"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b"); EXPECT_EQ(result, "123456789ab"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c"); EXPECT_EQ(result, "123456789abc"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d"); EXPECT_EQ(result, "123456789abcd"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e"); EXPECT_EQ(result, "123456789abcde"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"); EXPECT_EQ(result, "123456789abcdef"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g"); EXPECT_EQ(result, "123456789abcdefg"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h"); EXPECT_EQ(result, "123456789abcdefgh"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i"); EXPECT_EQ(result, "123456789abcdefghi"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"); EXPECT_EQ(result, "123456789abcdefghij"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); EXPECT_EQ(result, "123456789abcdefghijk"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"); EXPECT_EQ(result, "123456789abcdefghijkl"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"); EXPECT_EQ(result, "123456789abcdefghijklm"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"); EXPECT_EQ(result, "123456789abcdefghijklmn"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"); EXPECT_EQ(result, "123456789abcdefghijklmno"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"); EXPECT_EQ(result, "123456789abcdefghijklmnop"); result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q"); EXPECT_EQ(result, "123456789abcdefghijklmnopq"); result = absl::StrCat( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); EXPECT_EQ(result, "12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); } TEST(StrAppend, Basics) { std::string result = "existing text"; std::string strs[] = {"Hello", "Cruel", "World"}; std::string stdstrs[] = { "std::Hello", "std::Cruel", "std::World" }; absl::string_view pieces[] = {"Hello", "Cruel", "World"}; const char* c_strs[] = { "Hello", "Cruel", "World" }; int32_t i32s[] = {'H', 'C', 'W'}; uint64_t ui64s[] = {12345678910LL, 10987654321LL}; std::string::size_type old_size = result.size(); absl::StrAppend(&result); EXPECT_EQ(result.size(), old_size); old_size = result.size(); absl::StrAppend(&result, strs[0]); EXPECT_EQ(result.substr(old_size), "Hello"); old_size = result.size(); absl::StrAppend(&result, strs[1], pieces[2]); EXPECT_EQ(result.substr(old_size), "CruelWorld"); old_size = result.size(); absl::StrAppend(&result, stdstrs[0], ", ", pieces[2]); EXPECT_EQ(result.substr(old_size), "std::Hello, World"); old_size = result.size(); absl::StrAppend(&result, strs[0], ", ", stdstrs[1], " ", strs[2], "!"); EXPECT_EQ(result.substr(old_size), "Hello, std::Cruel World!"); old_size = result.size(); absl::StrAppend(&result, pieces[0], ", ", pieces[1], " ", pieces[2]); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World"); old_size = result.size(); absl::StrAppend(&result, c_strs[0], ", ", c_strs[1], " ", c_strs[2]); EXPECT_EQ(result.substr(old_size), "Hello, Cruel World"); old_size = result.size(); absl::StrAppend(&result, "ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!"); EXPECT_EQ(result.substr(old_size), "ASCII 72, 67 87!"); old_size = result.size(); absl::StrAppend(&result, ui64s[0], ", ", ui64s[1], "!"); EXPECT_EQ(result.substr(old_size), "12345678910, 10987654321!"); std::string one = "1"; old_size = result.size(); absl::StrAppend(&result, "And a ", one.size(), " and a ", &result[2] - &result[0], " and a ", one, " 2 3 4", "!"); EXPECT_EQ(result.substr(old_size), "And a 1 and a 2 and a 1 2 3 4!"); old_size = result.size(); absl::StrAppend(&result, "To output a char by ASCII/numeric value, use +: ", '!' + 0); EXPECT_EQ(result.substr(old_size), "To output a char by ASCII/numeric value, use +: 33"); old_size = result.size(); absl::StrAppend(&result, 1, 22, 333, 4444, 55555, 666666, 7777777, 88888888, 9); EXPECT_EQ(result.substr(old_size), "1223334444555556666667777777888888889"); old_size = result.size(); absl::StrAppend( &result, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "No limit thanks to C++11's variadic templates"); EXPECT_EQ(result.substr(old_size), "12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" "No limit thanks to C++11's variadic templates"); } TEST(StrCat, VectorBoolReferenceTypes) { std::vector<bool> v; v.push_back(true); v.push_back(false); std::vector<bool> const& cv = v; std::string result = absl::StrCat(v[0], v[1], cv[0], cv[1]); EXPECT_EQ(result, "1010"); } TEST(StrCat, AvoidsMemcpyWithNullptr) { EXPECT_EQ(absl::StrCat(42, absl::string_view{}), "42"); EXPECT_EQ(absl::StrCat(1, 2, 3, 4, 5, absl::string_view{}), "12345"); std::string result; absl::StrAppend(&result, 1, 2, 3, 4, 5, absl::string_view{}); EXPECT_EQ(result, "12345"); } #if GTEST_HAS_DEATH_TEST TEST(StrAppend, Death) { std::string s = "self"; ABSL_EXPECT_DEBUG_DEATH(absl::StrAppend(&s, s.c_str() + 1), "ssertion.*failed"); ABSL_EXPECT_DEBUG_DEATH(absl::StrAppend(&s, s), "ssertion.*failed"); } #endif TEST(StrAppend, CornerCases) { std::string result; absl::StrAppend(&result, ""); EXPECT_EQ(result, ""); absl::StrAppend(&result, "", ""); EXPECT_EQ(result, ""); absl::StrAppend(&result, "", "", ""); EXPECT_EQ(result, ""); absl::StrAppend(&result, "", "", "", ""); EXPECT_EQ(result, ""); absl::StrAppend(&result, "", "", "", "", ""); EXPECT_EQ(result, ""); } TEST(StrAppend, CornerCasesNonEmptyAppend) { for (std::string result : {"hello", "a string too long to fit in the SSO"}) { const std::string expected = result; absl::StrAppend(&result, ""); EXPECT_EQ(result, expected); absl::StrAppend(&result, "", ""); EXPECT_EQ(result, expected); absl::StrAppend(&result, "", "", ""); EXPECT_EQ(result, expected); absl::StrAppend(&result, "", "", "", ""); EXPECT_EQ(result, expected); absl::StrAppend(&result, "", "", "", "", ""); EXPECT_EQ(result, expected); } } template <typename IntType> void CheckHex(IntType v, const char* nopad_format, const char* zeropad_format, const char* spacepad_format) { char expected[256]; std::string actual = absl::StrCat(absl::Hex(v, absl::kNoPad)); snprintf(expected, sizeof(expected), nopad_format, v); EXPECT_EQ(expected, actual) << " decimal value " << v; for (int spec = absl::kZeroPad2; spec <= absl::kZeroPad20; ++spec) { std::string actual = absl::StrCat(absl::Hex(v, static_cast<absl::PadSpec>(spec))); snprintf(expected, sizeof(expected), zeropad_format, spec - absl::kZeroPad2 + 2, v); EXPECT_EQ(expected, actual) << " decimal value " << v; } for (int spec = absl::kSpacePad2; spec <= absl::kSpacePad20; ++spec) { std::string actual = absl::StrCat(absl::Hex(v, static_cast<absl::PadSpec>(spec))); snprintf(expected, sizeof(expected), spacepad_format, spec - absl::kSpacePad2 + 2, v); EXPECT_EQ(expected, actual) << " decimal value " << v; } } template <typename IntType> void CheckDec(IntType v, const char* nopad_format, const char* zeropad_format, const char* spacepad_format) { char expected[256]; std::string actual = absl::StrCat(absl::Dec(v, absl::kNoPad)); snprintf(expected, sizeof(expected), nopad_format, v); EXPECT_EQ(expected, actual) << " decimal value " << v; for (int spec = absl::kZeroPad2; spec <= absl::kZeroPad20; ++spec) { std::string actual = absl::StrCat(absl::Dec(v, static_cast<absl::PadSpec>(spec))); snprintf(expected, sizeof(expected), zeropad_format, spec - absl::kZeroPad2 + 2, v); EXPECT_EQ(expected, actual) << " decimal value " << v << " format '" << zeropad_format << "' digits " << (spec - absl::kZeroPad2 + 2); } for (int spec = absl::kSpacePad2; spec <= absl::kSpacePad20; ++spec) { std::string actual = absl::StrCat(absl::Dec(v, static_cast<absl::PadSpec>(spec))); snprintf(expected, sizeof(expected), spacepad_format, spec - absl::kSpacePad2 + 2, v); EXPECT_EQ(expected, actual) << " decimal value " << v << " format '" << spacepad_format << "' digits " << (spec - absl::kSpacePad2 + 2); } } void CheckHexDec64(uint64_t v) { unsigned long long ullv = v; CheckHex(ullv, "%llx", "%0*llx", "%*llx"); CheckDec(ullv, "%llu", "%0*llu", "%*llu"); long long llv = static_cast<long long>(ullv); CheckDec(llv, "%lld", "%0*lld", "%*lld"); if (sizeof(v) == sizeof(&v)) { auto uintptr = static_cast<uintptr_t>(v); void* ptr = reinterpret_cast<void*>(uintptr); CheckHex(ptr, "%llx", "%0*llx", "%*llx"); } } void CheckHexDec32(uint32_t uv) { CheckHex(uv, "%x", "%0*x", "%*x"); CheckDec(uv, "%u", "%0*u", "%*u"); int32_t v = static_cast<int32_t>(uv); CheckDec(v, "%d", "%0*d", "%*d"); if (sizeof(v) == sizeof(&v)) { auto uintptr = static_cast<uintptr_t>(v); void* ptr = reinterpret_cast<void*>(uintptr); CheckHex(ptr, "%x", "%0*x", "%*x"); } } void CheckAll(uint64_t v) { CheckHexDec64(v); CheckHexDec32(static_cast<uint32_t>(v)); } void TestFastPrints() { for (int i = 0; i < 10000; i++) { CheckAll(i); } CheckAll(std::numeric_limits<uint64_t>::max()); CheckAll(std::numeric_limits<uint64_t>::max() - 1); CheckAll(std::numeric_limits<int64_t>::min()); CheckAll(std::numeric_limits<int64_t>::min() + 1); CheckAll(std::numeric_limits<uint32_t>::max()); CheckAll(std::numeric_limits<uint32_t>::max() - 1); CheckAll(std::numeric_limits<int32_t>::min()); CheckAll(std::numeric_limits<int32_t>::min() + 1); CheckAll(999999999); CheckAll(1000000000); CheckAll(9999999999); CheckAll(10000000000); CheckAll(999999999999999999); CheckAll(9999999999999999999u); CheckAll(1000000000000000000); CheckAll(10000000000000000000u); CheckAll(999999999876543210); CheckAll(9999999999876543210u); CheckAll(0x123456789abcdef0); CheckAll(0x12345678); int8_t minus_one_8bit = -1; EXPECT_EQ("ff", absl::StrCat(absl::Hex(minus_one_8bit))); int16_t minus_one_16bit = -1; EXPECT_EQ("ffff", absl::StrCat(absl::Hex(minus_one_16bit))); } TEST(Numbers, TestFunctionsMovedOverFromNumbersMain) { TestFastPrints(); } struct PointStringify { template <typename FormatSink> friend void AbslStringify(FormatSink& sink, const PointStringify& p) { sink.Append("("); sink.Append(absl::StrCat(p.x)); sink.Append(", "); sink.Append(absl::StrCat(p.y)); sink.Append(")"); } double x = 10.0; double y = 20.0; }; TEST(StrCat, AbslStringifyExample) { PointStringify p; EXPECT_EQ(absl::StrCat(p), "(10, 20)"); EXPECT_EQ(absl::StrCat("a ", p, " z"), "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(StrCat, AbslStringifyExampleUsingFormat) { PointStringifyUsingFormat p; EXPECT_EQ(absl::StrCat(p), "(10, 20)"); EXPECT_EQ(absl::StrCat("a ", p, " z"), "a (10, 20) z"); } enum class EnumWithStringify { Many = 0, Choices = 1 }; template <typename Sink> void AbslStringify(Sink& sink, EnumWithStringify e) { absl::Format(&sink, "%s", e == EnumWithStringify::Many ? "Many" : "Choices"); } TEST(StrCat, AbslStringifyWithEnum) { const auto e = EnumWithStringify::Choices; EXPECT_EQ(absl::StrCat(e), "Choices"); } template <typename Integer> void CheckSingleArgumentIntegerLimits() { Integer max = std::numeric_limits<Integer>::max(); Integer min = std::numeric_limits<Integer>::min(); EXPECT_EQ(absl::StrCat(max), std::to_string(max)); EXPECT_EQ(absl::StrCat(min), std::to_string(min)); } TEST(StrCat, SingleArgumentLimits) { CheckSingleArgumentIntegerLimits<int32_t>(); CheckSingleArgumentIntegerLimits<uint32_t>(); CheckSingleArgumentIntegerLimits<int64_t>(); CheckSingleArgumentIntegerLimits<uint64_t>(); } }
2,559
#ifndef ABSL_STRINGS_STR_SPLIT_H_ #define ABSL_STRINGS_STR_SPLIT_H_ #include <algorithm> #include <cstddef> #include <map> #include <set> #include <string> #include <utility> #include <vector> #include "absl/base/internal/raw_logging.h" #include "absl/base/macros.h" #include "absl/strings/internal/str_split_internal.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" namespace absl { ABSL_NAMESPACE_BEGIN class ByString { public: explicit ByString(absl::string_view sp); absl::string_view Find(absl::string_view text, size_t pos) const; private: const std::string delimiter_; }; class ByAsciiWhitespace { public: absl::string_view Find(absl::string_view text, size_t pos) const; }; class ByChar { public: explicit ByChar(char c) : c_(c) {} absl::string_view Find(absl::string_view text, size_t pos) const; private: char c_; }; class ByAnyChar { public: explicit ByAnyChar(absl::string_view sp); absl::string_view Find(absl::string_view text, size_t pos) const; private: const std::string delimiters_; }; class ByLength { public: explicit ByLength(ptrdiff_t length); absl::string_view Find(absl::string_view text, size_t pos) const; private: const ptrdiff_t length_; }; namespace strings_internal { template <typename Delimiter> struct SelectDelimiter { using type = Delimiter; }; template <> struct SelectDelimiter<char> { using type = ByChar; }; template <> struct SelectDelimiter<char*> { using type = ByString; }; template <> struct SelectDelimiter<const char*> { using type = ByString; }; template <> struct SelectDelimiter<absl::string_view> { using type = ByString; }; template <> struct SelectDelimiter<std::string> { using type = ByString; }; template <typename Delimiter> class MaxSplitsImpl { public: MaxSplitsImpl(Delimiter delimiter, int limit) : delimiter_(delimiter), limit_(limit), count_(0) {} absl::string_view Find(absl::string_view text, size_t pos) { if (count_++ == limit_) { return absl::string_view(text.data() + text.size(), 0); } return delimiter_.Find(text, pos); } private: Delimiter delimiter_; const int limit_; int count_; }; } template <typename Delimiter> inline strings_internal::MaxSplitsImpl< typename strings_internal::SelectDelimiter<Delimiter>::type> MaxSplits(Delimiter delimiter, int limit) { typedef typename strings_internal::SelectDelimiter<Delimiter>::type DelimiterType; return strings_internal::MaxSplitsImpl<DelimiterType>( DelimiterType(delimiter), limit); } struct AllowEmpty { bool operator()(absl::string_view) const { return true; } }; struct SkipEmpty { bool operator()(absl::string_view sp) const { return !sp.empty(); } }; struct SkipWhitespace { bool operator()(absl::string_view sp) const { sp = absl::StripAsciiWhitespace(sp); return !sp.empty(); } }; template <typename T> using EnableSplitIfString = typename std::enable_if<std::is_same<T, std::string>::value || std::is_same<T, const std::string>::value, int>::type; template <typename Delimiter> strings_internal::Splitter< typename strings_internal::SelectDelimiter<Delimiter>::type, AllowEmpty, absl::string_view> StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d) { using DelimiterType = typename strings_internal::SelectDelimiter<Delimiter>::type; return strings_internal::Splitter<DelimiterType, AllowEmpty, absl::string_view>( text.value(), DelimiterType(d), AllowEmpty()); } template <typename Delimiter, typename StringType, EnableSplitIfString<StringType> = 0> strings_internal::Splitter< typename strings_internal::SelectDelimiter<Delimiter>::type, AllowEmpty, std::string> StrSplit(StringType&& text, Delimiter d) { using DelimiterType = typename strings_internal::SelectDelimiter<Delimiter>::type; return strings_internal::Splitter<DelimiterType, AllowEmpty, std::string>( std::move(text), DelimiterType(d), AllowEmpty()); } template <typename Delimiter, typename Predicate> strings_internal::Splitter< typename strings_internal::SelectDelimiter<Delimiter>::type, Predicate, absl::string_view> StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d, Predicate p) { using DelimiterType = typename strings_internal::SelectDelimiter<Delimiter>::type; return strings_internal::Splitter<DelimiterType, Predicate, absl::string_view>( text.value(), DelimiterType(std::move(d)), std::move(p)); } template <typename Delimiter, typename Predicate, typename StringType, EnableSplitIfString<StringType> = 0> strings_internal::Splitter< typename strings_internal::SelectDelimiter<Delimiter>::type, Predicate, std::string> StrSplit(StringType&& text, Delimiter d, Predicate p) { using DelimiterType = typename strings_internal::SelectDelimiter<Delimiter>::type; return strings_internal::Splitter<DelimiterType, Predicate, std::string>( std::move(text), DelimiterType(d), std::move(p)); } ABSL_NAMESPACE_END } #endif #include "absl/strings/str_split.h" #include <algorithm> #include <cstddef> #include <cstdlib> #include <cstring> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { template <typename FindPolicy> absl::string_view GenericFind(absl::string_view text, absl::string_view delimiter, size_t pos, FindPolicy find_policy) { if (delimiter.empty() && text.length() > 0) { return absl::string_view(text.data() + pos + 1, 0); } size_t found_pos = absl::string_view::npos; absl::string_view found(text.data() + text.size(), 0); found_pos = find_policy.Find(text, delimiter, pos); if (found_pos != absl::string_view::npos) { found = absl::string_view(text.data() + found_pos, find_policy.Length(delimiter)); } return found; } struct LiteralPolicy { static size_t Find(absl::string_view text, absl::string_view delimiter, size_t pos) { return text.find(delimiter, pos); } static size_t Length(absl::string_view delimiter) { return delimiter.length(); } }; struct AnyOfPolicy { static size_t Find(absl::string_view text, absl::string_view delimiter, size_t pos) { return text.find_first_of(delimiter, pos); } static size_t Length(absl::string_view ) { return 1; } }; } ByString::ByString(absl::string_view sp) : delimiter_(sp) {} absl::string_view ByString::Find(absl::string_view text, size_t pos) const { if (delimiter_.length() == 1) { size_t found_pos = text.find(delimiter_[0], pos); if (found_pos == absl::string_view::npos) return absl::string_view(text.data() + text.size(), 0); return text.substr(found_pos, 1); } return GenericFind(text, delimiter_, pos, LiteralPolicy()); } absl::string_view ByAsciiWhitespace::Find(absl::string_view text, size_t pos) const { return GenericFind(text, " \t\v\f\r\n", pos, AnyOfPolicy()); } absl::string_view ByChar::Find(absl::string_view text, size_t pos) const { size_t found_pos = text.find(c_, pos); if (found_pos == absl::string_view::npos) return absl::string_view(text.data() + text.size(), 0); return text.substr(found_pos, 1); } ByAnyChar::ByAnyChar(absl::string_view sp) : delimiters_(sp) {} absl::string_view ByAnyChar::Find(absl::string_view text, size_t pos) const { return GenericFind(text, delimiters_, pos, AnyOfPolicy()); } ByLength::ByLength(ptrdiff_t length) : length_(length) { ABSL_RAW_CHECK(length > 0, ""); } absl::string_view ByLength::Find(absl::string_view text, size_t pos) const { pos = std::min(pos, text.size()); absl::string_view substr = text.substr(pos); if (substr.length() <= static_cast<size_t>(length_)) return absl::string_view(text.data() + text.size(), 0); return absl::string_view(substr.data() + length_, 0); } ABSL_NAMESPACE_END }
#include "absl/strings/str_split.h" #include <cstddef> #include <cstdint> #include <deque> #include <initializer_list> #include <list> #include <map> #include <memory> #include <set> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/container/btree_map.h" #include "absl/container/btree_set.h" #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_map.h" #include "absl/strings/string_view.h" namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; TEST(Split, TraitsTest) { static_assert(!absl::strings_internal::SplitterIsConvertibleTo<int>::value, ""); static_assert( !absl::strings_internal::SplitterIsConvertibleTo<std::string>::value, ""); static_assert(absl::strings_internal::SplitterIsConvertibleTo< std::vector<std::string>>::value, ""); static_assert( !absl::strings_internal::SplitterIsConvertibleTo<std::vector<int>>::value, ""); static_assert(absl::strings_internal::SplitterIsConvertibleTo< std::vector<absl::string_view>>::value, ""); static_assert(absl::strings_internal::SplitterIsConvertibleTo< std::map<std::string, std::string>>::value, ""); static_assert(absl::strings_internal::SplitterIsConvertibleTo< std::map<absl::string_view, absl::string_view>>::value, ""); static_assert(!absl::strings_internal::SplitterIsConvertibleTo< std::map<int, std::string>>::value, ""); static_assert(!absl::strings_internal::SplitterIsConvertibleTo< std::map<std::string, int>>::value, ""); } TEST(Split, APIExamples) { { std::vector<std::string> v = absl::StrSplit("a,b,c", ","); EXPECT_THAT(v, ElementsAre("a", "b", "c")); using absl::ByString; v = absl::StrSplit("a,b,c", ByString(",")); EXPECT_THAT(v, ElementsAre("a", "b", "c")); EXPECT_THAT(absl::StrSplit("a,b,c", ByString(",")), ElementsAre("a", "b", "c")); } { std::vector<std::string> v = absl::StrSplit("a,b,c", ','); EXPECT_THAT(v, ElementsAre("a", "b", "c")); using absl::ByChar; v = absl::StrSplit("a,b,c", ByChar(',')); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { const std::vector<std::string> v = absl::StrSplit("a=>b=>c", "=>"); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { std::vector<absl::string_view> v = absl::StrSplit("a,b,c", ','); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { std::vector<std::string> v = absl::StrSplit(",a,b,c,", ','); EXPECT_THAT(v, ElementsAre("", "a", "b", "c", "")); } { std::vector<std::string> v = absl::StrSplit("abc", ','); EXPECT_THAT(v, ElementsAre("abc")); } { std::vector<std::string> v = absl::StrSplit("abc", ""); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { std::string embedded_nulls("a\0b\0c", 5); std::string null_delim("\0", 1); std::vector<std::string> v = absl::StrSplit(embedded_nulls, null_delim); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { std::pair<std::string, std::string> p = absl::StrSplit("a,b,c", ','); EXPECT_EQ("a", p.first); EXPECT_EQ("b", p.second); } { std::set<std::string> v = absl::StrSplit("a,b,c,a,b,c,a,b,c", ','); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { char a[] = ","; char* d = a + 0; std::vector<std::string> v = absl::StrSplit("a,b,c", d); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { using absl::ByAnyChar; std::vector<std::string> v = absl::StrSplit("a,b;c", ByAnyChar(",;")); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { using absl::SkipWhitespace; std::vector<std::string> v = absl::StrSplit(" a , ,,b,", ',', SkipWhitespace()); EXPECT_THAT(v, ElementsAre(" a ", "b")); } { using absl::ByLength; std::vector<std::string> v = absl::StrSplit("abcdefg", ByLength(3)); EXPECT_THAT(v, ElementsAre("abc", "def", "g")); } { std::vector<std::string> v1 = absl::StrSplit("a,b,c", ','); EXPECT_THAT(v1, ElementsAre("a", "b", "c")); std::vector<std::string> v2(absl::StrSplit("a,b,c", ',')); EXPECT_THAT(v2, ElementsAre("a", "b", "c")); auto v3 = std::vector<std::string>(absl::StrSplit("a,b,c", ',')); EXPECT_THAT(v3, ElementsAre("a", "b", "c")); v3 = absl::StrSplit("a,b,c", ','); EXPECT_THAT(v3, ElementsAre("a", "b", "c")); } { std::map<std::string, std::string> m = absl::StrSplit("a,1,b,2,a,3", ','); EXPECT_EQ(2, m.size()); EXPECT_EQ("3", m["a"]); EXPECT_EQ("2", m["b"]); } { std::multimap<std::string, std::string> m = absl::StrSplit("a,1,b,2,a,3", ','); EXPECT_EQ(3, m.size()); auto it = m.find("a"); EXPECT_EQ("1", it->second); ++it; EXPECT_EQ("3", it->second); it = m.find("b"); EXPECT_EQ("2", it->second); } { std::string s = "x,x,x,x,x,x,x"; for (absl::string_view sp : absl::StrSplit(s, ',')) { EXPECT_EQ("x", sp); } } { using absl::SkipWhitespace; std::string s = " ,x,,x,,x,x,x,,"; for (absl::string_view sp : absl::StrSplit(s, ',', SkipWhitespace())) { EXPECT_EQ("x", sp); } } { std::map<std::string, std::string> m; for (absl::string_view sp : absl::StrSplit("a=b=c,d=e,f=,g", ',')) { m.insert(absl::StrSplit(sp, absl::MaxSplits('=', 1))); } EXPECT_EQ("b=c", m.find("a")->second); EXPECT_EQ("e", m.find("d")->second); EXPECT_EQ("", m.find("f")->second); EXPECT_EQ("", m.find("g")->second); } } TEST(SplitIterator, Basics) { auto splitter = absl::StrSplit("a,b", ','); auto it = splitter.begin(); auto end = splitter.end(); EXPECT_NE(it, end); EXPECT_EQ("a", *it); ++it; EXPECT_NE(it, end); EXPECT_EQ("b", std::string(it->data(), it->size())); it++; EXPECT_EQ(it, end); } class Skip { public: explicit Skip(const std::string& s) : s_(s) {} bool operator()(absl::string_view sp) { return sp != s_; } private: std::string s_; }; TEST(SplitIterator, Predicate) { auto splitter = absl::StrSplit("a,b,c", ',', Skip("b")); auto it = splitter.begin(); auto end = splitter.end(); EXPECT_NE(it, end); EXPECT_EQ("a", *it); ++it; EXPECT_NE(it, end); EXPECT_EQ("c", std::string(it->data(), it->size())); it++; EXPECT_EQ(it, end); } TEST(SplitIterator, EdgeCases) { struct { std::string in; std::vector<std::string> expect; } specs[] = { {"", {""}}, {"foo", {"foo"}}, {",", {"", ""}}, {",foo", {"", "foo"}}, {"foo,", {"foo", ""}}, {",foo,", {"", "foo", ""}}, {"foo,bar", {"foo", "bar"}}, }; for (const auto& spec : specs) { SCOPED_TRACE(spec.in); auto splitter = absl::StrSplit(spec.in, ','); auto it = splitter.begin(); auto end = splitter.end(); for (const auto& expected : spec.expect) { EXPECT_NE(it, end); EXPECT_EQ(expected, *it++); } EXPECT_EQ(it, end); } } TEST(Splitter, Const) { const auto splitter = absl::StrSplit("a,b,c", ','); EXPECT_THAT(splitter, ElementsAre("a", "b", "c")); } TEST(Split, EmptyAndNull) { EXPECT_THAT(absl::StrSplit(absl::string_view(""), '-'), ElementsAre("")); EXPECT_THAT(absl::StrSplit(absl::string_view(), '-'), ElementsAre()); } TEST(SplitIterator, EqualityAsEndCondition) { auto splitter = absl::StrSplit("a,b,c", ','); auto it = splitter.begin(); auto it2 = it; ++it2; ++it2; EXPECT_EQ("c", *it2); std::vector<absl::string_view> v; for (; it != it2; ++it) { v.push_back(*it); } EXPECT_THAT(v, ElementsAre("a", "b")); } TEST(Splitter, RangeIterators) { auto splitter = absl::StrSplit("a,b,c", ','); std::vector<absl::string_view> output; for (absl::string_view p : splitter) { output.push_back(p); } EXPECT_THAT(output, ElementsAre("a", "b", "c")); } template <typename ContainerType, typename Splitter> void TestConversionOperator(const Splitter& splitter) { ContainerType output = splitter; EXPECT_THAT(output, UnorderedElementsAre("a", "b", "c", "d")); } template <typename MapType, typename Splitter> void TestMapConversionOperator(const Splitter& splitter) { MapType m = splitter; EXPECT_THAT(m, UnorderedElementsAre(Pair("a", "b"), Pair("c", "d"))); } template <typename FirstType, typename SecondType, typename Splitter> void TestPairConversionOperator(const Splitter& splitter) { std::pair<FirstType, SecondType> p = splitter; EXPECT_EQ(p, (std::pair<FirstType, SecondType>("a", "b"))); } TEST(Splitter, ConversionOperator) { auto splitter = absl::StrSplit("a,b,c,d", ','); TestConversionOperator<std::vector<absl::string_view>>(splitter); TestConversionOperator<std::vector<std::string>>(splitter); TestConversionOperator<std::list<absl::string_view>>(splitter); TestConversionOperator<std::list<std::string>>(splitter); TestConversionOperator<std::deque<absl::string_view>>(splitter); TestConversionOperator<std::deque<std::string>>(splitter); TestConversionOperator<std::set<absl::string_view>>(splitter); TestConversionOperator<std::set<std::string>>(splitter); TestConversionOperator<std::multiset<absl::string_view>>(splitter); TestConversionOperator<std::multiset<std::string>>(splitter); TestConversionOperator<absl::btree_set<absl::string_view>>(splitter); TestConversionOperator<absl::btree_set<std::string>>(splitter); TestConversionOperator<absl::btree_multiset<absl::string_view>>(splitter); TestConversionOperator<absl::btree_multiset<std::string>>(splitter); TestConversionOperator<std::unordered_set<std::string>>(splitter); TestMapConversionOperator<std::map<absl::string_view, absl::string_view>>( splitter); TestMapConversionOperator<std::map<absl::string_view, std::string>>(splitter); TestMapConversionOperator<std::map<std::string, absl::string_view>>(splitter); TestMapConversionOperator<std::map<std::string, std::string>>(splitter); TestMapConversionOperator< std::multimap<absl::string_view, absl::string_view>>(splitter); TestMapConversionOperator<std::multimap<absl::string_view, std::string>>( splitter); TestMapConversionOperator<std::multimap<std::string, absl::string_view>>( splitter); TestMapConversionOperator<std::multimap<std::string, std::string>>(splitter); TestMapConversionOperator< absl::btree_map<absl::string_view, absl::string_view>>(splitter); TestMapConversionOperator<absl::btree_map<absl::string_view, std::string>>( splitter); TestMapConversionOperator<absl::btree_map<std::string, absl::string_view>>( splitter); TestMapConversionOperator<absl::btree_map<std::string, std::string>>( splitter); TestMapConversionOperator< absl::btree_multimap<absl::string_view, absl::string_view>>(splitter); TestMapConversionOperator< absl::btree_multimap<absl::string_view, std::string>>(splitter); TestMapConversionOperator< absl::btree_multimap<std::string, absl::string_view>>(splitter); TestMapConversionOperator<absl::btree_multimap<std::string, std::string>>( splitter); TestMapConversionOperator<std::unordered_map<std::string, std::string>>( splitter); TestMapConversionOperator< absl::node_hash_map<absl::string_view, absl::string_view>>(splitter); TestMapConversionOperator< absl::node_hash_map<absl::string_view, std::string>>(splitter); TestMapConversionOperator< absl::node_hash_map<std::string, absl::string_view>>(splitter); TestMapConversionOperator< absl::flat_hash_map<absl::string_view, absl::string_view>>(splitter); TestMapConversionOperator< absl::flat_hash_map<absl::string_view, std::string>>(splitter); TestMapConversionOperator< absl::flat_hash_map<std::string, absl::string_view>>(splitter); TestPairConversionOperator<absl::string_view, absl::string_view>(splitter); TestPairConversionOperator<absl::string_view, std::string>(splitter); TestPairConversionOperator<std::string, absl::string_view>(splitter); TestPairConversionOperator<std::string, std::string>(splitter); } TEST(Splitter, ToPair) { { std::pair<std::string, std::string> p = absl::StrSplit("", ','); EXPECT_EQ("", p.first); EXPECT_EQ("", p.second); } { std::pair<std::string, std::string> p = absl::StrSplit("a", ','); EXPECT_EQ("a", p.first); EXPECT_EQ("", p.second); } { std::pair<std::string, std::string> p = absl::StrSplit(",b", ','); EXPECT_EQ("", p.first); EXPECT_EQ("b", p.second); } { std::pair<std::string, std::string> p = absl::StrSplit("a,b", ','); EXPECT_EQ("a", p.first); EXPECT_EQ("b", p.second); } { std::pair<std::string, std::string> p = absl::StrSplit("a,b,c", ','); EXPECT_EQ("a", p.first); EXPECT_EQ("b", p.second); } } TEST(Splitter, Predicates) { static const char kTestChars[] = ",a, ,b,"; using absl::AllowEmpty; using absl::SkipEmpty; using absl::SkipWhitespace; { auto splitter = absl::StrSplit(kTestChars, ','); std::vector<std::string> v = splitter; EXPECT_THAT(v, ElementsAre("", "a", " ", "b", "")); } { auto splitter = absl::StrSplit(kTestChars, ',', AllowEmpty()); std::vector<std::string> v_allowempty = splitter; EXPECT_THAT(v_allowempty, ElementsAre("", "a", " ", "b", "")); auto splitter_nopredicate = absl::StrSplit(kTestChars, ','); std::vector<std::string> v_nopredicate = splitter_nopredicate; EXPECT_EQ(v_allowempty, v_nopredicate); } { auto splitter = absl::StrSplit(kTestChars, ',', SkipEmpty()); std::vector<std::string> v = splitter; EXPECT_THAT(v, ElementsAre("a", " ", "b")); } { auto splitter = absl::StrSplit(kTestChars, ',', SkipWhitespace()); std::vector<std::string> v = splitter; EXPECT_THAT(v, ElementsAre("a", "b")); } } TEST(Split, Basics) { { absl::StrSplit("a,b,c", ','); } { std::vector<absl::string_view> v = absl::StrSplit("a,b,c", ','); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { std::vector<std::string> v = absl::StrSplit("a,b,c", ','); EXPECT_THAT(v, ElementsAre("a", "b", "c")); } { std::vector<std::string> v; v = absl::StrSplit("a,b,c", ','); EXPECT_THAT(v, ElementsAre("a", "b", "c")); std::map<std::string, std::string> m; m = absl::StrSplit("a,b,c", ','); EXPECT_EQ(2, m.size()); std::unordered_map<std::string, std::string> hm; hm = absl::StrSplit("a,b,c", ','); EXPECT_EQ(2, hm.size()); } } absl::string_view ReturnStringView() { return "Hello World"; } const char* ReturnConstCharP() { return "Hello World"; } char* ReturnCharP() { return const_cast<char*>("Hello World"); } TEST(Split, AcceptsCertainTemporaries) { std::vector<std::string> v; v = absl::StrSplit(ReturnStringView(), ' '); EXPECT_THAT(v, ElementsAre("Hello", "World")); v = absl::StrSplit(ReturnConstCharP(), ' '); EXPECT_THAT(v, ElementsAre("Hello", "World")); v = absl::StrSplit(ReturnCharP(), ' '); EXPECT_THAT(v, ElementsAre("Hello", "World")); } TEST(Split, Temporary) { const char input[] = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u"; EXPECT_LT(sizeof(std::string), ABSL_ARRAYSIZE(input)) << "Input should be larger than fits on the stack."; auto splitter = absl::StrSplit(std::string(input), ','); std::string expected = "a"; for (absl::string_view letter : splitter) { EXPECT_EQ(expected, letter); ++expected[0]; } EXPECT_EQ("v", expected); auto std_splitter = absl::StrSplit(std::string(input), ','); expected = "a"; for (absl::string_view letter : std_splitter) { EXPECT_EQ(expected, letter); ++expected[0]; } EXPECT_EQ("v", expected); } template <typename T> static std::unique_ptr<T> CopyToHeap(const T& value) { return std::unique_ptr<T>(new T(value)); } TEST(Split, LvalueCaptureIsCopyable) { std::string input = "a,b"; auto heap_splitter = CopyToHeap(absl::StrSplit(input, ',')); auto stack_splitter = *heap_splitter; heap_splitter.reset(); std::vector<std::string> result = stack_splitter; EXPECT_THAT(result, testing::ElementsAre("a", "b")); } TEST(Split, TemporaryCaptureIsCopyable) { auto heap_splitter = CopyToHeap(absl::StrSplit(std::string("a,b"), ',')); auto stack_splitter = *heap_splitter; heap_splitter.reset(); std::vector<std::string> result = stack_splitter; EXPECT_THAT(result, testing::ElementsAre("a", "b")); } TEST(Split, SplitterIsCopyableAndMoveable) { auto a = absl::StrSplit("foo", '-'); auto b = a; auto c = std::move(a); b = c; c = std::move(b); EXPECT_THAT(c, ElementsAre("foo")); } TEST(Split, StringDelimiter) { { std::vector<absl::string_view> v = absl::StrSplit("a,b", ','); EXPECT_THAT(v, ElementsAre("a", "b")); } { std::vector<absl::string_view> v = absl::StrSplit("a,b", std::string(",")); EXPECT_THAT(v, ElementsAre("a", "b")); } { std::vector<absl::string_view> v = absl::StrSplit("a,b", absl::string_view(",")); EXPECT_THAT(v, ElementsAre("a", "b")); } } #if !defined(__cpp_char8_t) #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++2a-compat" #endif TEST(Split, UTF8) { std::string utf8_string = u8"\u03BA\u1F79\u03C3\u03BC\u03B5"; { std::string to_split = "a," + utf8_string; std::vector<absl::string_view> v = absl::StrSplit(to_split, ','); EXPECT_THAT(v, ElementsAre("a", utf8_string)); } { std::string to_split = "a," + utf8_string + ",b"; std::string unicode_delimiter = "," + utf8_string + ","; std::vector<absl::string_view> v = absl::StrSplit(to_split, unicode_delimiter); EXPECT_THAT(v, ElementsAre("a", "b")); } { std::vector<absl::string_view> v = absl::StrSplit(u8"Foo h\u00E4llo th\u4E1Ere", absl::ByAnyChar(" \t")); EXPECT_THAT(v, ElementsAre("Foo", u8"h\u00E4llo", u8"th\u4E1Ere")); } } #if defined(__clang__) #pragma clang diagnostic pop #endif #endif TEST(Split, EmptyStringDelimiter) { { std::vector<std::string> v = absl::StrSplit("", ""); EXPECT_THAT(v, ElementsAre("")); } { std::vector<std::string> v = absl::StrSplit("a", ""); EXPECT_THAT(v, ElementsAre("a")); } { std::vector<std::string> v = absl::StrSplit("ab", ""); EXPECT_THAT(v, ElementsAre("a", "b")); } { std::vector<std::string> v = absl::StrSplit("a b", ""); EXPECT_THAT(v, ElementsAre("a", " ", "b")); } } TEST(Split, SubstrDelimiter) { std::vector<absl::string_view> results; absl::string_view delim(" results = absl::StrSplit("", delim); EXPECT_THAT(results, ElementsAre("")); results = absl::StrSplit(" EXPECT_THAT(results, ElementsAre("", "")); results = absl::StrSplit("ab", delim); EXPECT_THAT(results, ElementsAre("ab")); results = absl::StrSplit("ab EXPECT_THAT(results, ElementsAre("ab", "")); results = absl::StrSplit("ab/", delim); EXPECT_THAT(results, ElementsAre("ab/")); results = absl::StrSplit("a/b", delim); EXPECT_THAT(results, ElementsAre("a/b")); results = absl::StrSplit("a EXPECT_THAT(results, ElementsAre("a", "b")); results = absl::StrSplit("a EXPECT_THAT(results, ElementsAre("a", "/b")); results = absl::StrSplit("a EXPECT_THAT(results, ElementsAre("a", "", "b")); } TEST(Split, EmptyResults) { std::vector<absl::string_view> results; results = absl::StrSplit("", '#'); EXPECT_THAT(results, ElementsAre("")); results = absl::StrSplit("#", '#'); EXPECT_THAT(results, ElementsAre("", "")); results = absl::StrSplit("#cd", '#'); EXPECT_THAT(results, ElementsAre("", "cd")); results = absl::StrSplit("ab#cd#", '#'); EXPECT_THAT(results, ElementsAre("ab", "cd", "")); results = absl::StrSplit("ab##cd", '#'); EXPECT_THAT(results, ElementsAre("ab", "", "cd")); results = absl::StrSplit("ab##", '#'); EXPECT_THAT(results, ElementsAre("ab", "", "")); results = absl::StrSplit("ab#ab#", '#'); EXPECT_THAT(results, ElementsAre("ab", "ab", "")); results = absl::StrSplit("aaaa", 'a'); EXPECT_THAT(results, ElementsAre("", "", "", "", "")); results = absl::StrSplit("", '#', absl::SkipEmpty()); EXPECT_THAT(results, ElementsAre()); } template <typename Delimiter> static bool IsFoundAtStartingPos(absl::string_view text, Delimiter d, size_t starting_pos, int expected_pos) { absl::string_view found = d.Find(text, starting_pos); return found.data() != text.data() + text.size() && expected_pos == found.data() - text.data(); } template <typename Delimiter> static bool IsFoundAt(absl::string_view text, Delimiter d, int expected_pos) { const std::string leading_text = ",x,y,z,"; return IsFoundAtStartingPos(text, d, 0, expected_pos) && IsFoundAtStartingPos(leading_text + std::string(text), d, leading_text.length(), expected_pos + leading_text.length()); } template <typename Delimiter> void TestComma(Delimiter d) { EXPECT_TRUE(IsFoundAt(",", d, 0)); EXPECT_TRUE(IsFoundAt("a,", d, 1)); EXPECT_TRUE(IsFoundAt(",b", d, 0)); EXPECT_TRUE(IsFoundAt("a,b", d, 1)); EXPECT_TRUE(IsFoundAt("a,b,", d, 1)); EXPECT_TRUE(IsFoundAt("a,b,c", d, 1)); EXPECT_FALSE(IsFoundAt("", d, -1)); EXPECT_FALSE(IsFoundAt(" ", d, -1)); EXPECT_FALSE(IsFoundAt("a", d, -1)); EXPECT_FALSE(IsFoundAt("a b c", d, -1)); EXPECT_FALSE(IsFoundAt("a;b;c", d, -1)); EXPECT_FALSE(IsFoundAt(";", d, -1)); } TEST(Delimiter, ByString) { using absl::ByString; TestComma(ByString(",")); ByString comma_string(","); TestComma(comma_string); absl::string_view abc("abc"); EXPECT_EQ(0, abc.find("")); ByString empty(""); EXPECT_FALSE(IsFoundAt("", empty, 0)); EXPECT_FALSE(IsFoundAt("a", empty, 0)); EXPECT_TRUE(IsFoundAt("ab", empty, 1)); EXPECT_TRUE(IsFoundAt("abc", empty, 1)); } TEST(Split, ByChar) { using absl::ByChar; TestComma(ByChar(',')); ByChar comma_char(','); TestComma(comma_char); } TEST(Delimiter, ByAnyChar) { using absl::ByAnyChar; ByAnyChar one_delim(","); EXPECT_TRUE(IsFoundAt(",", one_delim, 0)); EXPECT_TRUE(IsFoundAt("a,", one_delim, 1)); EXPECT_TRUE(IsFoundAt("a,b", one_delim, 1)); EXPECT_TRUE(IsFoundAt(",b", one_delim, 0)); EXPECT_FALSE(IsFoundAt("", one_delim, -1)); EXPECT_FALSE(IsFoundAt(" ", one_delim, -1)); EXPECT_FALSE(IsFoundAt("a", one_delim, -1)); EXPECT_FALSE(IsFoundAt("a;b;c", one_delim, -1)); EXPECT_FALSE(IsFoundAt(";", one_delim, -1)); ByAnyChar two_delims(",;"); EXPECT_TRUE(IsFoundAt(",", two_delims, 0)); EXPECT_TRUE(IsFoundAt(";", two_delims, 0)); EXPECT_TRUE(IsFoundAt(",;", two_delims, 0)); EXPECT_TRUE(IsFoundAt(";,", two_delims, 0)); EXPECT_TRUE(IsFoundAt(",;b", two_delims, 0)); EXPECT_TRUE(IsFoundAt(";,b", two_delims, 0)); EXPECT_TRUE(IsFoundAt("a;,", two_delims, 1)); EXPECT_TRUE(IsFoundAt("a,;", two_delims, 1)); EXPECT_TRUE(IsFoundAt("a;,b", two_delims, 1)); EXPECT_TRUE(IsFoundAt("a,;b", two_delims, 1)); EXPECT_FALSE(IsFoundAt("", two_delims, -1)); EXPECT_FALSE(IsFoundAt(" ", two_delims, -1)); EXPECT_FALSE(IsFoundAt("a", two_delims, -1)); EXPECT_FALSE(IsFoundAt("a=b=c", two_delims, -1)); EXPECT_FALSE(IsFoundAt("=", two_delims, -1)); ByAnyChar empty(""); EXPECT_FALSE(IsFoundAt("", empty, 0)); EXPECT_FALSE(IsFoundAt("a", empty, 0)); EXPECT_TRUE(IsFoundAt("ab", empty, 1)); EXPECT_TRUE(IsFoundAt("abc", empty, 1)); } TEST(Split, ByAsciiWhitespace) { using absl::ByAsciiWhitespace; using absl::SkipEmpty; std::vector<absl::string_view> results; results = absl::StrSplit("aaaa\n", ByAsciiWhitespace()); EXPECT_THAT(results, ElementsAre("aaaa", "")); results = absl::StrSplit("aaaa\n", ByAsciiWhitespace(), SkipEmpty()); EXPECT_THAT(results, ElementsAre("aaaa")); results = absl::StrSplit(" ", ByAsciiWhitespace()); EXPECT_THAT(results, ElementsAre("", "")); results = absl::StrSplit(" ", ByAsciiWhitespace(), SkipEmpty()); EXPECT_THAT(results, IsEmpty()); results = absl::StrSplit("a", ByAsciiWhitespace()); EXPECT_THAT(results, ElementsAre("a")); results = absl::StrSplit("", ByAsciiWhitespace()); EXPECT_THAT(results, ElementsAre("")); results = absl::StrSplit("", ByAsciiWhitespace(), SkipEmpty()); EXPECT_THAT(results, IsEmpty()); results = absl::StrSplit("a b\tc\n d\n", ByAsciiWhitespace()); EXPECT_THAT(results, ElementsAre("a", "b", "c", "", "", "d", "")); results = absl::StrSplit("a b\tc\n d \n", ByAsciiWhitespace(), SkipEmpty()); EXPECT_THAT(results, ElementsAre("a", "b", "c", "d")); results = absl::StrSplit("a\t\n\v\f\r b", ByAsciiWhitespace(), SkipEmpty()); EXPECT_THAT(results, ElementsAre("a", "b")); } TEST(Delimiter, ByLength) { using absl::ByLength; ByLength four_char_delim(4); EXPECT_TRUE(IsFoundAt("abcde", four_char_delim, 4)); EXPECT_TRUE(IsFoundAt("abcdefghijklmnopqrstuvwxyz", four_char_delim, 4)); EXPECT_TRUE(IsFoundAt("a b,c\nd", four_char_delim, 4)); EXPECT_FALSE(IsFoundAt("", four_char_delim, 0)); EXPECT_FALSE(IsFoundAt("a", four_char_delim, 0)); EXPECT_FALSE(IsFoundAt("ab", four_char_delim, 0)); EXPECT_FALSE(IsFoundAt("abc", four_char_delim, 0)); EXPECT_FALSE(IsFoundAt("abcd", four_char_delim, 0)); } TEST(Split, WorksWithLargeStrings) { #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_MEMORY_SANITIZE
2,560
#ifndef ABSL_STRINGS_NUMBERS_H_ #define ABSL_STRINGS_NUMBERS_H_ #ifdef __SSSE3__ #include <tmmintrin.h> #endif #ifdef _MSC_VER #include <intrin.h> #endif #include <cstddef> #include <cstdlib> #include <cstring> #include <ctime> #include <limits> #include <string> #include <type_traits> #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/base/port.h" #include "absl/numeric/bits.h" #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename int_type> ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str, absl::Nonnull<int_type*> out); ABSL_MUST_USE_RESULT bool SimpleAtof(absl::string_view str, absl::Nonnull<float*> out); ABSL_MUST_USE_RESULT bool SimpleAtod(absl::string_view str, absl::Nonnull<double*> out); ABSL_MUST_USE_RESULT bool SimpleAtob(absl::string_view str, absl::Nonnull<bool*> out); template <typename int_type> ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str, absl::Nonnull<int_type*> out); ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi( absl::string_view str, absl::Nonnull<absl::int128*> out); ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi( absl::string_view str, absl::Nonnull<absl::uint128*> out); ABSL_NAMESPACE_END } namespace absl { ABSL_NAMESPACE_BEGIN namespace numbers_internal { ABSL_DLL extern const char kHexChar[17]; ABSL_DLL extern const char kHexTable[513]; void PutTwoDigits(uint32_t i, absl::Nonnull<char*> buf); bool safe_strto32_base(absl::string_view text, absl::Nonnull<int32_t*> value, int base); bool safe_strto64_base(absl::string_view text, absl::Nonnull<int64_t*> value, int base); bool safe_strto128_base(absl::string_view text, absl::Nonnull<absl::int128*> value, int base); bool safe_strtou32_base(absl::string_view text, absl::Nonnull<uint32_t*> value, int base); bool safe_strtou64_base(absl::string_view text, absl::Nonnull<uint64_t*> value, int base); bool safe_strtou128_base(absl::string_view text, absl::Nonnull<absl::uint128*> value, int base); static const int kFastToBufferSize = 32; static const int kSixDigitsToBufferSize = 16; size_t SixDigitsToBuffer(double d, absl::Nonnull<char*> buffer); absl::Nonnull<char*> FastIntToBuffer(int32_t i, absl::Nonnull<char*> buffer) ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize); absl::Nonnull<char*> FastIntToBuffer(uint32_t n, absl::Nonnull<char*> out_str) ABSL_INTERNAL_NEED_MIN_SIZE(out_str, kFastToBufferSize); absl::Nonnull<char*> FastIntToBuffer(int64_t i, absl::Nonnull<char*> buffer) ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize); absl::Nonnull<char*> FastIntToBuffer(uint64_t i, absl::Nonnull<char*> buffer) ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize); template <typename int_type> absl::Nonnull<char*> FastIntToBuffer(int_type i, absl::Nonnull<char*> buffer) ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize) { static_assert(sizeof(i) <= 64 / 8, "FastIntToBuffer works only with 64-bit-or-less integers."); constexpr bool kIsSigned = static_cast<int_type>(1) - 2 < 0; constexpr bool kUse64Bit = sizeof(i) > 32 / 8; if (kIsSigned) { if (kUse64Bit) { return FastIntToBuffer(static_cast<int64_t>(i), buffer); } else { return FastIntToBuffer(static_cast<int32_t>(i), buffer); } } else { if (kUse64Bit) { return FastIntToBuffer(static_cast<uint64_t>(i), buffer); } else { return FastIntToBuffer(static_cast<uint32_t>(i), buffer); } } } template <typename int_type> ABSL_MUST_USE_RESULT bool safe_strtoi_base(absl::string_view s, absl::Nonnull<int_type*> out, int base) { static_assert(sizeof(*out) == 4 || sizeof(*out) == 8, "SimpleAtoi works only with 32-bit or 64-bit integers."); static_assert(!std::is_floating_point<int_type>::value, "Use SimpleAtof or SimpleAtod instead."); bool parsed; constexpr bool kIsSigned = static_cast<int_type>(1) - 2 < 0; constexpr bool kUse64Bit = sizeof(*out) == 64 / 8; if (kIsSigned) { if (kUse64Bit) { int64_t val; parsed = numbers_internal::safe_strto64_base(s, &val, base); *out = static_cast<int_type>(val); } else { int32_t val; parsed = numbers_internal::safe_strto32_base(s, &val, base); *out = static_cast<int_type>(val); } } else { if (kUse64Bit) { uint64_t val; parsed = numbers_internal::safe_strtou64_base(s, &val, base); *out = static_cast<int_type>(val); } else { uint32_t val; parsed = numbers_internal::safe_strtou32_base(s, &val, base); *out = static_cast<int_type>(val); } } return parsed; } inline size_t FastHexToBufferZeroPad16(uint64_t val, absl::Nonnull<char*> out) { #ifdef ABSL_INTERNAL_HAVE_SSSE3 uint64_t be = absl::big_endian::FromHost64(val); const auto kNibbleMask = _mm_set1_epi8(0xf); const auto kHexDigits = _mm_setr_epi8('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); auto v = _mm_loadl_epi64(reinterpret_cast<__m128i*>(&be)); auto v4 = _mm_srli_epi64(v, 4); auto il = _mm_unpacklo_epi8(v4, v); auto m = _mm_and_si128(il, kNibbleMask); auto hexchars = _mm_shuffle_epi8(kHexDigits, m); _mm_storeu_si128(reinterpret_cast<__m128i*>(out), hexchars); #else for (int i = 0; i < 8; ++i) { auto byte = (val >> (56 - 8 * i)) & 0xFF; auto* hex = &absl::numbers_internal::kHexTable[byte * 2]; std::memcpy(out + 2 * i, hex, 2); } #endif return 16 - static_cast<size_t>(countl_zero(val | 0x1) / 4); } } template <typename int_type> ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str, absl::Nonnull<int_type*> out) { return numbers_internal::safe_strtoi_base(str, out, 10); } ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str, absl::Nonnull<absl::int128*> out) { return numbers_internal::safe_strto128_base(str, out, 10); } ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str, absl::Nonnull<absl::uint128*> out) { return numbers_internal::safe_strtou128_base(str, out, 10); } template <typename int_type> ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str, absl::Nonnull<int_type*> out) { return numbers_internal::safe_strtoi_base(str, out, 16); } ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi( absl::string_view str, absl::Nonnull<absl::int128*> out) { return numbers_internal::safe_strto128_base(str, out, 16); } ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi( absl::string_view str, absl::Nonnull<absl::uint128*> out) { return numbers_internal::safe_strtou128_base(str, out, 16); } ABSL_NAMESPACE_END } #endif #include "absl/strings/numbers.h" #include <algorithm> #include <cassert> #include <cfloat> #include <cmath> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <iterator> #include <limits> #include <system_error> #include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/numeric/bits.h" #include "absl/numeric/int128.h" #include "absl/strings/ascii.h" #include "absl/strings/charconv.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN bool SimpleAtof(absl::string_view str, absl::Nonnull<float*> out) { *out = 0.0; str = StripAsciiWhitespace(str); if (!str.empty() && str[0] == '+') { str.remove_prefix(1); if (!str.empty() && str[0] == '-') { return false; } } auto result = absl::from_chars(str.data(), str.data() + str.size(), *out); if (result.ec == std::errc::invalid_argument) { return false; } if (result.ptr != str.data() + str.size()) { return false; } if (result.ec == std::errc::result_out_of_range) { if (*out > 1.0) { *out = std::numeric_limits<float>::infinity(); } else if (*out < -1.0) { *out = -std::numeric_limits<float>::infinity(); } } return true; } bool SimpleAtod(absl::string_view str, absl::Nonnull<double*> out) { *out = 0.0; str = StripAsciiWhitespace(str); if (!str.empty() && str[0] == '+') { str.remove_prefix(1); if (!str.empty() && str[0] == '-') { return false; } } auto result = absl::from_chars(str.data(), str.data() + str.size(), *out); if (result.ec == std::errc::invalid_argument) { return false; } if (result.ptr != str.data() + str.size()) { return false; } if (result.ec == std::errc::result_out_of_range) { if (*out > 1.0) { *out = std::numeric_limits<double>::infinity(); } else if (*out < -1.0) { *out = -std::numeric_limits<double>::infinity(); } } return true; } bool SimpleAtob(absl::string_view str, absl::Nonnull<bool*> out) { ABSL_RAW_CHECK(out != nullptr, "Output pointer must not be nullptr."); if (EqualsIgnoreCase(str, "true") || EqualsIgnoreCase(str, "t") || EqualsIgnoreCase(str, "yes") || EqualsIgnoreCase(str, "y") || EqualsIgnoreCase(str, "1")) { *out = true; return true; } if (EqualsIgnoreCase(str, "false") || EqualsIgnoreCase(str, "f") || EqualsIgnoreCase(str, "no") || EqualsIgnoreCase(str, "n") || EqualsIgnoreCase(str, "0")) { *out = false; return true; } return false; } namespace { constexpr uint32_t kTwoZeroBytes = 0x0101 * '0'; constexpr uint64_t kFourZeroBytes = 0x01010101 * '0'; constexpr uint64_t kEightZeroBytes = 0x0101010101010101ull * '0'; constexpr uint64_t kDivisionBy10Mul = 103u; constexpr uint64_t kDivisionBy10Div = 1 << 10; constexpr uint64_t kDivisionBy100Mul = 10486u; constexpr uint64_t kDivisionBy100Div = 1 << 20; inline char* EncodeHundred(uint32_t n, absl::Nonnull<char*> out_str) { int num_digits = static_cast<int>(n - 10) >> 8; uint32_t div10 = (n * kDivisionBy10Mul) / kDivisionBy10Div; uint32_t mod10 = n - 10u * div10; uint32_t base = kTwoZeroBytes + div10 + (mod10 << 8); base >>= num_digits & 8; little_endian::Store16(out_str, static_cast<uint16_t>(base)); return out_str + 2 + num_digits; } inline char* EncodeTenThousand(uint32_t n, absl::Nonnull<char*> out_str) { uint32_t div100 = (n * kDivisionBy100Mul) / kDivisionBy100Div; uint32_t mod100 = n - 100ull * div100; uint32_t hundreds = (mod100 << 16) + div100; uint32_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div; tens &= (0xFull << 16) | 0xFull; tens += (hundreds - 10ull * tens) << 8; ABSL_ASSUME(tens != 0); uint32_t zeroes = static_cast<uint32_t>(absl::countr_zero(tens)) & (0 - 8u); tens += kFourZeroBytes; tens >>= zeroes; little_endian::Store32(out_str, tens); return out_str + sizeof(tens) - zeroes / 8; } inline uint64_t PrepareEightDigits(uint32_t i) { ABSL_ASSUME(i < 10000'0000); uint32_t hi = i / 10000; uint32_t lo = i % 10000; uint64_t merged = hi | (uint64_t{lo} << 32); uint64_t div100 = ((merged * kDivisionBy100Mul) / kDivisionBy100Div) & ((0x7Full << 32) | 0x7Full); uint64_t mod100 = merged - 100ull * div100; uint64_t hundreds = (mod100 << 16) + div100; uint64_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div; tens &= (0xFull << 48) | (0xFull << 32) | (0xFull << 16) | 0xFull; tens += (hundreds - 10ull * tens) << 8; return tens; } inline ABSL_ATTRIBUTE_ALWAYS_INLINE absl::Nonnull<char*> EncodeFullU32( uint32_t n, absl::Nonnull<char*> out_str) { if (n < 10) { *out_str = static_cast<char>('0' + n); return out_str + 1; } if (n < 100'000'000) { uint64_t bottom = PrepareEightDigits(n); ABSL_ASSUME(bottom != 0); uint32_t zeroes = static_cast<uint32_t>(absl::countr_zero(bottom)) & (0 - 8u); little_endian::Store64(out_str, (bottom + kEightZeroBytes) >> zeroes); return out_str + sizeof(bottom) - zeroes / 8; } uint32_t div08 = n / 100'000'000; uint32_t mod08 = n % 100'000'000; uint64_t bottom = PrepareEightDigits(mod08) + kEightZeroBytes; out_str = EncodeHundred(div08, out_str); little_endian::Store64(out_str, bottom); return out_str + sizeof(bottom); } inline ABSL_ATTRIBUTE_ALWAYS_INLINE char* EncodeFullU64(uint64_t i, char* buffer) { if (i <= std::numeric_limits<uint32_t>::max()) { return EncodeFullU32(static_cast<uint32_t>(i), buffer); } uint32_t mod08; if (i < 1'0000'0000'0000'0000ull) { uint32_t div08 = static_cast<uint32_t>(i / 100'000'000ull); mod08 = static_cast<uint32_t>(i % 100'000'000ull); buffer = EncodeFullU32(div08, buffer); } else { uint64_t div08 = i / 100'000'000ull; mod08 = static_cast<uint32_t>(i % 100'000'000ull); uint32_t div016 = static_cast<uint32_t>(div08 / 100'000'000ull); uint32_t div08mod08 = static_cast<uint32_t>(div08 % 100'000'000ull); uint64_t mid_result = PrepareEightDigits(div08mod08) + kEightZeroBytes; buffer = EncodeTenThousand(div016, buffer); little_endian::Store64(buffer, mid_result); buffer += sizeof(mid_result); } uint64_t mod_result = PrepareEightDigits(mod08) + kEightZeroBytes; little_endian::Store64(buffer, mod_result); return buffer + sizeof(mod_result); } } void numbers_internal::PutTwoDigits(uint32_t i, absl::Nonnull<char*> buf) { assert(i < 100); uint32_t base = kTwoZeroBytes; uint32_t div10 = (i * kDivisionBy10Mul) / kDivisionBy10Div; uint32_t mod10 = i - 10u * div10; base += div10 + (mod10 << 8); little_endian::Store16(buf, static_cast<uint16_t>(base)); } absl::Nonnull<char*> numbers_internal::FastIntToBuffer( uint32_t n, absl::Nonnull<char*> out_str) { out_str = EncodeFullU32(n, out_str); *out_str = '\0'; return out_str; } absl::Nonnull<char*> numbers_internal::FastIntToBuffer( int32_t i, absl::Nonnull<char*> buffer) { uint32_t u = static_cast<uint32_t>(i); if (i < 0) { *buffer++ = '-'; u = 0 - u; } buffer = EncodeFullU32(u, buffer); *buffer = '\0'; return buffer; } absl::Nonnull<char*> numbers_internal::FastIntToBuffer( uint64_t i, absl::Nonnull<char*> buffer) { buffer = EncodeFullU64(i, buffer); *buffer = '\0'; return buffer; } absl::Nonnull<char*> numbers_internal::FastIntToBuffer( int64_t i, absl::Nonnull<char*> buffer) { uint64_t u = static_cast<uint64_t>(i); if (i < 0) { *buffer++ = '-'; u = 0 - u; } buffer = EncodeFullU64(u, buffer); *buffer = '\0'; return buffer; } static std::pair<uint64_t, uint64_t> Mul32(std::pair<uint64_t, uint64_t> num, uint32_t mul) { uint64_t bits0_31 = num.second & 0xFFFFFFFF; uint64_t bits32_63 = num.second >> 32; uint64_t bits64_95 = num.first & 0xFFFFFFFF; uint64_t bits96_127 = num.first >> 32; bits0_31 *= mul; bits32_63 *= mul; bits64_95 *= mul; bits96_127 *= mul; uint64_t bits0_63 = bits0_31 + (bits32_63 << 32); uint64_t bits64_127 = bits64_95 + (bits96_127 << 32) + (bits32_63 >> 32) + (bits0_63 < bits0_31); uint64_t bits128_up = (bits96_127 >> 32) + (bits64_127 < bits64_95); if (bits128_up == 0) return {bits64_127, bits0_63}; auto shift = static_cast<unsigned>(bit_width(bits128_up)); uint64_t lo = (bits0_63 >> shift) + (bits64_127 << (64 - shift)); uint64_t hi = (bits64_127 >> shift) + (bits128_up << (64 - shift)); return {hi, lo}; } static std::pair<uint64_t, uint64_t> PowFive(uint64_t num, int expfive) { std::pair<uint64_t, uint64_t> result = {num, 0}; while (expfive >= 13) { result = Mul32(result, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5); expfive -= 13; } constexpr uint32_t powers_of_five[13] = { 1, 5, 5 * 5, 5 * 5 * 5, 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5}; result = Mul32(result, powers_of_five[expfive & 15]); int shift = countl_zero(result.first); if (shift != 0) { result.first = (result.first << shift) + (result.second >> (64 - shift)); result.second = (result.second << shift); } return result; } struct ExpDigits { int32_t exponent; char digits[6]; }; static ExpDigits SplitToSix(const double value) { ExpDigits exp_dig; int exp = 5; double d = value; if (d >= 999999.5) { if (d >= 1e+261) exp += 256, d *= 1e-256; if (d >= 1e+133) exp += 128, d *= 1e-128; if (d >= 1e+69) exp += 64, d *= 1e-64; if (d >= 1e+37) exp += 32, d *= 1e-32; if (d >= 1e+21) exp += 16, d *= 1e-16; if (d >= 1e+13) exp += 8, d *= 1e-8; if (d >= 1e+9) exp += 4, d *= 1e-4; if (d >= 1e+7) exp += 2, d *= 1e-2; if (d >= 1e+6) exp += 1, d *= 1e-1; } else { if (d < 1e-250) exp -= 256, d *= 1e256; if (d < 1e-122) exp -= 128, d *= 1e128; if (d < 1e-58) exp -= 64, d *= 1e64; if (d < 1e-26) exp -= 32, d *= 1e32; if (d < 1e-10) exp -= 16, d *= 1e16; if (d < 1e-2) exp -= 8, d *= 1e8; if (d < 1e+2) exp -= 4, d *= 1e4; if (d < 1e+4) exp -= 2, d *= 1e2; if (d < 1e+5) exp -= 1, d *= 1e1; } uint64_t d64k = d * 65536; uint32_t dddddd; if ((d64k % 65536) == 32767 || (d64k % 65536) == 32768) { dddddd = static_cast<uint32_t>(d64k / 65536); int exp2; double m = std::frexp(value, &exp2); uint64_t mantissa = m * (32768.0 * 65536.0 * 65536.0 * 65536.0);
#include "absl/strings/numbers.h" #include <sys/types.h> #include <cfenv> #include <cfloat> #include <cinttypes> #include <climits> #include <cmath> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <ios> #include <limits> #include <numeric> #include <random> #include <set> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/numeric/int128.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/strings/internal/numbers_test_common.h" #include "absl/strings/internal/ostringstream.h" #include "absl/strings/internal/pow10_helper.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace { using absl::SimpleAtoi; using absl::SimpleHexAtoi; using absl::numbers_internal::kSixDigitsToBufferSize; using absl::numbers_internal::safe_strto32_base; using absl::numbers_internal::safe_strto64_base; using absl::numbers_internal::safe_strtou32_base; using absl::numbers_internal::safe_strtou64_base; using absl::numbers_internal::SixDigitsToBuffer; using absl::strings_internal::Itoa; using absl::strings_internal::strtouint32_test_cases; using absl::strings_internal::strtouint64_test_cases; using testing::Eq; using testing::MatchesRegex; using testing::Pointee; const int kFloatNumCases = 5000000; std::string PerfectDtoa(double d) { if (d == 0) return "0"; if (d < 0) return "-" + PerfectDtoa(-d); int64_t mantissa, exp = 0; while (d >= 1ULL << 63) ++exp, d *= 0.5; while ((mantissa = d) != d) --exp, d *= 2.0; constexpr int maxlen = 1100; char buf[maxlen + 5]; for (int64_t num = mantissa, pos = maxlen; --pos >= 0;) { buf[pos] = '0' + (num % 10); num /= 10; } char* begin = &buf[0]; char* end = buf + maxlen; for (int i = 0; i != exp; i += (exp > 0) ? 1 : -1) { int carry = 0; for (char* p = end; --p != begin;) { int dig = *p - '0'; dig = dig * (exp > 0 ? 2 : 5) + carry; carry = dig / 10; dig %= 10; *p = '0' + dig; } } if (exp < 0) { memmove(end + 1 + exp, end + exp, 1 - exp); end[exp] = '.'; ++end; } while (*begin == '0' && begin[1] != '.') ++begin; return {begin, end}; } TEST(ToString, PerfectDtoa) { EXPECT_THAT(PerfectDtoa(1), Eq("1")); EXPECT_THAT(PerfectDtoa(0.1), Eq("0.1000000000000000055511151231257827021181583404541015625")); EXPECT_THAT(PerfectDtoa(1e24), Eq("999999999999999983222784")); EXPECT_THAT(PerfectDtoa(5e-324), MatchesRegex("0.0000.*625")); for (int i = 0; i < 100; ++i) { for (double multiplier : {1e-300, 1e-200, 1e-100, 0.1, 1.0, 10.0, 1e100, 1e300}) { double d = multiplier * i; std::string s = PerfectDtoa(d); EXPECT_DOUBLE_EQ(d, strtod(s.c_str(), nullptr)); } } } template <typename integer> struct MyInteger { integer i; explicit constexpr MyInteger(integer i) : i(i) {} constexpr operator integer() const { return i; } constexpr MyInteger operator+(MyInteger other) const { return i + other.i; } constexpr MyInteger operator-(MyInteger other) const { return i - other.i; } constexpr MyInteger operator*(MyInteger other) const { return i * other.i; } constexpr MyInteger operator/(MyInteger other) const { return i / other.i; } constexpr bool operator<(MyInteger other) const { return i < other.i; } constexpr bool operator<=(MyInteger other) const { return i <= other.i; } constexpr bool operator==(MyInteger other) const { return i == other.i; } constexpr bool operator>=(MyInteger other) const { return i >= other.i; } constexpr bool operator>(MyInteger other) const { return i > other.i; } constexpr bool operator!=(MyInteger other) const { return i != other.i; } integer as_integer() const { return i; } }; typedef MyInteger<int64_t> MyInt64; typedef MyInteger<uint64_t> MyUInt64; void CheckInt32(int32_t x) { char buffer[absl::numbers_internal::kFastToBufferSize]; char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer); std::string expected = std::to_string(x); EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x; char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer); EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x; } void CheckInt64(int64_t x) { char buffer[absl::numbers_internal::kFastToBufferSize + 3]; buffer[0] = '*'; buffer[23] = '*'; buffer[24] = '*'; char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]); std::string expected = std::to_string(x); EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x; EXPECT_EQ(buffer[0], '*'); EXPECT_EQ(buffer[23], '*'); EXPECT_EQ(buffer[24], '*'); char* my_actual = absl::numbers_internal::FastIntToBuffer(MyInt64(x), &buffer[1]); EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x; } void CheckUInt32(uint32_t x) { char buffer[absl::numbers_internal::kFastToBufferSize]; char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer); std::string expected = std::to_string(x); EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x; char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer); EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x; } void CheckUInt64(uint64_t x) { char buffer[absl::numbers_internal::kFastToBufferSize + 1]; char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]); std::string expected = std::to_string(x); EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x; char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]); EXPECT_EQ(expected, std::string(&buffer[1], generic_actual)) << " Input " << x; char* my_actual = absl::numbers_internal::FastIntToBuffer(MyUInt64(x), &buffer[1]); EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x; } void CheckHex64(uint64_t v) { char expected[16 + 1]; std::string actual = absl::StrCat(absl::Hex(v, absl::kZeroPad16)); snprintf(expected, sizeof(expected), "%016" PRIx64, static_cast<uint64_t>(v)); EXPECT_EQ(expected, actual) << " Input " << v; actual = absl::StrCat(absl::Hex(v, absl::kSpacePad16)); snprintf(expected, sizeof(expected), "%16" PRIx64, static_cast<uint64_t>(v)); EXPECT_EQ(expected, actual) << " Input " << v; } TEST(Numbers, TestFastPrints) { for (int i = -100; i <= 100; i++) { CheckInt32(i); CheckInt64(i); } for (int i = 0; i <= 100; i++) { CheckUInt32(i); CheckUInt64(i); } CheckInt32(INT_MIN); CheckInt32(INT_MAX); CheckInt64(LONG_MIN); CheckInt64(uint64_t{1000000000}); CheckInt64(uint64_t{9999999999}); CheckInt64(uint64_t{100000000000000}); CheckInt64(uint64_t{999999999999999}); CheckInt64(uint64_t{1000000000000000000}); CheckInt64(uint64_t{1199999999999999999}); CheckInt64(int64_t{-700000000000000000}); CheckInt64(LONG_MAX); CheckUInt32(std::numeric_limits<uint32_t>::max()); CheckUInt64(uint64_t{1000000000}); CheckUInt64(uint64_t{9999999999}); CheckUInt64(uint64_t{100000000000000}); CheckUInt64(uint64_t{999999999999999}); CheckUInt64(uint64_t{1000000000000000000}); CheckUInt64(uint64_t{1199999999999999999}); CheckUInt64(std::numeric_limits<uint64_t>::max()); for (int i = 0; i < 10000; i++) { CheckHex64(i); } CheckHex64(uint64_t{0x123456789abcdef0}); } template <typename int_type, typename in_val_type> void VerifySimpleAtoiGood(in_val_type in_value, int_type exp_value) { std::string s; absl::strings_internal::OStringStream(&s) << in_value; int_type x = static_cast<int_type>(~exp_value); EXPECT_TRUE(SimpleAtoi(s, &x)) << "in_value=" << in_value << " s=" << s << " x=" << x; EXPECT_EQ(exp_value, x); x = static_cast<int_type>(~exp_value); EXPECT_TRUE(SimpleAtoi(s.c_str(), &x)); EXPECT_EQ(exp_value, x); } template <typename int_type, typename in_val_type> void VerifySimpleAtoiBad(in_val_type in_value) { std::string s; absl::strings_internal::OStringStream(&s) << in_value; int_type x; EXPECT_FALSE(SimpleAtoi(s, &x)); EXPECT_FALSE(SimpleAtoi(s.c_str(), &x)); } TEST(NumbersTest, Atoi) { VerifySimpleAtoiGood<int32_t>(0, 0); VerifySimpleAtoiGood<int32_t>(42, 42); VerifySimpleAtoiGood<int32_t>(-42, -42); VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min()); VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleAtoiGood<uint32_t>(0, 0); VerifySimpleAtoiGood<uint32_t>(42, 42); VerifySimpleAtoiBad<uint32_t>(-42); VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min()); VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min()); VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max()); VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max()); VerifySimpleAtoiGood<int64_t>(0, 0); VerifySimpleAtoiGood<int64_t>(42, 42); VerifySimpleAtoiGood<int64_t>(-42, -42); VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min()); VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(), std::numeric_limits<int64_t>::min()); VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()); VerifySimpleAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max()); VerifySimpleAtoiGood<uint64_t>(0, 0); VerifySimpleAtoiGood<uint64_t>(42, 42); VerifySimpleAtoiBad<uint64_t>(-42); VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min()); VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min()); VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()); VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()); VerifySimpleAtoiGood<absl::uint128>(0, 0); VerifySimpleAtoiGood<absl::uint128>(42, 42); VerifySimpleAtoiBad<absl::uint128>(-42); VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min()); VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min()); VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()); VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()); VerifySimpleAtoiGood<absl::uint128>( std::numeric_limits<absl::uint128>::max(), std::numeric_limits<absl::uint128>::max()); VerifySimpleAtoiGood<absl::int128>(0, 0); VerifySimpleAtoiGood<absl::int128>(42, 42); VerifySimpleAtoiGood<absl::int128>(-42, -42); VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min()); VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::min(), std::numeric_limits<int64_t>::min()); VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()); VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()); VerifySimpleAtoiGood<absl::int128>( std::numeric_limits<absl::int128>::min(), std::numeric_limits<absl::int128>::min()); VerifySimpleAtoiGood<absl::int128>( std::numeric_limits<absl::int128>::max(), std::numeric_limits<absl::int128>::max()); VerifySimpleAtoiBad<absl::int128>(std::numeric_limits<absl::uint128>::max()); VerifySimpleAtoiGood<int>(-42, -42); VerifySimpleAtoiGood<int32_t>(-42, -42); VerifySimpleAtoiGood<uint32_t>(42, 42); VerifySimpleAtoiGood<unsigned int>(42, 42); VerifySimpleAtoiGood<int64_t>(-42, -42); VerifySimpleAtoiGood<long>(-42, -42); VerifySimpleAtoiGood<uint64_t>(42, 42); VerifySimpleAtoiGood<size_t>(42, 42); VerifySimpleAtoiGood<std::string::size_type>(42, 42); } TEST(NumbersTest, Atod) { #if !defined(DBL_TRUE_MIN) static constexpr double DBL_TRUE_MIN = 4.940656458412465441765687928682213723650598026143247644255856825e-324; #endif #if !defined(FLT_TRUE_MIN) static constexpr float FLT_TRUE_MIN = 1.401298464324817070923729583289916131280261941876515771757068284e-45f; #endif double d; float f; EXPECT_TRUE(absl::SimpleAtod("NaN", &d)); EXPECT_TRUE(std::isnan(d)); EXPECT_TRUE(absl::SimpleAtod("nAN", &d)); EXPECT_TRUE(std::isnan(d)); EXPECT_TRUE(absl::SimpleAtod("-nan", &d)); EXPECT_TRUE(std::isnan(d)); EXPECT_TRUE(absl::SimpleAtod("inf", &d)); EXPECT_TRUE(std::isinf(d) && (d > 0)); EXPECT_TRUE(absl::SimpleAtod("+Infinity", &d)); EXPECT_TRUE(std::isinf(d) && (d > 0)); EXPECT_TRUE(absl::SimpleAtod("-INF", &d)); EXPECT_TRUE(std::isinf(d) && (d < 0)); EXPECT_TRUE(absl::SimpleAtod("1.7976931348623157e+308", &d)); EXPECT_EQ(d, 1.7976931348623157e+308); EXPECT_TRUE(absl::SimpleAtod("5e308", &d)); EXPECT_TRUE(std::isinf(d) && (d > 0)); EXPECT_TRUE(absl::SimpleAtof("3.4028234663852886e+38", &f)); EXPECT_EQ(f, 3.4028234663852886e+38f); EXPECT_TRUE(absl::SimpleAtof("7e38", &f)); EXPECT_TRUE(std::isinf(f) && (f > 0)); EXPECT_TRUE(absl::SimpleAtod("1e308", &d)); EXPECT_EQ(d, 1e308); EXPECT_FALSE(std::isinf(d)); EXPECT_TRUE(absl::SimpleAtod("1e309", &d)); EXPECT_TRUE(std::isinf(d)); EXPECT_TRUE(absl::SimpleAtof("1e38", &f)); EXPECT_EQ(f, 1e38f); EXPECT_FALSE(std::isinf(f)); EXPECT_TRUE(absl::SimpleAtof("1e39", &f)); EXPECT_TRUE(std::isinf(f)); EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e307", &d)); EXPECT_EQ(d, 9.999999999999999999e307); EXPECT_FALSE(std::isinf(d)); EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e308", &d)); EXPECT_TRUE(std::isinf(d)); EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e37", &f)); EXPECT_EQ(f, 9.999999999999999999e37f); EXPECT_FALSE(std::isinf(f)); EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e38", &f)); EXPECT_TRUE(std::isinf(f)); EXPECT_TRUE(absl::SimpleAtod("2.2250738585072014e-308", &d)); EXPECT_EQ(d, 2.2250738585072014e-308); EXPECT_TRUE(absl::SimpleAtod("4.9406564584124654e-324", &d)); EXPECT_EQ(d, 4.9406564584124654e-324); EXPECT_TRUE(absl::SimpleAtod("4.9406564584124654e-325", &d)); EXPECT_EQ(d, 0); EXPECT_TRUE(absl::SimpleAtof("1.1754943508222875e-38", &f)); EXPECT_EQ(f, 1.1754943508222875e-38f); EXPECT_TRUE(absl::SimpleAtof("1.4012984643248171e-45", &f)); EXPECT_EQ(f, 1.4012984643248171e-45f); EXPECT_TRUE(absl::SimpleAtof("1.4012984643248171e-46", &f)); EXPECT_EQ(f, 0); EXPECT_TRUE(absl::SimpleAtod("1e-307", &d)); EXPECT_EQ(d, 1e-307); EXPECT_GE(d, DBL_MIN); EXPECT_LT(d, DBL_MIN * 10); EXPECT_TRUE(absl::SimpleAtod("1e-323", &d)); EXPECT_EQ(d, 1e-323); EXPECT_GE(d, DBL_TRUE_MIN); EXPECT_LT(d, DBL_TRUE_MIN * 10); EXPECT_TRUE(absl::SimpleAtod("1e-324", &d)); EXPECT_EQ(d, 0); EXPECT_TRUE(absl::SimpleAtof("1e-37", &f)); EXPECT_EQ(f, 1e-37f); EXPECT_GE(f, FLT_MIN); EXPECT_LT(f, FLT_MIN * 10); EXPECT_TRUE(absl::SimpleAtof("1e-45", &f)); EXPECT_EQ(f, 1e-45f); EXPECT_GE(f, FLT_TRUE_MIN); EXPECT_LT(f, FLT_TRUE_MIN * 10); EXPECT_TRUE(absl::SimpleAtof("1e-46", &f)); EXPECT_EQ(f, 0); EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-308", &d)); EXPECT_EQ(d, 9.999999999999999999e-308); EXPECT_GE(d, DBL_MIN); EXPECT_LT(d, DBL_MIN * 10); EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-324", &d)); EXPECT_EQ(d, 9.999999999999999999e-324); EXPECT_GE(d, DBL_TRUE_MIN); EXPECT_LT(d, DBL_TRUE_MIN * 10); EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-325", &d)); EXPECT_EQ(d, 0); EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-38", &f)); EXPECT_EQ(f, 9.999999999999999999e-38f); EXPECT_GE(f, FLT_MIN); EXPECT_LT(f, FLT_MIN * 10); EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-46", &f)); EXPECT_EQ(f, 9.999999999999999999e-46f); EXPECT_GE(f, FLT_TRUE_MIN); EXPECT_LT(f, FLT_TRUE_MIN * 10); EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-47", &f)); EXPECT_EQ(f, 0); EXPECT_TRUE(absl::SimpleAtod(" \t\r\n 2.718", &d)); EXPECT_EQ(d, 2.718); EXPECT_TRUE(absl::SimpleAtod(" 3.141 ", &d)); EXPECT_EQ(d, 3.141); EXPECT_FALSE(absl::SimpleAtod("n 0", &d)); EXPECT_FALSE(absl::SimpleAtod("0n ", &d)); EXPECT_TRUE(absl::SimpleAtod("000123", &d)); EXPECT_EQ(d, 123); EXPECT_TRUE(absl::SimpleAtod("000.456", &d)); EXPECT_EQ(d, 0.456); EXPECT_TRUE(absl::SimpleAtod(".5", &d)); EXPECT_EQ(d, 0.5); EXPECT_TRUE(absl::SimpleAtod("-.707", &d)); EXPECT_EQ(d, -0.707); EXPECT_TRUE(absl::SimpleAtod("+6.0221408e+23", &d)); EXPECT_EQ(d, 6.0221408e+23); EXPECT_FALSE(absl::SimpleAtod("123_456", &d)); EXPECT_TRUE(absl::SimpleAtod("8.9", &d)); EXPECT_FALSE(absl::SimpleAtod("8,9", &d)); EXPECT_TRUE(absl::SimpleAtod("4503599627370497.5", &d)); EXPECT_EQ(d, 4503599627370497.5); EXPECT_TRUE(absl::SimpleAtod("1e+23", &d)); EXPECT_EQ(d, 1e+23); EXPECT_TRUE(absl::SimpleAtod("9223372036854775807", &d)); EXPECT_EQ(d, 9223372036854775807); EXPECT_TRUE(absl::SimpleAtof("0.0625", &f)); EXPECT_EQ(f, 0.0625f); EXPECT_TRUE(absl::SimpleAtof("20040229.0", &f)); EXPECT_EQ(f, 20040229.0f); EXPECT_TRUE(absl::SimpleAtof("2147483647.0", &f)); EXPECT_EQ(f, 2147483647.0f); EXPECT_TRUE(absl::SimpleAtod("122.416294033786585", &d)); EXPECT_EQ(d, 122.416294033786585); EXPECT_TRUE(absl::SimpleAtof("122.416294033786585", &f)); EXPECT_EQ(f, 122.416294033786585f); } TEST(NumbersTest, Prefixes) { double d; EXPECT_FALSE(absl::SimpleAtod("++1", &d)); EXPECT_FALSE(absl::SimpleAtod("+-1", &d)); EXPECT_FALSE(absl::SimpleAtod("-+1", &d)); EXPECT_FALSE(absl::SimpleAtod("--1", &d)); EXPECT_TRUE(absl::SimpleAtod("-1", &d)); EXPECT_EQ(d, -1.); EXPECT_TRUE(absl::SimpleAtod("+1", &d)); EXPECT_EQ(d, +1.); float f; EXPECT_FALSE(absl::SimpleAtof("++1", &f)); EXPECT_FALSE(absl::SimpleAtof("+-1", &f)); EXPECT_FALSE(absl::SimpleAtof("-+1", &f)); EXPECT_FALSE(absl::SimpleAtof("--1", &f)); EXPECT_TRUE(absl::SimpleAtof("-1", &f)); EXPECT_EQ(f, -1.f); EXPECT_TRUE(absl::SimpleAtof("+1", &f)); EXPECT_EQ(f, +1.f); } TEST(NumbersTest, Atoenum) { enum E01 { E01_zero = 0, E01_one = 1, }; VerifySimpleAtoiGood<E01>(E01_zero, E01_zero); VerifySimpleAtoiGood<E01>(E01_one, E01_one); enum E_101 { E_101_minusone = -1, E_101_zero = 0, E_101_one = 1, }; VerifySimpleAtoiGood<E_101>(E_101_minusone, E_101_minusone); VerifySimpleAtoiGood<E_101>(E_101_zero, E_101_zero); VerifySimpleAtoiGood<E_101>(E_101_one, E_101_one); enum E_bigint { E_bigint_zero = 0, E_bigint_one = 1, E_bigint_max31 = static_cast<int32_t>(0x7FFFFFFF), }; VerifySimpleAtoiGood<E_bigint>(E_bigint_zero, E_bigint_zero); VerifySimpleAtoiGood<E_bigint>(E_bigint_one, E_bigint_one); VerifySimpleAtoiGood<E_bigint>(E_bigint_max31, E_bigint_max31); enum E_fullint { E_fullint_zero = 0, E_fullint_one = 1, E_fullint_max31 = static_cast<int32_t>(0x7FFFFFFF), E_fullint_min32 = INT32_MIN, }; VerifySimpleAtoiGood<E_fullint>(E_fullint_zero, E_fullint_zero); VerifySimpleAtoiGood<E_fullint>(E_fullint_one, E_fullint_one); VerifySimpleAtoiGood<E_fullint>(E_fullint_max31, E_fullint_max31); VerifySimpleAtoiGood<E_fullint>(E_fullint_min32, E_fullint_min32); enum E_biguint { E_biguint_zero = 0, E_biguint_one = 1, E_biguint_max31 = static_cast<uint32_t>(0x7FFFFFFF), E_biguint_max32 = static_cast<uint32_t>(0xFFFFFFFF), }; VerifySimpleAtoiGood<E_biguint>(E_biguint_zero, E_biguint_zero); VerifySimpleAtoiGood<E_biguint>(E_biguint_one, E_biguint_one); VerifySimpleAtoiGood<E_biguint>(E_biguint_max31, E_biguint_max31); VerifySimpleAtoiGood<E_biguint>(E_biguint_max32, E_biguint_max32); } template <typename int_type, typename in_val_type> void VerifySimpleHexAtoiGood(in_val_type in_value, int_type exp_value) { std::string s; absl::strings_internal::OStringStream strm(&s); if (in_value >= 0) { strm << std::hex << in_value; } else { strm << "-" << std::hex << -absl::uint128(in_value); } int_type x = static_cast<int_type>(~exp_value); EXPECT_TRUE(SimpleHexAtoi(s, &x)) << "in_value=" << std::hex << in_value << " s=" << s << " x=" << x; EXPECT_EQ(exp_value, x); x = static_cast<int_type>(~exp_value); EXPECT_TRUE(SimpleHexAtoi( s.c_str(), &x)); EXPECT_EQ(exp_value, x); } template <typename int_type, typename in_val_type> void VerifySimpleHexAtoiBad(in_val_type in_value) { std::string s; absl::strings_internal::OStringStream strm(&s); if (in_value >= 0) { strm << std::hex << in_value; } else { strm << "-" << std::hex << -absl::uint128(in_value); } int_type x; EXPECT_FALSE(SimpleHexAtoi(s, &x)); EXPECT_FALSE(SimpleHexAtoi( s.c_str(), &x)); } TEST(NumbersTest, HexAtoi) { VerifySimpleHexAtoiGood<int32_t>(0, 0); VerifySimpleHexAtoiGood<int32_t>(0x42, 0x42); VerifySimpleHexAtoiGood<int32_t>(-0x42, -0x42); VerifySimpleHexAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min()); VerifySimpleHexAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleHexAtoiGood<uint32_t>(0, 0); VerifySimpleHexAtoiGood<uint32_t>(0x42, 0x42); VerifySimpleHexAtoiBad<uint32_t>(-0x42); VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min()); VerifySimpleHexAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleHexAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min()); VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max()); VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max()); VerifySimpleHexAtoiGood<int64_t>(0, 0); VerifySimpleHexAtoiGood<int64_t>(0x42, 0x42); VerifySimpleHexAtoiGood<int64_t>(-0x42, -0x42); VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(), std::numeric_limits<int32_t>::min()); VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(), std::numeric_limits<int64_t>::min()); VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()); VerifySimpleHexAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max()); VerifySimpleHexAtoiGood<uint64_t>(0, 0); VerifySimpleHexAtoiGood<uint64_t>(0x42, 0x42); VerifySimpleHexAtoiBad<uint64_t>(-0x42); VerifySimpleHexAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min()); VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleHexAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min()); VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()); VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()); VerifySimpleHexAtoiGood<absl::uint128>(0, 0); VerifySimpleHexAtoiGood<absl::uint128>(0x42, 0x42); VerifySimpleHexAtoiBad<absl::uint128>(-0x42); VerifySimpleHexAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min()); VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max()); VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint32_t>::max()); VerifySimpleHexAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min()); VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()); VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max()); VerifySimpleHexAtoiGood<absl::uint128>( std::numeric_limits<absl::uint128>::max(), std::numeric_limits<absl::uint128>::max()); VerifySimpleHexAtoiGood<int>(-0x42, -0x42); VerifySimpleHexAtoiGood<int32_t>(-0x42, -0x42); VerifySimpleHexAtoiGood<uint32_t>(0x42, 0x42); VerifySimpleHexAtoiGood<unsigned int>(0x42, 0x42); VerifySimpleHexAtoiGood<int64_t>(-0x42, -0x42); VerifySimpleHexAtoiGood<long>(-0x42, -0x42); VerifySimpleHexAtoiGood<uint64_t>(0x42, 0x42); VerifySimpleHexAtoiGood<size_t>(0x42, 0x42); VerifySimpleHexAtoiGood<std::string::size_type>(0x42, 0x42); int32_t value; EXPECT_TRUE(safe_strto32_base("0x34234324", &value, 16)); EXPECT_EQ(0x34234324, value); EXPECT_TRUE(safe_strto32_base("0X34234324", &value, 16)); EXPECT_EQ(0x34234324, value); EXPECT_TRUE(safe_strto32_base(" \t\n 34234324", &value, 16)); EXPECT_EQ(0x34234324, value); EXPECT_TRUE(safe_str
2,561
#ifndef ABSL_STRINGS_STRING_VIEW_H_ #define ABSL_STRINGS_STRING_VIEW_H_ #include <algorithm> #include <cassert> #include <cstddef> #include <cstring> #include <iosfwd> #include <iterator> #include <limits> #include <string> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/base/config.h" #include "absl/base/internal/throw_delegate.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/base/port.h" #ifdef ABSL_USES_STD_STRING_VIEW #include <string_view> namespace absl { ABSL_NAMESPACE_BEGIN using string_view = std::string_view; ABSL_NAMESPACE_END } #else #if ABSL_HAVE_BUILTIN(__builtin_memcmp) || \ (defined(__GNUC__) && !defined(__clang__)) || \ (defined(_MSC_VER) && _MSC_VER >= 1928) #define ABSL_INTERNAL_STRING_VIEW_MEMCMP __builtin_memcmp #else #define ABSL_INTERNAL_STRING_VIEW_MEMCMP memcmp #endif namespace absl { ABSL_NAMESPACE_BEGIN class ABSL_INTERNAL_ATTRIBUTE_VIEW string_view { public: using traits_type = std::char_traits<char>; using value_type = char; using pointer = absl::Nullable<char*>; using const_pointer = absl::Nullable<const char*>; using reference = char&; using const_reference = const char&; using const_iterator = absl::Nullable<const char*>; using iterator = const_iterator; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using reverse_iterator = const_reverse_iterator; using size_type = size_t; using difference_type = std::ptrdiff_t; using absl_internal_is_view = std::true_type; static constexpr size_type npos = static_cast<size_type>(-1); constexpr string_view() noexcept : ptr_(nullptr), length_(0) {} template <typename Allocator> string_view( const std::basic_string<char, std::char_traits<char>, Allocator>& str ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept : string_view(str.data(), str.size(), SkipCheckLengthTag{}) {} constexpr string_view( absl::Nonnull<const char*> str) : ptr_(str), length_(str ? StrlenInternal(str) : 0) {} constexpr string_view(absl::Nullable<const char*> data, size_type len) : ptr_(data), length_(CheckLengthInternal(len)) {} constexpr const_iterator begin() const noexcept { return ptr_; } constexpr const_iterator end() const noexcept { return ptr_ + length_; } constexpr const_iterator cbegin() const noexcept { return begin(); } constexpr const_iterator cend() const noexcept { return end(); } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } const_reverse_iterator crbegin() const noexcept { return rbegin(); } const_reverse_iterator crend() const noexcept { return rend(); } constexpr size_type size() const noexcept { return length_; } constexpr size_type length() const noexcept { return size(); } constexpr size_type max_size() const noexcept { return kMaxSize; } constexpr bool empty() const noexcept { return length_ == 0; } constexpr const_reference operator[](size_type i) const { return ABSL_HARDENING_ASSERT(i < size()), ptr_[i]; } constexpr const_reference at(size_type i) const { return ABSL_PREDICT_TRUE(i < size()) ? ptr_[i] : ((void)base_internal::ThrowStdOutOfRange( "absl::string_view::at"), ptr_[i]); } constexpr const_reference front() const { return ABSL_HARDENING_ASSERT(!empty()), ptr_[0]; } constexpr const_reference back() const { return ABSL_HARDENING_ASSERT(!empty()), ptr_[size() - 1]; } constexpr const_pointer data() const noexcept { return ptr_; } constexpr void remove_prefix(size_type n) { ABSL_HARDENING_ASSERT(n <= length_); ptr_ += n; length_ -= n; } constexpr void remove_suffix(size_type n) { ABSL_HARDENING_ASSERT(n <= length_); length_ -= n; } constexpr void swap(string_view& s) noexcept { auto t = *this; *this = s; s = t; } template <typename A> explicit operator std::basic_string<char, traits_type, A>() const { if (!data()) return {}; return std::basic_string<char, traits_type, A>(data(), size()); } size_type copy(char* buf, size_type n, size_type pos = 0) const { if (ABSL_PREDICT_FALSE(pos > length_)) { base_internal::ThrowStdOutOfRange("absl::string_view::copy"); } size_type rlen = (std::min)(length_ - pos, n); if (rlen > 0) { const char* start = ptr_ + pos; traits_type::copy(buf, start, rlen); } return rlen; } constexpr string_view substr(size_type pos = 0, size_type n = npos) const { return ABSL_PREDICT_FALSE(pos > length_) ? (base_internal::ThrowStdOutOfRange( "absl::string_view::substr"), string_view()) : string_view(ptr_ + pos, Min(n, length_ - pos)); } constexpr int compare(string_view x) const noexcept { return CompareImpl(length_, x.length_, Min(length_, x.length_) == 0 ? 0 : ABSL_INTERNAL_STRING_VIEW_MEMCMP( ptr_, x.ptr_, Min(length_, x.length_))); } constexpr int compare(size_type pos1, size_type count1, string_view v) const { return substr(pos1, count1).compare(v); } constexpr int compare(size_type pos1, size_type count1, string_view v, size_type pos2, size_type count2) const { return substr(pos1, count1).compare(v.substr(pos2, count2)); } constexpr int compare(absl::Nonnull<const char*> s) const { return compare(string_view(s)); } constexpr int compare(size_type pos1, size_type count1, absl::Nonnull<const char*> s) const { return substr(pos1, count1).compare(string_view(s)); } constexpr int compare(size_type pos1, size_type count1, absl::Nonnull<const char*> s, size_type count2) const { return substr(pos1, count1).compare(string_view(s, count2)); } size_type find(string_view s, size_type pos = 0) const noexcept; size_type find(char c, size_type pos = 0) const noexcept; size_type find(absl::Nonnull<const char*> s, size_type pos, size_type count) const { return find(string_view(s, count), pos); } size_type find(absl::Nonnull<const char *> s, size_type pos = 0) const { return find(string_view(s), pos); } size_type rfind(string_view s, size_type pos = npos) const noexcept; size_type rfind(char c, size_type pos = npos) const noexcept; size_type rfind(absl::Nonnull<const char*> s, size_type pos, size_type count) const { return rfind(string_view(s, count), pos); } size_type rfind(absl::Nonnull<const char*> s, size_type pos = npos) const { return rfind(string_view(s), pos); } size_type find_first_of(string_view s, size_type pos = 0) const noexcept; size_type find_first_of(char c, size_type pos = 0) const noexcept { return find(c, pos); } size_type find_first_of(absl::Nonnull<const char*> s, size_type pos, size_type count) const { return find_first_of(string_view(s, count), pos); } size_type find_first_of(absl::Nonnull<const char*> s, size_type pos = 0) const { return find_first_of(string_view(s), pos); } size_type find_last_of(string_view s, size_type pos = npos) const noexcept; size_type find_last_of(char c, size_type pos = npos) const noexcept { return rfind(c, pos); } size_type find_last_of(absl::Nonnull<const char*> s, size_type pos, size_type count) const { return find_last_of(string_view(s, count), pos); } size_type find_last_of(absl::Nonnull<const char*> s, size_type pos = npos) const { return find_last_of(string_view(s), pos); } size_type find_first_not_of(string_view s, size_type pos = 0) const noexcept; size_type find_first_not_of(char c, size_type pos = 0) const noexcept; size_type find_first_not_of(absl::Nonnull<const char*> s, size_type pos, size_type count) const { return find_first_not_of(string_view(s, count), pos); } size_type find_first_not_of(absl::Nonnull<const char*> s, size_type pos = 0) const { return find_first_not_of(string_view(s), pos); } size_type find_last_not_of(string_view s, size_type pos = npos) const noexcept; size_type find_last_not_of(char c, size_type pos = npos) const noexcept; size_type find_last_not_of(absl::Nonnull<const char*> s, size_type pos, size_type count) const { return find_last_not_of(string_view(s, count), pos); } size_type find_last_not_of(absl::Nonnull<const char*> s, size_type pos = npos) const { return find_last_not_of(string_view(s), pos); } #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L constexpr bool starts_with(string_view s) const noexcept { return s.empty() || (size() >= s.size() && ABSL_INTERNAL_STRING_VIEW_MEMCMP(data(), s.data(), s.size()) == 0); } constexpr bool starts_with(char c) const noexcept { return !empty() && front() == c; } constexpr bool starts_with(const char* s) const { return starts_with(string_view(s)); } constexpr bool ends_with(string_view s) const noexcept { return s.empty() || (size() >= s.size() && ABSL_INTERNAL_STRING_VIEW_MEMCMP( data() + (size() - s.size()), s.data(), s.size()) == 0); } constexpr bool ends_with(char c) const noexcept { return !empty() && back() == c; } constexpr bool ends_with(const char* s) const { return ends_with(string_view(s)); } #endif private: struct SkipCheckLengthTag {}; string_view(absl::Nullable<const char*> data, size_type len, SkipCheckLengthTag) noexcept : ptr_(data), length_(len) {} static constexpr size_type kMaxSize = (std::numeric_limits<difference_type>::max)(); static constexpr size_type CheckLengthInternal(size_type len) { return ABSL_HARDENING_ASSERT(len <= kMaxSize), len; } static constexpr size_type StrlenInternal(absl::Nonnull<const char*> str) { #if defined(_MSC_VER) && !defined(__clang__) const char* begin = str; while (*str != '\0') ++str; return str - begin; #elif ABSL_HAVE_BUILTIN(__builtin_strlen) || \ (defined(__GNUC__) && !defined(__clang__)) return __builtin_strlen(str); #else return str ? strlen(str) : 0; #endif } static constexpr size_t Min(size_type length_a, size_type length_b) { return length_a < length_b ? length_a : length_b; } static constexpr int CompareImpl(size_type length_a, size_type length_b, int compare_result) { return compare_result == 0 ? static_cast<int>(length_a > length_b) - static_cast<int>(length_a < length_b) : (compare_result < 0 ? -1 : 1); } absl::Nullable<const char*> ptr_; size_type length_; }; constexpr bool operator==(string_view x, string_view y) noexcept { return x.size() == y.size() && (x.empty() || ABSL_INTERNAL_STRING_VIEW_MEMCMP(x.data(), y.data(), x.size()) == 0); } constexpr bool operator!=(string_view x, string_view y) noexcept { return !(x == y); } constexpr bool operator<(string_view x, string_view y) noexcept { return x.compare(y) < 0; } constexpr bool operator>(string_view x, string_view y) noexcept { return y < x; } constexpr bool operator<=(string_view x, string_view y) noexcept { return !(y < x); } constexpr bool operator>=(string_view x, string_view y) noexcept { return !(x < y); } std::ostream& operator<<(std::ostream& o, string_view piece); ABSL_NAMESPACE_END } #undef ABSL_INTERNAL_STRING_VIEW_MEMCMP #endif namespace absl { ABSL_NAMESPACE_BEGIN inline string_view ClippedSubstr(string_view s, size_t pos, size_t n = string_view::npos) { pos = (std::min)(pos, static_cast<size_t>(s.size())); return s.substr(pos, n); } constexpr string_view NullSafeStringView(absl::Nullable<const char*> p) { return p ? string_view(p) : string_view(); } ABSL_NAMESPACE_END } #endif #include "absl/strings/string_view.h" #ifndef ABSL_USES_STD_STRING_VIEW #include <algorithm> #include <climits> #include <cstring> #include <ostream> #include "absl/base/nullability.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { absl::Nullable<const char*> memmatch(absl::Nullable<const char*> phaystack, size_t haylen, absl::Nullable<const char*> pneedle, size_t neelen) { if (0 == neelen) { return phaystack; } if (haylen < neelen) return nullptr; const char* match; const char* hayend = phaystack + haylen - neelen + 1; while ( (match = static_cast<const char*>(memchr( phaystack, pneedle[0], static_cast<size_t>(hayend - phaystack))))) { if (memcmp(match, pneedle, neelen) == 0) return match; else phaystack = match + 1; } return nullptr; } void WritePadding(std::ostream& o, size_t pad) { char fill_buf[32]; memset(fill_buf, o.fill(), sizeof(fill_buf)); while (pad) { size_t n = std::min(pad, sizeof(fill_buf)); o.write(fill_buf, static_cast<std::streamsize>(n)); pad -= n; } } class LookupTable { public: explicit LookupTable(string_view wanted) { for (char c : wanted) { table_[Index(c)] = true; } } bool operator[](char c) const { return table_[Index(c)]; } private: static unsigned char Index(char c) { return static_cast<unsigned char>(c); } bool table_[UCHAR_MAX + 1] = {}; }; } std::ostream& operator<<(std::ostream& o, string_view piece) { std::ostream::sentry sentry(o); if (sentry) { size_t lpad = 0; size_t rpad = 0; if (static_cast<size_t>(o.width()) > piece.size()) { size_t pad = static_cast<size_t>(o.width()) - piece.size(); if ((o.flags() & o.adjustfield) == o.left) { rpad = pad; } else { lpad = pad; } } if (lpad) WritePadding(o, lpad); o.write(piece.data(), static_cast<std::streamsize>(piece.size())); if (rpa
#include "absl/strings/string_view.h" #include <stdlib.h> #include <cstddef> #include <cstdlib> #include <cstring> #include <iomanip> #include <ios> #include <iterator> #include <limits> #include <map> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/meta/type_traits.h" #if defined(ABSL_HAVE_STD_STRING_VIEW) || defined(__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 { static_assert(!absl::type_traits_internal::IsOwner<absl::string_view>::value && absl::type_traits_internal::IsView<absl::string_view>::value, "string_view is a view, not an owner"); static_assert(absl::type_traits_internal::IsLifetimeBoundAssignment< absl::string_view, std::string>::value, "lifetimebound assignment not detected"); template <typename T> struct Mallocator { typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; size_type max_size() const { return size_t(std::numeric_limits<size_type>::max()) / sizeof(value_type); } template <typename U> struct rebind { typedef Mallocator<U> other; }; Mallocator() = default; template <class U> Mallocator(const Mallocator<U>&) {} T* allocate(size_t n) { return static_cast<T*>(std::malloc(n * sizeof(T))); } void deallocate(T* p, size_t) { std::free(p); } }; template <typename T, typename U> bool operator==(const Mallocator<T>&, const Mallocator<U>&) { return true; } template <typename T, typename U> bool operator!=(const Mallocator<T>&, const Mallocator<U>&) { return false; } TEST(StringViewTest, Ctor) { { absl::string_view s10; EXPECT_TRUE(s10.data() == nullptr); EXPECT_EQ(0u, s10.length()); } { const char* hello = "hello"; absl::string_view s20(hello); EXPECT_TRUE(s20.data() == hello); EXPECT_EQ(5u, s20.length()); absl::string_view s21(hello, 4); EXPECT_TRUE(s21.data() == hello); EXPECT_EQ(4u, s21.length()); absl::string_view s22(hello, 6); EXPECT_TRUE(s22.data() == hello); EXPECT_EQ(6u, s22.length()); } { std::string hola = "hola"; absl::string_view s30(hola); EXPECT_TRUE(s30.data() == hola.data()); EXPECT_EQ(4u, s30.length()); hola.push_back('\0'); hola.append("h2"); hola.push_back('\0'); absl::string_view s31(hola); EXPECT_TRUE(s31.data() == hola.data()); EXPECT_EQ(8u, s31.length()); } { using mstring = std::basic_string<char, std::char_traits<char>, Mallocator<char>>; mstring str1("BUNGIE-JUMPING!"); const mstring str2("SLEEPING!"); absl::string_view s1(str1); s1.remove_prefix(strlen("BUNGIE-JUM")); absl::string_view s2(str2); s2.remove_prefix(strlen("SLEE")); EXPECT_EQ(s1, s2); EXPECT_EQ(s1, "PING!"); } } TEST(StringViewTest, Swap) { absl::string_view a("a"); absl::string_view b("bbb"); EXPECT_TRUE(noexcept(a.swap(b))); a.swap(b); EXPECT_EQ(a, "bbb"); EXPECT_EQ(b, "a"); a.swap(b); EXPECT_EQ(a, "a"); EXPECT_EQ(b, "bbb"); } TEST(StringViewTest, STLComparator) { std::string s1("foo"); std::string s2("bar"); std::string s3("baz"); absl::string_view p1(s1); absl::string_view p2(s2); absl::string_view p3(s3); typedef std::map<absl::string_view, int> TestMap; TestMap map; map.insert(std::make_pair(p1, 0)); map.insert(std::make_pair(p2, 1)); map.insert(std::make_pair(p3, 2)); EXPECT_EQ(map.size(), 3u); TestMap::const_iterator iter = map.begin(); EXPECT_EQ(iter->second, 1); ++iter; EXPECT_EQ(iter->second, 2); ++iter; EXPECT_EQ(iter->second, 0); ++iter; EXPECT_TRUE(iter == map.end()); TestMap::iterator new_iter = map.find("zot"); EXPECT_TRUE(new_iter == map.end()); new_iter = map.find("bar"); EXPECT_TRUE(new_iter != map.end()); map.erase(new_iter); EXPECT_EQ(map.size(), 2u); iter = map.begin(); EXPECT_EQ(iter->second, 2); ++iter; EXPECT_EQ(iter->second, 0); ++iter; EXPECT_TRUE(iter == map.end()); } #define COMPARE(result, op, x, y) \ EXPECT_EQ(result, absl::string_view((x)) op absl::string_view((y))); \ EXPECT_EQ(result, absl::string_view((x)).compare(absl::string_view((y))) op 0) TEST(StringViewTest, ComparisonOperators) { COMPARE(true, ==, "", ""); COMPARE(true, ==, "", absl::string_view()); COMPARE(true, ==, absl::string_view(), ""); COMPARE(true, ==, "a", "a"); COMPARE(true, ==, "aa", "aa"); COMPARE(false, ==, "a", ""); COMPARE(false, ==, "", "a"); COMPARE(false, ==, "a", "b"); COMPARE(false, ==, "a", "aa"); COMPARE(false, ==, "aa", "a"); COMPARE(false, !=, "", ""); COMPARE(false, !=, "a", "a"); COMPARE(false, !=, "aa", "aa"); COMPARE(true, !=, "a", ""); COMPARE(true, !=, "", "a"); COMPARE(true, !=, "a", "b"); COMPARE(true, !=, "a", "aa"); COMPARE(true, !=, "aa", "a"); COMPARE(true, <, "a", "b"); COMPARE(true, <, "a", "aa"); COMPARE(true, <, "aa", "b"); COMPARE(true, <, "aa", "bb"); COMPARE(false, <, "a", "a"); COMPARE(false, <, "b", "a"); COMPARE(false, <, "aa", "a"); COMPARE(false, <, "b", "aa"); COMPARE(false, <, "bb", "aa"); COMPARE(true, <=, "a", "a"); COMPARE(true, <=, "a", "b"); COMPARE(true, <=, "a", "aa"); COMPARE(true, <=, "aa", "b"); COMPARE(true, <=, "aa", "bb"); COMPARE(false, <=, "b", "a"); COMPARE(false, <=, "aa", "a"); COMPARE(false, <=, "b", "aa"); COMPARE(false, <=, "bb", "aa"); COMPARE(false, >=, "a", "b"); COMPARE(false, >=, "a", "aa"); COMPARE(false, >=, "aa", "b"); COMPARE(false, >=, "aa", "bb"); COMPARE(true, >=, "a", "a"); COMPARE(true, >=, "b", "a"); COMPARE(true, >=, "aa", "a"); COMPARE(true, >=, "b", "aa"); COMPARE(true, >=, "bb", "aa"); COMPARE(false, >, "a", "a"); COMPARE(false, >, "a", "b"); COMPARE(false, >, "a", "aa"); COMPARE(false, >, "aa", "b"); COMPARE(false, >, "aa", "bb"); COMPARE(true, >, "b", "a"); COMPARE(true, >, "aa", "a"); COMPARE(true, >, "b", "aa"); COMPARE(true, >, "bb", "aa"); } TEST(StringViewTest, ComparisonOperatorsByCharacterPosition) { std::string x; for (size_t i = 0; i < 256; i++) { x += 'a'; std::string y = x; COMPARE(true, ==, x, y); for (size_t j = 0; j < i; j++) { std::string z = x; z[j] = 'b'; COMPARE(false, ==, x, z); COMPARE(true, <, x, z); COMPARE(true, >, z, x); if (j + 1 < i) { z[j + 1] = 'A'; COMPARE(false, ==, x, z); COMPARE(true, <, x, z); COMPARE(true, >, z, x); z[j + 1] = 'z'; COMPARE(false, ==, x, z); COMPARE(true, <, x, z); COMPARE(true, >, z, x); } } } } #undef COMPARE template <typename T> struct is_type { template <typename U> static bool same(U) { return false; } static bool same(T) { return true; } }; TEST(StringViewTest, NposMatchesStdStringView) { EXPECT_EQ(absl::string_view::npos, std::string::npos); EXPECT_TRUE(is_type<size_t>::same(absl::string_view::npos)); EXPECT_FALSE(is_type<size_t>::same("")); char test[absl::string_view::npos & 1] = {0}; EXPECT_EQ(0, test[0]); } TEST(StringViewTest, STL1) { const absl::string_view a("abcdefghijklmnopqrstuvwxyz"); const absl::string_view b("abc"); const absl::string_view c("xyz"); const absl::string_view d("foobar"); const absl::string_view e; std::string temp("123"); temp += '\0'; temp += "456"; const absl::string_view f(temp); EXPECT_EQ(a[6], 'g'); EXPECT_EQ(b[0], 'a'); EXPECT_EQ(c[2], 'z'); EXPECT_EQ(f[3], '\0'); EXPECT_EQ(f[5], '5'); EXPECT_EQ(*d.data(), 'f'); EXPECT_EQ(d.data()[5], 'r'); EXPECT_TRUE(e.data() == nullptr); EXPECT_EQ(*a.begin(), 'a'); EXPECT_EQ(*(b.begin() + 2), 'c'); EXPECT_EQ(*(c.end() - 1), 'z'); EXPECT_EQ(*a.rbegin(), 'z'); EXPECT_EQ(*(b.rbegin() + 2), 'a'); EXPECT_EQ(*(c.rend() - 1), 'x'); EXPECT_TRUE(a.rbegin() + 26 == a.rend()); EXPECT_EQ(a.size(), 26u); EXPECT_EQ(b.size(), 3u); EXPECT_EQ(c.size(), 3u); EXPECT_EQ(d.size(), 6u); EXPECT_EQ(e.size(), 0u); EXPECT_EQ(f.size(), 7u); EXPECT_TRUE(!d.empty()); EXPECT_TRUE(d.begin() != d.end()); EXPECT_TRUE(d.begin() + 6 == d.end()); EXPECT_TRUE(e.empty()); EXPECT_TRUE(e.begin() == e.end()); char buf[4] = { '%', '%', '%', '%' }; EXPECT_EQ(a.copy(buf, 4), 4u); EXPECT_EQ(buf[0], a[0]); EXPECT_EQ(buf[1], a[1]); EXPECT_EQ(buf[2], a[2]); EXPECT_EQ(buf[3], a[3]); EXPECT_EQ(a.copy(buf, 3, 7), 3u); EXPECT_EQ(buf[0], a[7]); EXPECT_EQ(buf[1], a[8]); EXPECT_EQ(buf[2], a[9]); EXPECT_EQ(buf[3], a[3]); EXPECT_EQ(c.copy(buf, 99), 3u); EXPECT_EQ(buf[0], c[0]); EXPECT_EQ(buf[1], c[1]); EXPECT_EQ(buf[2], c[2]); EXPECT_EQ(buf[3], a[3]); #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW(a.copy(buf, 1, 27), std::out_of_range); #else ABSL_EXPECT_DEATH_IF_SUPPORTED(a.copy(buf, 1, 27), "absl::string_view::copy"); #endif } TEST(StringViewTest, STL2) { const absl::string_view a("abcdefghijklmnopqrstuvwxyz"); const absl::string_view b("abc"); const absl::string_view c("xyz"); absl::string_view d("foobar"); const absl::string_view e; const absl::string_view f( "123" "\0" "456", 7); d = absl::string_view(); EXPECT_EQ(d.size(), 0u); EXPECT_TRUE(d.empty()); EXPECT_TRUE(d.data() == nullptr); EXPECT_TRUE(d.begin() == d.end()); EXPECT_EQ(a.find(b), 0u); EXPECT_EQ(a.find(b, 1), absl::string_view::npos); EXPECT_EQ(a.find(c), 23u); EXPECT_EQ(a.find(c, 9), 23u); EXPECT_EQ(a.find(c, absl::string_view::npos), absl::string_view::npos); EXPECT_EQ(b.find(c), absl::string_view::npos); EXPECT_EQ(b.find(c, absl::string_view::npos), absl::string_view::npos); EXPECT_EQ(a.find(d), 0u); EXPECT_EQ(a.find(e), 0u); EXPECT_EQ(a.find(d, 12), 12u); EXPECT_EQ(a.find(e, 17), 17u); absl::string_view g("xx not found bb"); EXPECT_EQ(a.find(g), absl::string_view::npos); EXPECT_EQ(d.find(b), absl::string_view::npos); EXPECT_EQ(e.find(b), absl::string_view::npos); EXPECT_EQ(d.find(b, 4), absl::string_view::npos); EXPECT_EQ(e.find(b, 7), absl::string_view::npos); size_t empty_search_pos = std::string().find(std::string()); EXPECT_EQ(d.find(d), empty_search_pos); EXPECT_EQ(d.find(e), empty_search_pos); EXPECT_EQ(e.find(d), empty_search_pos); EXPECT_EQ(e.find(e), empty_search_pos); EXPECT_EQ(d.find(d, 4), std::string().find(std::string(), 4)); EXPECT_EQ(d.find(e, 4), std::string().find(std::string(), 4)); EXPECT_EQ(e.find(d, 4), std::string().find(std::string(), 4)); EXPECT_EQ(e.find(e, 4), std::string().find(std::string(), 4)); EXPECT_EQ(a.find('a'), 0u); EXPECT_EQ(a.find('c'), 2u); EXPECT_EQ(a.find('z'), 25u); EXPECT_EQ(a.find('$'), absl::string_view::npos); EXPECT_EQ(a.find('\0'), absl::string_view::npos); EXPECT_EQ(f.find('\0'), 3u); EXPECT_EQ(f.find('3'), 2u); EXPECT_EQ(f.find('5'), 5u); EXPECT_EQ(g.find('o'), 4u); EXPECT_EQ(g.find('o', 4), 4u); EXPECT_EQ(g.find('o', 5), 8u); EXPECT_EQ(a.find('b', 5), absl::string_view::npos); EXPECT_EQ(d.find('\0'), absl::string_view::npos); EXPECT_EQ(e.find('\0'), absl::string_view::npos); EXPECT_EQ(d.find('\0', 4), absl::string_view::npos); EXPECT_EQ(e.find('\0', 7), absl::string_view::npos); EXPECT_EQ(d.find('x'), absl::string_view::npos); EXPECT_EQ(e.find('x'), absl::string_view::npos); EXPECT_EQ(d.find('x', 4), absl::string_view::npos); EXPECT_EQ(e.find('x', 7), absl::string_view::npos); EXPECT_EQ(a.find(b.data(), 1, 0), 1u); EXPECT_EQ(a.find(c.data(), 9, 0), 9u); EXPECT_EQ(a.find(c.data(), absl::string_view::npos, 0), absl::string_view::npos); EXPECT_EQ(b.find(c.data(), absl::string_view::npos, 0), absl::string_view::npos); EXPECT_EQ(d.find(b.data(), 4, 0), absl::string_view::npos); EXPECT_EQ(e.find(b.data(), 7, 0), absl::string_view::npos); EXPECT_EQ(a.find(b.data(), 1), absl::string_view::npos); EXPECT_EQ(a.find(c.data(), 9), 23u); EXPECT_EQ(a.find(c.data(), absl::string_view::npos), absl::string_view::npos); EXPECT_EQ(b.find(c.data(), absl::string_view::npos), absl::string_view::npos); EXPECT_EQ(d.find(b.data(), 4), absl::string_view::npos); EXPECT_EQ(e.find(b.data(), 7), absl::string_view::npos); EXPECT_EQ(a.rfind(b), 0u); EXPECT_EQ(a.rfind(b, 1), 0u); EXPECT_EQ(a.rfind(c), 23u); EXPECT_EQ(a.rfind(c, 22), absl::string_view::npos); EXPECT_EQ(a.rfind(c, 1), absl::string_view::npos); EXPECT_EQ(a.rfind(c, 0), absl::string_view::npos); EXPECT_EQ(b.rfind(c), absl::string_view::npos); EXPECT_EQ(b.rfind(c, 0), absl::string_view::npos); EXPECT_EQ(a.rfind(d), std::string(a).rfind(std::string())); EXPECT_EQ(a.rfind(e), std::string(a).rfind(std::string())); EXPECT_EQ(a.rfind(d, 12), 12u); EXPECT_EQ(a.rfind(e, 17), 17u); EXPECT_EQ(a.rfind(g), absl::string_view::npos); EXPECT_EQ(d.rfind(b), absl::string_view::npos); EXPECT_EQ(e.rfind(b), absl::string_view::npos); EXPECT_EQ(d.rfind(b, 4), absl::string_view::npos); EXPECT_EQ(e.rfind(b, 7), absl::string_view::npos); EXPECT_EQ(d.rfind(d, 4), std::string().rfind(std::string())); EXPECT_EQ(e.rfind(d, 7), std::string().rfind(std::string())); EXPECT_EQ(d.rfind(e, 4), std::string().rfind(std::string())); EXPECT_EQ(e.rfind(e, 7), std::string().rfind(std::string())); EXPECT_EQ(d.rfind(d), std::string().rfind(std::string())); EXPECT_EQ(e.rfind(d), std::string().rfind(std::string())); EXPECT_EQ(d.rfind(e), std::string().rfind(std::string())); EXPECT_EQ(e.rfind(e), std::string().rfind(std::string())); EXPECT_EQ(g.rfind('o'), 8u); EXPECT_EQ(g.rfind('q'), absl::string_view::npos); EXPECT_EQ(g.rfind('o', 8), 8u); EXPECT_EQ(g.rfind('o', 7), 4u); EXPECT_EQ(g.rfind('o', 3), absl::string_view::npos); EXPECT_EQ(f.rfind('\0'), 3u); EXPECT_EQ(f.rfind('\0', 12), 3u); EXPECT_EQ(f.rfind('3'), 2u); EXPECT_EQ(f.rfind('5'), 5u); EXPECT_EQ(d.rfind('o'), absl::string_view::npos); EXPECT_EQ(e.rfind('o'), absl::string_view::npos); EXPECT_EQ(d.rfind('o', 4), absl::string_view::npos); EXPECT_EQ(e.rfind('o', 7), absl::string_view::npos); EXPECT_EQ(a.rfind(b.data(), 1, 0), 1u); EXPECT_EQ(a.rfind(c.data(), 22, 0), 22u); EXPECT_EQ(a.rfind(c.data(), 1, 0), 1u); EXPECT_EQ(a.rfind(c.data(), 0, 0), 0u); EXPECT_EQ(b.rfind(c.data(), 0, 0), 0u); EXPECT_EQ(d.rfind(b.data(), 4, 0), 0u); EXPECT_EQ(e.rfind(b.data(), 7, 0), 0u); } TEST(StringViewTest, STL2FindFirst) { const absl::string_view a("abcdefghijklmnopqrstuvwxyz"); const absl::string_view b("abc"); const absl::string_view c("xyz"); absl::string_view d("foobar"); const absl::string_view e; const absl::string_view f( "123" "\0" "456", 7); absl::string_view g("xx not found bb"); d = absl::string_view(); EXPECT_EQ(a.find_first_of(b), 0u); EXPECT_EQ(a.find_first_of(b, 0), 0u); EXPECT_EQ(a.find_first_of(b, 1), 1u); EXPECT_EQ(a.find_first_of(b, 2), 2u); EXPECT_EQ(a.find_first_of(b, 3), absl::string_view::npos); EXPECT_EQ(a.find_first_of(c), 23u); EXPECT_EQ(a.find_first_of(c, 23), 23u); EXPECT_EQ(a.find_first_of(c, 24), 24u); EXPECT_EQ(a.find_first_of(c, 25), 25u); EXPECT_EQ(a.find_first_of(c, 26), absl::string_view::npos); EXPECT_EQ(g.find_first_of(b), 13u); EXPECT_EQ(g.find_first_of(c), 0u); EXPECT_EQ(a.find_first_of(f), absl::string_view::npos); EXPECT_EQ(f.find_first_of(a), absl::string_view::npos); EXPECT_EQ(a.find_first_of(d), absl::string_view::npos); EXPECT_EQ(a.find_first_of(e), absl::string_view::npos); EXPECT_EQ(d.find_first_of(b), absl::string_view::npos); EXPECT_EQ(e.find_first_of(b), absl::string_view::npos); EXPECT_EQ(d.find_first_of(d), absl::string_view::npos); EXPECT_EQ(e.find_first_of(d), absl::string_view::npos); EXPECT_EQ(d.find_first_of(e), absl::string_view::npos); EXPECT_EQ(e.find_first_of(e), absl::string_view::npos); EXPECT_EQ(a.find_first_not_of(b), 3u); EXPECT_EQ(a.find_first_not_of(c), 0u); EXPECT_EQ(b.find_first_not_of(a), absl::string_view::npos); EXPECT_EQ(c.find_first_not_of(a), absl::string_view::npos); EXPECT_EQ(f.find_first_not_of(a), 0u); EXPECT_EQ(a.find_first_not_of(f), 0u); EXPECT_EQ(a.find_first_not_of(d), 0u); EXPECT_EQ(a.find_first_not_of(e), 0u); EXPECT_EQ(a.find_first_not_of(d), 0u); EXPECT_EQ(a.find_first_not_of(e), 0u); EXPECT_EQ(a.find_first_not_of(d, 1), 1u); EXPECT_EQ(a.find_first_not_of(e, 1), 1u); EXPECT_EQ(a.find_first_not_of(d, a.size() - 1), a.size() - 1); EXPECT_EQ(a.find_first_not_of(e, a.size() - 1), a.size() - 1); EXPECT_EQ(a.find_first_not_of(d, a.size()), absl::string_view::npos); EXPECT_EQ(a.find_first_not_of(e, a.size()), absl::string_view::npos); EXPECT_EQ(a.find_first_not_of(d, absl::string_view::npos), absl::string_view::npos); EXPECT_EQ(a.find_first_not_of(e, absl::string_view::npos), absl::string_view::npos); EXPECT_EQ(d.find_first_not_of(a), absl::string_view::npos); EXPECT_EQ(e.find_first_not_of(a), absl::string_view::npos); EXPECT_EQ(d.find_first_not_of(d), absl::string_view::npos); EXPECT_EQ(e.find_first_not_of(d), absl::string_view::npos); EXPECT_EQ(d.find_first_not_of(e), absl::string_view::npos); EXPECT_EQ(e.find_first_not_of(e), absl::string_view::npos); absl::string_view h("===="); EXPECT_EQ(h.find_first_not_of('='), absl::string_view::npos); EXPECT_EQ(h.find_first_not_of('=', 3), absl::string_view::npos); EXPECT_EQ(h.find_first_not_of('\0'), 0u); EXPECT_EQ(g.find_first_not_of('x'), 2u); EXPECT_EQ(f.find_first_not_of('\0'), 0u); EXPECT_EQ(f.find_first_not_of('\0', 3), 4u); EXPECT_EQ(f.find_first_not_of('\0', 2), 2u); EXPECT_EQ(d.find_first_not_of('x'), absl::string_view::npos); EXPECT_EQ(e.find_first_not_of('x'), absl::string_view::npos); EXPECT_EQ(d.find_first_not_of('\0'), absl::string_view::npos); EXPECT_EQ(e.find_first_not_of('\0'), absl::string_view::npos); } TEST(StringViewTest, STL2FindLast) { const absl::string_view a("abcdefghijklmnopqrstuvwxyz"); const absl::string_view b("abc"); const absl::string_view c("xyz"); absl::string_view d("foobar"); const absl::string_view e; const absl::string_view f( "123" "\0" "456", 7); absl::string_view g("xx not found bb"); absl::string_view h("===="); absl::string_view i("56"); d = absl::string_view(); EXPECT_EQ(h.find_last_of(a), absl::string_view::npos); EXPECT_EQ(g.find_last_of(a), g.size() - 1); EXPECT_EQ(a.find_last_of(b), 2u); EXPECT_EQ(a.find_last_of(c), a.size() - 1); EXPECT_EQ(f.find_last_of(i), 6u); EXPECT_EQ(a.find_last_of('a'), 0u); EXPECT_EQ(a.find_last_of('b'), 1u); EXPECT_EQ(a.find_last_of('z'), 25u); EXPECT_EQ(a.find_last_of('a', 5), 0u); EXPECT_EQ(a.find_last_of('b', 5), 1u); EXPECT_EQ(a.find_last_of('b', 0), absl::string_view::npos); EXPECT_EQ(a.find_last_of('z', 25), 25u); EXPECT_EQ(a.find_last_of('z', 24), absl::string_view::npos); EXPECT_EQ(f.find_last_of(i, 5), 5u); EXPECT_EQ(f.find_last_of(i, 6), 6u); EXPECT_EQ(f.find_last_of(a, 4), absl::string_view::npos); EXPECT_EQ(f.find_last_of(d), absl::string_view::npos); EXPECT_EQ(f.find_last_of(e), absl::string_view::npos); EXPECT_EQ(f.find_last_of(d, 4), absl::string_view::npos); EXPECT_EQ(f.find_last_of(e, 4), absl::string_view::npos); EXPECT_EQ(d.find_last_of(d), absl::string_view::npos); EXPECT_EQ(d.find_last_of(e), absl::string_view::npos); EXPECT_EQ(e.find_last_of(d), absl::string_view::npos); EXPECT_EQ(e.find_last_of(e), absl::string_view::npos); EXPECT_EQ(d.find_last_of(f), absl::string_view::npos); EXPECT_EQ(e.find_last_of(f), absl::string_view::npos); EXPECT_EQ(d.find_last_of(d, 4), absl::string_view::npos); EXPECT_EQ(d.find_last_of(e, 4), absl::string_view::npos); EXPECT_EQ(e.find_last_of(d, 4), absl::string_view::npos); EXPECT_EQ(e.find_last_of(e, 4), absl::string_view::npos); EXPECT_EQ(d.find_last_of(f, 4), absl::string_view::npos); EXPECT_EQ(e.find_last_of(f, 4), absl::string_view::npos); EXPECT_EQ(a.find_last_not_of(b), a.size() - 1); EXPECT_EQ(a.find_last_not_of(c), 22u); EXPECT_EQ(b.find_last_not_of(a), absl::string_view::npos); EXPECT_EQ(b.find_last_not_of(b), absl::string_view::npos); EXPECT_EQ(f.find_last_not_of(i), 4u); EXPECT_EQ(a.find_last_not_of(c, 24), 22u); EXPECT_EQ(a.find_last_not_of(b, 3), 3u); EXPECT_EQ(a.find_last_not_of(b, 2), absl::string_view::npos); EXPECT_EQ(f.find_last_not_of(d), f.size() - 1); EXPECT_EQ(f.find_last_not_of(e), f.size() - 1); EXPECT_EQ(f.find_last_not_of(d, 4), 4u); EXPECT_EQ(f.find_last_not_of(e, 4), 4u); EXPECT_EQ(d.find_last_not_of(d), absl::string_view::npos); EXPECT_EQ(d.find_last_not_of(e), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of(d), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of(e), absl::string_view::npos); EXPECT_EQ(d.find_last_not_of(f), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of(f), absl::string_view::npos); EXPECT_EQ(d.find_last_not_of(d, 4), absl::string_view::npos); EXPECT_EQ(d.find_last_not_of(e, 4), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of(d, 4), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of(e, 4), absl::string_view::npos); EXPECT_EQ(d.find_last_not_of(f, 4), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of(f, 4), absl::string_view::npos); EXPECT_EQ(h.find_last_not_of('x'), h.size() - 1); EXPECT_EQ(h.find_last_not_of('='), absl::string_view::npos); EXPECT_EQ(b.find_last_not_of('c'), 1u); EXPECT_EQ(h.find_last_not_of('x', 2), 2u); EXPECT_EQ(h.find_last_not_of('=', 2), absl::string_view::npos); EXPECT_EQ(b.find_last_not_of('b', 1), 0u); EXPECT_EQ(d.find_last_not_of('x'), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of('x'), absl::string_view::npos); EXPECT_EQ(d.find_last_not_of('\0'), absl::string_view::npos); EXPECT_EQ(e.find_last_not_of('\0'), absl::string_view::npos); } TEST(StringViewTest, STL2Substr) { const absl::string_view a("abcdefghijklmnopqrstuvwxyz"); const absl::string_view b("abc"); const absl::string_view c("xyz"); absl::string_view d("foobar"); const absl::string_view e; d = absl::string_view(); EXPECT_EQ(a.substr(0, 3), b); EXPECT_EQ(a.substr(23), c); EXPECT_EQ(a.substr(23, 3), c); EXPECT_EQ(a.substr(23, 99), c); EXPECT_EQ(a.substr(0), a); EXPECT_EQ(a.substr(), a); EXPECT_EQ(a.substr(3, 2), "de"); EXPECT_EQ(d.substr(0, 99), e); EXPECT_EQ(a.substr(0, absl::string_view::npos), a); EXPECT_EQ(a.substr(23, absl::string_view::npos), c); #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW((void)a.substr(99, 2), std::out_of_range); #else ABSL_EXPECT_DEATH_IF_SUPPORTED((void)a.substr(99, 2), "absl::string_view::substr"); #endif } TEST(StringViewTest, TruncSubstr) { const absl::string_view hi("hi"); EXPECT_EQ("", absl::ClippedSubstr(hi, 0, 0)); EXPECT_EQ("h", absl::ClippedSubstr(hi, 0, 1)); EXPECT_EQ("hi", absl::ClippedSubstr(hi, 0)); EXPECT_EQ("i", absl::ClippedSubstr(hi, 1)); EXPECT_EQ("", absl::ClippedSubstr(hi, 2)); EXPECT_EQ("", absl::ClippedSubstr(hi, 3)); EXPECT_EQ("", absl::ClippedSubstr(hi, 3, 2)); } TEST(StringViewTest, UTF8) { std::string utf8 = "\u00E1"; std::string utf8_twice = utf8 + " " + utf8; size_t utf8_len = strlen(utf8.data()); EXPECT_EQ(utf8_len, absl::string_view(utf8_twice).find_first_of(" ")); EXPECT_EQ(utf8_len, absl::string_view(utf8_twice).find_first_of(" \t")); } TEST(StringViewTest, FindConformance) { struct { std::string haystack; std::string needle; } specs[] = { {"", ""}, {"", "a"}, {"a", ""}, {"a", "a"}, {"a", "b"}, {"aa", ""}, {"aa", "a"}, {"aa", "b"}, {"ab", "a"}, {"ab", "b"}, {"abcd", ""}, {"abcd", "a"}, {"abcd", "d"}, {"abcd", "ab"}, {"abcd", "bc"}, {"abcd", "cd"}, {"abcd", "abcd"}, }; for (const auto& s : specs) { SCOPED_TRACE(s.haystack); SCOPED_TRACE(s.needle); std::string st = s.haystack; absl::string_view sp = s.haystack; for (size_t i = 0; i <= sp.size(); ++i) { size_t pos = (i == sp.size()) ? absl::string_view::npos : i; SCOPED_TRACE(pos); EXPECT_EQ(sp.find(s.needle, pos), st.find(s.needle, pos)); EXPECT_EQ(sp.rfind(s.needle, pos), st.rfind(s.needle, pos)); EXPECT_EQ(sp.find_first_of(s.needle, pos), st.find_first_of(s.needle, pos)); EXPECT_EQ(sp.find_first_not_of(s.needle, pos), st.find_first_not_of(s.needle, pos)); EXPECT_EQ(sp.find_last_of(s.needle, pos), st.find_last_of(s.needle, pos)); EXPECT_EQ(sp.find_last_not_of(s.needle, pos), st.find_last_not_of(s.needle, pos)); } } } TEST(StringViewTest, Remove) { absl::string_view a("foobar"); std::string s1("123"); s1 += '\0'; s1 += "456"; absl::string_view e; std::string s2; absl::string_view c(a); c.remove_prefix(3); EXPECT_EQ(c, "bar"); c = a; c.remove_prefix(0); EXPECT_EQ(c, a); c.remove_prefix(c.size()); EXPECT_EQ(c, e); c = a; c.remove_suffix(3); EXPECT_EQ(c, "foo"); c = a; c.remove_suffix(0); EXPECT_EQ(c, a); c.remove_suffix(c.size()); EXPECT_EQ(c, e); } TEST(StringViewTest, Set) { absl::string_view a("foobar"); absl::string_view empty; absl::string_view b; b = absl::string_view("foobar", 6); EXPECT_EQ(b, a); b = absl::string_view("foobar", 0); EXPECT_EQ(b, empty); b = absl::string_view("foobar", 7); EXPECT_NE(b, a); b = absl::string_view("foobar"); EXPECT_EQ(b, a); } TEST(StringViewTest, FrontBack) { static const char arr[] = "abcd"; const absl::string_view csp(arr, 4); EXPECT_EQ(&arr[0], &csp.front()); EXPECT_EQ(&arr[3], &csp.back()); } TEST(StringViewTest, FrontBackSingleChar) { static const char c = 'a'; const absl::string_view csp(&c, 1); EXPECT_EQ(&c, &csp.front()); EXPECT_EQ(&c, &csp.back()); } TEST(StringViewTest, FrontBackEmpty) { #ifndef ABSL_USES_STD_STRING_VIEW #if !defined(NDEBUG) || ABSL_OPTION_HARDENED absl::string_view sv; ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.front(), ""); ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.back(), ""); #endif #endif } #if !defined(ABSL_USES_STD_STRING_VIEW) || \ (!(defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE >= 9) && \ !defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) #define ABSL_HAVE_STRING_VIEW_FROM_NULLPTR 1 #endif TEST(StringViewTest, NULLInput) { absl::string_view s; EXPECT_EQ(s.data(), nullptr); EXPECT_EQ(s.size(), 0u); #ifdef ABSL_HAVE_STRING_VIEW_FROM_NULLPTR s = absl::string_view(nullptr); EXPECT_EQ(s.data(), nullptr); EXPECT_EQ(s.size(), 0u); EXPECT_EQ("", std::string(s)); #endif } TEST(StringViewTest, Comparisons2) { absl::string_view abc("abcdefghijklmnopqrstuvwxyz"); EXPECT_EQ(abc, absl::string_view("abcdefghijklmnopqrstuvwxyz")); EXPECT_EQ(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxyz")), 0); EXPECT_LT(abc, absl::string_view("abcdefghijklmnopqrstuvwxzz")); EXPECT_LT(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxzz")), 0); EXPECT_GT(abc, absl::string_view("abcdefghijklmnopqrstuvwxyy")); EXPECT_GT(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxyy")), 0); absl::string_view digits("0123456789"); auto npos = absl::string_view::npos; EXPECT_EQ(digits.compare(3, npos, absl::string_view("3456789")), 0); EXPECT_EQ(digits.compare(3, 4, absl::string_view("3456")), 0); EXPECT_EQ(digits.compare(10, 0, absl::string_view()), 0); EXPECT_EQ(digits.compare(3, 4, absl::string_view("0123456789"), 3, 4), 0); EXPECT_LT(digits.compare(3, 4, absl::string_view("0123456789"), 3, 5), 0); EXPECT_LT(digits.compare(0, npos, absl::string_view("0123456789"), 3, 5), 0); EXPECT_EQ(digits.compare(3, 4, "3456"), 0); EXPECT_EQ(digits.compare(3, npos, "3456789"), 0); EXPECT_EQ(digits.compare(10, 0, ""), 0); EXPECT_EQ(digits.compare(3, 4, "0123456789", 3, 4), 0); EXPECT_LT(digits.compare(3, 4, "0123456789", 3, 5), 0); EXPECT_LT(digits.compare(0, npos, "0123456789", 3, 5), 0); } TEST(StringViewTest, At) { absl::string_view abc = "abc"; EXPECT_EQ(abc.at(0), 'a'); EXPECT_EQ(abc.at(1), 'b'); EXPECT_EQ(abc.at(2), 'c'); #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW((void)abc.at(3), std::out_of_range); #else ABSL_EXPECT_DEATH_IF_SUPPORTED((void)abc.at(3), "absl::string_view::at"); #endif } #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L TEST(St
2,562
#ifndef ABSL_STRINGS_STR_REPLACE_H_ #define ABSL_STRINGS_STR_REPLACE_H_ #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/nullability.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN ABSL_MUST_USE_RESULT std::string StrReplaceAll( absl::string_view s, std::initializer_list<std::pair<absl::string_view, absl::string_view>> replacements); template <typename StrToStrMapping> std::string StrReplaceAll(absl::string_view s, const StrToStrMapping& replacements); int StrReplaceAll( std::initializer_list<std::pair<absl::string_view, absl::string_view>> replacements, absl::Nonnull<std::string*> target); template <typename StrToStrMapping> int StrReplaceAll(const StrToStrMapping& replacements, absl::Nonnull<std::string*> target); namespace strings_internal { struct ViableSubstitution { absl::string_view old; absl::string_view replacement; size_t offset; ViableSubstitution(absl::string_view old_str, absl::string_view replacement_str, size_t offset_val) : old(old_str), replacement(replacement_str), offset(offset_val) {} bool OccursBefore(const ViableSubstitution& y) const { if (offset != y.offset) return offset < y.offset; return old.size() > y.old.size(); } }; template <typename StrToStrMapping> std::vector<ViableSubstitution> FindSubstitutions( absl::string_view s, const StrToStrMapping& replacements) { std::vector<ViableSubstitution> subs; subs.reserve(replacements.size()); for (const auto& rep : replacements) { using std::get; absl::string_view old(get<0>(rep)); size_t pos = s.find(old); if (pos == s.npos) continue; if (old.empty()) continue; subs.emplace_back(old, get<1>(rep), pos); size_t index = subs.size(); while (--index && subs[index - 1].OccursBefore(subs[index])) { std::swap(subs[index], subs[index - 1]); } } return subs; } int ApplySubstitutions(absl::string_view s, absl::Nonnull<std::vector<ViableSubstitution>*> subs_ptr, absl::Nonnull<std::string*> result_ptr); } template <typename StrToStrMapping> std::string StrReplaceAll(absl::string_view s, const StrToStrMapping& replacements) { auto subs = strings_internal::FindSubstitutions(s, replacements); std::string result; result.reserve(s.size()); strings_internal::ApplySubstitutions(s, &subs, &result); return result; } template <typename StrToStrMapping> int StrReplaceAll(const StrToStrMapping& replacements, absl::Nonnull<std::string*> target) { auto subs = strings_internal::FindSubstitutions(*target, replacements); if (subs.empty()) return 0; std::string result; result.reserve(target->size()); int substitutions = strings_internal::ApplySubstitutions(*target, &subs, &result); target->swap(result); return substitutions; } ABSL_NAMESPACE_END } #endif #include "absl/strings/str_replace.h" #include <cstddef> #include <initializer_list> #include <string> #include <utility> #include <vector> #include "absl/base/config.h" #include "absl/base/nullability.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { using FixedMapping = std::initializer_list<std::pair<absl::string_view, absl::string_view>>; int ApplySubstitutions( absl::string_view s, absl::Nonnull<std::vector<strings_internal::ViableSubstitution>*> subs_ptr, absl::Nonnull<std::string*> result_ptr) { auto& subs = *subs_ptr; int substitutions = 0; size_t pos = 0; while (!subs.empty()) { auto& sub = subs.back(); if (sub.offset >= pos) { if (pos <= s.size()) { StrAppend(result_ptr, s.substr(pos, sub.offset - pos), sub.replacement); } pos = sub.offset + sub.old.size(); substitutions += 1; } sub.offset = s.find(sub.old, pos); if (sub.offset == s.npos) { subs.pop_back(); } else { size_t index = subs.size(); while (--index && subs[index - 1].OccursBefore(subs[index])) { std::swap(subs[index], subs[index - 1]); } } } result_ptr->append(s.data() + pos, s.size() - pos); return substitutions; } } std::string StrReplaceAll(absl::string_view s, strings_internal::FixedMapping replacements) { return StrReplaceAll<strings_internal::FixedMapping>(s, replacements); } int StrReplaceAll(strings_internal::FixedMapping replacements, absl::Nonnull<std::string*> target) { return StrReplaceAll<strings_internal::FixedMapping>(replacements, target); } ABSL_NAMESPACE_END }
#include "absl/strings/str_replace.h" #include <list> #include <map> #include <string> #include <tuple> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" TEST(StrReplaceAll, OneReplacement) { std::string s; s = absl::StrReplaceAll(s, {{"", ""}}); EXPECT_EQ(s, ""); s = absl::StrReplaceAll(s, {{"x", ""}}); EXPECT_EQ(s, ""); s = absl::StrReplaceAll(s, {{"", "y"}}); EXPECT_EQ(s, ""); s = absl::StrReplaceAll(s, {{"x", "y"}}); EXPECT_EQ(s, ""); s = absl::StrReplaceAll("abc", {{"", ""}}); EXPECT_EQ(s, "abc"); s = absl::StrReplaceAll("abc", {{"", "y"}}); EXPECT_EQ(s, "abc"); s = absl::StrReplaceAll("abc", {{"x", ""}}); EXPECT_EQ(s, "abc"); s = absl::StrReplaceAll("abc", {{"xyz", "123"}}); EXPECT_EQ(s, "abc"); s = absl::StrReplaceAll("abc", {{"abc", "xyz"}}); EXPECT_EQ(s, "xyz"); s = absl::StrReplaceAll("abc", {{"a", "x"}}); EXPECT_EQ(s, "xbc"); s = absl::StrReplaceAll("abc", {{"b", "x"}}); EXPECT_EQ(s, "axc"); s = absl::StrReplaceAll("abc", {{"c", "x"}}); EXPECT_EQ(s, "abx"); s = absl::StrReplaceAll("ababa", {{"a", "xxx"}}); EXPECT_EQ(s, "xxxbxxxbxxx"); s = absl::StrReplaceAll("ababa", {{"b", "xxx"}}); EXPECT_EQ(s, "axxxaxxxa"); s = absl::StrReplaceAll("aaabaaabaaa", {{"aaa", "x"}}); EXPECT_EQ(s, "xbxbx"); s = absl::StrReplaceAll("abbbabbba", {{"bbb", "x"}}); EXPECT_EQ(s, "axaxa"); s = absl::StrReplaceAll("aaa", {{"aa", "x"}}); EXPECT_EQ(s, "xa"); s = absl::StrReplaceAll("aaa", {{"aa", "a"}}); EXPECT_EQ(s, "aa"); } TEST(StrReplaceAll, ManyReplacements) { std::string s; s = absl::StrReplaceAll("", {{"", ""}, {"x", ""}, {"", "y"}, {"x", "y"}}); EXPECT_EQ(s, ""); s = absl::StrReplaceAll("abc", {{"", ""}, {"", "y"}, {"x", ""}}); EXPECT_EQ(s, "abc"); s = absl::StrReplaceAll("abc", {{"a", "x"}, {"b", "y"}, {"c", "z"}}); EXPECT_EQ(s, "xyz"); s = absl::StrReplaceAll("zxy", {{"z", "x"}, {"x", "y"}, {"y", "z"}}); EXPECT_EQ(s, "xyz"); s = absl::StrReplaceAll("abc", {{"a", "x"}, {"ab", "xy"}, {"abc", "xyz"}}); EXPECT_EQ(s, "xyz"); s = absl::StrReplaceAll( "Abc!", {{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc", "yz"}, {"c", "z"}}); EXPECT_EQ(s, "Ayz!"); s = absl::StrReplaceAll( "Abc!", {{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc!", "yz?"}, {"c!", "z;"}}); EXPECT_EQ(s, "Ayz?"); s = absl::StrReplaceAll("ababa", {{"a", "xxx"}, {"b", "XXXX"}}); EXPECT_EQ(s, "xxxXXXXxxxXXXXxxx"); s = absl::StrReplaceAll("aaa", {{"aa", "x"}, {"a", "X"}}); EXPECT_EQ(s, "xX"); s = absl::StrReplaceAll("aaa", {{"a", "X"}, {"aa", "x"}}); EXPECT_EQ(s, "xX"); s = absl::StrReplaceAll("the quick brown fox jumped over the lazy dogs", { {"brown", "box"}, {"dogs", "jugs"}, {"fox", "with"}, {"jumped", "five"}, {"over", "dozen"}, {"quick", "my"}, {"the", "pack"}, {"the lazy", "liquor"}, }); EXPECT_EQ(s, "pack my box with five dozen liquor jugs"); } TEST(StrReplaceAll, ManyReplacementsInMap) { std::map<const char *, const char *> replacements; replacements["$who"] = "Bob"; replacements["$count"] = "5"; replacements["#Noun"] = "Apples"; std::string s = absl::StrReplaceAll("$who bought $count #Noun. Thanks $who!", replacements); EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s); } TEST(StrReplaceAll, ReplacementsInPlace) { std::string s = std::string("$who bought $count #Noun. Thanks $who!"); int count; count = absl::StrReplaceAll({{"$count", absl::StrCat(5)}, {"$who", "Bob"}, {"#Noun", "Apples"}}, &s); EXPECT_EQ(count, 4); EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s); } TEST(StrReplaceAll, ReplacementsInPlaceInMap) { std::string s = std::string("$who bought $count #Noun. Thanks $who!"); std::map<absl::string_view, absl::string_view> replacements; replacements["$who"] = "Bob"; replacements["$count"] = "5"; replacements["#Noun"] = "Apples"; int count; count = absl::StrReplaceAll(replacements, &s); EXPECT_EQ(count, 4); EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s); } struct Cont { Cont() = default; explicit Cont(absl::string_view src) : data(src) {} absl::string_view data; }; template <int index> absl::string_view get(const Cont& c) { auto splitter = absl::StrSplit(c.data, ':'); auto it = splitter.begin(); for (int i = 0; i < index; ++i) ++it; return *it; } TEST(StrReplaceAll, VariableNumber) { std::string s; { std::vector<std::pair<std::string, std::string>> replacements; s = "abc"; EXPECT_EQ(0, absl::StrReplaceAll(replacements, &s)); EXPECT_EQ("abc", s); s = "abc"; replacements.push_back({"a", "A"}); EXPECT_EQ(1, absl::StrReplaceAll(replacements, &s)); EXPECT_EQ("Abc", s); s = "abc"; replacements.push_back({"b", "B"}); EXPECT_EQ(2, absl::StrReplaceAll(replacements, &s)); EXPECT_EQ("ABc", s); s = "abc"; replacements.push_back({"d", "D"}); EXPECT_EQ(2, absl::StrReplaceAll(replacements, &s)); EXPECT_EQ("ABc", s); EXPECT_EQ("ABcABc", absl::StrReplaceAll("abcabc", replacements)); } { std::map<const char*, const char*> replacements; replacements["aa"] = "x"; replacements["a"] = "X"; s = "aaa"; EXPECT_EQ(2, absl::StrReplaceAll(replacements, &s)); EXPECT_EQ("xX", s); EXPECT_EQ("xxX", absl::StrReplaceAll("aaaaa", replacements)); } { std::list<std::pair<absl::string_view, absl::string_view>> replacements = { {"a", "x"}, {"b", "y"}, {"c", "z"}}; std::string s = absl::StrReplaceAll("abc", replacements); EXPECT_EQ(s, "xyz"); } { using X = std::tuple<absl::string_view, std::string, int>; std::vector<X> replacements(3); replacements[0] = X{"a", "x", 1}; replacements[1] = X{"b", "y", 0}; replacements[2] = X{"c", "z", -1}; std::string s = absl::StrReplaceAll("abc", replacements); EXPECT_EQ(s, "xyz"); } { std::vector<Cont> replacements(3); replacements[0] = Cont{"a:x"}; replacements[1] = Cont{"b:y"}; replacements[2] = Cont{"c:z"}; std::string s = absl::StrReplaceAll("abc", replacements); EXPECT_EQ(s, "xyz"); } } TEST(StrReplaceAll, Inplace) { std::string s; int reps; s = ""; reps = absl::StrReplaceAll({{"", ""}, {"x", ""}, {"", "y"}, {"x", "y"}}, &s); EXPECT_EQ(reps, 0); EXPECT_EQ(s, ""); s = "abc"; reps = absl::StrReplaceAll({{"", ""}, {"", "y"}, {"x", ""}}, &s); EXPECT_EQ(reps, 0); EXPECT_EQ(s, "abc"); s = "abc"; reps = absl::StrReplaceAll({{"a", "x"}, {"b", "y"}, {"c", "z"}}, &s); EXPECT_EQ(reps, 3); EXPECT_EQ(s, "xyz"); s = "zxy"; reps = absl::StrReplaceAll({{"z", "x"}, {"x", "y"}, {"y", "z"}}, &s); EXPECT_EQ(reps, 3); EXPECT_EQ(s, "xyz"); s = "abc"; reps = absl::StrReplaceAll({{"a", "x"}, {"ab", "xy"}, {"abc", "xyz"}}, &s); EXPECT_EQ(reps, 1); EXPECT_EQ(s, "xyz"); s = "Abc!"; reps = absl::StrReplaceAll( {{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc", "yz"}, {"c", "z"}}, &s); EXPECT_EQ(reps, 1); EXPECT_EQ(s, "Ayz!"); s = "Abc!"; reps = absl::StrReplaceAll( {{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc!", "yz?"}, {"c!", "z;"}}, &s); EXPECT_EQ(reps, 1); EXPECT_EQ(s, "Ayz?"); s = "ababa"; reps = absl::StrReplaceAll({{"a", "xxx"}, {"b", "XXXX"}}, &s); EXPECT_EQ(reps, 5); EXPECT_EQ(s, "xxxXXXXxxxXXXXxxx"); s = "aaa"; reps = absl::StrReplaceAll({{"aa", "x"}, {"a", "X"}}, &s); EXPECT_EQ(reps, 2); EXPECT_EQ(s, "xX"); s = "aaa"; reps = absl::StrReplaceAll({{"a", "X"}, {"aa", "x"}}, &s); EXPECT_EQ(reps, 2); EXPECT_EQ(s, "xX"); s = "the quick brown fox jumped over the lazy dogs"; reps = absl::StrReplaceAll( { {"brown", "box"}, {"dogs", "jugs"}, {"fox", "with"}, {"jumped", "five"}, {"over", "dozen"}, {"quick", "my"}, {"the", "pack"}, {"the lazy", "liquor"}, }, &s); EXPECT_EQ(reps, 8); EXPECT_EQ(s, "pack my box with five dozen liquor jugs"); }
2,563
#ifndef ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_ #define ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_ #include <algorithm> #include <cstdint> #include <iostream> #include <string> #include "absl/base/config.h" #include "absl/strings/ascii.h" #include "absl/strings/internal/charconv_parse.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { constexpr int kMaxSmallPowerOfFive = 13; constexpr int kMaxSmallPowerOfTen = 9; ABSL_DLL extern const uint32_t kFiveToNth[kMaxSmallPowerOfFive + 1]; ABSL_DLL extern const uint32_t kTenToNth[kMaxSmallPowerOfTen + 1]; template <int max_words> class BigUnsigned { public: static_assert(max_words == 4 || max_words == 84, "unsupported max_words value"); BigUnsigned() : size_(0), words_{} {} explicit constexpr BigUnsigned(uint64_t v) : size_((v >> 32) ? 2 : v ? 1 : 0), words_{static_cast<uint32_t>(v & 0xffffffffu), static_cast<uint32_t>(v >> 32)} {} explicit BigUnsigned(absl::string_view sv) : size_(0), words_{} { if (std::find_if_not(sv.begin(), sv.end(), ascii_isdigit) != sv.end() || sv.empty()) { return; } int exponent_adjust = ReadDigits(sv.data(), sv.data() + sv.size(), Digits10() + 1); if (exponent_adjust > 0) { MultiplyByTenToTheNth(exponent_adjust); } } int ReadFloatMantissa(const ParsedFloat& fp, int significant_digits); static constexpr int Digits10() { return static_cast<uint64_t>(max_words) * 9975007 / 1035508; } void ShiftLeft(int count) { if (count > 0) { const int word_shift = count / 32; if (word_shift >= max_words) { SetToZero(); return; } size_ = (std::min)(size_ + word_shift, max_words); count %= 32; if (count == 0) { #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(14, 0) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" #endif std::copy_backward(words_, words_ + size_ - word_shift, words_ + size_); #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(14, 0) #pragma GCC diagnostic pop #endif } else { for (int i = (std::min)(size_, max_words - 1); i > word_shift; --i) { words_[i] = (words_[i - word_shift] << count) | (words_[i - word_shift - 1] >> (32 - count)); } words_[word_shift] = words_[0] << count; if (size_ < max_words && words_[size_]) { ++size_; } } std::fill_n(words_, word_shift, 0u); } } void MultiplyBy(uint32_t v) { if (size_ == 0 || v == 1) { return; } if (v == 0) { SetToZero(); return; } const uint64_t factor = v; uint64_t window = 0; for (int i = 0; i < size_; ++i) { window += factor * words_[i]; words_[i] = window & 0xffffffff; window >>= 32; } if (window && size_ < max_words) { words_[size_] = window & 0xffffffff; ++size_; } } void MultiplyBy(uint64_t v) { uint32_t words[2]; words[0] = static_cast<uint32_t>(v); words[1] = static_cast<uint32_t>(v >> 32); if (words[1] == 0) { MultiplyBy(words[0]); } else { MultiplyBy(2, words); } } void MultiplyByFiveToTheNth(int n) { while (n >= kMaxSmallPowerOfFive) { MultiplyBy(kFiveToNth[kMaxSmallPowerOfFive]); n -= kMaxSmallPowerOfFive; } if (n > 0) { MultiplyBy(kFiveToNth[n]); } } void MultiplyByTenToTheNth(int n) { if (n > kMaxSmallPowerOfTen) { MultiplyByFiveToTheNth(n); ShiftLeft(n); } else if (n > 0) { MultiplyBy(kTenToNth[n]); } } static BigUnsigned FiveToTheNth(int n); template <int M> void MultiplyBy(const BigUnsigned<M>& other) { MultiplyBy(other.size(), other.words()); } void SetToZero() { std::fill_n(words_, size_, 0u); size_ = 0; } uint32_t GetWord(int index) const { if (index < 0 || index >= size_) { return 0; } return words_[index]; } std::string ToString() const; int size() const { return size_; } const uint32_t* words() const { return words_; } private: int ReadDigits(const char* begin, const char* end, int significant_digits); void MultiplyStep(int original_size, const uint32_t* other_words, int other_size, int step); void MultiplyBy(int other_size, const uint32_t* other_words) { const int original_size = size_; const int first_step = (std::min)(original_size + other_size - 2, max_words - 1); for (int step = first_step; step >= 0; --step) { MultiplyStep(original_size, other_words, other_size, step); } } void AddWithCarry(int index, uint32_t value) { if (value) { while (index < max_words && value > 0) { words_[index] += value; if (value > words_[index]) { value = 1; ++index; } else { value = 0; } } size_ = (std::min)(max_words, (std::max)(index + 1, size_)); } } void AddWithCarry(int index, uint64_t value) { if (value && index < max_words) { uint32_t high = value >> 32; uint32_t low = value & 0xffffffff; words_[index] += low; if (words_[index] < low) { ++high; if (high == 0) { AddWithCarry(index + 2, static_cast<uint32_t>(1)); return; } } if (high > 0) { AddWithCarry(index + 1, high); } else { size_ = (std::min)(max_words, (std::max)(index + 1, size_)); } } } template <uint32_t divisor> uint32_t DivMod() { uint64_t accumulator = 0; for (int i = size_ - 1; i >= 0; --i) { accumulator <<= 32; accumulator += words_[i]; words_[i] = static_cast<uint32_t>(accumulator / divisor); accumulator = accumulator % divisor; } while (size_ > 0 && words_[size_ - 1] == 0) { --size_; } return static_cast<uint32_t>(accumulator); } int size_; uint32_t words_[max_words]; }; template <int N, int M> int Compare(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) { int limit = (std::max)(lhs.size(), rhs.size()); for (int i = limit - 1; i >= 0; --i) { const uint32_t lhs_word = lhs.GetWord(i); const uint32_t rhs_word = rhs.GetWord(i); if (lhs_word < rhs_word) { return -1; } else if (lhs_word > rhs_word) { return 1; } } return 0; } template <int N, int M> bool operator==(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) { int limit = (std::max)(lhs.size(), rhs.size()); for (int i = 0; i < limit; ++i) { if (lhs.GetWord(i) != rhs.GetWord(i)) { return false; } } return true; } template <int N, int M> bool operator!=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) { return !(lhs == rhs); } template <int N, int M> bool operator<(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) { return Compare(lhs, rhs) == -1; } template <int N, int M> bool operator>(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) { return rhs < lhs; } template <int N, int M> bool operator<=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) { return !(rhs < lhs); } template <int N, int M> bool operator>=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) { return !(lhs < rhs); } template <int N> std::ostream& operator<<(std::ostream& os, const BigUnsigned<N>& num) { return os << num.ToString(); } extern template class BigUnsigned<4>; extern template class BigUnsigned<84>; } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/charconv_bigint.h" #include <algorithm> #include <cassert> #include <string> namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { namespace { constexpr int kLargePowerOfFiveStep = 27; constexpr int kLargestPowerOfFiveIndex = 20; const uint32_t kLargePowersOfFive[] = { 0xfa10079dU, 0x6765c793U, 0x97d9f649U, 0x6664242dU, 0x29939b14U, 0x29c30f10U, 0xc4f809c5U, 0x7bf3f22aU, 0x67bdae34U, 0xad340517U, 0x369d1b5fU, 0x10de1593U, 0x92b260d1U, 0x9efff7c7U, 0x81de0ec6U, 0xaeba5d56U, 0x410664a4U, 0x4f40737aU, 0x20d3846fU, 0x06d00f73U, 0xff1b172dU, 0x13a1d71cU, 0xefa07617U, 0x7f682d3dU, 0xff8c90c0U, 0x3f0131e7U, 0x3fdcb9feU, 0x917b0177U, 0x16c407a7U, 0x02c06b9dU, 0x960f7199U, 0x056667ecU, 0xe07aefd8U, 0x80f2b9ccU, 0x8273f5e3U, 0xeb9a214aU, 0x40b38005U, 0x0e477ad4U, 0x277d08e6U, 0xfa28b11eU, 0xd3f7d784U, 0x011c835bU, 0xf723d9d5U, 0x3282d3f3U, 0xe00857d1U, 0x69659d25U, 0x2cf117cfU, 0x24da6d07U, 0x954d1417U, 0x3e5d8cedU, 0x7a8bb766U, 0xfd785ae6U, 0x645436d2U, 0x40c78b34U, 0x94151217U, 0x0072e9f7U, 0x2b416aa1U, 0x7893c5a7U, 0xe37dc6d4U, 0x2bad2beaU, 0xf0fc846cU, 0x7575ae4bU, 0x62587b14U, 0x83b67a34U, 0x02110cdbU, 0xf7992f55U, 0x00deb022U, 0xa4a23becU, 0x8af5c5cdU, 0xb85b654fU, 0x818df38bU, 0x002e69d2U, 0x3518cbbdU, 0x20b0c15fU, 0x38756c2fU, 0xfb5dc3ddU, 0x22ad2d94U, 0xbf35a952U, 0xa699192aU, 0x9a613326U, 0xad2a9cedU, 0xd7f48968U, 0xe87dfb54U, 0xc8f05db6U, 0x5ef67531U, 0x31c1ab49U, 0xe202ac9fU, 0x9b2957b5U, 0xa143f6d3U, 0x0012bf07U, 0x8b971de9U, 0x21aba2e1U, 0x63944362U, 0x57172336U, 0xd9544225U, 0xfb534166U, 0x08c563eeU, 0x14640ee2U, 0x24e40d31U, 0x02b06537U, 0x03887f14U, 0x0285e533U, 0xb744ef26U, 0x8be3a6c4U, 0x266979b4U, 0x6761ece2U, 0xd9cb39e4U, 0xe67de319U, 0x0d39e796U, 0x00079250U, 0x260eb6e5U, 0xf414a796U, 0xee1a7491U, 0xdb9368ebU, 0xf50c105bU, 0x59157750U, 0x9ed2fb5cU, 0xf6e56d8bU, 0xeaee8d23U, 0x0f319f75U, 0x2aa134d6U, 0xac2908e9U, 0xd4413298U, 0x02f02a55U, 0x989d5a7aU, 0x70dde184U, 0xba8040a7U, 0x03200981U, 0xbe03b11cU, 0x3c1c2a18U, 0xd60427a1U, 0x00030ee0U, 0xce566d71U, 0xf1c4aa25U, 0x4e93ca53U, 0xa72283d0U, 0x551a73eaU, 0x3d0538e2U, 0x8da4303fU, 0x6a58de60U, 0x0e660221U, 0x49cf61a6U, 0x8d058fc1U, 0xb9d1a14cU, 0x4bab157dU, 0xc85c6932U, 0x518c8b9eU, 0x9b92b8d0U, 0x0d8a0e21U, 0xbd855df9U, 0xb3ea59a1U, 0x8da29289U, 0x4584d506U, 0x3752d80fU, 0xb72569c6U, 0x00013c33U, 0x190f354dU, 0x83695cfeU, 0xe5a4d0c7U, 0xb60fb7e8U, 0xee5bbcc4U, 0xb922054cU, 0xbb4f0d85U, 0x48394028U, 0x1d8957dbU, 0x0d7edb14U, 0x4ecc7587U, 0x505e9e02U, 0x4c87f36bU, 0x99e66bd6U, 0x44b9ed35U, 0x753037d4U, 0xe5fe5f27U, 0x2742c203U, 0x13b2ed2bU, 0xdc525d2cU, 0xe6fde59aU, 0x77ffb18fU, 0x13c5752cU, 0x08a84bccU, 0x859a4940U, 0x00007fb6U, 0x4f98cb39U, 0xa60edbbcU, 0x83b5872eU, 0xa501acffU, 0x9cc76f78U, 0xbadd4c73U, 0x43e989faU, 0xca7acf80U, 0x2e0c824fU, 0xb19f4ffcU, 0x092fd81cU, 0xe4eb645bU, 0xa1ff84c2U, 0x8a5a83baU, 0xa8a1fae9U, 0x1db43609U, 0xb0fed50bU, 0x0dd7d2bdU, 0x7d7accd8U, 0x91fa640fU, 0x37dcc6c5U, 0x1c417fd5U, 0xe4d462adU, 0xe8a43399U, 0x131bf9a5U, 0x8df54d29U, 0x36547dc1U, 0x00003395U, 0x5bd330f5U, 0x77d21967U, 0x1ac481b7U, 0x6be2f7ceU, 0x7f4792a9U, 0xe84c2c52U, 0x84592228U, 0x9dcaf829U, 0xdab44ce1U, 0x3d0c311bU, 0x532e297dU, 0x4704e8b4U, 0x9cdc32beU, 0x41e64d9dU, 0x7717bea1U, 0xa824c00dU, 0x08f50b27U, 0x0f198d77U, 0x49bbfdf0U, 0x025c6c69U, 0xd4e55cd3U, 0xf083602bU, 0xb9f0fecdU, 0xc0864aeaU, 0x9cb98681U, 0xaaf620e9U, 0xacb6df30U, 0x4faafe66U, 0x8af13c3bU, 0x000014d5U, 0x682bb941U, 0x89a9f297U, 0xcba75d7bU, 0x404217b1U, 0xb4e519e9U, 0xa1bc162bU, 0xf7f5910aU, 0x98715af5U, 0x2ff53e57U, 0xe3ef118cU, 0x490c4543U, 0xbc9b1734U, 0x2affbe4dU, 0x4cedcb4cU, 0xfb14e99eU, 0x35e34212U, 0xece39c24U, 0x07673ab3U, 0xe73115ddU, 0xd15d38e7U, 0x093eed3bU, 0xf8e7eac5U, 0x78a8cc80U, 0x25227aacU, 0x3f590551U, 0x413da1cbU, 0xdf643a55U, 0xab65ad44U, 0xd70b23d7U, 0xc672cd76U, 0x3364ea62U, 0x0000086aU, 0x22f163ddU, 0x23cf07acU, 0xbe2af6c2U, 0xf412f6f6U, 0xc3ff541eU, 0x6eeaf7deU, 0xa47047e0U, 0x408cda92U, 0x0f0eeb08U, 0x56deba9dU, 0xcfc6b090U, 0x8bbbdf04U, 0x3933cdb3U, 0x9e7bb67dU, 0x9f297035U, 0x38946244U, 0xee1d37bbU, 0xde898174U, 0x63f3559dU, 0x705b72fbU, 0x138d27d9U, 0xf8603a78U, 0x735eec44U, 0xe30987d5U, 0xc6d38070U, 0x9cfe548eU, 0x9ff01422U, 0x7c564aa8U, 0x91cc60baU, 0xcbc3565dU, 0x7550a50bU, 0x6909aeadU, 0x13234c45U, 0x00000366U, 0x17954989U, 0x3a7d7709U, 0x98042de5U, 0xa9011443U, 0x45e723c2U, 0x269ffd6fU, 0x58852a46U, 0xaaa1042aU, 0x2eee8153U, 0xb2b6c39eU, 0xaf845b65U, 0xf6c365d7U, 0xe4cffb2bU, 0xc840e90cU, 0xabea8abbU, 0x5c58f8d2U, 0x5c19fa3aU, 0x4670910aU, 0x4449f21cU, 0xefa645b3U, 0xcc427decU, 0x083c3d73U, 0x467cb413U, 0x6fe10ae4U, 0x3caffc72U, 0x9f8da55eU, 0x5e5c8ea7U, 0x490594bbU, 0xf0871b0bU, 0xdd89816cU, 0x8e931df8U, 0xe85ce1c9U, 0xcca090a5U, 0x575fa16bU, 0x6b9f106cU, 0x0000015fU, 0xee20d805U, 0x57bc3c07U, 0xcdea624eU, 0xd3f0f52dU, 0x9924b4f4U, 0xcf968640U, 0x61d41962U, 0xe87fb464U, 0xeaaf51c7U, 0x564c8b60U, 0xccda4028U, 0x529428bbU, 0x313a1fa8U, 0x96bd0f94U, 0x7a82ebaaU, 0xad99e7e9U, 0xf2668cd4U, 0xbe33a45eU, 0xfd0db669U, 0x87ee369fU, 0xd3ec20edU, 0x9c4d7db7U, 0xdedcf0d8U, 0x7cd2ca64U, 0xe25a6577U, 0x61003fd4U, 0xe56f54ccU, 0x10b7c748U, 0x40526e5eU, 0x7300ae87U, 0x5c439261U, 0x2c0ff469U, 0xbf723f12U, 0xb2379b61U, 0xbf59b4f5U, 0xc91b1c3fU, 0xf0046d27U, 0x0000008dU, 0x525c9e11U, 0xf4e0eb41U, 0xebb2895dU, 0x5da512f9U, 0x7d9b29d4U, 0x452f4edcU, 0x0b90bc37U, 0x341777cbU, 0x63d269afU, 0x1da77929U, 0x0a5c1826U, 0x77991898U, 0x5aeddf86U, 0xf853a877U, 0x538c31ccU, 0xe84896daU, 0xb7a0010bU, 0x17ef4de5U, 0xa52a2adeU, 0x029fd81cU, 0x987ce701U, 0x27fefd77U, 0xdb46c66fU, 0x5d301900U, 0x496998c0U, 0xbb6598b9U, 0x5eebb607U, 0xe547354aU, 0xdf4a2f7eU, 0xf06c4955U, 0x96242ffaU, 0x1775fb27U, 0xbecc58ceU, 0xebf2a53bU, 0x3eaad82aU, 0xf41137baU, 0x573e6fbaU, 0xfb4866b8U, 0x54002148U, 0x00000039U, }; const uint32_t* LargePowerOfFiveData(int i) { return kLargePowersOfFive + i * (i - 1); } int LargePowerOfFiveSize(int i) { return 2 * i; } } ABSL_DLL const uint32_t kFiveToNth[14] = { 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625, 1220703125, }; ABSL_DLL const uint32_t kTenToNth[10] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, }; template <int max_words> int BigUnsigned<max_words>::ReadFloatMantissa(const ParsedFloat& fp, int significant_digits) { SetToZero(); assert(fp.type == FloatType::kNumber); if (fp.subrange_begin == nullptr) { words_[0] = fp.mantissa & 0xffffffffu; words_[1] = fp.mantissa >> 32; if (words_[1]) { size_ = 2; } else if (words_[0]) { size_ = 1; } return fp.exponent; } int exponent_adjust = ReadDigits(fp.subrange_begin, fp.subrange_end, significant_digits); return fp.literal_exponent + exponent_adjust; } template <int max_words> int BigUnsigned<max_words>::ReadDigits(const char* begin, const char* end, int significant_digits) { assert(significant_digits <= Digits10() + 1); SetToZero(); bool after_decimal_point = false; while (begin < end && *begin == '0') { ++begin; } int dropped_digits = 0; while (begin < end && *std::prev(end) == '0') { --end; ++dropped_digits; } if (begin < end && *std::prev(end) == '.') { dropped_digits = 0; --end; while (begin < end && *std::prev(end) == '0') { --end; ++dropped_digits; } } else if (dropped_digits) { const char* dp = std::find(begin, end, '.'); if (dp != end) { dropped_digits = 0; } } int exponent_adjust = dropped_digits; uint32_t queued = 0; int digits_queued = 0; for (; begin != end && significant_digits > 0; ++begin) { if (*begin == '.') { after_decimal_point = true; continue; } if (after_decimal_point) { --exponent_adjust; } char digit = (*begin - '0'); --significant_digits; if (significant_digits == 0 && std::next(begin) != end && (digit == 0 || digit == 5)) { ++digit; } queued = 10 * queued + static_cast<uint32_t>(digit); ++digits_queued; if (digits_queued == kMaxSmallPowerOfTen) { MultiplyBy(kTenToNth[kMaxSmallPowerOfTen]); AddWithCarry(0, queued); queued = digits_queued = 0; } } if (digits_queued) { MultiplyBy(kTenToNth[digits_queued]); AddWithCarry(0, queued); } if (begin < end && !after_decimal_point) { const char* decimal_point = std::find(begin, end, '.'); exponent_adjust += (decimal_point - begin); } return exponent_adjust; } template <int max_words> BigUnsigned<max_words> BigUnsigned<max_words>::FiveToTheNth( int n) { BigUnsigned answer(1u); bool first_pass = true; while (n >= kLargePowerOfFiveStep) { int big_power = std::min(n / kLargePowerOfFiveStep, kLargestPowerOfFiveIndex); if (first_pass) { std::copy_n(LargePowerOfFiveData(big_power), LargePowerOfFiveSize(big_power), answer.words_); answer.size_ = LargePowerOfFiveSize(big_power); first_pass = false; } else { answer.MultiplyBy(LargePowerOfFiveSize(big_power), LargePowerOfFiveData(big_power)); } n -= kLargePowerOfFiveStep * big_power; } answer.MultiplyByFiveToTheNth(n); return answer; } template <int max_words> void BigUnsigned<max_words>::MultiplyStep(int original_size, const uint32_t* other_words, int other_size, int step) { int this_i = std::min(original_size - 1, step); int other_i = step - this_i; uint64_t this_word = 0; uint64_t carry = 0; for (; this_i >= 0 && other_i < other_size; --this_i, ++other_i) { uint64_t product = words_[this_i]; product *= other_words[other_i]; this_word += product; carry += (this_word >> 32); this_word &= 0xffffffff; } AddWithCarry(step + 1, carry); words_[step] = this_word & 0xffffffff; if (this_word > 0 && size_ <= step) { size_ = step + 1; } } template <int max_words> std::string BigUnsigned<max_words>::ToString() const { BigUnsigned<max_words> copy = *this; std::string result; while (copy.size() > 0) { uint32_t next_digit = copy.DivMod<10>(); result.push_back('0' + static_cast<char>(next_digit)); } if (result.empty()) { result.push_back('0'); } std::reverse(result.begin(), result.end()); return result; } template class BigUnsigned<4>; template class BigUnsigned<84>; } ABSL_NAMESPACE_END }
#include "absl/strings/internal/charconv_bigint.h" #include <string> #include "gtest/gtest.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { TEST(BigUnsigned, ShiftLeft) { { BigUnsigned<4> num(3u); num.ShiftLeft(100); EXPECT_EQ(num, BigUnsigned<4>("3802951800684688204490109616128")); } { BigUnsigned<4> a(15u); BigUnsigned<4> b(7u); BigUnsigned<4> c(3u); a.ShiftLeft(125); b.ShiftLeft(125); c.ShiftLeft(125); EXPECT_EQ(a, b); EXPECT_NE(a, c); } { BigUnsigned<84> a(15u); BigUnsigned<84> b(7u); BigUnsigned<84> c(3u); a.ShiftLeft(84 * 32 - 3); b.ShiftLeft(84 * 32 - 3); c.ShiftLeft(84 * 32 - 3); EXPECT_EQ(a, b); EXPECT_NE(a, c); } { const std::string seed = "1234567890123456789012345678901234567890"; BigUnsigned<84> a(seed); for (int i = 1; i <= 84 * 32; ++i) { a.ShiftLeft(1); BigUnsigned<84> b(seed); b.ShiftLeft(i); EXPECT_EQ(a, b); } EXPECT_EQ(a, BigUnsigned<84>(0u)); } { const BigUnsigned<84> all_bits_one( "1474444211396924248063325089479706787923460402125687709454567433186613" "6228083464060749874845919674257665016359189106695900028098437021384227" "3285029708032466536084583113729486015826557532750465299832071590813090" "2011853039837649252477307070509704043541368002938784757296893793903797" "8180292336310543540677175225040919704702800559606097685920595947397024" "8303316808753252115729411497720357971050627997031988036134171378490368" "6008000778741115399296162550786288457245180872759047016734959330367829" "5235612397427686310674725251378116268607113017720538636924549612987647" "5767411074510311386444547332882472126067840027882117834454260409440463" "9345147252664893456053258463203120637089916304618696601333953616715125" "2115882482473279040772264257431663818610405673876655957323083702713344" "4201105427930770976052393421467136557055"); const BigUnsigned<84> zero(0u); const BigUnsigned<84> one(1u); for (int i = 1; i < 84*32; ++i) { BigUnsigned<84> big_shifted = all_bits_one; big_shifted.ShiftLeft(i); EXPECT_GT(all_bits_one, big_shifted); BigUnsigned<84> small_shifted = one; small_shifted.ShiftLeft(i); EXPECT_LT(one, small_shifted); } for (int no_op_shift : {0, -1, -84 * 32, std::numeric_limits<int>::min()}) { BigUnsigned<84> big_shifted = all_bits_one; big_shifted.ShiftLeft(no_op_shift); EXPECT_EQ(all_bits_one, big_shifted); BigUnsigned<84> small_shifted = one; big_shifted.ShiftLeft(no_op_shift); EXPECT_EQ(one, small_shifted); } for (int out_of_bounds_shift : {84 * 32, 84 * 32 + 1, std::numeric_limits<int>::max()}) { BigUnsigned<84> big_shifted = all_bits_one; big_shifted.ShiftLeft(out_of_bounds_shift); EXPECT_EQ(zero, big_shifted); BigUnsigned<84> small_shifted = one; small_shifted.ShiftLeft(out_of_bounds_shift); EXPECT_EQ(zero, small_shifted); } } } TEST(BigUnsigned, MultiplyByUint32) { const BigUnsigned<84> factorial_100( "933262154439441526816992388562667004907159682643816214685929638952175999" "932299156089414639761565182862536979208272237582511852109168640000000000" "00000000000000"); BigUnsigned<84> a(1u); for (uint32_t i = 1; i <= 100; ++i) { a.MultiplyBy(i); } EXPECT_EQ(a, BigUnsigned<84>(factorial_100)); } TEST(BigUnsigned, MultiplyByBigUnsigned) { { const BigUnsigned<84> factorial_200( "7886578673647905035523632139321850622951359776871732632947425332443594" "4996340334292030428401198462390417721213891963883025764279024263710506" "1926624952829931113462857270763317237396988943922445621451664240254033" "2918641312274282948532775242424075739032403212574055795686602260319041" "7032406235170085879617892222278962370389737472000000000000000000000000" "0000000000000000000000000"); BigUnsigned<84> evens(1u); BigUnsigned<84> odds(1u); for (uint32_t i = 1; i < 200; i += 2) { odds.MultiplyBy(i); evens.MultiplyBy(i + 1); } evens.MultiplyBy(odds); EXPECT_EQ(evens, factorial_200); } { for (int a = 0 ; a < 700; a += 25) { SCOPED_TRACE(a); BigUnsigned<84> a_value("3" + std::string(a, '0')); for (int b = 0; b < (700 - a); b += 25) { SCOPED_TRACE(b); BigUnsigned<84> b_value("2" + std::string(b, '0')); BigUnsigned<84> expected_product("6" + std::string(a + b, '0')); b_value.MultiplyBy(a_value); EXPECT_EQ(b_value, expected_product); } } } } TEST(BigUnsigned, MultiplyByOverflow) { { BigUnsigned<4> all_bits_on("340282366920938463463374607431768211455"); all_bits_on.MultiplyBy(all_bits_on); EXPECT_EQ(all_bits_on, BigUnsigned<4>(1u)); } { BigUnsigned<4> value_1("12345678901234567890123456789012345678"); BigUnsigned<4> value_2("12345678901234567890123456789012345678"); BigUnsigned<4> two_to_fiftieth(1u); two_to_fiftieth.ShiftLeft(50); value_1.ShiftLeft(50); value_2.MultiplyBy(two_to_fiftieth); EXPECT_EQ(value_1, value_2); } } TEST(BigUnsigned, FiveToTheNth) { { for (int i = 0; i < 1160; ++i) { SCOPED_TRACE(i); BigUnsigned<84> value_1(123u); BigUnsigned<84> value_2(123u); value_1.MultiplyByFiveToTheNth(i); for (int j = 0; j < i; j++) { value_2.MultiplyBy(5u); } EXPECT_EQ(value_1, value_2); } } { for (int i = 0; i < 1160; ++i) { SCOPED_TRACE(i); BigUnsigned<84> value_1(1u); value_1.MultiplyByFiveToTheNth(i); BigUnsigned<84> value_2 = BigUnsigned<84>::FiveToTheNth(i); EXPECT_EQ(value_1, value_2); } } } TEST(BigUnsigned, TenToTheNth) { { for (int i = 0; i < 800; ++i) { SCOPED_TRACE(i); BigUnsigned<84> value_1(123u); BigUnsigned<84> value_2(123u); value_1.MultiplyByTenToTheNth(i); for (int j = 0; j < i; j++) { value_2.MultiplyBy(10u); } EXPECT_EQ(value_1, value_2); } } { for (int i = 0; i < 200; ++i) { SCOPED_TRACE(i); BigUnsigned<84> value_1(135u); value_1.MultiplyByTenToTheNth(i); BigUnsigned<84> value_2("135" + std::string(i, '0')); EXPECT_EQ(value_1, value_2); } } } } ABSL_NAMESPACE_END }
2,564
#ifndef ABSL_STRINGS_INTERNAL_CORDZ_FUNCTIONS_H_ #define ABSL_STRINGS_INTERNAL_CORDZ_FUNCTIONS_H_ #include <stdint.h> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/optimization.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { int32_t get_cordz_mean_interval(); void set_cordz_mean_interval(int32_t mean_interval); #if defined(ABSL_INTERNAL_CORDZ_ENABLED) #error ABSL_INTERNAL_CORDZ_ENABLED cannot be set directly #elif defined(__linux__) && defined(ABSL_HAVE_THREAD_LOCAL) #define ABSL_INTERNAL_CORDZ_ENABLED 1 #endif #ifdef ABSL_INTERNAL_CORDZ_ENABLED struct SamplingState { int64_t next_sample; int64_t sample_stride; }; ABSL_CONST_INIT extern thread_local SamplingState cordz_next_sample; int64_t cordz_should_profile_slow(SamplingState& state); inline int64_t cordz_should_profile() { if (ABSL_PREDICT_TRUE(cordz_next_sample.next_sample > 1)) { cordz_next_sample.next_sample--; return 0; } return cordz_should_profile_slow(cordz_next_sample); } void cordz_set_next_sample_for_testing(int64_t next_sample); #else inline int64_t cordz_should_profile() { return 0; } inline void cordz_set_next_sample_for_testing(int64_t) {} #endif } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/cordz_functions.h" #include <atomic> #include <cmath> #include <limits> #include <random> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/profiling/internal/exponential_biased.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { std::atomic<int> g_cordz_mean_interval(50000); } #ifdef ABSL_INTERNAL_CORDZ_ENABLED static constexpr int64_t kInitCordzNextSample = -1; ABSL_CONST_INIT thread_local SamplingState cordz_next_sample = { kInitCordzNextSample, 1}; constexpr int64_t kIntervalIfDisabled = 1 << 16; ABSL_ATTRIBUTE_NOINLINE int64_t cordz_should_profile_slow(SamplingState& state) { thread_local absl::profiling_internal::ExponentialBiased exponential_biased_generator; int32_t mean_interval = get_cordz_mean_interval(); if (mean_interval <= 0) { state = {kIntervalIfDisabled, kIntervalIfDisabled}; return 0; } if (mean_interval == 1) { state = {1, 1}; return 1; } if (cordz_next_sample.next_sample <= 0) { const bool initialized = cordz_next_sample.next_sample != kInitCordzNextSample; auto old_stride = state.sample_stride; auto stride = exponential_biased_generator.GetStride(mean_interval); state = {stride, stride}; bool should_sample = initialized || cordz_should_profile() > 0; return should_sample ? old_stride : 0; } --state.next_sample; return 0; } void cordz_set_next_sample_for_testing(int64_t next_sample) { cordz_next_sample = {next_sample, next_sample}; } #endif int32_t get_cordz_mean_interval() { return g_cordz_mean_interval.load(std::memory_order_acquire); } void set_cordz_mean_interval(int32_t mean_interval) { g_cordz_mean_interval.store(mean_interval, std::memory_order_release); } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/cordz_functions.h" #include <thread> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::testing::Eq; using ::testing::Ge; using ::testing::Le; TEST(CordzFunctionsTest, SampleRate) { int32_t orig_sample_rate = get_cordz_mean_interval(); int32_t expected_sample_rate = 123; set_cordz_mean_interval(expected_sample_rate); EXPECT_THAT(get_cordz_mean_interval(), Eq(expected_sample_rate)); set_cordz_mean_interval(orig_sample_rate); } #ifdef ABSL_INTERNAL_CORDZ_ENABLED TEST(CordzFunctionsTest, ShouldProfileDisable) { int32_t orig_sample_rate = get_cordz_mean_interval(); set_cordz_mean_interval(0); cordz_set_next_sample_for_testing(0); EXPECT_EQ(cordz_should_profile(), 0); EXPECT_THAT(cordz_next_sample.next_sample, Eq(1 << 16)); set_cordz_mean_interval(orig_sample_rate); } TEST(CordzFunctionsTest, ShouldProfileAlways) { int32_t orig_sample_rate = get_cordz_mean_interval(); set_cordz_mean_interval(1); cordz_set_next_sample_for_testing(1); EXPECT_GT(cordz_should_profile(), 0); EXPECT_THAT(cordz_next_sample.next_sample, Le(1)); set_cordz_mean_interval(orig_sample_rate); } TEST(CordzFunctionsTest, DoesNotAlwaysSampleFirstCord) { set_cordz_mean_interval(10000); int tries = 0; bool sampled = false; do { ++tries; ASSERT_THAT(tries, Le(1000)); std::thread thread([&sampled] { sampled = cordz_should_profile() > 0; }); thread.join(); } while (sampled); } TEST(CordzFunctionsTest, ShouldProfileRate) { static constexpr int kDesiredMeanInterval = 1000; static constexpr int kSamples = 10000; int32_t orig_sample_rate = get_cordz_mean_interval(); set_cordz_mean_interval(kDesiredMeanInterval); int64_t sum_of_intervals = 0; for (int i = 0; i < kSamples; i++) { cordz_set_next_sample_for_testing(0); cordz_should_profile(); sum_of_intervals += cordz_next_sample.next_sample; } EXPECT_THAT(sum_of_intervals, Ge(9396115)); EXPECT_THAT(sum_of_intervals, Le(10618100)); set_cordz_mean_interval(orig_sample_rate); } #else TEST(CordzFunctionsTest, ShouldProfileDisabled) { int32_t orig_sample_rate = get_cordz_mean_interval(); set_cordz_mean_interval(1); cordz_set_next_sample_for_testing(0); EXPECT_FALSE(cordz_should_profile()); set_cordz_mean_interval(orig_sample_rate); } #endif } } ABSL_NAMESPACE_END }
2,565
#ifndef ABSL_STRINGS_INTERNAL_OSTRINGSTREAM_H_ #define ABSL_STRINGS_INTERNAL_OSTRINGSTREAM_H_ #include <cassert> #include <ios> #include <ostream> #include <streambuf> #include <string> #include <utility> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { class OStringStream final : public std::ostream { public: explicit OStringStream(std::string* str) : std::ostream(&buf_), buf_(str) {} OStringStream(OStringStream&& that) : std::ostream(std::move(static_cast<std::ostream&>(that))), buf_(that.buf_) { rdbuf(&buf_); } OStringStream& operator=(OStringStream&& that) { std::ostream::operator=(std::move(static_cast<std::ostream&>(that))); buf_ = that.buf_; rdbuf(&buf_); return *this; } std::string* str() { return buf_.str(); } const std::string* str() const { return buf_.str(); } void str(std::string* str) { buf_.str(str); } private: class Streambuf final : public std::streambuf { public: explicit Streambuf(std::string* str) : str_(str) {} Streambuf(const Streambuf&) = default; Streambuf& operator=(const Streambuf&) = default; std::string* str() { return str_; } const std::string* str() const { return str_; } void str(std::string* str) { str_ = str; } protected: int_type overflow(int c) override; std::streamsize xsputn(const char* s, std::streamsize n) override; private: std::string* str_; } buf_; }; } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/ostringstream.h" #include <cassert> #include <cstddef> #include <ios> #include <streambuf> namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { OStringStream::Streambuf::int_type OStringStream::Streambuf::overflow(int c) { assert(str_); if (!std::streambuf::traits_type::eq_int_type( c, std::streambuf::traits_type::eof())) str_->push_back(static_cast<char>(c)); return 1; } std::streamsize OStringStream::Streambuf::xsputn(const char* s, std::streamsize n) { assert(str_); str_->append(s, static_cast<size_t>(n)); return n; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/ostringstream.h" #include <ios> #include <memory> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "gtest/gtest.h" namespace { TEST(OStringStream, IsOStream) { static_assert( std::is_base_of<std::ostream, absl::strings_internal::OStringStream>(), ""); } TEST(OStringStream, ConstructNullptr) { absl::strings_internal::OStringStream strm(nullptr); EXPECT_EQ(nullptr, strm.str()); } TEST(OStringStream, ConstructStr) { std::string s = "abc"; { absl::strings_internal::OStringStream strm(&s); EXPECT_EQ(&s, strm.str()); } EXPECT_EQ("abc", s); } TEST(OStringStream, Destroy) { std::unique_ptr<std::string> s(new std::string); absl::strings_internal::OStringStream strm(s.get()); s.reset(); } TEST(OStringStream, MoveConstruct) { std::string s = "abc"; { absl::strings_internal::OStringStream strm1(&s); strm1 << std::hex << 16; EXPECT_EQ(&s, strm1.str()); absl::strings_internal::OStringStream strm2(std::move(strm1)); strm2 << 16; EXPECT_EQ(&s, strm2.str()); } EXPECT_EQ("abc1010", s); } TEST(OStringStream, MoveAssign) { std::string s = "abc"; { absl::strings_internal::OStringStream strm1(&s); strm1 << std::hex << 16; EXPECT_EQ(&s, strm1.str()); absl::strings_internal::OStringStream strm2(nullptr); strm2 = std::move(strm1); strm2 << 16; EXPECT_EQ(&s, strm2.str()); } EXPECT_EQ("abc1010", s); } TEST(OStringStream, Str) { std::string s1; absl::strings_internal::OStringStream strm(&s1); const absl::strings_internal::OStringStream& c_strm(strm); static_assert(std::is_same<decltype(strm.str()), std::string*>(), ""); static_assert(std::is_same<decltype(c_strm.str()), const std::string*>(), ""); EXPECT_EQ(&s1, strm.str()); EXPECT_EQ(&s1, c_strm.str()); strm.str(&s1); EXPECT_EQ(&s1, strm.str()); EXPECT_EQ(&s1, c_strm.str()); std::string s2; strm.str(&s2); EXPECT_EQ(&s2, strm.str()); EXPECT_EQ(&s2, c_strm.str()); strm.str(nullptr); EXPECT_EQ(nullptr, strm.str()); EXPECT_EQ(nullptr, c_strm.str()); } TEST(OStreamStream, WriteToLValue) { std::string s = "abc"; { absl::strings_internal::OStringStream strm(&s); EXPECT_EQ("abc", s); strm << ""; EXPECT_EQ("abc", s); strm << 42; EXPECT_EQ("abc42", s); strm << 'x' << 'y'; EXPECT_EQ("abc42xy", s); } EXPECT_EQ("abc42xy", s); } TEST(OStreamStream, WriteToRValue) { std::string s = "abc"; absl::strings_internal::OStringStream(&s) << ""; EXPECT_EQ("abc", s); absl::strings_internal::OStringStream(&s) << 42; EXPECT_EQ("abc42", s); absl::strings_internal::OStringStream(&s) << 'x' << 'y'; EXPECT_EQ("abc42xy", s); } }
2,566
#ifndef ABSL_STRINGS_INTERNAL_CORDZ_INFO_H_ #define ABSL_STRINGS_INTERNAL_CORDZ_INFO_H_ #include <atomic> #include <cstdint> #include <functional> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/spinlock.h" #include "absl/base/thread_annotations.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cordz_functions.h" #include "absl/strings/internal/cordz_handle.h" #include "absl/strings/internal/cordz_statistics.h" #include "absl/strings/internal/cordz_update_tracker.h" #include "absl/synchronization/mutex.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class ABSL_LOCKABLE CordzInfo : public CordzHandle { public: using MethodIdentifier = CordzUpdateTracker::MethodIdentifier; static void TrackCord(InlineData& cord, MethodIdentifier method, int64_t sampling_stride); static void TrackCord(InlineData& cord, const InlineData& src, MethodIdentifier method); static void MaybeTrackCord(InlineData& cord, MethodIdentifier method); static void MaybeTrackCord(InlineData& cord, const InlineData& src, MethodIdentifier method); void Untrack(); static void MaybeUntrackCord(CordzInfo* info); CordzInfo() = delete; CordzInfo(const CordzInfo&) = delete; CordzInfo& operator=(const CordzInfo&) = delete; static CordzInfo* Head(const CordzSnapshot& snapshot) ABSL_NO_THREAD_SAFETY_ANALYSIS; CordzInfo* Next(const CordzSnapshot& snapshot) const ABSL_NO_THREAD_SAFETY_ANALYSIS; void Lock(MethodIdentifier method) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex_); void Unlock() ABSL_UNLOCK_FUNCTION(mutex_); void AssertHeld() ABSL_ASSERT_EXCLUSIVE_LOCK(mutex_); void SetCordRep(CordRep* rep); CordRep* RefCordRep() const ABSL_LOCKS_EXCLUDED(mutex_); CordRep* GetCordRepForTesting() const ABSL_NO_THREAD_SAFETY_ANALYSIS { return rep_; } void SetCordRepForTesting(CordRep* rep) ABSL_NO_THREAD_SAFETY_ANALYSIS { rep_ = rep; } absl::Span<void* const> GetStack() const; absl::Span<void* const> GetParentStack() const; CordzStatistics GetCordzStatistics() const; int64_t sampling_stride() const { return sampling_stride_; } private: using SpinLock = absl::base_internal::SpinLock; using SpinLockHolder = ::absl::base_internal::SpinLockHolder; struct List { constexpr explicit List(absl::ConstInitType) : mutex(absl::kConstInit, absl::base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL) {} SpinLock mutex; std::atomic<CordzInfo*> head ABSL_GUARDED_BY(mutex){nullptr}; }; static constexpr size_t kMaxStackDepth = 64; explicit CordzInfo(CordRep* rep, const CordzInfo* src, MethodIdentifier method, int64_t weight); ~CordzInfo() override; void UnsafeSetCordRep(CordRep* rep) ABSL_NO_THREAD_SAFETY_ANALYSIS; void Track(); static MethodIdentifier GetParentMethod(const CordzInfo* src); static size_t FillParentStack(const CordzInfo* src, void** stack); void ODRCheck() const { #ifndef NDEBUG ABSL_RAW_CHECK(list_ == &global_list_, "ODR violation in Cord"); #endif } static void MaybeTrackCordImpl(InlineData& cord, const InlineData& src, MethodIdentifier method); ABSL_CONST_INIT static List global_list_; List* const list_ = &global_list_; std::atomic<CordzInfo*> ci_prev_{nullptr}; std::atomic<CordzInfo*> ci_next_{nullptr}; mutable absl::Mutex mutex_; CordRep* rep_ ABSL_GUARDED_BY(mutex_); void* stack_[kMaxStackDepth]; void* parent_stack_[kMaxStackDepth]; const size_t stack_depth_; const size_t parent_stack_depth_; const MethodIdentifier method_; const MethodIdentifier parent_method_; CordzUpdateTracker update_tracker_; const absl::Time create_time_; const int64_t sampling_stride_; }; inline ABSL_ATTRIBUTE_ALWAYS_INLINE void CordzInfo::MaybeTrackCord( InlineData& cord, MethodIdentifier method) { auto stride = cordz_should_profile(); if (ABSL_PREDICT_FALSE(stride > 0)) { TrackCord(cord, method, stride); } } inline ABSL_ATTRIBUTE_ALWAYS_INLINE void CordzInfo::MaybeTrackCord( InlineData& cord, const InlineData& src, MethodIdentifier method) { if (ABSL_PREDICT_FALSE(InlineData::is_either_profiled(cord, src))) { MaybeTrackCordImpl(cord, src, method); } } inline ABSL_ATTRIBUTE_ALWAYS_INLINE void CordzInfo::MaybeUntrackCord( CordzInfo* info) { if (ABSL_PREDICT_FALSE(info)) { info->Untrack(); } } inline void CordzInfo::AssertHeld() ABSL_ASSERT_EXCLUSIVE_LOCK(mutex_) { #ifndef NDEBUG mutex_.AssertHeld(); #endif } inline void CordzInfo::SetCordRep(CordRep* rep) { AssertHeld(); rep_ = rep; } inline void CordzInfo::UnsafeSetCordRep(CordRep* rep) { rep_ = rep; } inline CordRep* CordzInfo::RefCordRep() const ABSL_LOCKS_EXCLUDED(mutex_) { MutexLock lock(&mutex_); return rep_ ? CordRep::Ref(rep_) : nullptr; } } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/cordz_info.h" #include <cstdint> #include "absl/base/config.h" #include "absl/base/internal/spinlock.h" #include "absl/container/inlined_vector.h" #include "absl/debugging/stacktrace.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" #include "absl/strings/internal/cord_rep_crc.h" #include "absl/strings/internal/cordz_handle.h" #include "absl/strings/internal/cordz_statistics.h" #include "absl/strings/internal/cordz_update_tracker.h" #include "absl/synchronization/mutex.h" #include "absl/time/clock.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr size_t CordzInfo::kMaxStackDepth; #endif ABSL_CONST_INIT CordzInfo::List CordzInfo::global_list_{absl::kConstInit}; namespace { class CordRepAnalyzer { public: explicit CordRepAnalyzer(CordzStatistics& statistics) : statistics_(statistics) {} void AnalyzeCordRep(const CordRep* rep) { ABSL_ASSERT(rep != nullptr); size_t refcount = rep->refcount.Get(); RepRef repref{rep, (refcount > 1) ? refcount - 1 : 1}; if (repref.tag() == CRC) { statistics_.node_count++; statistics_.node_counts.crc++; memory_usage_.Add(sizeof(CordRepCrc), repref.refcount); repref = repref.Child(repref.rep->crc()->child); } repref = CountLinearReps(repref, memory_usage_); switch (repref.tag()) { case CordRepKind::BTREE: AnalyzeBtree(repref); break; default: ABSL_ASSERT(repref.tag() == CordRepKind::UNUSED_0); break; } statistics_.estimated_memory_usage += memory_usage_.total; statistics_.estimated_fair_share_memory_usage += static_cast<size_t>(memory_usage_.fair_share); } private: struct RepRef { const CordRep* rep; size_t refcount; RepRef Child(const CordRep* child) const { if (child == nullptr) return RepRef{nullptr, 0}; return RepRef{child, refcount * child->refcount.Get()}; } constexpr CordRepKind tag() const { ABSL_ASSERT(rep == nullptr || rep->tag != CordRepKind::UNUSED_0); return rep ? static_cast<CordRepKind>(rep->tag) : CordRepKind::UNUSED_0; } }; struct MemoryUsage { size_t total = 0; double fair_share = 0.0; void Add(size_t size, size_t refcount) { total += size; fair_share += static_cast<double>(size) / refcount; } }; void CountFlat(size_t size) { statistics_.node_count++; statistics_.node_counts.flat++; if (size <= 64) { statistics_.node_counts.flat_64++; } else if (size <= 128) { statistics_.node_counts.flat_128++; } else if (size <= 256) { statistics_.node_counts.flat_256++; } else if (size <= 512) { statistics_.node_counts.flat_512++; } else if (size <= 1024) { statistics_.node_counts.flat_1k++; } } RepRef CountLinearReps(RepRef rep, MemoryUsage& memory_usage) { while (rep.tag() == SUBSTRING) { statistics_.node_count++; statistics_.node_counts.substring++; memory_usage.Add(sizeof(CordRepSubstring), rep.refcount); rep = rep.Child(rep.rep->substring()->child); } if (rep.tag() >= FLAT) { size_t size = rep.rep->flat()->AllocatedSize(); CountFlat(size); memory_usage.Add(size, rep.refcount); return RepRef{nullptr, 0}; } if (rep.tag() == EXTERNAL) { statistics_.node_count++; statistics_.node_counts.external++; size_t size = rep.rep->length + sizeof(CordRepExternalImpl<intptr_t>); memory_usage.Add(size, rep.refcount); return RepRef{nullptr, 0}; } return rep; } void AnalyzeBtree(RepRef rep) { statistics_.node_count++; statistics_.node_counts.btree++; memory_usage_.Add(sizeof(CordRepBtree), rep.refcount); const CordRepBtree* tree = rep.rep->btree(); if (tree->height() > 0) { for (CordRep* edge : tree->Edges()) { AnalyzeBtree(rep.Child(edge)); } } else { for (CordRep* edge : tree->Edges()) { CountLinearReps(rep.Child(edge), memory_usage_); } } } CordzStatistics& statistics_; MemoryUsage memory_usage_; }; } CordzInfo* CordzInfo::Head(const CordzSnapshot& snapshot) { ABSL_ASSERT(snapshot.is_snapshot()); CordzInfo* head = global_list_.head.load(std::memory_order_acquire); ABSL_ASSERT(snapshot.DiagnosticsHandleIsSafeToInspect(head)); return head; } CordzInfo* CordzInfo::Next(const CordzSnapshot& snapshot) const { ABSL_ASSERT(snapshot.is_snapshot()); CordzInfo* next = ci_next_.load(std::memory_order_acquire); ABSL_ASSERT(snapshot.DiagnosticsHandleIsSafeToInspect(this)); ABSL_ASSERT(snapshot.DiagnosticsHandleIsSafeToInspect(next)); return next; } void CordzInfo::TrackCord(InlineData& cord, MethodIdentifier method, int64_t sampling_stride) { assert(cord.is_tree()); assert(!cord.is_profiled()); CordzInfo* cordz_info = new CordzInfo(cord.as_tree(), nullptr, method, sampling_stride); cord.set_cordz_info(cordz_info); cordz_info->Track(); } void CordzInfo::TrackCord(InlineData& cord, const InlineData& src, MethodIdentifier method) { assert(cord.is_tree()); assert(src.is_tree()); CordzInfo* cordz_info = cord.cordz_info(); if (cordz_info != nullptr) cordz_info->Untrack(); cordz_info = new CordzInfo(cord.as_tree(), src.cordz_info(), method, src.cordz_info()->sampling_stride()); cord.set_cordz_info(cordz_info); cordz_info->Track(); } void CordzInfo::MaybeTrackCordImpl(InlineData& cord, const InlineData& src, MethodIdentifier method) { if (src.is_profiled()) { TrackCord(cord, src, method); } else if (cord.is_profiled()) { cord.cordz_info()->Untrack(); cord.clear_cordz_info(); } } CordzInfo::MethodIdentifier CordzInfo::GetParentMethod(const CordzInfo* src) { if (src == nullptr) return MethodIdentifier::kUnknown; return src->parent_method_ != MethodIdentifier::kUnknown ? src->parent_method_ : src->method_; } size_t CordzInfo::FillParentStack(const CordzInfo* src, void** stack) { assert(stack); if (src == nullptr) return 0; if (src->parent_stack_depth_) { memcpy(stack, src->parent_stack_, src->parent_stack_depth_ * sizeof(void*)); return src->parent_stack_depth_; } memcpy(stack, src->stack_, src->stack_depth_ * sizeof(void*)); return src->stack_depth_; } CordzInfo::CordzInfo(CordRep* rep, const CordzInfo* src, MethodIdentifier method, int64_t sampling_stride) : rep_(rep), stack_depth_( static_cast<size_t>(absl::GetStackTrace(stack_, kMaxStackDepth, 1))), parent_stack_depth_(FillParentStack(src, parent_stack_)), method_(method), parent_method_(GetParentMethod(src)), create_time_(absl::Now()), sampling_stride_(sampling_stride) { update_tracker_.LossyAdd(method); if (src) { update_tracker_.LossyAdd(src->update_tracker_); } } CordzInfo::~CordzInfo() { if (ABSL_PREDICT_FALSE(rep_)) { CordRep::Unref(rep_); } } void CordzInfo::Track() { SpinLockHolder l(&list_->mutex); CordzInfo* const head = list_->head.load(std::memory_order_acquire); if (head != nullptr) { head->ci_prev_.store(this, std::memory_order_release); } ci_next_.store(head, std::memory_order_release); list_->head.store(this, std::memory_order_release); } void CordzInfo::Untrack() { ODRCheck(); { SpinLockHolder l(&list_->mutex); CordzInfo* const head = list_->head.load(std::memory_order_acquire); CordzInfo* const next = ci_next_.load(std::memory_order_acquire); CordzInfo* const prev = ci_prev_.load(std::memory_order_acquire); if (next) { ABSL_ASSERT(next->ci_prev_.load(std::memory_order_acquire) == this); next->ci_prev_.store(prev, std::memory_order_release); } if (prev) { ABSL_ASSERT(head != this); ABSL_ASSERT(prev->ci_next_.load(std::memory_order_acquire) == this); prev->ci_next_.store(next, std::memory_order_release); } else { ABSL_ASSERT(head == this); list_->head.store(next, std::memory_order_release); } } if (SafeToDelete()) { UnsafeSetCordRep(nullptr); delete this; return; } { absl::MutexLock lock(&mutex_); if (rep_) CordRep::Ref(rep_); } CordzHandle::Delete(this); } void CordzInfo::Lock(MethodIdentifier method) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex_) { mutex_.Lock(); update_tracker_.LossyAdd(method); assert(rep_); } void CordzInfo::Unlock() ABSL_UNLOCK_FUNCTION(mutex_) { bool tracked = rep_ != nullptr; mutex_.Unlock(); if (!tracked) { Untrack(); } } absl::Span<void* const> CordzInfo::GetStack() const { return absl::MakeConstSpan(stack_, stack_depth_); } absl::Span<void* const> CordzInfo::GetParentStack() const { return absl::MakeConstSpan(parent_stack_, parent_stack_depth_); } CordzStatistics CordzInfo::GetCordzStatistics() const { CordzStatistics stats; stats.method = method_; stats.parent_method = parent_method_; stats.update_tracker = update_tracker_; if (CordRep* rep = RefCordRep()) { stats.size = rep->length; CordRepAnalyzer analyzer(stats); analyzer.AnalyzeCordRep(rep); CordRep::Unref(rep); } return stats; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/cordz_info.h" #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/strings/cordz_test_helpers.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/internal/cordz_handle.h" #include "absl/strings/internal/cordz_statistics.h" #include "absl/strings/internal/cordz_update_tracker.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Ne; using ::testing::SizeIs; auto constexpr kUnknownMethod = CordzUpdateTracker::kUnknown; auto constexpr kTrackCordMethod = CordzUpdateTracker::kConstructorString; auto constexpr kChildMethod = CordzUpdateTracker::kConstructorCord; auto constexpr kUpdateMethod = CordzUpdateTracker::kAppendString; std::vector<const CordzHandle*> DeleteQueue() { return CordzHandle::DiagnosticsGetDeleteQueue(); } std::string FormatStack(absl::Span<void* const> raw_stack) { static constexpr size_t buf_size = 1 << 14; std::unique_ptr<char[]> buf(new char[buf_size]); std::string output; for (void* stackp : raw_stack) { if (absl::Symbolize(stackp, buf.get(), buf_size)) { absl::StrAppend(&output, " ", buf.get(), "\n"); } } return output; } TEST(CordzInfoTest, TrackCord) { TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); ASSERT_THAT(info, Ne(nullptr)); EXPECT_FALSE(info->is_snapshot()); EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(info)); EXPECT_THAT(info->GetCordRepForTesting(), Eq(data.rep.rep)); info->Untrack(); } TEST(CordzInfoTest, MaybeTrackChildCordWithoutSampling) { CordzSamplingIntervalHelper sample_none(99999); TestCordData parent, child; CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod); EXPECT_THAT(child.data.cordz_info(), Eq(nullptr)); } TEST(CordzInfoTest, MaybeTrackChildCordWithSampling) { CordzSamplingIntervalHelper sample_all(1); TestCordData parent, child; CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod); EXPECT_THAT(child.data.cordz_info(), Eq(nullptr)); } TEST(CordzInfoTest, MaybeTrackChildCordWithoutSamplingParentSampled) { CordzSamplingIntervalHelper sample_none(99999); TestCordData parent, child; CordzInfo::TrackCord(parent.data, kTrackCordMethod, 1); CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod); CordzInfo* parent_info = parent.data.cordz_info(); CordzInfo* child_info = child.data.cordz_info(); ASSERT_THAT(child_info, Ne(nullptr)); EXPECT_THAT(child_info->GetCordRepForTesting(), Eq(child.rep.rep)); EXPECT_THAT(child_info->GetParentStack(), parent_info->GetStack()); parent_info->Untrack(); child_info->Untrack(); } TEST(CordzInfoTest, MaybeTrackChildCordWithoutSamplingChildSampled) { CordzSamplingIntervalHelper sample_none(99999); TestCordData parent, child; CordzInfo::TrackCord(child.data, kTrackCordMethod, 1); CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod); EXPECT_THAT(child.data.cordz_info(), Eq(nullptr)); } TEST(CordzInfoTest, MaybeTrackChildCordWithSamplingChildSampled) { CordzSamplingIntervalHelper sample_all(1); TestCordData parent, child; CordzInfo::TrackCord(child.data, kTrackCordMethod, 1); CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod); EXPECT_THAT(child.data.cordz_info(), Eq(nullptr)); } TEST(CordzInfoTest, UntrackCord) { TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); info->Untrack(); EXPECT_THAT(DeleteQueue(), SizeIs(0u)); } TEST(CordzInfoTest, UntrackCordWithSnapshot) { TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); CordzSnapshot snapshot; info->Untrack(); EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(nullptr)); EXPECT_THAT(info->GetCordRepForTesting(), Eq(data.rep.rep)); EXPECT_THAT(DeleteQueue(), ElementsAre(info, &snapshot)); } TEST(CordzInfoTest, SetCordRep) { TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); TestCordRep rep; info->Lock(CordzUpdateTracker::kAppendCord); info->SetCordRep(rep.rep); info->Unlock(); EXPECT_THAT(info->GetCordRepForTesting(), Eq(rep.rep)); info->Untrack(); } TEST(CordzInfoTest, SetCordRepNullUntracksCordOnUnlock) { TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); info->Lock(CordzUpdateTracker::kAppendString); info->SetCordRep(nullptr); EXPECT_THAT(info->GetCordRepForTesting(), Eq(nullptr)); EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(info)); info->Unlock(); EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(nullptr)); } TEST(CordzInfoTest, RefCordRep) { TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); size_t refcount = data.rep.rep->refcount.Get(); EXPECT_THAT(info->RefCordRep(), Eq(data.rep.rep)); EXPECT_THAT(data.rep.rep->refcount.Get(), Eq(refcount + 1)); CordRep::Unref(data.rep.rep); info->Untrack(); } #if GTEST_HAS_DEATH_TEST TEST(CordzInfoTest, SetCordRepRequiresMutex) { TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); TestCordRep rep; EXPECT_DEBUG_DEATH(info->SetCordRep(rep.rep), ".*"); info->Untrack(); } #endif TEST(CordzInfoTest, TrackUntrackHeadFirstV2) { CordzSnapshot snapshot; EXPECT_THAT(CordzInfo::Head(snapshot), Eq(nullptr)); TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info1 = data.data.cordz_info(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info1)); EXPECT_THAT(info1->Next(snapshot), Eq(nullptr)); TestCordData data2; CordzInfo::TrackCord(data2.data, kTrackCordMethod, 1); CordzInfo* info2 = data2.data.cordz_info(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info2)); EXPECT_THAT(info2->Next(snapshot), Eq(info1)); EXPECT_THAT(info1->Next(snapshot), Eq(nullptr)); info2->Untrack(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info1)); EXPECT_THAT(info1->Next(snapshot), Eq(nullptr)); info1->Untrack(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(nullptr)); } TEST(CordzInfoTest, TrackUntrackTailFirstV2) { CordzSnapshot snapshot; EXPECT_THAT(CordzInfo::Head(snapshot), Eq(nullptr)); TestCordData data; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info1 = data.data.cordz_info(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info1)); EXPECT_THAT(info1->Next(snapshot), Eq(nullptr)); TestCordData data2; CordzInfo::TrackCord(data2.data, kTrackCordMethod, 1); CordzInfo* info2 = data2.data.cordz_info(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info2)); EXPECT_THAT(info2->Next(snapshot), Eq(info1)); EXPECT_THAT(info1->Next(snapshot), Eq(nullptr)); info1->Untrack(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info2)); EXPECT_THAT(info2->Next(snapshot), Eq(nullptr)); info2->Untrack(); ASSERT_THAT(CordzInfo::Head(snapshot), Eq(nullptr)); } TEST(CordzInfoTest, StackV2) { TestCordData data; static constexpr int kMaxStackDepth = 50; CordzInfo::TrackCord(data.data, kTrackCordMethod, 1); CordzInfo* info = data.data.cordz_info(); std::vector<void*> local_stack; local_stack.resize(kMaxStackDepth); local_stack.resize(static_cast<size_t>( absl::GetStackTrace(local_stack.data(), kMaxStackDepth, 1))); std::string got_stack = FormatStack(info->GetStack()); std::string expected_stack = FormatStack(local_stack); EXPECT_THAT(got_stack, HasSubstr(expected_stack)); info->Untrack(); } CordzInfo* TrackChildCord(InlineData& data, const InlineData& parent) { CordzInfo::TrackCord(data, parent, kChildMethod); return data.cordz_info(); } CordzInfo* TrackParentCord(InlineData& data) { CordzInfo::TrackCord(data, kTrackCordMethod, 1); return data.cordz_info(); } TEST(CordzInfoTest, GetStatistics) { TestCordData data; CordzInfo* info = TrackParentCord(data.data); CordzStatistics statistics = info->GetCordzStatistics(); EXPECT_THAT(statistics.size, Eq(data.rep.rep->length)); EXPECT_THAT(statistics.method, Eq(kTrackCordMethod)); EXPECT_THAT(statistics.parent_method, Eq(kUnknownMethod)); EXPECT_THAT(statistics.update_tracker.Value(kTrackCordMethod), Eq(1)); info->Untrack(); } TEST(CordzInfoTest, LockCountsMethod) { TestCordData data; CordzInfo* info = TrackParentCord(data.data); info->Lock(kUpdateMethod); info->Unlock(); info->Lock(kUpdateMethod); info->Unlock(); CordzStatistics statistics = info->GetCordzStatistics(); EXPECT_THAT(statistics.update_tracker.Value(kUpdateMethod), Eq(2)); info->Untrack(); } TEST(CordzInfoTest, FromParent) { TestCordData parent; TestCordData child; CordzInfo* info_parent = TrackParentCord(parent.data); CordzInfo* info_child = TrackChildCord(child.data, parent.data); std::string stack = FormatStack(info_parent->GetStack()); std::string parent_stack = FormatStack(info_child->GetParentStack()); EXPECT_THAT(stack, Eq(parent_stack)); CordzStatistics statistics = info_child->GetCordzStatistics(); EXPECT_THAT(statistics.size, Eq(child.rep.rep->length)); EXPECT_THAT(statistics.method, Eq(kChildMethod)); EXPECT_THAT(statistics.parent_method, Eq(kTrackCordMethod)); EXPECT_THAT(statistics.update_tracker.Value(kChildMethod), Eq(1)); info_parent->Untrack(); info_child->Untrack(); } } } ABSL_NAMESPACE_END }
2,567
#ifndef ABSL_STRINGS_INTERNAL_CHARCONV_PARSE_H_ #define ABSL_STRINGS_INTERNAL_CHARCONV_PARSE_H_ #include <cstdint> #include "absl/base/config.h" #include "absl/strings/charconv.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { enum class FloatType { kNumber, kInfinity, kNan }; struct ParsedFloat { uint64_t mantissa = 0; int exponent = 0; int literal_exponent = 0; FloatType type = FloatType::kNumber; const char* subrange_begin = nullptr; const char* subrange_end = nullptr; const char* end = nullptr; }; template <int base> ParsedFloat ParseFloat(const char* begin, const char* end, absl::chars_format format_flags); extern template ParsedFloat ParseFloat<10>(const char* begin, const char* end, absl::chars_format format_flags); extern template ParsedFloat ParseFloat<16>(const char* begin, const char* end, absl::chars_format format_flags); } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/charconv_parse.h" #include "absl/strings/charconv.h" #include <cassert> #include <cstdint> #include <limits> #include "absl/strings/internal/memutil.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { constexpr int kDecimalMantissaDigitsMax = 19; static_assert(std::numeric_limits<uint64_t>::digits10 == kDecimalMantissaDigitsMax, "(a) above"); static_assert(std::numeric_limits<double>::is_iec559, "IEEE double assumed"); static_assert(std::numeric_limits<double>::radix == 2, "IEEE double fact"); static_assert(std::numeric_limits<double>::digits == 53, "IEEE double fact"); static_assert(1000000000000000000u > (uint64_t{1} << (53 + 3)), "(b) above"); constexpr int kHexadecimalMantissaDigitsMax = 15; constexpr int kGuaranteedHexadecimalMantissaBitPrecision = 4 * kHexadecimalMantissaDigitsMax - 3; static_assert(kGuaranteedHexadecimalMantissaBitPrecision > std::numeric_limits<double>::digits + 2, "kHexadecimalMantissaDigitsMax too small"); constexpr int kDecimalExponentDigitsMax = 9; static_assert(std::numeric_limits<int>::digits10 >= kDecimalExponentDigitsMax, "int type too small"); constexpr int kDecimalDigitLimit = 50000000; constexpr int kHexadecimalDigitLimit = kDecimalDigitLimit / 4; static_assert(999999999 + 2 * kDecimalDigitLimit < std::numeric_limits<int>::max(), "int type too small"); static_assert(999999999 + 2 * (4 * kHexadecimalDigitLimit) < std::numeric_limits<int>::max(), "int type too small"); bool AllowExponent(chars_format flags) { bool fixed = (flags & chars_format::fixed) == chars_format::fixed; bool scientific = (flags & chars_format::scientific) == chars_format::scientific; return scientific || !fixed; } bool RequireExponent(chars_format flags) { bool fixed = (flags & chars_format::fixed) == chars_format::fixed; bool scientific = (flags & chars_format::scientific) == chars_format::scientific; return scientific && !fixed; } const int8_t kAsciiToInt[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; template <int base> bool IsDigit(char ch); template <int base> unsigned ToDigit(char ch); template <int base> bool IsExponentCharacter(char ch); template <int base> constexpr int MantissaDigitsMax(); template <int base> constexpr int DigitLimit(); template <int base> constexpr int DigitMagnitude(); template <> bool IsDigit<10>(char ch) { return ch >= '0' && ch <= '9'; } template <> bool IsDigit<16>(char ch) { return kAsciiToInt[static_cast<unsigned char>(ch)] >= 0; } template <> unsigned ToDigit<10>(char ch) { return static_cast<unsigned>(ch - '0'); } template <> unsigned ToDigit<16>(char ch) { return static_cast<unsigned>(kAsciiToInt[static_cast<unsigned char>(ch)]); } template <> bool IsExponentCharacter<10>(char ch) { return ch == 'e' || ch == 'E'; } template <> bool IsExponentCharacter<16>(char ch) { return ch == 'p' || ch == 'P'; } template <> constexpr int MantissaDigitsMax<10>() { return kDecimalMantissaDigitsMax; } template <> constexpr int MantissaDigitsMax<16>() { return kHexadecimalMantissaDigitsMax; } template <> constexpr int DigitLimit<10>() { return kDecimalDigitLimit; } template <> constexpr int DigitLimit<16>() { return kHexadecimalDigitLimit; } template <> constexpr int DigitMagnitude<10>() { return 1; } template <> constexpr int DigitMagnitude<16>() { return 4; } template <int base, typename T> int ConsumeDigits(const char* begin, const char* end, int max_digits, T* out, bool* dropped_nonzero_digit) { if (base == 10) { assert(max_digits <= std::numeric_limits<T>::digits10); } else if (base == 16) { assert(max_digits * 4 <= std::numeric_limits<T>::digits); } const char* const original_begin = begin; while (!*out && end != begin && *begin == '0') ++begin; T accumulator = *out; const char* significant_digits_end = (end - begin > max_digits) ? begin + max_digits : end; while (begin < significant_digits_end && IsDigit<base>(*begin)) { auto digit = static_cast<T>(ToDigit<base>(*begin)); assert(accumulator * base >= accumulator); accumulator *= base; assert(accumulator + digit >= accumulator); accumulator += digit; ++begin; } bool dropped_nonzero = false; while (begin < end && IsDigit<base>(*begin)) { dropped_nonzero = dropped_nonzero || (*begin != '0'); ++begin; } if (dropped_nonzero && dropped_nonzero_digit != nullptr) { *dropped_nonzero_digit = true; } *out = accumulator; return static_cast<int>(begin - original_begin); } bool IsNanChar(char v) { return (v == '_') || (v >= '0' && v <= '9') || (v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z'); } bool ParseInfinityOrNan(const char* begin, const char* end, strings_internal::ParsedFloat* out) { if (end - begin < 3) { return false; } switch (*begin) { case 'i': case 'I': { if (strings_internal::memcasecmp(begin + 1, "nf", 2) != 0) { return false; } out->type = strings_internal::FloatType::kInfinity; if (end - begin >= 8 && strings_internal::memcasecmp(begin + 3, "inity", 5) == 0) { out->end = begin + 8; } else { out->end = begin + 3; } return true; } case 'n': case 'N': { if (strings_internal::memcasecmp(begin + 1, "an", 2) != 0) { return false; } out->type = strings_internal::FloatType::kNan; out->end = begin + 3; begin += 3; if (begin < end && *begin == '(') { const char* nan_begin = begin + 1; while (nan_begin < end && IsNanChar(*nan_begin)) { ++nan_begin; } if (nan_begin < end && *nan_begin == ')') { out->subrange_begin = begin + 1; out->subrange_end = nan_begin; out->end = nan_begin + 1; } } return true; } default: return false; } } } namespace strings_internal { template <int base> strings_internal::ParsedFloat ParseFloat(const char* begin, const char* end, chars_format format_flags) { strings_internal::ParsedFloat result; if (begin == end) return result; if (ParseInfinityOrNan(begin, end, &result)) { return result; } const char* const mantissa_begin = begin; while (begin < end && *begin == '0') { ++begin; } uint64_t mantissa = 0; int exponent_adjustment = 0; bool mantissa_is_inexact = false; int pre_decimal_digits = ConsumeDigits<base>( begin, end, MantissaDigitsMax<base>(), &mantissa, &mantissa_is_inexact); begin += pre_decimal_digits; int digits_left; if (pre_decimal_digits >= DigitLimit<base>()) { return result; } else if (pre_decimal_digits > MantissaDigitsMax<base>()) { exponent_adjustment = static_cast<int>(pre_decimal_digits - MantissaDigitsMax<base>()); digits_left = 0; } else { digits_left = static_cast<int>(MantissaDigitsMax<base>() - pre_decimal_digits); } if (begin < end && *begin == '.') { ++begin; if (mantissa == 0) { const char* begin_zeros = begin; while (begin < end && *begin == '0') { ++begin; } int zeros_skipped = static_cast<int>(begin - begin_zeros); if (zeros_skipped >= DigitLimit<base>()) { return result; } exponent_adjustment -= static_cast<int>(zeros_skipped); } int post_decimal_digits = ConsumeDigits<base>( begin, end, digits_left, &mantissa, &mantissa_is_inexact); begin += post_decimal_digits; if (post_decimal_digits >= DigitLimit<base>()) { return result; } else if (post_decimal_digits > digits_left) { exponent_adjustment -= digits_left; } else { exponent_adjustment -= post_decimal_digits; } } if (mantissa_begin == begin) { return result; } if (begin - mantissa_begin == 1 && *mantissa_begin == '.') { return result; } if (mantissa_is_inexact) { if (base == 10) { result.subrange_begin = mantissa_begin; result.subrange_end = begin; } else if (base == 16) { mantissa |= 1; } } result.mantissa = mantissa; const char* const exponent_begin = begin; result.literal_exponent = 0; bool found_exponent = false; if (AllowExponent(format_flags) && begin < end && IsExponentCharacter<base>(*begin)) { bool negative_exponent = false; ++begin; if (begin < end && *begin == '-') { negative_exponent = true; ++begin; } else if (begin < end && *begin == '+') { ++begin; } const char* const exponent_digits_begin = begin; begin += ConsumeDigits<10>(begin, end, kDecimalExponentDigitsMax, &result.literal_exponent, nullptr); if (begin == exponent_digits_begin) { found_exponent = false; begin = exponent_begin; } else { found_exponent = true; if (negative_exponent) { result.literal_exponent = -result.literal_exponent; } } } if (!found_exponent && RequireExponent(format_flags)) { return result; } result.type = strings_internal::FloatType::kNumber; if (result.mantissa > 0) { result.exponent = result.literal_exponent + (DigitMagnitude<base>() * exponent_adjustment); } else { result.exponent = 0; } result.end = begin; return result; } template ParsedFloat ParseFloat<10>(const char* begin, const char* end, chars_format format_flags); template ParsedFloat ParseFloat<16>(const char* begin, const char* end, chars_format format_flags); } ABSL_NAMESPACE_END }
#include "absl/strings/internal/charconv_parse.h" #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/strings/str_cat.h" using absl::chars_format; using absl::strings_internal::FloatType; using absl::strings_internal::ParsedFloat; using absl::strings_internal::ParseFloat; namespace { template <int base> void ExpectParsedFloat(std::string s, absl::chars_format format_flags, FloatType expected_type, uint64_t expected_mantissa, int expected_exponent, int expected_literal_exponent = -999) { SCOPED_TRACE(s); int begin_subrange = -1; int end_subrange = -1; std::string::size_type open_bracket_pos = s.find('['); if (open_bracket_pos != std::string::npos) { begin_subrange = static_cast<int>(open_bracket_pos); s.replace(open_bracket_pos, 1, ""); std::string::size_type close_bracket_pos = s.find(']'); CHECK_NE(close_bracket_pos, absl::string_view::npos) << "Test input contains [ without matching ]"; end_subrange = static_cast<int>(close_bracket_pos); s.replace(close_bracket_pos, 1, ""); } const std::string::size_type expected_characters_matched = s.find('$'); CHECK_NE(expected_characters_matched, std::string::npos) << "Input string must contain $"; s.replace(expected_characters_matched, 1, ""); ParsedFloat parsed = ParseFloat<base>(s.data(), s.data() + s.size(), format_flags); EXPECT_NE(parsed.end, nullptr); if (parsed.end == nullptr) { return; } EXPECT_EQ(parsed.type, expected_type); if (begin_subrange == -1) { EXPECT_EQ(parsed.subrange_begin, nullptr); EXPECT_EQ(parsed.subrange_end, nullptr); } else { EXPECT_EQ(parsed.subrange_begin, s.data() + begin_subrange); EXPECT_EQ(parsed.subrange_end, s.data() + end_subrange); } if (parsed.type == FloatType::kNumber) { EXPECT_EQ(parsed.mantissa, expected_mantissa); EXPECT_EQ(parsed.exponent, expected_exponent); if (expected_literal_exponent != -999) { EXPECT_EQ(parsed.literal_exponent, expected_literal_exponent); } } auto characters_matched = static_cast<int>(parsed.end - s.data()); EXPECT_EQ(characters_matched, expected_characters_matched); } template <int base> void ExpectNumber(std::string s, absl::chars_format format_flags, uint64_t expected_mantissa, int expected_exponent, int expected_literal_exponent = -999) { ExpectParsedFloat<base>(std::move(s), format_flags, FloatType::kNumber, expected_mantissa, expected_exponent, expected_literal_exponent); } void ExpectSpecial(const std::string& s, absl::chars_format format_flags, FloatType type) { ExpectParsedFloat<10>(s, format_flags, type, 0, 0); ExpectParsedFloat<16>(s, format_flags, type, 0, 0); } template <int base> void ExpectFailedParse(absl::string_view s, absl::chars_format format_flags) { ParsedFloat parsed = ParseFloat<base>(s.data(), s.data() + s.size(), format_flags); EXPECT_EQ(parsed.end, nullptr); } TEST(ParseFloat, SimpleValue) { ExpectNumber<10>("1.23456789e5$", chars_format::general, 123456789, -3); ExpectNumber<10>("1.23456789e+5$", chars_format::general, 123456789, -3); ExpectNumber<10>("1.23456789E5$", chars_format::general, 123456789, -3); ExpectNumber<10>("1.23456789e05$", chars_format::general, 123456789, -3); ExpectNumber<10>("123.456789e3$", chars_format::general, 123456789, -3); ExpectNumber<10>("0.000123456789e9$", chars_format::general, 123456789, -3); ExpectNumber<10>("123456.789$", chars_format::general, 123456789, -3); ExpectNumber<10>("123456789e-3$", chars_format::general, 123456789, -3); ExpectNumber<16>("1.234abcdefp28$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1.234abcdefp+28$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1.234ABCDEFp28$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1.234AbCdEfP0028$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("123.4abcdefp20$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("0.0001234abcdefp44$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1234abcd.ef$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1234abcdefp-8$", chars_format::general, 0x1234abcdef, -8); ExpectNumber<10>("0001.2345678900e005$", chars_format::general, 12345678900, -5); ExpectNumber<16>("0001.234abcdef000p28$", chars_format::general, 0x1234abcdef000, -20); ExpectNumber<10>("1.23456789e5$ ", chars_format::general, 123456789, -3); ExpectNumber<10>("1.23456789e5$e5e5", chars_format::general, 123456789, -3); ExpectNumber<10>("1.23456789e5$.25", chars_format::general, 123456789, -3); ExpectNumber<10>("1.23456789e5$-", chars_format::general, 123456789, -3); ExpectNumber<10>("1.23456789e5$PUPPERS!!!", chars_format::general, 123456789, -3); ExpectNumber<10>("123456.789$efghij", chars_format::general, 123456789, -3); ExpectNumber<10>("123456.789$e", chars_format::general, 123456789, -3); ExpectNumber<10>("123456.789$p5", chars_format::general, 123456789, -3); ExpectNumber<10>("123456.789$.10", chars_format::general, 123456789, -3); ExpectNumber<16>("1.234abcdefp28$ ", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1.234abcdefp28$p28", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1.234abcdefp28$.125", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1.234abcdefp28$-", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1.234abcdefp28$KITTEHS!!!", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1234abcd.ef$ghijk", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1234abcd.ef$p", chars_format::general, 0x1234abcdef, -8); ExpectNumber<16>("1234abcd.ef$.10", chars_format::general, 0x1234abcdef, -8); ExpectNumber<10>("9999999999999999999$", chars_format::general, 9999999999999999999u, 0); ExpectNumber<16>("fffffffffffffff$", chars_format::general, 0xfffffffffffffffu, 0); ExpectNumber<10>("0$", chars_format::general, 0, 0); ExpectNumber<16>("0$", chars_format::general, 0, 0); ExpectNumber<10>("000000000000000000000000000000000000000$", chars_format::general, 0, 0); ExpectNumber<16>("000000000000000000000000000000000000000$", chars_format::general, 0, 0); ExpectNumber<10>("0000000000000000000000.000000000000000000$", chars_format::general, 0, 0); ExpectNumber<16>("0000000000000000000000.000000000000000000$", chars_format::general, 0, 0); ExpectNumber<10>("0.00000000000000000000000000000000e123456$", chars_format::general, 0, 0); ExpectNumber<16>("0.00000000000000000000000000000000p123456$", chars_format::general, 0, 0); } TEST(ParseFloat, LargeDecimalMantissa) { ExpectNumber<10>("100000000000000000000000000$", chars_format::general, 1000000000000000000, 8); ExpectNumber<10>("123456789123456789100000000$", chars_format::general, 1234567891234567891, 8); ExpectNumber<10>("[123456789123456789123456789]$", chars_format::general, 1234567891234567891, 8, 0); ExpectNumber<10>("[123456789123456789100000009]$", chars_format::general, 1234567891234567891, 8, 0); ExpectNumber<10>("[123456789123456789120000000]$", chars_format::general, 1234567891234567891, 8, 0); ExpectNumber<10>("[00000000123456789123456789123456789]$", chars_format::general, 1234567891234567891, 8, 0); ExpectNumber<10>("00000000123456789123456789100000000$", chars_format::general, 1234567891234567891, 8); ExpectNumber<10>("1.234567891234567891e123$", chars_format::general, 1234567891234567891, 105); ExpectNumber<10>("[1.23456789123456789123456789]e123$", chars_format::general, 1234567891234567891, 105, 123); ExpectNumber<10>("[1999999999999999999999]$", chars_format::general, 1999999999999999999, 3, 0); } TEST(ParseFloat, LargeHexadecimalMantissa) { ExpectNumber<16>("123456789abcdef123456789abcdef$", chars_format::general, 0x123456789abcdef, 60); ExpectNumber<16>("000000123456789abcdef123456789abcdef$", chars_format::general, 0x123456789abcdef, 60); ExpectNumber<16>("1.23456789abcdefp100$", chars_format::general, 0x123456789abcdef, 44); ExpectNumber<16>("1.23456789abcdef123456789abcdefp100$", chars_format::general, 0x123456789abcdef, 44); ExpectNumber<16>("123456789abcdee123456789abcdee$", chars_format::general, 0x123456789abcdef, 60); ExpectNumber<16>("123456789abcdee000000000000001$", chars_format::general, 0x123456789abcdef, 60); ExpectNumber<16>("123456789abcdee000000000000000$", chars_format::general, 0x123456789abcdee, 60); } TEST(ParseFloat, ScientificVsFixed) { ExpectNumber<10>("1.23456789$e5", chars_format::fixed, 123456789, -8); ExpectNumber<10>("123456.789$", chars_format::fixed, 123456789, -3); ExpectNumber<16>("1.234abcdef$p28", chars_format::fixed, 0x1234abcdef, -36); ExpectNumber<16>("1234abcd.ef$", chars_format::fixed, 0x1234abcdef, -8); ExpectNumber<10>("1.23456789e5$", chars_format::scientific, 123456789, -3); ExpectFailedParse<10>("-123456.789$", chars_format::scientific); ExpectNumber<16>("1.234abcdefp28$", chars_format::scientific, 0x1234abcdef, -8); ExpectFailedParse<16>("1234abcd.ef$", chars_format::scientific); } TEST(ParseFloat, Infinity) { ExpectFailedParse<10>("in", chars_format::general); ExpectFailedParse<16>("in", chars_format::general); ExpectFailedParse<10>("inx", chars_format::general); ExpectFailedParse<16>("inx", chars_format::general); ExpectSpecial("inf$", chars_format::general, FloatType::kInfinity); ExpectSpecial("Inf$", chars_format::general, FloatType::kInfinity); ExpectSpecial("INF$", chars_format::general, FloatType::kInfinity); ExpectSpecial("inf$inite", chars_format::general, FloatType::kInfinity); ExpectSpecial("iNfInItY$", chars_format::general, FloatType::kInfinity); ExpectSpecial("infinity$!!!", chars_format::general, FloatType::kInfinity); } TEST(ParseFloat, NaN) { ExpectFailedParse<10>("na", chars_format::general); ExpectFailedParse<16>("na", chars_format::general); ExpectFailedParse<10>("nah", chars_format::general); ExpectFailedParse<16>("nah", chars_format::general); ExpectSpecial("nan$", chars_format::general, FloatType::kNan); ExpectSpecial("NaN$", chars_format::general, FloatType::kNan); ExpectSpecial("nAn$", chars_format::general, FloatType::kNan); ExpectSpecial("NAN$", chars_format::general, FloatType::kNan); ExpectSpecial("NaN$aNaNaNaNaBatman!", chars_format::general, FloatType::kNan); ExpectSpecial("nan([0xabcdef])$", chars_format::general, FloatType::kNan); ExpectSpecial("nan([0xabcdef])$...", chars_format::general, FloatType::kNan); ExpectSpecial("nan([0xabcdef])$)...", chars_format::general, FloatType::kNan); ExpectSpecial("nan([])$", chars_format::general, FloatType::kNan); ExpectSpecial("nan([aAzZ09_])$", chars_format::general, FloatType::kNan); ExpectSpecial("nan$(bad-char)", chars_format::general, FloatType::kNan); ExpectSpecial("nan$(0xabcdef", chars_format::general, FloatType::kNan); } }
2,568
#ifndef ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_H_ #define ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_H_ #include <cassert> #include <cstdint> #include <iosfwd> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/optimization.h" #include "absl/strings/internal/cord_data_edge.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { void SetCordBtreeExhaustiveValidation(bool do_exaustive_validation); bool IsCordBtreeExhaustiveValidationEnabled(); class CordRepBtreeNavigator; class CordRepBtree : public CordRep { public: enum class EdgeType { kFront, kBack }; static constexpr EdgeType kFront = EdgeType::kFront; static constexpr EdgeType kBack = EdgeType::kBack; static constexpr size_t kMaxCapacity = 6; static constexpr size_t kMaxDepth = 12; static constexpr int kMaxHeight = static_cast<int>(kMaxDepth - 1); enum Action { kSelf, kCopied, kPopped }; struct OpResult { CordRepBtree* tree; Action action; }; struct CopyResult { CordRep* edge; int height; }; struct Position { size_t index; size_t n; }; static CordRepBtree* Create(CordRep* rep); static void Destroy(CordRepBtree* tree); static void Delete(CordRepBtree* tree) { delete tree; } using CordRep::Unref; static void Unref(absl::Span<CordRep* const> edges); static CordRepBtree* Append(CordRepBtree* tree, CordRep* rep); static CordRepBtree* Prepend(CordRepBtree* tree, CordRep* rep); static CordRepBtree* Append(CordRepBtree* tree, string_view data, size_t extra = 0); static CordRepBtree* Prepend(CordRepBtree* tree, string_view data, size_t extra = 0); CordRep* SubTree(size_t offset, size_t n); static CordRep* RemoveSuffix(CordRepBtree* tree, size_t n); char GetCharacter(size_t offset) const; bool IsFlat(absl::string_view* fragment) const; bool IsFlat(size_t offset, size_t n, absl::string_view* fragment) const; Span<char> GetAppendBuffer(size_t size); static ExtractResult ExtractAppendBuffer(CordRepBtree* tree, size_t extra_capacity = 1); int height() const { return static_cast<int>(storage[0]); } size_t begin() const { return static_cast<size_t>(storage[1]); } size_t back() const { return static_cast<size_t>(storage[2]) - 1; } size_t end() const { return static_cast<size_t>(storage[2]); } size_t index(EdgeType edge) const { return edge == kFront ? begin() : back(); } size_t size() const { return end() - begin(); } size_t capacity() const { return kMaxCapacity; } inline CordRep* Edge(size_t index) const; inline CordRep* Edge(EdgeType edge_type) const; inline absl::Span<CordRep* const> Edges() const; inline absl::Span<CordRep* const> Edges(size_t begin, size_t end) const; inline absl::string_view Data(size_t index) const; static bool IsValid(const CordRepBtree* tree, bool shallow = false); static CordRepBtree* AssertValid(CordRepBtree* tree, bool shallow = true); static const CordRepBtree* AssertValid(const CordRepBtree* tree, bool shallow = true); static void Dump(const CordRep* rep, std::ostream& stream); static void Dump(const CordRep* rep, absl::string_view label, std::ostream& stream); static void Dump(const CordRep* rep, absl::string_view label, bool include_contents, std::ostream& stream); template <EdgeType edge_type> inline OpResult AddEdge(bool owned, CordRep* edge, size_t delta); template <EdgeType edge_type> OpResult SetEdge(bool owned, CordRep* edge, size_t delta); static CordRepBtree* New(int height = 0); static CordRepBtree* New(CordRep* rep); static CordRepBtree* New(CordRepBtree* front, CordRepBtree* back); static CordRepBtree* Rebuild(CordRepBtree* tree); private: CordRepBtree() = default; ~CordRepBtree() = default; inline void InitInstance(int height, size_t begin = 0, size_t end = 0); void set_begin(size_t begin) { storage[1] = static_cast<uint8_t>(begin); } void set_end(size_t end) { storage[2] = static_cast<uint8_t>(end); } size_t sub_fetch_begin(size_t n) { storage[1] -= static_cast<uint8_t>(n); return storage[1]; } size_t fetch_add_end(size_t n) { const uint8_t current = storage[2]; storage[2] = static_cast<uint8_t>(current + n); return current; } Position IndexOf(size_t offset) const; Position IndexBefore(size_t offset) const; Position IndexOfLength(size_t n) const; Position IndexBefore(Position front, size_t offset) const; Position IndexBeyond(size_t offset) const; template <EdgeType edge_type> static CordRepBtree* NewLeaf(absl::string_view data, size_t extra); CordRepBtree* CopyRaw(size_t new_length) const; CordRepBtree* Copy() const; CordRepBtree* CopyBeginTo(size_t end, size_t new_length) const; static CordRepBtree* ConsumeBeginTo(CordRepBtree* tree, size_t end, size_t new_length); CordRepBtree* CopyToEndFrom(size_t begin, size_t new_length) const; static CordRep* ExtractFront(CordRepBtree* tree); static CordRepBtree* MergeTrees(CordRepBtree* left, CordRepBtree* right); static CordRepBtree* CreateSlow(CordRep* rep); static CordRepBtree* AppendSlow(CordRepBtree*, CordRep* rep); static CordRepBtree* PrependSlow(CordRepBtree*, CordRep* rep); static void Rebuild(CordRepBtree** stack, CordRepBtree* tree, bool consume); inline void AlignBegin(); inline void AlignEnd(); template <EdgeType edge_type> inline void Add(CordRep* rep); template <EdgeType edge_type> inline void Add(absl::Span<CordRep* const>); template <EdgeType edge_type> absl::string_view AddData(absl::string_view data, size_t extra); template <EdgeType edge_type> inline void SetEdge(CordRep* edge); CopyResult CopyPrefix(size_t n, bool allow_folding = true); CopyResult CopySuffix(size_t offset); inline OpResult ToOpResult(bool owned); template <EdgeType edge_type> static CordRepBtree* AddCordRep(CordRepBtree* tree, CordRep* rep); template <EdgeType edge_type> static CordRepBtree* AddData(CordRepBtree* tree, absl::string_view data, size_t extra = 0); template <EdgeType edge_type> static CordRepBtree* Merge(CordRepBtree* dst, CordRepBtree* src); Span<char> GetAppendBufferSlow(size_t size); CordRep* edges_[kMaxCapacity]; friend class CordRepBtreeTestPeer; friend class CordRepBtreeNavigator; }; inline CordRepBtree* CordRep::btree() { assert(IsBtree()); return static_cast<CordRepBtree*>(this); } inline const CordRepBtree* CordRep::btree() const { assert(IsBtree()); return static_cast<const CordRepBtree*>(this); } inline void CordRepBtree::InitInstance(int height, size_t begin, size_t end) { tag = BTREE; storage[0] = static_cast<uint8_t>(height); storage[1] = static_cast<uint8_t>(begin); storage[2] = static_cast<uint8_t>(end); } inline CordRep* CordRepBtree::Edge(size_t index) const { assert(index >= begin()); assert(index < end()); return edges_[index]; } inline CordRep* CordRepBtree::Edge(EdgeType edge_type) const { return edges_[edge_type == kFront ? begin() : back()]; } inline absl::Span<CordRep* const> CordRepBtree::Edges() const { return {edges_ + begin(), size()}; } inline absl::Span<CordRep* const> CordRepBtree::Edges(size_t begin, size_t end) const { assert(begin <= end); assert(begin >= this->begin()); assert(end <= this->end()); return {edges_ + begin, static_cast<size_t>(end - begin)}; } inline absl::string_view CordRepBtree::Data(size_t index) const { assert(height() == 0); return EdgeData(Edge(index)); } inline CordRepBtree* CordRepBtree::New(int height) { CordRepBtree* tree = new CordRepBtree; tree->length = 0; tree->InitInstance(height); return tree; } inline CordRepBtree* CordRepBtree::New(CordRep* rep) { CordRepBtree* tree = new CordRepBtree; int height = rep->IsBtree() ? rep->btree()->height() + 1 : 0; tree->length = rep->length; tree->InitInstance(height, 0, 1); tree->edges_[0] = rep; return tree; } inline CordRepBtree* CordRepBtree::New(CordRepBtree* front, CordRepBtree* back) { assert(front->height() == back->height()); CordRepBtree* tree = new CordRepBtree; tree->length = front->length + back->length; tree->InitInstance(front->height() + 1, 0, 2); tree->edges_[0] = front; tree->edges_[1] = back; return tree; } inline void CordRepBtree::Unref(absl::Span<CordRep* const> edges) { for (CordRep* edge : edges) { if (ABSL_PREDICT_FALSE(!edge->refcount.Decrement())) { CordRep::Destroy(edge); } } } inline CordRepBtree* CordRepBtree::CopyRaw(size_t new_length) const { CordRepBtree* tree = new CordRepBtree;
#include "absl/strings/internal/cord_rep_btree.h" #include <cmath> #include <deque> #include <iostream> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/cleanup/cleanup.h" #include "absl/strings/internal/cord_data_edge.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_test_util.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class CordRepBtreeTestPeer { public: static void SetEdge(CordRepBtree* node, size_t idx, CordRep* edge) { node->edges_[idx] = edge; } static void AddEdge(CordRepBtree* node, CordRep* edge) { node->edges_[node->fetch_add_end(1)] = edge; } }; namespace { using ::absl::cordrep_testing::AutoUnref; using ::absl::cordrep_testing::CordCollectRepsIf; using ::absl::cordrep_testing::CordToString; using ::absl::cordrep_testing::CordVisitReps; using ::absl::cordrep_testing::CreateFlatsFromString; using ::absl::cordrep_testing::CreateRandomString; using ::absl::cordrep_testing::MakeExternal; using ::absl::cordrep_testing::MakeFlat; using ::absl::cordrep_testing::MakeSubstring; using ::testing::_; using ::testing::AllOf; using ::testing::AnyOf; using ::testing::Conditional; using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Le; using ::testing::Ne; using ::testing::Not; using ::testing::SizeIs; using ::testing::TypedEq; MATCHER_P(EqFlatHolding, data, "Equals flat holding data") { if (arg->tag < FLAT) { *result_listener << "Expected FLAT, got tag " << static_cast<int>(arg->tag); return false; } std::string actual = CordToString(arg); if (actual != data) { *result_listener << "Expected flat holding \"" << data << "\", got flat holding \"" << actual << "\""; return false; } return true; } MATCHER_P(IsNode, height, absl::StrCat("Is a valid node of height ", height)) { if (arg == nullptr) { *result_listener << "Expected NODE, got nullptr"; return false; } if (arg->tag != BTREE) { *result_listener << "Expected NODE, got " << static_cast<int>(arg->tag); return false; } if (!CordRepBtree::IsValid(arg->btree())) { CordRepBtree::Dump(arg->btree(), "Expected valid NODE, got:", false, *result_listener->stream()); return false; } if (arg->btree()->height() != height) { *result_listener << "Expected NODE of height " << height << ", got " << arg->btree()->height(); return false; } return true; } MATCHER_P2(IsSubstring, start, length, absl::StrCat("Is a substring(start = ", start, ", length = ", length, ")")) { if (arg == nullptr) { *result_listener << "Expected substring, got nullptr"; return false; } if (arg->tag != SUBSTRING) { *result_listener << "Expected SUBSTRING, got " << static_cast<int>(arg->tag); return false; } const CordRepSubstring* const substr = arg->substring(); if (substr->start != start || substr->length != length) { *result_listener << "Expected substring(" << start << ", " << length << "), got substring(" << substr->start << ", " << substr->length << ")"; return false; } return true; } MATCHER_P2(EqExtractResult, tree, rep, "Equals ExtractResult") { if (arg.tree != tree || arg.extracted != rep) { *result_listener << "Expected {" << static_cast<const void*>(tree) << ", " << static_cast<const void*>(rep) << "}, got {" << arg.tree << ", " << arg.extracted << "}"; return false; } return true; } class DataConsumer { public: DataConsumer(absl::string_view data, bool forward) : data_(data), forward_(forward) {} absl::string_view Next(size_t n) { assert(n <= data_.size() - consumed_); consumed_ += n; return data_.substr(forward_ ? consumed_ - n : data_.size() - consumed_, n); } absl::string_view Consumed() const { return forward_ ? data_.substr(0, consumed_) : data_.substr(data_.size() - consumed_); } private: absl::string_view data_; size_t consumed_ = 0; bool forward_; }; CordRepBtree* BtreeAdd(CordRepBtree* node, bool append, absl::string_view data) { return append ? CordRepBtree::Append(node, data) : CordRepBtree::Prepend(node, data); } void GetLeafEdges(const CordRepBtree* tree, std::vector<CordRep*>& edges) { if (tree->height() == 0) { for (CordRep* edge : tree->Edges()) { edges.push_back(edge); } } else { for (CordRep* edge : tree->Edges()) { GetLeafEdges(edge->btree(), edges); } } } std::vector<CordRep*> GetLeafEdges(const CordRepBtree* tree) { std::vector<CordRep*> edges; GetLeafEdges(tree, edges); return edges; } CordRepFlat* MakeHexFlat(size_t i) { return MakeFlat(absl::StrCat("0x", absl::Hex(i, absl::kZeroPad4))); } CordRepBtree* MakeLeaf(size_t size = CordRepBtree::kMaxCapacity) { assert(size <= CordRepBtree::kMaxCapacity); CordRepBtree* leaf = CordRepBtree::Create(MakeHexFlat(0)); for (size_t i = 1; i < size; ++i) { leaf = CordRepBtree::Append(leaf, MakeHexFlat(i)); } return leaf; } CordRepBtree* MakeTree(size_t size, bool append = true) { CordRepBtree* tree = CordRepBtree::Create(MakeHexFlat(0)); for (size_t i = 1; i < size; ++i) { tree = append ? CordRepBtree::Append(tree, MakeHexFlat(i)) : CordRepBtree::Prepend(tree, MakeHexFlat(i)); } return tree; } CordRepBtree* CreateTree(absl::Span<CordRep* const> reps) { auto it = reps.begin(); CordRepBtree* tree = CordRepBtree::Create(*it); while (++it != reps.end()) tree = CordRepBtree::Append(tree, *it); return tree; } CordRepBtree* CreateTree(absl::string_view data, size_t chunk_size) { return CreateTree(CreateFlatsFromString(data, chunk_size)); } CordRepBtree* CreateTreeReverse(absl::string_view data, size_t chunk_size) { std::vector<CordRep*> flats = CreateFlatsFromString(data, chunk_size); auto rit = flats.rbegin(); CordRepBtree* tree = CordRepBtree::Create(*rit); while (++rit != flats.rend()) tree = CordRepBtree::Prepend(tree, *rit); return tree; } class CordRepBtreeTest : public testing::TestWithParam<bool> { public: bool shared() const { return GetParam(); } static std::string ToString(testing::TestParamInfo<bool> param) { return param.param ? "Shared" : "Private"; } }; INSTANTIATE_TEST_SUITE_P(WithParam, CordRepBtreeTest, testing::Bool(), CordRepBtreeTest::ToString); class CordRepBtreeHeightTest : public testing::TestWithParam<int> { public: int height() const { return GetParam(); } static std::string ToString(testing::TestParamInfo<int> param) { return absl::StrCat(param.param); } }; INSTANTIATE_TEST_SUITE_P(WithHeights, CordRepBtreeHeightTest, testing::Range(0, CordRepBtree::kMaxHeight), CordRepBtreeHeightTest::ToString); using TwoBools = testing::tuple<bool, bool>; class CordRepBtreeDualTest : public testing::TestWithParam<TwoBools> { public: bool first_shared() const { return std::get<0>(GetParam()); } bool second_shared() const { return std::get<1>(GetParam()); } static std::string ToString(testing::TestParamInfo<TwoBools> param) { if (std::get<0>(param.param)) { return std::get<1>(param.param) ? "BothShared" : "FirstShared"; } return std::get<1>(param.param) ? "SecondShared" : "Private"; } }; INSTANTIATE_TEST_SUITE_P(WithParam, CordRepBtreeDualTest, testing::Combine(testing::Bool(), testing::Bool()), CordRepBtreeDualTest::ToString); TEST(CordRepBtreeTest, SizeIsMultipleOf64) { if (sizeof(size_t) == 8 && sizeof(void*) == 8) { EXPECT_THAT(sizeof(CordRepBtree) % 64, Eq(0u)) << "Should be multiple of 64"; } } TEST(CordRepBtreeTest, NewDestroyEmptyTree) { auto* tree = CordRepBtree::New(); EXPECT_THAT(tree->size(), Eq(0u)); EXPECT_THAT(tree->height(), Eq(0)); EXPECT_THAT(tree->Edges(), ElementsAre()); CordRepBtree::Destroy(tree); } TEST(CordRepBtreeTest, NewDestroyEmptyTreeAtHeight) { auto* tree = CordRepBtree::New(3); EXPECT_THAT(tree->size(), Eq(0u)); EXPECT_THAT(tree->height(), Eq(3)); EXPECT_THAT(tree->Edges(), ElementsAre()); CordRepBtree::Destroy(tree); } TEST(CordRepBtreeTest, Btree) { CordRep* rep = CordRepBtree::New(); EXPECT_THAT(rep->btree(), Eq(rep)); EXPECT_THAT(static_cast<const CordRep*>(rep)->btree(), Eq(rep)); CordRep::Unref(rep); #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) rep = MakeFlat("Hello world"); EXPECT_DEATH(rep->btree(), ".*"); EXPECT_DEATH(static_cast<const CordRep*>(rep)->btree(), ".*"); CordRep::Unref(rep); #endif } TEST(CordRepBtreeTest, EdgeData) { CordRepFlat* flat = MakeFlat("Hello world"); CordRepExternal* external = MakeExternal("Hello external"); CordRep* substr1 = MakeSubstring(1, 6, CordRep::Ref(flat)); CordRep* substr2 = MakeSubstring(1, 6, CordRep::Ref(external)); CordRep* bad_substr = MakeSubstring(1, 2, CordRep::Ref(substr1)); EXPECT_TRUE(IsDataEdge(flat)); EXPECT_THAT(EdgeData(flat).data(), TypedEq<const void*>(flat->Data())); EXPECT_THAT(EdgeData(flat), Eq("Hello world")); EXPECT_TRUE(IsDataEdge(external)); EXPECT_THAT(EdgeData(external).data(), TypedEq<const void*>(external->base)); EXPECT_THAT(EdgeData(external), Eq("Hello external")); EXPECT_TRUE(IsDataEdge(substr1)); EXPECT_THAT(EdgeData(substr1).data(), TypedEq<const void*>(flat->Data() + 1)); EXPECT_THAT(EdgeData(substr1), Eq("ello w")); EXPECT_TRUE(IsDataEdge(substr2)); EXPECT_THAT(EdgeData(substr2).data(), TypedEq<const void*>(external->base + 1)); EXPECT_THAT(EdgeData(substr2), Eq("ello e")); EXPECT_FALSE(IsDataEdge(bad_substr)); #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) EXPECT_DEATH(EdgeData(bad_substr), ".*"); #endif CordRep::Unref(bad_substr); CordRep::Unref(substr2); CordRep::Unref(substr1); CordRep::Unref(external); CordRep::Unref(flat); } TEST(CordRepBtreeTest, CreateUnrefLeaf) { auto* flat = MakeFlat("a"); auto* leaf = CordRepBtree::Create(flat); EXPECT_THAT(leaf->size(), Eq(1u)); EXPECT_THAT(leaf->height(), Eq(0)); EXPECT_THAT(leaf->Edges(), ElementsAre(flat)); CordRepBtree::Unref(leaf); } TEST(CordRepBtreeTest, NewUnrefNode) { auto* leaf = CordRepBtree::Create(MakeFlat("a")); CordRepBtree* tree = CordRepBtree::New(leaf); EXPECT_THAT(tree->size(), Eq(1u)); EXPECT_THAT(tree->height(), Eq(1)); EXPECT_THAT(tree->Edges(), ElementsAre(leaf)); CordRepBtree::Unref(tree); } TEST_P(CordRepBtreeTest, AppendToLeafToCapacity) { AutoUnref refs; std::vector<CordRep*> flats; flats.push_back(MakeHexFlat(0)); auto* leaf = CordRepBtree::Create(flats.back()); for (size_t i = 1; i < CordRepBtree::kMaxCapacity; ++i) { refs.RefIf(shared(), leaf); flats.push_back(MakeHexFlat(i)); auto* result = CordRepBtree::Append(leaf, flats.back()); EXPECT_THAT(result->height(), Eq(0)); EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf))); EXPECT_THAT(result->Edges(), ElementsAreArray(flats)); leaf = result; } CordRep::Unref(leaf); } TEST_P(CordRepBtreeTest, PrependToLeafToCapacity) { AutoUnref refs; std::deque<CordRep*> flats; flats.push_front(MakeHexFlat(0)); auto* leaf = CordRepBtree::Create(flats.front()); for (size_t i = 1; i < CordRepBtree::kMaxCapacity; ++i) { refs.RefIf(shared(), leaf); flats.push_front(MakeHexFlat(i)); auto* result = CordRepBtree::Prepend(leaf, flats.front()); EXPECT_THAT(result->height(), Eq(0)); EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf))); EXPECT_THAT(result->Edges(), ElementsAreArray(flats)); leaf = result; } CordRep::Unref(leaf); } TEST_P(CordRepBtreeTest, AppendPrependToLeafToCapacity) { AutoUnref refs; std::deque<CordRep*> flats; flats.push_front(MakeHexFlat(0)); auto* leaf = CordRepBtree::Create(flats.front()); for (size_t i = 1; i < CordRepBtree::kMaxCapacity; ++i) { refs.RefIf(shared(), leaf); CordRepBtree* result; if (i % 2 != 0) { flats.push_front(MakeHexFlat(i)); result = CordRepBtree::Prepend(leaf, flats.front()); } else { flats.push_back(MakeHexFlat(i)); result = CordRepBtree::Append(leaf, flats.back()); } EXPECT_THAT(result->height(), Eq(0)); EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf))); EXPECT_THAT(result->Edges(), ElementsAreArray(flats)); leaf = result; } CordRep::Unref(leaf); } TEST_P(CordRepBtreeTest, AppendToLeafBeyondCapacity) { AutoUnref refs; auto* leaf = MakeLeaf(); refs.RefIf(shared(), leaf); CordRep* flat = MakeFlat("abc"); auto* result = CordRepBtree::Append(leaf, flat); ASSERT_THAT(result, IsNode(1)); EXPECT_THAT(result, Ne(leaf)); absl::Span<CordRep* const> edges = result->Edges(); ASSERT_THAT(edges, ElementsAre(leaf, IsNode(0))); EXPECT_THAT(edges[1]->btree()->Edges(), ElementsAre(flat)); CordRep::Unref(result); } TEST_P(CordRepBtreeTest, PrependToLeafBeyondCapacity) { AutoUnref refs; auto* leaf = MakeLeaf(); refs.RefIf(shared(), leaf); CordRep* flat = MakeFlat("abc"); auto* result = CordRepBtree::Prepend(leaf, flat); ASSERT_THAT(result, IsNode(1)); EXPECT_THAT(result, Ne(leaf)); absl::Span<CordRep* const> edges = result->Edges(); ASSERT_THAT(edges, ElementsAre(IsNode(0), leaf)); EXPECT_THAT(edges[0]->btree()->Edges(), ElementsAre(flat)); CordRep::Unref(result); } TEST_P(CordRepBtreeTest, AppendToTreeOneDeep) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; AutoUnref refs; std::vector<CordRep*> flats; flats.push_back(MakeHexFlat(0)); CordRepBtree* tree = CordRepBtree::Create(flats.back()); for (size_t i = 1; i <= max_cap; ++i) { flats.push_back(MakeHexFlat(i)); tree = CordRepBtree::Append(tree, flats.back()); } ASSERT_THAT(tree, IsNode(1)); for (size_t i = max_cap + 1; i < max_cap * max_cap; ++i) { refs.RefIf(shared(), tree); refs.RefIf(i % 4 == 0, tree->Edges().back()); flats.push_back(MakeHexFlat(i)); CordRepBtree* result = CordRepBtree::Append(tree, flats.back()); ASSERT_THAT(result, IsNode(1)); ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); std::vector<CordRep*> edges = GetLeafEdges(result); ASSERT_THAT(edges, ElementsAreArray(flats)); tree = result; } CordRep::Unref(tree); } TEST_P(CordRepBtreeTest, AppendToTreeTwoDeep) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; AutoUnref refs; std::vector<CordRep*> flats; flats.push_back(MakeHexFlat(0)); CordRepBtree* tree = CordRepBtree::Create(flats.back()); for (size_t i = 1; i <= max_cap * max_cap; ++i) { flats.push_back(MakeHexFlat(i)); tree = CordRepBtree::Append(tree, flats.back()); } ASSERT_THAT(tree, IsNode(2)); for (size_t i = max_cap * max_cap + 1; i < max_cap * max_cap * max_cap; ++i) { refs.RefIf(shared(), tree); refs.RefIf(i % 16 == 0, tree->Edges().back()); refs.RefIf(i % 4 == 0, tree->Edges().back()->btree()->Edges().back()); flats.push_back(MakeHexFlat(i)); CordRepBtree* result = CordRepBtree::Append(tree, flats.back()); ASSERT_THAT(result, IsNode(2)); ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); std::vector<CordRep*> edges = GetLeafEdges(result); ASSERT_THAT(edges, ElementsAreArray(flats)); tree = result; } CordRep::Unref(tree); } TEST_P(CordRepBtreeTest, PrependToTreeOneDeep) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; AutoUnref refs; std::deque<CordRep*> flats; flats.push_back(MakeHexFlat(0)); CordRepBtree* tree = CordRepBtree::Create(flats.back()); for (size_t i = 1; i <= max_cap; ++i) { flats.push_front(MakeHexFlat(i)); tree = CordRepBtree::Prepend(tree, flats.front()); } ASSERT_THAT(tree, IsNode(1)); for (size_t i = max_cap + 1; i < max_cap * max_cap; ++i) { refs.RefIf(shared(), tree); refs.RefIf(i % 4 == 0, tree->Edges().back()); flats.push_front(MakeHexFlat(i)); CordRepBtree* result = CordRepBtree::Prepend(tree, flats.front()); ASSERT_THAT(result, IsNode(1)); ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); std::vector<CordRep*> edges = GetLeafEdges(result); ASSERT_THAT(edges, ElementsAreArray(flats)); tree = result; } CordRep::Unref(tree); } TEST_P(CordRepBtreeTest, PrependToTreeTwoDeep) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; AutoUnref refs; std::deque<CordRep*> flats; flats.push_back(MakeHexFlat(0)); CordRepBtree* tree = CordRepBtree::Create(flats.back()); for (size_t i = 1; i <= max_cap * max_cap; ++i) { flats.push_front(MakeHexFlat(i)); tree = CordRepBtree::Prepend(tree, flats.front()); } ASSERT_THAT(tree, IsNode(2)); for (size_t i = max_cap * max_cap + 1; i < max_cap * max_cap * max_cap; ++i) { refs.RefIf(shared(), tree); refs.RefIf(i % 16 == 0, tree->Edges().back()); refs.RefIf(i % 4 == 0, tree->Edges().back()->btree()->Edges().back()); flats.push_front(MakeHexFlat(i)); CordRepBtree* result = CordRepBtree::Prepend(tree, flats.front()); ASSERT_THAT(result, IsNode(2)); ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); std::vector<CordRep*> edges = GetLeafEdges(result); ASSERT_THAT(edges, ElementsAreArray(flats)); tree = result; } CordRep::Unref(tree); } TEST_P(CordRepBtreeDualTest, MergeLeafsNotExceedingCapacity) { for (bool use_append : {false, true}) { SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend"); AutoUnref refs; std::vector<CordRep*> flats; CordRepBtree* left = MakeLeaf(3); GetLeafEdges(left, flats); refs.RefIf(first_shared(), left); CordRepBtree* right = MakeLeaf(2); GetLeafEdges(right, flats); refs.RefIf(second_shared(), right); CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right) : CordRepBtree::Prepend(right, left); EXPECT_THAT(tree, IsNode(0)); EXPECT_THAT(tree->Edges(), ElementsAreArray(flats)); CordRepBtree::Unref(tree); } } TEST_P(CordRepBtreeDualTest, MergeLeafsExceedingCapacity) { for (bool use_append : {false, true}) { SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend"); AutoUnref refs; CordRepBtree* left = MakeLeaf(CordRepBtree::kMaxCapacity - 2); refs.RefIf(first_shared(), left); CordRepBtree* right = MakeLeaf(CordRepBtree::kMaxCapacity - 1); refs.RefIf(second_shared(), right); CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right) : CordRepBtree::Prepend(right, left); EXPECT_THAT(tree, IsNode(1)); EXPECT_THAT(tree->Edges(), ElementsAre(left, right)); CordRepBtree::Unref(tree); } } TEST_P(CordRepBtreeDualTest, MergeEqualHeightTrees) { for (bool use_append : {false, true}) { SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend"); AutoUnref refs; std::vector<CordRep*> flats; CordRepBtree* left = MakeTree(CordRepBtree::kMaxCapacity * 3); GetLeafEdges(left, flats); refs.RefIf(first_shared(), left); CordRepBtree* right = MakeTree(CordRepBtree::kMaxCapacity * 2); GetLeafEdges(right, flats); refs.RefIf(second_shared(), right); CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right) : CordRepBtree::Prepend(right, left); EXPECT_THAT(tree, IsNode(1)); EXPECT_THAT(tree->Edges(), SizeIs(5u)); EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats)); CordRepBtree::Unref(tree); } } TEST_P(CordRepBtreeDualTest, MergeLeafWithTreeNotExceedingLeafCapacity) { for (bool use_append : {false, true}) { SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend"); AutoUnref refs; std::vector<CordRep*> flats; CordRepBtree* left = MakeTree(CordRepBtree::kMaxCapacity * 2 + 2); GetLeafEdges(left, flats); refs.RefIf(first_shared(), left); CordRepBtree* right = MakeTree(3); GetLeafEdges(right, flats); refs.RefIf(second_shared(), right); CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right) : CordRepBtree::Prepend(right, left); EXPECT_THAT(tree, IsNode(1)); EXPECT_THAT(tree->Edges(), SizeIs(3u)); EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats)); CordRepBtree::Unref(tree); } } TEST_P(CordRepBtreeDualTest, MergeLeafWithTreeExceedingLeafCapacity) { for (bool use_append : {false, true}) { SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend"); AutoUnref refs; std::vector<CordRep*> flats; CordRepBtree* left = MakeTree(CordRepBtree::kMaxCapacity * 3 - 2); GetLeafEdges(left, flats); refs.RefIf(first_shared(), left); CordRepBtree* right = MakeTree(3); GetLeafEdges(right, flats); refs.RefIf(second_shared(), right); CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right) : CordRepBtree::Prepend(right, left); EXPECT_THAT(tree, IsNode(1)); EXPECT_THAT(tree->Edges(), SizeIs(4u)); EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats)); CordRepBtree::Unref(tree); } } void RefEdgesAt(size_t depth, AutoUnref& refs, CordRepBtree* tree) { absl::Span<CordRep* const> edges = tree->Edges(); if (depth == 0) { refs.Ref(edges.front()); refs.Ref(edges.back()); } else { assert(tree->height() > 0); RefEdgesAt(depth - 1, refs, edges.front()->btree()); RefEdgesAt(depth - 1, refs, edges.back()->btree()); } } TEST(CordRepBtreeTest, MergeFuzzTest) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; std::minstd_rand rnd; std::uniform_int_distribution<int> coin_flip(0, 1); std::uniform_int_distribution<int> dice_throw(1, 6); auto random_leaf_count = [&]() { std::uniform_int_distribution<int> dist_height(0, 3); std::uniform_int_distribution<int> dist_leaf(0, max_cap - 1); const int height = dist_height(rnd); return (height ? pow(max_cap, height) : 0) + dist_leaf(rnd); }; for (int i = 0; i < 10000; ++i) { AutoUnref refs; std::vector<CordRep*> flats; CordRepBtree* left = MakeTree(random_leaf_count(), coin_flip(rnd)); GetLeafEdges(left, flats); if (dice_throw(rnd) == 1) { std::uniform_int_distribution<size_t> dist( 0, static_cast<size_t>(left->height())); RefEdgesAt(dist(rnd), refs, left); } CordRepBtree* right = MakeTree(random_leaf_count(), coin_flip(rnd)); GetLeafEdges(right, flats); if (dice_throw(rnd) == 1) { std::uniform_int_distribution<size_t> dist( 0, static_cast<size_t>(right->height())); RefEdgesAt(dist(rnd), refs, right); } CordRepBtree* tree = CordRepBtree::Append(left, right); EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats)); CordRepBtree::Unref(tree); } } TEST_P(CordRepBtreeTest, RemoveSuffix) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; for (size_t cap : {max_cap - 1, max_cap * 2, max_cap * max_cap * 2}) { const std::string data = CreateRandomString(cap * 512); { AutoUnref refs; CordRepBtree* node = refs.RefIf(shared(), CreateTree(data, 512)); EXPECT_THAT(CordRepBtree::RemoveSuffix(node, data.length()), Eq(nullptr)); node = refs.RefIf(shared(), CreateTree(data, 512)); EXPECT_THAT(CordRepBtree::RemoveSuffix(node, 0), Eq(node)); CordRep::Unref(node); } for (size_t n = 1; n < data.length(); ++n) { AutoUnref refs; auto flats = CreateFlatsFromString(data, 512); CordRepBtree* node = refs.RefIf(shared(), CreateTree(flats)); CordRep* rep = refs.Add(CordRepBtree::RemoveSuffix(node, n)); EXPECT_THAT(CordToString(rep), Eq(data.substr(0, data.length() - n))); auto is_flat = [](CordRep* rep) { return rep->tag >= FLAT; }; std::vector<CordRep*> edges = CordCollectRepsIf(is_flat, rep); ASSERT_THAT(edges.size(), Le(flats.size())); CordRep* last_edge = edges.back(); edges.pop_back(); const size_t last_length = rep->length - edges.size() * 512; size_t index = 0; for (CordRep* edge : edges) { ASSERT_THAT(edge, Eq(flats[index++])); ASSERT_THAT(edge->length, Eq(512u)); } if (last_length >= 500) { EXPECT_THAT(last_edge, Eq(flats[index++])); if (shared()) { EXPECT_THAT(last_edge->length, Eq(512u)); } else { EXPECT_TRUE(last_edge->refcount.IsOne()); EXPECT_THAT(last_edge->length, Eq(last_length)); } } } } } TEST(CordRepBtreeTest, SubTree) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; const size_t n = max_cap * max_cap * 2; const std::string data = CreateRandomString(n * 3); std::vector<CordRep*> flats; for (absl::string_view s = data; !s.empty(); s.remove_prefix(3)) { flats.push_back(MakeFlat(s.substr(0, 3))); } CordRepBtree* node = CordRepBtree::Create(CordRep::Ref(flats[0])); for (size_t i = 1; i < flats.size(); ++i) { node = CordRepBtree::Append(node, CordRep::Ref(flats[i])); } for (size_t offset = 0; offset < data.length(); ++offset) { for (size_t length = 1; length <= data.length() - offset; ++length) { CordRep* rep = node->SubTree(offset, length); EXPECT_THAT(CordToString(rep), Eq(data.substr(offset, length))); CordRep::Unref(rep); } } CordRepBtree::Unref(node); for (CordRep* rep : flats) { CordRep::Unref(rep); } } TEST(CordRepBtreeTest, SubTreeOnExistingSubstring) { AutoUnref refs; std::string data = CreateRandomString(1000); CordRepBtree* leaf = CordRepBtree::Create(MakeFlat("abc")); CordRep* flat = MakeFlat(data); leaf = CordRepBtree::Append(leaf, flat); CordRep* result = leaf->SubTree(0, 3 + 990); ASSERT_THAT(result->tag, Eq(BTREE)); CordRep::Unref(leaf); leaf = result->btree(); ASSERT_THAT(leaf->Edges(), ElementsAre(_, IsSubstring(0u, 990u))); EXPECT_THAT(leaf->Edges()[1]->substring()->child, Eq(flat)); result = leaf->SubTree(3 + 5, 970); ASSERT_THAT(result, IsSubstring(5u, 970u)); EXPECT_THAT(result->substring()->child, Eq(flat)); CordRep::Unref(result); CordRep::Unref(leaf); } TEST_P(CordRepBtreeTest, AddDataToLeaf) { const size_t n = CordRepBtree::kMaxCapacity; const std::string data = CreateRandomString(n * 3); for (bool append : {true, false}) { AutoUnref refs; DataConsumer consumer(data, append); SCOPED_TRACE(append ? "Append" : "Prepend"); CordRepBtree* leaf = CordRepBtree::Create(MakeFlat(consumer.Next(3))); for (size_t i = 1; i < n; ++i) { refs.RefIf(shared(), leaf); CordRepBtree* result = BtreeAdd(leaf, append, consumer.Next(3)); EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf))); EXPECT_THAT(CordToString(result), Eq(consumer.Consumed())); leaf = result; } CordRep::Unref(leaf); } } TEST_P(CordRepBtreeTest, AppendDataToTree) { AutoUnref refs; size_t n = CordRepBtree::kMaxCapacity + CordRepBtree::kMaxCapacity / 2; std::string data = CreateRandomString(n * 3); CordRepBtree* tree = refs.RefIf(shared(), CreateTree(data, 3)); CordRepBtree* leaf0 = tree->Edges()[0]->btree(); CordRepBtree* leaf1 = tree->Edges()[1]->btree(); CordRepBtree* result = CordRepBtree::Append(tree, "123456789"); EXPECT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); EXPECT_THAT(result->Edges(), ElementsAre(leaf0, Conditional(shared(), Ne(leaf1), Eq(leaf1)))); EXPECT_THAT(CordToString(result), Eq(data + "123456789")); CordRep::Unref(result); } TEST_P(CordRepBtreeTest, PrependDataToTree) { AutoUnref refs; size_t n = CordRepBtree::kMaxCapacity + CordRepBtree::kMaxCapacity / 2; std::string data = CreateRandomString(n * 3); CordRepBtree* tree = refs.RefIf(shared(), CreateTreeReverse(data, 3)); CordRepBtree* leaf0 = tree->Edges()[0]->btree(); CordRepBtree* leaf1 = tree->Edges()[1]->btree(); CordRepBtree* result = CordRepBtree::Prepend(tree, "123456789"); EXPECT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); EXPECT_THAT(result->Edges(),
2,569
#ifndef ABSL_STRINGS_INTERNAL_DAMERAU_LEVENSHTEIN_DISTANCE_H_ #define ABSL_STRINGS_INTERNAL_DAMERAU_LEVENSHTEIN_DISTANCE_H_ #include <cstdint> #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { uint8_t CappedDamerauLevenshteinDistance(absl::string_view s1, absl::string_view s2, uint8_t cutoff); } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/damerau_levenshtein_distance.h" #include <algorithm> #include <array> #include <numeric> #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { uint8_t CappedDamerauLevenshteinDistance(absl::string_view s1, absl::string_view s2, uint8_t cutoff) { const uint8_t MAX_SIZE = 100; const uint8_t _cutoff = std::min(MAX_SIZE, cutoff); const uint8_t cutoff_plus_1 = static_cast<uint8_t>(_cutoff + 1); if (s1.size() > s2.size()) std::swap(s1, s2); if (s1.size() + _cutoff < s2.size() || s2.size() > MAX_SIZE) return cutoff_plus_1; if (s1.empty()) return static_cast<uint8_t>(s2.size()); const uint8_t lower_diag = _cutoff - static_cast<uint8_t>(s2.size() - s1.size()); const uint8_t upper_diag = _cutoff; std::array<std::array<uint8_t, MAX_SIZE + 2>, MAX_SIZE + 2> d; std::iota(d[0].begin(), d[0].begin() + upper_diag + 1, 0); d[0][cutoff_plus_1] = cutoff_plus_1; for (size_t i = 1; i <= s1.size(); ++i) { size_t j_begin = 1; if (i > lower_diag) { j_begin = i - lower_diag; d[i][j_begin - 1] = cutoff_plus_1; } else { d[i][0] = static_cast<uint8_t>(i); } size_t j_end = i + upper_diag; if (j_end > s2.size()) { j_end = s2.size(); } else { d[i][j_end + 1] = cutoff_plus_1; } for (size_t j = j_begin; j <= j_end; ++j) { const uint8_t deletion_distance = d[i - 1][j] + 1; const uint8_t insertion_distance = d[i][j - 1] + 1; const uint8_t mismatched_tail_cost = s1[i - 1] == s2[j - 1] ? 0 : 1; const uint8_t mismatch_distance = d[i - 1][j - 1] + mismatched_tail_cost; uint8_t transposition_distance = _cutoff + 1; if (i > 1 && j > 1 && s1[i - 1] == s2[j - 2] && s1[i - 2] == s2[j - 1]) transposition_distance = d[i - 2][j - 2] + 1; d[i][j] = std::min({cutoff_plus_1, deletion_distance, insertion_distance, mismatch_distance, transposition_distance}); } } return d[s1.size()][s2.size()]; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/damerau_levenshtein_distance.h" #include <cstdint> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using absl::strings_internal::CappedDamerauLevenshteinDistance; TEST(Distance, TestDistances) { EXPECT_THAT(CappedDamerauLevenshteinDistance("ab", "ab", 6), uint8_t{0}); EXPECT_THAT(CappedDamerauLevenshteinDistance("a", "b", 6), uint8_t{1}); EXPECT_THAT(CappedDamerauLevenshteinDistance("ca", "abc", 6), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "ad", 6), uint8_t{2}); EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "cadb", 6), uint8_t{4}); EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "bdac", 6), uint8_t{4}); EXPECT_THAT(CappedDamerauLevenshteinDistance("ab", "ab", 0), uint8_t{0}); EXPECT_THAT(CappedDamerauLevenshteinDistance("", "", 0), uint8_t{0}); EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", "abc", 6), uint8_t{0}); for (auto res : {"", "ca", "efg", "ea", "ce", "ceb", "eca", "cae", "cea", "bea"}) { EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", res, 6), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance(res, "abc", 6), uint8_t{3}); } for (auto res : {"a", "b", "c", "ba", "cb", "bca", "cab", "cba", "ace", "efc", "ebf", "aef", "ae", "be", "eb", "ec", "ecb", "bec", "bce", "cbe", "ace", "eac", "aeb", "bae", "eab", "eba"}) { EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", res, 6), uint8_t{2}); EXPECT_THAT(CappedDamerauLevenshteinDistance(res, "abc", 6), uint8_t{2}); } for (auto res : {"ab", "ac", "bc", "acb", "bac", "ebc", "aec", "abe"}) { EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", res, 6), uint8_t{1}); EXPECT_THAT(CappedDamerauLevenshteinDistance(res, "abc", 6), uint8_t{1}); } } TEST(Distance, TestCutoff) { EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "a", 3), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "a", 2), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "a", 1), uint8_t{2}); EXPECT_THAT(CappedDamerauLevenshteinDistance("abcdefg", "a", 2), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance("a", "abcde", 2), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(102, 'a'), std::string(102, 'a'), 105), uint8_t{101}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'), std::string(100, 'a'), 100), uint8_t{0}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'), std::string(100, 'b'), 100), uint8_t{100}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'), std::string(99, 'a'), 2), uint8_t{1}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'), std::string(101, 'a'), 2), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'), std::string(101, 'a'), 2), uint8_t{3}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(UINT8_MAX + 1, 'a'), std::string(UINT8_MAX + 1, 'b'), UINT8_MAX), uint8_t{101}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(UINT8_MAX - 1, 'a'), std::string(UINT8_MAX - 1, 'b'), UINT8_MAX), uint8_t{101}); EXPECT_THAT( CappedDamerauLevenshteinDistance(std::string(UINT8_MAX, 'a'), std::string(UINT8_MAX, 'b'), UINT8_MAX), uint8_t{101}); EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(UINT8_MAX - 1, 'a'), std::string(UINT8_MAX - 1, 'a'), UINT8_MAX), uint8_t{101}); } }
2,570
#ifndef ABSL_STRINGS_INTERNAL_MEMUTIL_H_ #define ABSL_STRINGS_INTERNAL_MEMUTIL_H_ #include <cstddef> #include <cstring> #include "absl/base/port.h" #include "absl/strings/ascii.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { int memcasecmp(const char* s1, const char* s2, size_t len); } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/memutil.h" #include <cstdlib> #include "absl/strings/ascii.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { int memcasecmp(const char* s1, const char* s2, size_t len) { const unsigned char* us1 = reinterpret_cast<const unsigned char*>(s1); const unsigned char* us2 = reinterpret_cast<const unsigned char*>(s2); for (size_t i = 0; i < len; i++) { unsigned char c1 = us1[i]; unsigned char c2 = us2[i]; if (c1 != c2) { c1 = c1 >= 'A' && c1 <= 'Z' ? c1 - 'A' + 'a' : c1; c2 = c2 >= 'A' && c2 <= 'Z' ? c2 - 'A' + 'a' : c2; const int diff = int{c1} - int{c2}; if (diff != 0) return diff; } } return 0; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/memutil.h" #include <cstdlib> #include "gtest/gtest.h" namespace { TEST(MemUtil, memcasecmp) { const char a[] = "hello there"; EXPECT_EQ(absl::strings_internal::memcasecmp(a, "heLLO there", sizeof("hello there") - 1), 0); EXPECT_EQ(absl::strings_internal::memcasecmp(a, "heLLO therf", sizeof("hello there") - 1), -1); EXPECT_EQ(absl::strings_internal::memcasecmp(a, "heLLO therf", sizeof("hello there") - 2), 0); EXPECT_EQ(absl::strings_internal::memcasecmp(a, "whatever", 0), 0); } }
2,571
#include "absl/base/config.h" #include "absl/strings/internal/cordz_handle.h" #include "absl/strings/internal/cordz_info.h" #ifndef ABSL_STRINGS_INTERNAL_CORDZ_SAMPLE_TOKEN_H_ #define ABSL_STRINGS_INTERNAL_CORDZ_SAMPLE_TOKEN_H_ namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class CordzSampleToken : public CordzSnapshot { public: class Iterator { public: using iterator_category = std::input_iterator_tag; using value_type = const CordzInfo&; using difference_type = ptrdiff_t; using pointer = const CordzInfo*; using reference = value_type; Iterator() = default; Iterator& operator++(); Iterator operator++(int); friend bool operator==(const Iterator& lhs, const Iterator& rhs); friend bool operator!=(const Iterator& lhs, const Iterator& rhs); reference operator*() const; pointer operator->() const; private: friend class CordzSampleToken; explicit Iterator(const CordzSampleToken* token); const CordzSampleToken* token_ = nullptr; pointer current_ = nullptr; }; CordzSampleToken() = default; CordzSampleToken(const CordzSampleToken&) = delete; CordzSampleToken& operator=(const CordzSampleToken&) = delete; Iterator begin() { return Iterator(this); } Iterator end() { return Iterator(); } }; } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/cordz_sample_token.h" #include "absl/base/config.h" #include "absl/strings/internal/cordz_handle.h" #include "absl/strings/internal/cordz_info.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { CordzSampleToken::Iterator& CordzSampleToken::Iterator::operator++() { if (current_) { current_ = current_->Next(*token_); } return *this; } CordzSampleToken::Iterator CordzSampleToken::Iterator::operator++(int) { Iterator it(*this); operator++(); return it; } bool operator==(const CordzSampleToken::Iterator& lhs, const CordzSampleToken::Iterator& rhs) { return lhs.current_ == rhs.current_ && (lhs.current_ == nullptr || lhs.token_ == rhs.token_); } bool operator!=(const CordzSampleToken::Iterator& lhs, const CordzSampleToken::Iterator& rhs) { return !(lhs == rhs); } CordzSampleToken::Iterator::reference CordzSampleToken::Iterator::operator*() const { return *current_; } CordzSampleToken::Iterator::pointer CordzSampleToken::Iterator::operator->() const { return current_; } CordzSampleToken::Iterator::Iterator(const CordzSampleToken* token) : token_(token), current_(CordzInfo::Head(*token)) {} } ABSL_NAMESPACE_END }
#include "absl/strings/internal/cordz_sample_token.h" #include <memory> #include <type_traits> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" #include "absl/random/random.h" #include "absl/strings/cordz_test_helpers.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/internal/cordz_handle.h" #include "absl/strings/internal/cordz_info.h" #include "absl/synchronization/internal/thread_pool.h" #include "absl/synchronization/notification.h" #include "absl/time/clock.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Ne; auto constexpr kTrackCordMethod = CordzUpdateTracker::kConstructorString; TEST(CordzSampleTokenTest, IteratorTraits) { static_assert(std::is_copy_constructible<CordzSampleToken::Iterator>::value, ""); static_assert(std::is_copy_assignable<CordzSampleToken::Iterator>::value, ""); static_assert(std::is_move_constructible<CordzSampleToken::Iterator>::value, ""); static_assert(std::is_move_assignable<CordzSampleToken::Iterator>::value, ""); static_assert( std::is_same< std::iterator_traits<CordzSampleToken::Iterator>::iterator_category, std::input_iterator_tag>::value, ""); static_assert( std::is_same<std::iterator_traits<CordzSampleToken::Iterator>::value_type, const CordzInfo&>::value, ""); static_assert( std::is_same< std::iterator_traits<CordzSampleToken::Iterator>::difference_type, ptrdiff_t>::value, ""); static_assert( std::is_same<std::iterator_traits<CordzSampleToken::Iterator>::pointer, const CordzInfo*>::value, ""); static_assert( std::is_same<std::iterator_traits<CordzSampleToken::Iterator>::reference, const CordzInfo&>::value, ""); } TEST(CordzSampleTokenTest, IteratorEmpty) { CordzSampleToken token; EXPECT_THAT(token.begin(), Eq(token.end())); } TEST(CordzSampleTokenTest, Iterator) { TestCordData cord1, cord2, cord3; CordzInfo::TrackCord(cord1.data, kTrackCordMethod, 1); CordzInfo* info1 = cord1.data.cordz_info(); CordzInfo::TrackCord(cord2.data, kTrackCordMethod, 1); CordzInfo* info2 = cord2.data.cordz_info(); CordzInfo::TrackCord(cord3.data, kTrackCordMethod, 1); CordzInfo* info3 = cord3.data.cordz_info(); CordzSampleToken token; std::vector<const CordzInfo*> found; for (const CordzInfo& cord_info : token) { found.push_back(&cord_info); } EXPECT_THAT(found, ElementsAre(info3, info2, info1)); info1->Untrack(); info2->Untrack(); info3->Untrack(); } TEST(CordzSampleTokenTest, IteratorEquality) { TestCordData cord1; TestCordData cord2; TestCordData cord3; CordzInfo::TrackCord(cord1.data, kTrackCordMethod, 1); CordzInfo* info1 = cord1.data.cordz_info(); CordzSampleToken token1; CordzSampleToken::Iterator lhs = token1.begin(); CordzInfo::TrackCord(cord2.data, kTrackCordMethod, 1); CordzInfo* info2 = cord2.data.cordz_info(); CordzSampleToken token2; CordzSampleToken::Iterator rhs = token2.begin(); CordzInfo::TrackCord(cord3.data, kTrackCordMethod, 1); CordzInfo* info3 = cord3.data.cordz_info(); EXPECT_THAT(lhs, Ne(rhs)); rhs++; EXPECT_THAT(lhs, Ne(rhs)); lhs++; rhs++; EXPECT_THAT(lhs, Eq(rhs)); info1->Untrack(); info2->Untrack(); info3->Untrack(); } TEST(CordzSampleTokenTest, MultiThreaded) { Notification stop; static constexpr int kNumThreads = 4; static constexpr int kNumCords = 3; static constexpr int kNumTokens = 3; absl::synchronization_internal::ThreadPool pool(kNumThreads); for (int i = 0; i < kNumThreads; ++i) { pool.Schedule([&stop]() { absl::BitGen gen; TestCordData cords[kNumCords]; std::unique_ptr<CordzSampleToken> tokens[kNumTokens]; while (!stop.HasBeenNotified()) { int index = absl::Uniform(gen, 0, kNumCords); if (absl::Bernoulli(gen, 0.5)) { TestCordData& cord = cords[index]; if (cord.data.is_profiled()) { cord.data.cordz_info()->Untrack(); cord.data.clear_cordz_info(); } else { CordzInfo::TrackCord(cord.data, kTrackCordMethod, 1); } } else { std::unique_ptr<CordzSampleToken>& token = tokens[index]; if (token) { if (absl::Bernoulli(gen, 0.5)) { for (const CordzInfo& info : *token) { EXPECT_THAT(info.Next(*token), Ne(&info)); } } else { token = nullptr; } } else { token = absl::make_unique<CordzSampleToken>(); } } } for (TestCordData& cord : cords) { CordzInfo::MaybeUntrackCord(cord.data.cordz_info()); } }); } absl::SleepFor(absl::Seconds(3)); stop.Notify(); } } } ABSL_NAMESPACE_END }
2,572
#ifndef ABSL_STRINGS_INTERNAL_CORDZ_HANDLE_H_ #define ABSL_STRINGS_INTERNAL_CORDZ_HANDLE_H_ #include <atomic> #include <vector> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class ABSL_DLL CordzHandle { public: CordzHandle() : CordzHandle(false) {} bool is_snapshot() const { return is_snapshot_; } bool SafeToDelete() const; static void Delete(CordzHandle* handle); static std::vector<const CordzHandle*> DiagnosticsGetDeleteQueue(); bool DiagnosticsHandleIsSafeToInspect(const CordzHandle* handle) const; std::vector<const CordzHandle*> DiagnosticsGetSafeToInspectDeletedHandles(); protected: explicit CordzHandle(bool is_snapshot); virtual ~CordzHandle(); private: const bool is_snapshot_; CordzHandle* dq_prev_ = nullptr; CordzHandle* dq_next_ = nullptr; }; class CordzSnapshot : public CordzHandle { public: CordzSnapshot() : CordzHandle(true) {} }; } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/cordz_handle.h" #include <atomic> #include "absl/base/internal/raw_logging.h" #include "absl/base/no_destructor.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { struct Queue { Queue() = default; absl::Mutex mutex; std::atomic<CordzHandle*> dq_tail ABSL_GUARDED_BY(mutex){nullptr}; bool IsEmpty() const ABSL_NO_THREAD_SAFETY_ANALYSIS { return dq_tail.load(std::memory_order_acquire) == nullptr; } }; static Queue& GlobalQueue() { static absl::NoDestructor<Queue> global_queue; return *global_queue; } } CordzHandle::CordzHandle(bool is_snapshot) : is_snapshot_(is_snapshot) { Queue& global_queue = GlobalQueue(); if (is_snapshot) { MutexLock lock(&global_queue.mutex); CordzHandle* dq_tail = global_queue.dq_tail.load(std::memory_order_acquire); if (dq_tail != nullptr) { dq_prev_ = dq_tail; dq_tail->dq_next_ = this; } global_queue.dq_tail.store(this, std::memory_order_release); } } CordzHandle::~CordzHandle() { Queue& global_queue = GlobalQueue(); if (is_snapshot_) { std::vector<CordzHandle*> to_delete; { MutexLock lock(&global_queue.mutex); CordzHandle* next = dq_next_; if (dq_prev_ == nullptr) { while (next && !next->is_snapshot_) { to_delete.push_back(next); next = next->dq_next_; } } else { dq_prev_->dq_next_ = next; } if (next) { next->dq_prev_ = dq_prev_; } else { global_queue.dq_tail.store(dq_prev_, std::memory_order_release); } } for (CordzHandle* handle : to_delete) { delete handle; } } } bool CordzHandle::SafeToDelete() const { return is_snapshot_ || GlobalQueue().IsEmpty(); } void CordzHandle::Delete(CordzHandle* handle) { assert(handle); if (handle) { Queue& queue = GlobalQueue(); if (!handle->SafeToDelete()) { MutexLock lock(&queue.mutex); CordzHandle* dq_tail = queue.dq_tail.load(std::memory_order_acquire); if (dq_tail != nullptr) { handle->dq_prev_ = dq_tail; dq_tail->dq_next_ = handle; queue.dq_tail.store(handle, std::memory_order_release); return; } } delete handle; } } std::vector<const CordzHandle*> CordzHandle::DiagnosticsGetDeleteQueue() { std::vector<const CordzHandle*> handles; Queue& global_queue = GlobalQueue(); MutexLock lock(&global_queue.mutex); CordzHandle* dq_tail = global_queue.dq_tail.load(std::memory_order_acquire); for (const CordzHandle* p = dq_tail; p; p = p->dq_prev_) { handles.push_back(p); } return handles; } bool CordzHandle::DiagnosticsHandleIsSafeToInspect( const CordzHandle* handle) const { if (!is_snapshot_) return false; if (handle == nullptr) return true; if (handle->is_snapshot_) return false; bool snapshot_found = false; Queue& global_queue = GlobalQueue(); MutexLock lock(&global_queue.mutex); for (const CordzHandle* p = global_queue.dq_tail; p; p = p->dq_prev_) { if (p == handle) return !snapshot_found; if (p == this) snapshot_found = true; } ABSL_ASSERT(snapshot_found); return true; } std::vector<const CordzHandle*> CordzHandle::DiagnosticsGetSafeToInspectDeletedHandles() { std::vector<const CordzHandle*> handles; if (!is_snapshot()) { return handles; } Queue& global_queue = GlobalQueue(); MutexLock lock(&global_queue.mutex); for (const CordzHandle* p = dq_next_; p != nullptr; p = p->dq_next_) { if (!p->is_snapshot()) { handles.push_back(p); } } return handles; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/cordz_handle.h" #include <random> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" #include "absl/synchronization/internal/thread_pool.h" #include "absl/synchronization/notification.h" #include "absl/time/clock.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::testing::ElementsAre; using ::testing::Gt; using ::testing::IsEmpty; using ::testing::SizeIs; std::vector<const CordzHandle*> DeleteQueue() { return CordzHandle::DiagnosticsGetDeleteQueue(); } struct CordzHandleDeleteTracker : public CordzHandle { bool* deleted; explicit CordzHandleDeleteTracker(bool* deleted) : deleted(deleted) {} ~CordzHandleDeleteTracker() override { *deleted = true; } }; TEST(CordzHandleTest, DeleteQueueIsEmpty) { EXPECT_THAT(DeleteQueue(), SizeIs(0)); } TEST(CordzHandleTest, CordzHandleCreateDelete) { bool deleted = false; auto* handle = new CordzHandleDeleteTracker(&deleted); EXPECT_FALSE(handle->is_snapshot()); EXPECT_TRUE(handle->SafeToDelete()); EXPECT_THAT(DeleteQueue(), SizeIs(0)); CordzHandle::Delete(handle); EXPECT_THAT(DeleteQueue(), SizeIs(0)); EXPECT_TRUE(deleted); } TEST(CordzHandleTest, CordzSnapshotCreateDelete) { auto* snapshot = new CordzSnapshot(); EXPECT_TRUE(snapshot->is_snapshot()); EXPECT_TRUE(snapshot->SafeToDelete()); EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot)); delete snapshot; EXPECT_THAT(DeleteQueue(), SizeIs(0)); } TEST(CordzHandleTest, CordzHandleCreateDeleteWithSnapshot) { bool deleted = false; auto* snapshot = new CordzSnapshot(); auto* handle = new CordzHandleDeleteTracker(&deleted); EXPECT_FALSE(handle->SafeToDelete()); CordzHandle::Delete(handle); EXPECT_THAT(DeleteQueue(), ElementsAre(handle, snapshot)); EXPECT_FALSE(deleted); EXPECT_FALSE(handle->SafeToDelete()); delete snapshot; EXPECT_THAT(DeleteQueue(), SizeIs(0)); EXPECT_TRUE(deleted); } TEST(CordzHandleTest, MultiSnapshot) { bool deleted[3] = {false, false, false}; CordzSnapshot* snapshot[3]; CordzHandleDeleteTracker* handle[3]; for (int i = 0; i < 3; ++i) { snapshot[i] = new CordzSnapshot(); handle[i] = new CordzHandleDeleteTracker(&deleted[i]); CordzHandle::Delete(handle[i]); } EXPECT_THAT(DeleteQueue(), ElementsAre(handle[2], snapshot[2], handle[1], snapshot[1], handle[0], snapshot[0])); EXPECT_THAT(deleted, ElementsAre(false, false, false)); delete snapshot[1]; EXPECT_THAT(DeleteQueue(), ElementsAre(handle[2], snapshot[2], handle[1], handle[0], snapshot[0])); EXPECT_THAT(deleted, ElementsAre(false, false, false)); delete snapshot[0]; EXPECT_THAT(DeleteQueue(), ElementsAre(handle[2], snapshot[2])); EXPECT_THAT(deleted, ElementsAre(true, true, false)); delete snapshot[2]; EXPECT_THAT(DeleteQueue(), SizeIs(0)); EXPECT_THAT(deleted, ElementsAre(true, true, deleted)); } TEST(CordzHandleTest, DiagnosticsHandleIsSafeToInspect) { CordzSnapshot snapshot1; EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(nullptr)); auto* handle1 = new CordzHandle(); EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1)); CordzHandle::Delete(handle1); EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1)); CordzSnapshot snapshot2; auto* handle2 = new CordzHandle(); EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1)); EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle2)); EXPECT_FALSE(snapshot2.DiagnosticsHandleIsSafeToInspect(handle1)); EXPECT_TRUE(snapshot2.DiagnosticsHandleIsSafeToInspect(handle2)); CordzHandle::Delete(handle2); EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1)); } TEST(CordzHandleTest, DiagnosticsGetSafeToInspectDeletedHandles) { EXPECT_THAT(DeleteQueue(), IsEmpty()); auto* handle = new CordzHandle(); auto* snapshot1 = new CordzSnapshot(); EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot1)); EXPECT_TRUE(snapshot1->DiagnosticsHandleIsSafeToInspect(handle)); EXPECT_THAT(snapshot1->DiagnosticsGetSafeToInspectDeletedHandles(), IsEmpty()); CordzHandle::Delete(handle); auto* snapshot2 = new CordzSnapshot(); EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot2, handle, snapshot1)); EXPECT_TRUE(snapshot1->DiagnosticsHandleIsSafeToInspect(handle)); EXPECT_FALSE(snapshot2->DiagnosticsHandleIsSafeToInspect(handle)); EXPECT_THAT(snapshot1->DiagnosticsGetSafeToInspectDeletedHandles(), ElementsAre(handle)); EXPECT_THAT(snapshot2->DiagnosticsGetSafeToInspectDeletedHandles(), IsEmpty()); CordzHandle::Delete(snapshot1); EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot2)); CordzHandle::Delete(snapshot2); EXPECT_THAT(DeleteQueue(), IsEmpty()); } TEST(CordzHandleTest, MultiThreaded) { Notification stop; static constexpr int kNumThreads = 4; static constexpr int kNumHandles = 10; std::vector<std::atomic<CordzHandle*>> handles(kNumHandles); std::atomic<bool> found_safe_to_inspect(false); { absl::synchronization_internal::ThreadPool pool(kNumThreads); for (int i = 0; i < kNumThreads; ++i) { pool.Schedule([&stop, &handles, &found_safe_to_inspect]() { std::minstd_rand gen; std::uniform_int_distribution<int> dist_type(0, 2); std::uniform_int_distribution<int> dist_handle(0, kNumHandles - 1); while (!stop.HasBeenNotified()) { CordzHandle* handle; switch (dist_type(gen)) { case 0: handle = new CordzHandle(); break; case 1: handle = new CordzSnapshot(); break; default: handle = nullptr; break; } CordzHandle* old_handle = handles[dist_handle(gen)].exchange(handle); if (old_handle != nullptr) { std::vector<const CordzHandle*> safe_to_inspect = old_handle->DiagnosticsGetSafeToInspectDeletedHandles(); for (const CordzHandle* handle : safe_to_inspect) { ASSERT_FALSE(handle->is_snapshot()); } if (!safe_to_inspect.empty()) { found_safe_to_inspect.store(true); } CordzHandle::Delete(old_handle); } } for (auto& h : handles) { if (CordzHandle* handle = h.exchange(nullptr)) { CordzHandle::Delete(handle); } } }); } absl::SleepFor(absl::Seconds(3)); stop.Notify(); } EXPECT_TRUE(found_safe_to_inspect.load()); } } } ABSL_NAMESPACE_END }
2,573
#ifndef ABSL_STRINGS_INTERNAL_POW10_HELPER_H_ #define ABSL_STRINGS_INTERNAL_POW10_HELPER_H_ #include <vector> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { double Pow10(int exp); } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/pow10_helper.h" #include <cmath> namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { namespace { constexpr double k1e23 = 9999999999999999e7; constexpr double kPowersOfTen[] = { 0.0, 1e-323, 1e-322, 1e-321, 1e-320, 1e-319, 1e-318, 1e-317, 1e-316, 1e-315, 1e-314, 1e-313, 1e-312, 1e-311, 1e-310, 1e-309, 1e-308, 1e-307, 1e-306, 1e-305, 1e-304, 1e-303, 1e-302, 1e-301, 1e-300, 1e-299, 1e-298, 1e-297, 1e-296, 1e-295, 1e-294, 1e-293, 1e-292, 1e-291, 1e-290, 1e-289, 1e-288, 1e-287, 1e-286, 1e-285, 1e-284, 1e-283, 1e-282, 1e-281, 1e-280, 1e-279, 1e-278, 1e-277, 1e-276, 1e-275, 1e-274, 1e-273, 1e-272, 1e-271, 1e-270, 1e-269, 1e-268, 1e-267, 1e-266, 1e-265, 1e-264, 1e-263, 1e-262, 1e-261, 1e-260, 1e-259, 1e-258, 1e-257, 1e-256, 1e-255, 1e-254, 1e-253, 1e-252, 1e-251, 1e-250, 1e-249, 1e-248, 1e-247, 1e-246, 1e-245, 1e-244, 1e-243, 1e-242, 1e-241, 1e-240, 1e-239, 1e-238, 1e-237, 1e-236, 1e-235, 1e-234, 1e-233, 1e-232, 1e-231, 1e-230, 1e-229, 1e-228, 1e-227, 1e-226, 1e-225, 1e-224, 1e-223, 1e-222, 1e-221, 1e-220, 1e-219, 1e-218, 1e-217, 1e-216, 1e-215, 1e-214, 1e-213, 1e-212, 1e-211, 1e-210, 1e-209, 1e-208, 1e-207, 1e-206, 1e-205, 1e-204, 1e-203, 1e-202, 1e-201, 1e-200, 1e-199, 1e-198, 1e-197, 1e-196, 1e-195, 1e-194, 1e-193, 1e-192, 1e-191, 1e-190, 1e-189, 1e-188, 1e-187, 1e-186, 1e-185, 1e-184, 1e-183, 1e-182, 1e-181, 1e-180, 1e-179, 1e-178, 1e-177, 1e-176, 1e-175, 1e-174, 1e-173, 1e-172, 1e-171, 1e-170, 1e-169, 1e-168, 1e-167, 1e-166, 1e-165, 1e-164, 1e-163, 1e-162, 1e-161, 1e-160, 1e-159, 1e-158, 1e-157, 1e-156, 1e-155, 1e-154, 1e-153, 1e-152, 1e-151, 1e-150, 1e-149, 1e-148, 1e-147, 1e-146, 1e-145, 1e-144, 1e-143, 1e-142, 1e-141, 1e-140, 1e-139, 1e-138, 1e-137, 1e-136, 1e-135, 1e-134, 1e-133, 1e-132, 1e-131, 1e-130, 1e-129, 1e-128, 1e-127, 1e-126, 1e-125, 1e-124, 1e-123, 1e-122, 1e-121, 1e-120, 1e-119, 1e-118, 1e-117, 1e-116, 1e-115, 1e-114, 1e-113, 1e-112, 1e-111, 1e-110, 1e-109, 1e-108, 1e-107, 1e-106, 1e-105, 1e-104, 1e-103, 1e-102, 1e-101, 1e-100, 1e-99, 1e-98, 1e-97, 1e-96, 1e-95, 1e-94, 1e-93, 1e-92, 1e-91, 1e-90, 1e-89, 1e-88, 1e-87, 1e-86, 1e-85, 1e-84, 1e-83, 1e-82, 1e-81, 1e-80, 1e-79, 1e-78, 1e-77, 1e-76, 1e-75, 1e-74, 1e-73, 1e-72, 1e-71, 1e-70, 1e-69, 1e-68, 1e-67, 1e-66, 1e-65, 1e-64, 1e-63, 1e-62, 1e-61, 1e-60, 1e-59, 1e-58, 1e-57, 1e-56, 1e-55, 1e-54, 1e-53, 1e-52, 1e-51, 1e-50, 1e-49, 1e-48, 1e-47, 1e-46, 1e-45, 1e-44, 1e-43, 1e-42, 1e-41, 1e-40, 1e-39, 1e-38, 1e-37, 1e-36, 1e-35, 1e-34, 1e-33, 1e-32, 1e-31, 1e-30, 1e-29, 1e-28, 1e-27, 1e-26, 1e-25, 1e-24, 1e-23, 1e-22, 1e-21, 1e-20, 1e-19, 1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e+0, 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, 1e+21, 1e+22, k1e23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40, 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80, 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100, 1e+101, 1e+102, 1e+103, 1e+104, 1e+105, 1e+106, 1e+107, 1e+108, 1e+109, 1e+110, 1e+111, 1e+112, 1e+113, 1e+114, 1e+115, 1e+116, 1e+117, 1e+118, 1e+119, 1e+120, 1e+121, 1e+122, 1e+123, 1e+124, 1e+125, 1e+126, 1e+127, 1e+128, 1e+129, 1e+130, 1e+131, 1e+132, 1e+133, 1e+134, 1e+135, 1e+136, 1e+137, 1e+138, 1e+139, 1e+140, 1e+141, 1e+142, 1e+143, 1e+144, 1e+145, 1e+146, 1e+147, 1e+148, 1e+149, 1e+150, 1e+151, 1e+152, 1e+153, 1e+154, 1e+155, 1e+156, 1e+157, 1e+158, 1e+159, 1e+160, 1e+161, 1e+162, 1e+163, 1e+164, 1e+165, 1e+166, 1e+167, 1e+168, 1e+169, 1e+170, 1e+171, 1e+172, 1e+173, 1e+174, 1e+175, 1e+176, 1e+177, 1e+178, 1e+179, 1e+180, 1e+181, 1e+182, 1e+183, 1e+184, 1e+185, 1e+186, 1e+187, 1e+188, 1e+189, 1e+190, 1e+191, 1e+192, 1e+193, 1e+194, 1e+195, 1e+196, 1e+197, 1e+198, 1e+199, 1e+200, 1e+201, 1e+202, 1e+203, 1e+204, 1e+205, 1e+206, 1e+207, 1e+208, 1e+209, 1e+210, 1e+211, 1e+212, 1e+213, 1e+214, 1e+215, 1e+216, 1e+217, 1e+218, 1e+219, 1e+220, 1e+221, 1e+222, 1e+223, 1e+224, 1e+225, 1e+226, 1e+227, 1e+228, 1e+229, 1e+230, 1e+231, 1e+232, 1e+233, 1e+234, 1e+235, 1e+236, 1e+237, 1e+238, 1e+239, 1e+240, 1e+241, 1e+242, 1e+243, 1e+244, 1e+245, 1e+246, 1e+247, 1e+248, 1e+249, 1e+250, 1e+251, 1e+252, 1e+253, 1e+254, 1e+255, 1e+256, 1e+257, 1e+258, 1e+259, 1e+260, 1e+261, 1e+262, 1e+263, 1e+264, 1e+265, 1e+266, 1e+267, 1e+268, 1e+269, 1e+270, 1e+271, 1e+272, 1e+273, 1e+274, 1e+275, 1e+276, 1e+277, 1e+278, 1e+279, 1e+280, 1e+281, 1e+282, 1e+283, 1e+284, 1e+285, 1e+286, 1e+287, 1e+288, 1e+289, 1e+290, 1e+291, 1e+292, 1e+293, 1e+294, 1e+295, 1e+296, 1e+297, 1e+298, 1e+299, 1e+300, 1e+301, 1e+302, 1e+303, 1e+304, 1e+305, 1e+306, 1e+307, 1e+308, }; } double Pow10(int exp) { if (exp < -324) { return 0.0; } else if (exp > 308) { return INFINITY; } else { return kPowersOfTen[exp + 324]; } } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/pow10_helper.h" #include <cmath> #include "gtest/gtest.h" #include "absl/strings/str_format.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { namespace { struct TestCase { int power; uint64_t significand; int radix; }; TEST(Pow10HelperTest, Works) { constexpr TestCase kTestCases[] = { {-323, 0x2, -1074}, {-322, 0x14, -1074}, {-321, 0xca, -1074}, {-320, 0x7e8, -1074}, {-319, 0x4f10, -1074}, {-318, 0x316a2, -1074}, {-317, 0x1ee257, -1074}, {-316, 0x134d761, -1074}, {-315, 0xc1069cd, -1074}, {-314, 0x78a42205, -1074}, {-313, 0x4b6695433, -1074}, {-312, 0x2f201d49fb, -1074}, {-311, 0x1d74124e3d1, -1074}, {-310, 0x12688b70e62b, -1074}, {-309, 0xb8157268fdaf, -1074}, {-308, 0x730d67819e8d2, -1074}, {-307, 0x11fa182c40c60d, -1072}, {-290, 0x18f2b061aea072, -1016}, {-276, 0x11BA03F5B21000, -969}, {-259, 0x1899C2F6732210, -913}, {-252, 0x1D53844EE47DD1, -890}, {-227, 0x1E5297287C2F45, -807}, {-198, 0x1322E220A5B17E, -710}, {-195, 0x12B010D3E1CF56, -700}, {-192, 0x123FF06EEA847A, -690}, {-163, 0x1708D0F84D3DE7, -594}, {-145, 0x13FAAC3E3FA1F3, -534}, {-111, 0x133D4032C2C7F5, -421}, {-106, 0x1D5B561574765B, -405}, {-104, 0x16EF5B40C2FC77, -398}, {-88, 0x197683DF2F268D, -345}, {-86, 0x13E497065CD61F, -338}, {-76, 0x17288E1271F513, -305}, {-63, 0x1A53FC9631D10D, -262}, {-30, 0x14484BFEEBC2A0, -152}, {-21, 0x12E3B40A0E9B4F, -122}, {-5, 0x14F8B588E368F1, -69}, {23, 0x152D02C7E14AF6, 24}, {29, 0x1431E0FAE6D721, 44}, {34, 0x1ED09BEAD87C03, 60}, {70, 0x172EBAD6DDC73D, 180}, {105, 0x1BE7ABD3781ECA, 296}, {126, 0x17A2ECC414A03F, 366}, {130, 0x1CDA62055B2D9E, 379}, {165, 0x115D847AD00087, 496}, {172, 0x14B378469B6732, 519}, {187, 0x1262DFEEBBB0F9, 569}, {210, 0x18557F31326BBB, 645}, {212, 0x1302CB5E6F642A, 652}, {215, 0x1290BA9A38C7D1, 662}, {236, 0x1F736F9B3494E9, 731}, {244, 0x176EC98994F489, 758}, {250, 0x1658E3AB795204, 778}, {252, 0x117571DDF6C814, 785}, {254, 0x1B4781EAD1989E, 791}, {260, 0x1A03FDE214CAF1, 811}, {284, 0x1585041B2C477F, 891}, {304, 0x1D2A1BE4048F90, 957}, {-324, 0x0, 0}, {-325, 0x0, 0}, {-326, 0x0, 0}, {309, 1, 2000}, {310, 1, 2000}, {311, 1, 2000}, }; for (const TestCase& test_case : kTestCases) { EXPECT_EQ(Pow10(test_case.power), std::ldexp(test_case.significand, test_case.radix)) << absl::StrFormat("Failure for Pow10(%d): %a vs %a", test_case.power, Pow10(test_case.power), std::ldexp(test_case.significand, test_case.radix)); } } } } ABSL_NAMESPACE_END }
2,574
#ifndef ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_READER_H_ #define ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_READER_H_ #include <cassert> #include "absl/base/config.h" #include "absl/strings/internal/cord_data_edge.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" #include "absl/strings/internal/cord_rep_btree_navigator.h" #include "absl/strings/internal/cord_rep_flat.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class CordRepBtreeReader { public: using ReadResult = CordRepBtreeNavigator::ReadResult; using Position = CordRepBtreeNavigator::Position; explicit operator bool() const { return navigator_.btree() != nullptr; } CordRepBtree* btree() const { return navigator_.btree(); } CordRep* node() const { return navigator_.Current(); } size_t length() const; size_t remaining() const { return remaining_; } void Reset() { navigator_.Reset(); } absl::string_view Init(CordRepBtree* tree); absl::string_view Next(); absl::string_view Skip(size_t skip); absl::string_view Read(size_t n, size_t chunk_size, CordRep*& tree); absl::string_view Seek(size_t offset); private: size_t remaining_ = 0; CordRepBtreeNavigator navigator_; }; inline size_t CordRepBtreeReader::length() const { assert(btree() != nullptr); return btree()->length; } inline absl::string_view CordRepBtreeReader::Init(CordRepBtree* tree) { assert(tree != nullptr); const CordRep* edge = navigator_.InitFirst(tree); remaining_ = tree->length - edge->length; return EdgeData(edge); } inline absl::string_view CordRepBtreeReader::Next() { if (remaining_ == 0) return {}; const CordRep* edge = navigator_.Next(); assert(edge != nullptr); remaining_ -= edge->length; return EdgeData(edge); } inline absl::string_view CordRepBtreeReader::Skip(size_t skip) { const size_t edge_length = navigator_.Current()->length; CordRepBtreeNavigator::Position pos = navigator_.Skip(skip + edge_length); if (ABSL_PREDICT_FALSE(pos.edge == nullptr)) { remaining_ = 0; return {}; } remaining_ -= skip - pos.offset + pos.edge->length; return EdgeData(pos.edge).substr(pos.offset); } inline absl::string_view CordRepBtreeReader::Seek(size_t offset) { const CordRepBtreeNavigator::Position pos = navigator_.Seek(offset); if (ABSL_PREDICT_FALSE(pos.edge == nullptr)) { remaining_ = 0; return {}; } absl::string_view chunk = EdgeData(pos.edge).substr(pos.offset); remaining_ = length() - offset - chunk.length(); return chunk; } } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/cord_rep_btree_reader.h" #include <cassert> #include "absl/base/config.h" #include "absl/strings/internal/cord_data_edge.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" #include "absl/strings/internal/cord_rep_btree_navigator.h" #include "absl/strings/internal/cord_rep_flat.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { absl::string_view CordRepBtreeReader::Read(size_t n, size_t chunk_size, CordRep*& tree) { assert(chunk_size <= navigator_.Current()->length); CordRep* edge = chunk_size ? navigator_.Current() : navigator_.Next(); const size_t offset = chunk_size ? edge->length - chunk_size : 0; ReadResult result = navigator_.Read(offset, n); tree = result.tree; if (n < chunk_size) return EdgeData(edge).substr(result.n); const size_t consumed_by_read = n - chunk_size - result.n; if (consumed_by_read >= remaining_) { remaining_ = 0; return {}; } edge = navigator_.Current(); remaining_ -= consumed_by_read + edge->length; return EdgeData(edge).substr(result.n); } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/cord_rep_btree_reader.h" #include <iostream> #include <random> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/strings/cord.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" #include "absl/strings/internal/cord_rep_test_util.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::testing::Eq; using ::testing::IsEmpty; using ::testing::Ne; using ::testing::Not; using ::absl::cordrep_testing::CordRepBtreeFromFlats; using ::absl::cordrep_testing::MakeFlat; using ::absl::cordrep_testing::CordToString; using ::absl::cordrep_testing::CreateFlatsFromString; using ::absl::cordrep_testing::CreateRandomString; using ReadResult = CordRepBtreeReader::ReadResult; TEST(CordRepBtreeReaderTest, Next) { constexpr size_t kChars = 3; const size_t cap = CordRepBtree::kMaxCapacity; size_t counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17}; for (size_t count : counts) { std::string data = CreateRandomString(count * kChars); std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars); CordRepBtree* node = CordRepBtreeFromFlats(flats); CordRepBtreeReader reader; size_t remaining = data.length(); absl::string_view chunk = reader.Init(node); EXPECT_THAT(chunk, Eq(data.substr(0, chunk.length()))); remaining -= chunk.length(); EXPECT_THAT(reader.remaining(), Eq(remaining)); while (remaining > 0) { const size_t offset = data.length() - remaining; chunk = reader.Next(); EXPECT_THAT(chunk, Eq(data.substr(offset, chunk.length()))); remaining -= chunk.length(); EXPECT_THAT(reader.remaining(), Eq(remaining)); } EXPECT_THAT(reader.remaining(), Eq(0u)); EXPECT_THAT(reader.Next(), testing::IsEmpty()); CordRep::Unref(node); } } TEST(CordRepBtreeReaderTest, Skip) { constexpr size_t kChars = 3; const size_t cap = CordRepBtree::kMaxCapacity; size_t counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17}; for (size_t count : counts) { std::string data = CreateRandomString(count * kChars); std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars); CordRepBtree* node = CordRepBtreeFromFlats(flats); for (size_t skip1 = 0; skip1 < data.length() - kChars; ++skip1) { for (size_t skip2 = 0; skip2 < data.length() - kChars; ++skip2) { CordRepBtreeReader reader; size_t remaining = data.length(); absl::string_view chunk = reader.Init(node); remaining -= chunk.length(); chunk = reader.Skip(skip1); size_t offset = data.length() - remaining; ASSERT_THAT(chunk, Eq(data.substr(offset + skip1, chunk.length()))); remaining -= chunk.length() + skip1; ASSERT_THAT(reader.remaining(), Eq(remaining)); if (remaining == 0) continue; size_t skip = std::min(remaining - 1, skip2); chunk = reader.Skip(skip); offset = data.length() - remaining; ASSERT_THAT(chunk, Eq(data.substr(offset + skip, chunk.length()))); } } CordRep::Unref(node); } } TEST(CordRepBtreeReaderTest, SkipBeyondLength) { CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc")); tree = CordRepBtree::Append(tree, MakeFlat("def")); CordRepBtreeReader reader; reader.Init(tree); EXPECT_THAT(reader.Skip(100), IsEmpty()); EXPECT_THAT(reader.remaining(), Eq(0u)); CordRep::Unref(tree); } TEST(CordRepBtreeReaderTest, Seek) { constexpr size_t kChars = 3; const size_t cap = CordRepBtree::kMaxCapacity; size_t counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17}; for (size_t count : counts) { std::string data = CreateRandomString(count * kChars); std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars); CordRepBtree* node = CordRepBtreeFromFlats(flats); for (size_t seek = 0; seek < data.length() - 1; ++seek) { CordRepBtreeReader reader; reader.Init(node); absl::string_view chunk = reader.Seek(seek); ASSERT_THAT(chunk, Not(IsEmpty())); ASSERT_THAT(chunk, Eq(data.substr(seek, chunk.length()))); ASSERT_THAT(reader.remaining(), Eq(data.length() - seek - chunk.length())); } CordRep::Unref(node); } } TEST(CordRepBtreeReaderTest, SeekBeyondLength) { CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc")); tree = CordRepBtree::Append(tree, MakeFlat("def")); CordRepBtreeReader reader; reader.Init(tree); EXPECT_THAT(reader.Seek(6), IsEmpty()); EXPECT_THAT(reader.remaining(), Eq(0u)); EXPECT_THAT(reader.Seek(100), IsEmpty()); EXPECT_THAT(reader.remaining(), Eq(0u)); CordRep::Unref(tree); } TEST(CordRepBtreeReaderTest, Read) { std::string data = "abcdefghijklmno"; std::vector<CordRep*> flats = CreateFlatsFromString(data, 5); CordRepBtree* node = CordRepBtreeFromFlats(flats); CordRep* tree; CordRepBtreeReader reader; absl::string_view chunk; chunk = reader.Init(node); chunk = reader.Read(0, chunk.length(), tree); EXPECT_THAT(tree, Eq(nullptr)); EXPECT_THAT(chunk, Eq("abcde")); EXPECT_THAT(reader.remaining(), Eq(10u)); EXPECT_THAT(reader.Next(), Eq("fghij")); chunk = reader.Init(node); chunk = reader.Read(15, chunk.length(), tree); EXPECT_THAT(tree, Ne(nullptr)); EXPECT_THAT(CordToString(tree), Eq("abcdefghijklmno")); EXPECT_THAT(chunk, Eq("")); EXPECT_THAT(reader.remaining(), Eq(0u)); CordRep::Unref(tree); chunk = reader.Init(node); chunk = reader.Read(3, chunk.length(), tree); ASSERT_THAT(tree, Ne(nullptr)); EXPECT_THAT(CordToString(tree), Eq("abc")); EXPECT_THAT(chunk, Eq("de")); EXPECT_THAT(reader.remaining(), Eq(10u)); EXPECT_THAT(reader.Next(), Eq("fghij")); CordRep::Unref(tree); chunk = reader.Init(node); chunk = reader.Read(2, chunk.length() - 2, tree); ASSERT_THAT(tree, Ne(nullptr)); EXPECT_THAT(CordToString(tree), Eq("cd")); EXPECT_THAT(chunk, Eq("e")); EXPECT_THAT(reader.remaining(), Eq(10u)); EXPECT_THAT(reader.Next(), Eq("fghij")); CordRep::Unref(tree); chunk = reader.Init(node); chunk = reader.Read(3, 0, tree); ASSERT_THAT(tree, Ne(nullptr)); EXPECT_THAT(CordToString(tree), Eq("fgh")); EXPECT_THAT(chunk, Eq("ij")); EXPECT_THAT(reader.remaining(), Eq(5u)); EXPECT_THAT(reader.Next(), Eq("klmno")); CordRep::Unref(tree); chunk = reader.Init(node); chunk = reader.Read(12, chunk.length() - 2, tree); ASSERT_THAT(tree, Ne(nullptr)); EXPECT_THAT(CordToString(tree), Eq("cdefghijklmn")); EXPECT_THAT(chunk, Eq("o")); EXPECT_THAT(reader.remaining(), Eq(0u)); CordRep::Unref(tree); chunk = reader.Init(node); chunk = reader.Read(10 - 2, chunk.length() - 2, tree); ASSERT_THAT(tree, Ne(nullptr)); EXPECT_THAT(CordToString(tree), Eq("cdefghij")); EXPECT_THAT(chunk, Eq("klmno")); EXPECT_THAT(reader.remaining(), Eq(0u)); CordRep::Unref(tree); CordRep::Unref(node); } TEST(CordRepBtreeReaderTest, ReadExhaustive) { constexpr size_t kChars = 3; const size_t cap = CordRepBtree::kMaxCapacity; size_t counts[] = {1, 2, cap, cap * cap + 1, cap * cap * cap * 2 + 17}; for (size_t count : counts) { std::string data = CreateRandomString(count * kChars); std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars); CordRepBtree* node = CordRepBtreeFromFlats(flats); for (size_t read_size : {kChars - 1, kChars, kChars + 7, cap * cap}) { CordRepBtreeReader reader; absl::string_view chunk = reader.Init(node); size_t consumed = 0; size_t remaining = data.length(); while (remaining > 0) { CordRep* tree; size_t n = (std::min)(remaining, read_size); chunk = reader.Read(n, chunk.length(), tree); EXPECT_THAT(tree, Ne(nullptr)); if (tree) { EXPECT_THAT(CordToString(tree), Eq(data.substr(consumed, n))); CordRep::Unref(tree); } consumed += n; remaining -= n; EXPECT_THAT(reader.remaining(), Eq(remaining - chunk.length())); if (remaining > 0) { ASSERT_FALSE(chunk.empty()); ASSERT_THAT(chunk, Eq(data.substr(consumed, chunk.length()))); } else { ASSERT_TRUE(chunk.empty()) << chunk; } } } CordRep::Unref(node); } } } } ABSL_NAMESPACE_END }
2,575
#ifndef ABSL_STRINGS_INTERNAL_UTF8_H_ #define ABSL_STRINGS_INTERNAL_UTF8_H_ #include <cstddef> #include <cstdint> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { enum { kMaxEncodedUTF8Size = 4 }; size_t EncodeUTF8Char(char *buffer, char32_t utf8_char); } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/utf8.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { size_t EncodeUTF8Char(char *buffer, char32_t utf8_char) { if (utf8_char <= 0x7F) { *buffer = static_cast<char>(utf8_char); return 1; } else if (utf8_char <= 0x7FF) { buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F)); utf8_char >>= 6; buffer[0] = static_cast<char>(0xC0 | utf8_char); return 2; } else if (utf8_char <= 0xFFFF) { buffer[2] = static_cast<char>(0x80 | (utf8_char & 0x3F)); utf8_char >>= 6; buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F)); utf8_char >>= 6; buffer[0] = static_cast<char>(0xE0 | utf8_char); return 3; } else { buffer[3] = static_cast<char>(0x80 | (utf8_char & 0x3F)); utf8_char >>= 6; buffer[2] = static_cast<char>(0x80 | (utf8_char & 0x3F)); utf8_char >>= 6; buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F)); utf8_char >>= 6; buffer[0] = static_cast<char>(0xF0 | utf8_char); return 4; } } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/utf8.h" #include <cstdint> #include <utility> #include "gtest/gtest.h" #include "absl/base/port.h" namespace { #if !defined(__cpp_char8_t) #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++2a-compat" #endif TEST(EncodeUTF8Char, BasicFunction) { std::pair<char32_t, std::string> tests[] = {{0x0030, u8"\u0030"}, {0x00A3, u8"\u00A3"}, {0x00010000, u8"\U00010000"}, {0x0000FFFF, u8"\U0000FFFF"}, {0x0010FFFD, u8"\U0010FFFD"}}; for (auto &test : tests) { char buf0[7] = {'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}; char buf1[7] = {'\xFF', '\xFF', '\xFF', '\xFF', '\xFF', '\xFF', '\xFF'}; char *buf0_written = &buf0[absl::strings_internal::EncodeUTF8Char(buf0, test.first)]; char *buf1_written = &buf1[absl::strings_internal::EncodeUTF8Char(buf1, test.first)]; int apparent_length = 7; while (buf0[apparent_length - 1] == '\x00' && buf1[apparent_length - 1] == '\xFF') { if (--apparent_length == 0) break; } EXPECT_EQ(apparent_length, buf0_written - buf0); EXPECT_EQ(apparent_length, buf1_written - buf1); EXPECT_EQ(apparent_length, test.second.length()); EXPECT_EQ(std::string(buf0, apparent_length), test.second); EXPECT_EQ(std::string(buf1, apparent_length), test.second); } char buf[32] = "Don't Tread On Me"; EXPECT_LE(absl::strings_internal::EncodeUTF8Char(buf, 0x00110000), absl::strings_internal::kMaxEncodedUTF8Size); char buf2[32] = "Negative is invalid but sane"; EXPECT_LE(absl::strings_internal::EncodeUTF8Char(buf2, -1), absl::strings_internal::kMaxEncodedUTF8Size); } #if defined(__clang__) #pragma clang diagnostic pop #endif #endif }
2,576
#ifndef ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_NAVIGATOR_H_ #define ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_NAVIGATOR_H_ #include <cassert> #include <iostream> #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class CordRepBtreeNavigator { public: struct Position { CordRep* edge; size_t offset; }; struct ReadResult { CordRep* tree; size_t n; }; explicit operator bool() const; CordRepBtree* btree() const; CordRep* Current() const; CordRep* InitFirst(CordRepBtree* tree); CordRep* InitLast(CordRepBtree* tree); Position InitOffset(CordRepBtree* tree, size_t offset); CordRep* Next(); CordRep* Previous(); Position Seek(size_t offset); ReadResult Read(size_t edge_offset, size_t n); Position Skip(size_t n); void Reset(); private: CordRep* NextUp(); CordRep* PreviousUp(); template <CordRepBtree::EdgeType edge_type> CordRep* Init(CordRepBtree* tree); int height_ = -1; uint8_t index_[CordRepBtree::kMaxDepth]; CordRepBtree* node_[CordRepBtree::kMaxDepth]; }; inline CordRepBtreeNavigator::operator bool() const { return height_ >= 0; } inline CordRepBtree* CordRepBtreeNavigator::btree() const { return height_ >= 0 ? node_[height_] : nullptr; } inline CordRep* CordRepBtreeNavigator::Current() const { assert(height_ >= 0); return node_[0]->Edge(index_[0]); } inline void CordRepBtreeNavigator::Reset() { height_ = -1; } inline CordRep* CordRepBtreeNavigator::InitFirst(CordRepBtree* tree) { return Init<CordRepBtree::kFront>(tree); } inline CordRep* CordRepBtreeNavigator::InitLast(CordRepBtree* tree) { return Init<CordRepBtree::kBack>(tree); } template <CordRepBtree::EdgeType edge_type> inline CordRep* CordRepBtreeNavigator::Init(CordRepBtree* tree) { assert(tree != nullptr); assert(tree->size() > 0); assert(tree->height() <= CordRepBtree::kMaxHeight); int height = height_ = tree->height(); size_t index = tree->index(edge_type); node_[height] = tree; index_[height] = static_cast<uint8_t>(index); while (--height >= 0) { tree = tree->Edge(index)->btree(); node_[height] = tree; index = tree->index(edge_type); index_[height] = static_cast<uint8_t>(index); } return node_[0]->Edge(index); } inline CordRepBtreeNavigator::Position CordRepBtreeNavigator::Seek( size_t offset) { assert(btree() != nullptr); int height = height_; CordRepBtree* edge = node_[height]; if (ABSL_PREDICT_FALSE(offset >= edge->length)) return {nullptr, 0}; CordRepBtree::Position index = edge->IndexOf(offset); index_[height] = static_cast<uint8_t>(index.index); while (--height >= 0) { edge = edge->Edge(index.index)->btree(); node_[height] = edge; index = edge->IndexOf(index.n); index_[height] = static_cast<uint8_t>(index.index); } return {edge->Edge(index.index), index.n}; } inline CordRepBtreeNavigator::Position CordRepBtreeNavigator::InitOffset( CordRepBtree* tree, size_t offset) { assert(tree != nullptr); assert(tree->height() <= CordRepBtree::kMaxHeight); if (ABSL_PREDICT_FALSE(offset >= tree->length)) return {nullptr, 0}; height_ = tree->height(); node_[height_] = tree; return Seek(offset); } inline CordRep* CordRepBtreeNavigator::Next() { CordRepBtree* edge = node_[0]; return index_[0] == edge->back() ? NextUp() : edge->Edge(++index_[0]); } inline CordRep* CordRepBtreeNavigator::Previous() { CordRepBtree* edge = node_[0]; return index_[0] == edge->begin() ? PreviousUp() : edge->Edge(--index_[0]); } inline CordRep* CordRepBtreeNavigator::NextUp() { assert(index_[0] == node_[0]->back()); CordRepBtree* edge; size_t index; int height = 0; do { if (++height > height_) return nullptr; edge = node_[height]; index = index_[height] + 1; } while (index == edge->end()); index_[height] = static_cast<uint8_t>(index); do { node_[--height] = edge = edge->Edge(index)->btree(); index_[height] = static_cast<uint8_t>(index = edge->begin()); } while (height > 0); return edge->Edge(index); } inline CordRep* CordRepBtreeNavigator::PreviousUp() { assert(index_[0] == node_[0]->begin()); CordRepBtree* edge; size_t index; int height = 0; do { if (++height > height_) return nullptr; edge = node_[height]; index = index_[height]; } while (index == edge->begin()); index_[height] = static_cast<uint8_t>(--index); do { node_[--height] = edge = edge->Edge(index)->btree(); index_[height] = static_cast<uint8_t>(index = edge->back()); } while (height > 0); return edge->Edge(index); } } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/cord_rep_btree_navigator.h" #include <cassert> #include "absl/strings/internal/cord_data_edge.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { using ReadResult = CordRepBtreeNavigator::ReadResult; namespace { inline CordRep* Substring(CordRep* rep, size_t offset, size_t n) { assert(n <= rep->length); assert(offset < rep->length); assert(offset <= rep->length - n); assert(IsDataEdge(rep)); if (n == 0) return nullptr; if (n == rep->length) return CordRep::Ref(rep); if (rep->tag == SUBSTRING) { offset += rep->substring()->start; rep = rep->substring()->child; } assert(rep->IsExternal() || rep->IsFlat()); CordRepSubstring* substring = new CordRepSubstring(); substring->length = n; substring->tag = SUBSTRING; substring->start = offset; substring->child = CordRep::Ref(rep); return substring; } inline CordRep* Substring(CordRep* rep, size_t offset) { return Substring(rep, offset, rep->length - offset); } } CordRepBtreeNavigator::Position CordRepBtreeNavigator::Skip(size_t n) { int height = 0; size_t index = index_[0]; CordRepBtree* node = node_[0]; CordRep* edge = node->Edge(index); while (n >= edge->length) { n -= edge->length; while (++index == node->end()) { if (++height > height_) return {nullptr, n}; node = node_[height]; index = index_[height]; } edge = node->Edge(index); } while (height > 0) { node = edge->btree(); index_[height] = static_cast<uint8_t>(index); node_[--height] = node; index = node->begin(); edge = node->Edge(index); while (n >= edge->length) { n -= edge->length; ++index; assert(index != node->end()); edge = node->Edge(index); } } index_[0] = static_cast<uint8_t>(index); return {edge, n}; } ReadResult CordRepBtreeNavigator::Read(size_t edge_offset, size_t n) { int height = 0; size_t length = edge_offset + n; size_t index = index_[0]; CordRepBtree* node = node_[0]; CordRep* edge = node->Edge(index); assert(edge_offset < edge->length); if (length < edge->length) { return {Substring(edge, edge_offset, n), length}; } CordRepBtree* subtree = CordRepBtree::New(Substring(edge, edge_offset)); size_t subtree_end = 1; do { length -= edge->length; while (++index == node->end()) { index_[height] = static_cast<uint8_t>(index); if (++height > height_) { subtree->set_end(subtree_end); if (length == 0) return {subtree, 0}; CordRep::Unref(subtree); return {nullptr, length}; } if (length != 0) { subtree->set_end(subtree_end); subtree = CordRepBtree::New(subtree); subtree_end = 1; } node = node_[height]; index = index_[height]; } edge = node->Edge(index); if (length >= edge->length) { subtree->length += edge->length; subtree->edges_[subtree_end++] = CordRep::Ref(edge); } } while (length >= edge->length); CordRepBtree* tree = subtree; subtree->length += length; while (height > 0) { node = edge->btree(); index_[height] = static_cast<uint8_t>(index); node_[--height] = node; index = node->begin(); edge = node->Edge(index); if (length != 0) { CordRepBtree* right = CordRepBtree::New(height); right->length = length; subtree->edges_[subtree_end++] = right; subtree->set_end(subtree_end); subtree = right; subtree_end = 0; while (length >= edge->length) { subtree->edges_[subtree_end++] = CordRep::Ref(edge); length -= edge->length; edge = node->Edge(++index); } } } if (length != 0) { subtree->edges_[subtree_end++] = Substring(edge, 0, length); } subtree->set_end(subtree_end); index_[0] = static_cast<uint8_t>(index); return {tree, length}; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/cord_rep_btree_navigator.h" #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_btree.h" #include "absl/strings/internal/cord_rep_test_util.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::testing::Eq; using ::testing::Ne; using ::absl::cordrep_testing::CordRepBtreeFromFlats; using ::absl::cordrep_testing::CordToString; using ::absl::cordrep_testing::CreateFlatsFromString; using ::absl::cordrep_testing::CreateRandomString; using ::absl::cordrep_testing::MakeFlat; using ::absl::cordrep_testing::MakeSubstring; using ReadResult = CordRepBtreeNavigator::ReadResult; using Position = CordRepBtreeNavigator::Position; class CordRepBtreeNavigatorTest : public testing::TestWithParam<size_t> { public: using Flats = std::vector<CordRep*>; static constexpr size_t kCharsPerFlat = 3; CordRepBtreeNavigatorTest() { data_ = CreateRandomString(count() * kCharsPerFlat); flats_ = CreateFlatsFromString(data_, kCharsPerFlat); if (count() > 1) { CordRep::Unref(flats_[1]); flats_[1] = MakeSubstring(kCharsPerFlat, kCharsPerFlat, MakeFlat(data_)); } else { CordRep::Unref(flats_[0]); flats_[0] = MakeSubstring(0, kCharsPerFlat, MakeFlat(data_)); } tree_ = CordRepBtreeFromFlats(flats_); } ~CordRepBtreeNavigatorTest() override { CordRep::Unref(tree_); } size_t count() const { return GetParam(); } CordRepBtree* tree() { return tree_; } const std::string& data() const { return data_; } const std::vector<CordRep*>& flats() const { return flats_; } static std::string ToString(testing::TestParamInfo<size_t> param) { return absl::StrCat(param.param, "_Flats"); } private: std::string data_; Flats flats_; CordRepBtree* tree_; }; INSTANTIATE_TEST_SUITE_P( WithParam, CordRepBtreeNavigatorTest, testing::Values(1, CordRepBtree::kMaxCapacity - 1, CordRepBtree::kMaxCapacity, CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity - 1, CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity, CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity + 1, CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity * 2 + 17), CordRepBtreeNavigatorTest::ToString); TEST(CordRepBtreeNavigatorTest, Uninitialized) { CordRepBtreeNavigator nav; EXPECT_FALSE(nav); EXPECT_THAT(nav.btree(), Eq(nullptr)); #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) EXPECT_DEATH(nav.Current(), ".*"); #endif } TEST_P(CordRepBtreeNavigatorTest, InitFirst) { CordRepBtreeNavigator nav; CordRep* edge = nav.InitFirst(tree()); EXPECT_TRUE(nav); EXPECT_THAT(nav.btree(), Eq(tree())); EXPECT_THAT(nav.Current(), Eq(flats().front())); EXPECT_THAT(edge, Eq(flats().front())); } TEST_P(CordRepBtreeNavigatorTest, InitLast) { CordRepBtreeNavigator nav; CordRep* edge = nav.InitLast(tree()); EXPECT_TRUE(nav); EXPECT_THAT(nav.btree(), Eq(tree())); EXPECT_THAT(nav.Current(), Eq(flats().back())); EXPECT_THAT(edge, Eq(flats().back())); } TEST_P(CordRepBtreeNavigatorTest, NextPrev) { CordRepBtreeNavigator nav; nav.InitFirst(tree()); const Flats& flats = this->flats(); EXPECT_THAT(nav.Previous(), Eq(nullptr)); EXPECT_THAT(nav.Current(), Eq(flats.front())); for (size_t i = 1; i < flats.size(); ++i) { ASSERT_THAT(nav.Next(), Eq(flats[i])); EXPECT_THAT(nav.Current(), Eq(flats[i])); } EXPECT_THAT(nav.Next(), Eq(nullptr)); EXPECT_THAT(nav.Current(), Eq(flats.back())); for (size_t i = flats.size() - 1; i > 0; --i) { ASSERT_THAT(nav.Previous(), Eq(flats[i - 1])); EXPECT_THAT(nav.Current(), Eq(flats[i - 1])); } EXPECT_THAT(nav.Previous(), Eq(nullptr)); EXPECT_THAT(nav.Current(), Eq(flats.front())); } TEST_P(CordRepBtreeNavigatorTest, PrevNext) { CordRepBtreeNavigator nav; nav.InitLast(tree()); const Flats& flats = this->flats(); EXPECT_THAT(nav.Next(), Eq(nullptr)); EXPECT_THAT(nav.Current(), Eq(flats.back())); for (size_t i = flats.size() - 1; i > 0; --i) { ASSERT_THAT(nav.Previous(), Eq(flats[i - 1])); EXPECT_THAT(nav.Current(), Eq(flats[i - 1])); } EXPECT_THAT(nav.Previous(), Eq(nullptr)); EXPECT_THAT(nav.Current(), Eq(flats.front())); for (size_t i = 1; i < flats.size(); ++i) { ASSERT_THAT(nav.Next(), Eq(flats[i])); EXPECT_THAT(nav.Current(), Eq(flats[i])); } EXPECT_THAT(nav.Next(), Eq(nullptr)); EXPECT_THAT(nav.Current(), Eq(flats.back())); } TEST(CordRepBtreeNavigatorTest, Reset) { CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc")); CordRepBtreeNavigator nav; nav.InitFirst(tree); nav.Reset(); EXPECT_FALSE(nav); EXPECT_THAT(nav.btree(), Eq(nullptr)); #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) EXPECT_DEATH(nav.Current(), ".*"); #endif CordRep::Unref(tree); } TEST_P(CordRepBtreeNavigatorTest, Skip) { size_t count = this->count(); const Flats& flats = this->flats(); CordRepBtreeNavigator nav; nav.InitFirst(tree()); for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) { Position pos = nav.Skip(char_offset); EXPECT_THAT(pos.edge, Eq(nav.Current())); EXPECT_THAT(pos.edge, Eq(flats[0])); EXPECT_THAT(pos.offset, Eq(char_offset)); } for (size_t index1 = 0; index1 < count; ++index1) { for (size_t index2 = index1; index2 < count; ++index2) { for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) { CordRepBtreeNavigator nav; nav.InitFirst(tree()); size_t length1 = index1 * kCharsPerFlat; Position pos1 = nav.Skip(length1 + char_offset); ASSERT_THAT(pos1.edge, Eq(flats[index1])); ASSERT_THAT(pos1.edge, Eq(nav.Current())); ASSERT_THAT(pos1.offset, Eq(char_offset)); size_t length2 = index2 * kCharsPerFlat; Position pos2 = nav.Skip(length2 - length1 + char_offset); ASSERT_THAT(pos2.edge, Eq(flats[index2])); ASSERT_THAT(pos2.edge, Eq(nav.Current())); ASSERT_THAT(pos2.offset, Eq(char_offset)); } } } } TEST_P(CordRepBtreeNavigatorTest, Seek) { size_t count = this->count(); const Flats& flats = this->flats(); CordRepBtreeNavigator nav; nav.InitFirst(tree()); for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) { Position pos = nav.Seek(char_offset); EXPECT_THAT(pos.edge, Eq(nav.Current())); EXPECT_THAT(pos.edge, Eq(flats[0])); EXPECT_THAT(pos.offset, Eq(char_offset)); } for (size_t index = 0; index < count; ++index) { for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) { size_t offset = index * kCharsPerFlat + char_offset; Position pos1 = nav.Seek(offset); ASSERT_THAT(pos1.edge, Eq(flats[index])); ASSERT_THAT(pos1.edge, Eq(nav.Current())); ASSERT_THAT(pos1.offset, Eq(char_offset)); } } } TEST(CordRepBtreeNavigatorTest, InitOffset) { CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc")); tree = CordRepBtree::Append(tree, MakeFlat("def")); CordRepBtreeNavigator nav; Position pos = nav.InitOffset(tree, 5); EXPECT_TRUE(nav); EXPECT_THAT(nav.btree(), Eq(tree)); EXPECT_THAT(pos.edge, Eq(tree->Edges()[1])); EXPECT_THAT(pos.edge, Eq(nav.Current())); EXPECT_THAT(pos.offset, Eq(2u)); CordRep::Unref(tree); } TEST(CordRepBtreeNavigatorTest, InitOffsetAndSeekBeyondLength) { CordRepBtree* tree1 = CordRepBtree::Create(MakeFlat("abc")); CordRepBtree* tree2 = CordRepBtree::Create(MakeFlat("def")); CordRepBtreeNavigator nav; nav.InitFirst(tree1); EXPECT_THAT(nav.Seek(3).edge, Eq(nullptr)); EXPECT_THAT(nav.Seek(100).edge, Eq(nullptr)); EXPECT_THAT(nav.btree(), Eq(tree1)); EXPECT_THAT(nav.Current(), Eq(tree1->Edges().front())); EXPECT_THAT(nav.InitOffset(tree2, 3).edge, Eq(nullptr)); EXPECT_THAT(nav.InitOffset(tree2, 100).edge, Eq(nullptr)); EXPECT_THAT(nav.btree(), Eq(tree1)); EXPECT_THAT(nav.Current(), Eq(tree1->Edges().front())); CordRep::Unref(tree1); CordRep::Unref(tree2); } TEST_P(CordRepBtreeNavigatorTest, Read) { const Flats& flats = this->flats(); const std::string& data = this->data(); for (size_t offset = 0; offset < data.size(); ++offset) { for (size_t length = 1; length <= data.size() - offset; ++length) { CordRepBtreeNavigator nav; nav.InitFirst(tree()); size_t edge_offset = nav.Skip(offset).offset; ReadResult result = nav.Read(edge_offset, length); ASSERT_THAT(result.tree, Ne(nullptr)); EXPECT_THAT(result.tree->length, Eq(length)); if (result.tree->tag == BTREE) { ASSERT_TRUE(CordRepBtree::IsValid(result.tree->btree())); } std::string value = CordToString(result.tree); EXPECT_THAT(value, Eq(data.substr(offset, length))); size_t partial = (offset + length) % kCharsPerFlat; ASSERT_THAT(result.n, Eq(partial)); if (offset + length < data.size()) { size_t index = (offset + length) / kCharsPerFlat; EXPECT_THAT(nav.Current(), Eq(flats[index])); } CordRep::Unref(result.tree); } } } TEST_P(CordRepBtreeNavigatorTest, ReadBeyondLengthOfTree) { CordRepBtreeNavigator nav; nav.InitFirst(tree()); ReadResult result = nav.Read(2, tree()->length); ASSERT_THAT(result.tree, Eq(nullptr)); } TEST(CordRepBtreeNavigatorTest, NavigateMaximumTreeDepth) { CordRepFlat* flat1 = MakeFlat("Hello world"); CordRepFlat* flat2 = MakeFlat("World Hello"); CordRepBtree* node = CordRepBtree::Create(flat1); node = CordRepBtree::Append(node, flat2); while (node->height() < CordRepBtree::kMaxHeight) { node = CordRepBtree::New(node); } CordRepBtreeNavigator nav; CordRep* edge = nav.InitFirst(node); EXPECT_THAT(edge, Eq(flat1)); EXPECT_THAT(nav.Next(), Eq(flat2)); EXPECT_THAT(nav.Next(), Eq(nullptr)); EXPECT_THAT(nav.Previous(), Eq(flat1)); EXPECT_THAT(nav.Previous(), Eq(nullptr)); CordRep::Unref(node); } } } ABSL_NAMESPACE_END }
2,577
#ifndef ABSL_STRINGS_INTERNAL_CORD_REP_CRC_H_ #define ABSL_STRINGS_INTERNAL_CORD_REP_CRC_H_ #include <cassert> #include <cstdint> #include "absl/base/config.h" #include "absl/base/optimization.h" #include "absl/crc/internal/crc_cord_state.h" #include "absl/strings/internal/cord_internal.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { struct CordRepCrc : public CordRep { CordRep* child; absl::crc_internal::CrcCordState crc_cord_state; static CordRepCrc* New(CordRep* child, crc_internal::CrcCordState state); static void Destroy(CordRepCrc* node); }; inline CordRep* RemoveCrcNode(CordRep* rep) { assert(rep != nullptr); if (ABSL_PREDICT_FALSE(rep->IsCrc())) { CordRep* child = rep->crc()->child; if (rep->refcount.IsOne()) { delete rep->crc(); } else { CordRep::Ref(child); CordRep::Unref(rep); } return child; } return rep; } inline CordRep* SkipCrcNode(CordRep* rep) { assert(rep != nullptr); if (ABSL_PREDICT_FALSE(rep->IsCrc())) { return rep->crc()->child; } else { return rep; } } inline const CordRep* SkipCrcNode(const CordRep* rep) { assert(rep != nullptr); if (ABSL_PREDICT_FALSE(rep->IsCrc())) { return rep->crc()->child; } else { return rep; } } inline CordRepCrc* CordRep::crc() { assert(IsCrc()); return static_cast<CordRepCrc*>(this); } inline const CordRepCrc* CordRep::crc() const { assert(IsCrc()); return static_cast<const CordRepCrc*>(this); } } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/cord_rep_crc.h" #include <cassert> #include <cstdint> #include <utility> #include "absl/base/config.h" #include "absl/strings/internal/cord_internal.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { CordRepCrc* CordRepCrc::New(CordRep* child, crc_internal::CrcCordState state) { if (child != nullptr && child->IsCrc()) { if (child->refcount.IsOne()) { child->crc()->crc_cord_state = std::move(state); return child->crc(); } CordRep* old = child; child = old->crc()->child; CordRep::Ref(child); CordRep::Unref(old); } auto* new_cordrep = new CordRepCrc; new_cordrep->length = child != nullptr ? child->length : 0; new_cordrep->tag = cord_internal::CRC; new_cordrep->child = child; new_cordrep->crc_cord_state = std::move(state); return new_cordrep; } void CordRepCrc::Destroy(CordRepCrc* node) { if (node->child != nullptr) { CordRep::Unref(node->child); } delete node; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/cord_rep_crc.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/crc/internal/crc_cord_state.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::MakeFlat; using ::testing::Eq; using ::testing::IsNull; using ::testing::Ne; #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST TEST(CordRepCrc, RemoveCrcWithNullptr) { EXPECT_DEATH(RemoveCrcNode(nullptr), ""); } #endif absl::crc_internal::CrcCordState MakeCrcCordState(uint32_t crc) { crc_internal::CrcCordState state; state.mutable_rep()->prefix_crc.push_back( crc_internal::CrcCordState::PrefixCrc(42, crc32c_t{crc})); return state; } TEST(CordRepCrc, NewDestroy) { CordRep* rep = cordrep_testing::MakeFlat("Hello world"); CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345)); EXPECT_TRUE(crc->refcount.IsOne()); EXPECT_THAT(crc->child, Eq(rep)); EXPECT_THAT(crc->crc_cord_state.Checksum(), Eq(crc32c_t{12345u})); EXPECT_TRUE(rep->refcount.IsOne()); CordRepCrc::Destroy(crc); } TEST(CordRepCrc, NewExistingCrcNotShared) { CordRep* rep = cordrep_testing::MakeFlat("Hello world"); CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345)); CordRepCrc* new_crc = CordRepCrc::New(crc, MakeCrcCordState(54321)); EXPECT_THAT(new_crc, Eq(crc)); EXPECT_TRUE(new_crc->refcount.IsOne()); EXPECT_THAT(new_crc->child, Eq(rep)); EXPECT_THAT(new_crc->crc_cord_state.Checksum(), Eq(crc32c_t{54321u})); EXPECT_TRUE(rep->refcount.IsOne()); CordRepCrc::Destroy(new_crc); } TEST(CordRepCrc, NewExistingCrcShared) { CordRep* rep = cordrep_testing::MakeFlat("Hello world"); CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345)); CordRep::Ref(crc); CordRepCrc* new_crc = CordRepCrc::New(crc, MakeCrcCordState(54321)); EXPECT_THAT(new_crc, Ne(crc)); EXPECT_TRUE(new_crc->refcount.IsOne()); EXPECT_TRUE(crc->refcount.IsOne()); EXPECT_FALSE(rep->refcount.IsOne()); EXPECT_THAT(crc->child, Eq(rep)); EXPECT_THAT(new_crc->child, Eq(rep)); EXPECT_THAT(crc->crc_cord_state.Checksum(), Eq(crc32c_t{12345u})); EXPECT_THAT(new_crc->crc_cord_state.Checksum(), Eq(crc32c_t{54321u})); CordRep::Unref(crc); CordRep::Unref(new_crc); } TEST(CordRepCrc, NewEmpty) { CordRepCrc* crc = CordRepCrc::New(nullptr, MakeCrcCordState(12345)); EXPECT_TRUE(crc->refcount.IsOne()); EXPECT_THAT(crc->child, IsNull()); EXPECT_THAT(crc->length, Eq(0u)); EXPECT_THAT(crc->crc_cord_state.Checksum(), Eq(crc32c_t{12345u})); EXPECT_TRUE(crc->refcount.IsOne()); CordRepCrc::Destroy(crc); } TEST(CordRepCrc, RemoveCrcNotCrc) { CordRep* rep = cordrep_testing::MakeFlat("Hello world"); CordRep* nocrc = RemoveCrcNode(rep); EXPECT_THAT(nocrc, Eq(rep)); CordRep::Unref(nocrc); } TEST(CordRepCrc, RemoveCrcNotShared) { CordRep* rep = cordrep_testing::MakeFlat("Hello world"); CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345)); CordRep* nocrc = RemoveCrcNode(crc); EXPECT_THAT(nocrc, Eq(rep)); EXPECT_TRUE(rep->refcount.IsOne()); CordRep::Unref(nocrc); } TEST(CordRepCrc, RemoveCrcShared) { CordRep* rep = cordrep_testing::MakeFlat("Hello world"); CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345)); CordRep::Ref(crc); CordRep* nocrc = RemoveCrcNode(crc); EXPECT_THAT(nocrc, Eq(rep)); EXPECT_FALSE(rep->refcount.IsOne()); CordRep::Unref(nocrc); CordRep::Unref(crc); } } } ABSL_NAMESPACE_END }
2,578
#ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_EXTENSION_H_ #define ABSL_STRINGS_INTERNAL_STR_FORMAT_EXTENSION_H_ #include <cstddef> #include <cstdint> #include <cstring> #include <ostream> #include <string> #include "absl/base/config.h" #include "absl/strings/internal/str_format/output.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN enum class FormatConversionChar : uint8_t; enum class FormatConversionCharSet : uint64_t; enum class LengthMod : std::uint8_t { h, hh, l, ll, L, j, z, t, q, none }; namespace str_format_internal { class FormatRawSinkImpl { public: template <typename T, decltype(str_format_internal::InvokeFlush( std::declval<T*>(), string_view()))* = nullptr> FormatRawSinkImpl(T* raw) : sink_(raw), write_(&FormatRawSinkImpl::Flush<T>) {} void Write(string_view s) { write_(sink_, s); } template <typename T> static FormatRawSinkImpl Extract(T s) { return s.sink_; } private: template <typename T> static void Flush(void* r, string_view s) { str_format_internal::InvokeFlush(static_cast<T*>(r), s); } void* sink_; void (*write_)(void*, string_view); }; class FormatSinkImpl { public: explicit FormatSinkImpl(FormatRawSinkImpl raw) : raw_(raw) {} ~FormatSinkImpl() { Flush(); } void Flush() { raw_.Write(string_view(buf_, static_cast<size_t>(pos_ - buf_))); pos_ = buf_; } void Append(size_t n, char c) { if (n == 0) return; size_ += n; auto raw_append = [&](size_t count) { memset(pos_, c, count); pos_ += count; }; while (n > Avail()) { n -= Avail(); if (Avail() > 0) { raw_append(Avail()); } Flush(); } raw_append(n); } void Append(string_view v) { size_t n = v.size(); if (n == 0) return; size_ += n; if (n >= Avail()) { Flush(); raw_.Write(v); return; } memcpy(pos_, v.data(), n); pos_ += n; } size_t size() const { return size_; } bool PutPaddedString(string_view v, int width, int precision, bool left); template <typename T> T Wrap() { return T(this); } template <typename T> static FormatSinkImpl* Extract(T* s) { return s->sink_; } private: size_t Avail() const { return static_cast<size_t>(buf_ + sizeof(buf_) - pos_); } FormatRawSinkImpl raw_; size_t size_ = 0; char* pos_ = buf_; char buf_[1024]; }; enum class Flags : uint8_t { kBasic = 0, kLeft = 1 << 0, kShowPos = 1 << 1, kSignCol = 1 << 2, kAlt = 1 << 3, kZero = 1 << 4, kNonBasic = 1 << 5, }; constexpr Flags operator|(Flags a, Flags b) { return static_cast<Flags>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b)); } constexpr bool FlagsContains(Flags haystack, Flags needle) { return (static_cast<uint8_t>(haystack) & static_cast<uint8_t>(needle)) == static_cast<uint8_t>(needle); } std::string FlagsToString(Flags v); inline std::ostream& operator<<(std::ostream& os, Flags v) { return os << FlagsToString(v); } #define ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(X_VAL, X_SEP) \ \ X_VAL(c) X_SEP X_VAL(s) X_SEP \ \ X_VAL(d) X_SEP X_VAL(i) X_SEP X_VAL(o) X_SEP \ X_VAL(u) X_SEP X_VAL(x) X_SEP X_VAL(X) X_SEP \ \ X_VAL(f) X_SEP X_VAL(F) X_SEP X_VAL(e) X_SEP X_VAL(E) X_SEP \ X_VAL(g) X_SEP X_VAL(G) X_SEP X_VAL(a) X_SEP X_VAL(A) X_SEP \ \ X_VAL(n) X_SEP X_VAL(p) X_SEP X_VAL(v) struct FormatConversionCharInternal { FormatConversionCharInternal() = delete; private: enum class Enum : uint8_t { c, s, d, i, o, u, x, X, f, F, e, E, g, G, a, A, n, p, v, kNone }; public: #define ABSL_INTERNAL_X_VAL(id) \ static constexpr FormatConversionChar id = \ static_cast<FormatConversionChar>(Enum::id); ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL, ) #undef ABSL_INTERNAL_X_VAL static constexpr FormatConversionChar kNone = static_cast<FormatConversionChar>(Enum::kNone); }; inline FormatConversionChar FormatConversionCharFromChar(char c) { switch (c) { #define ABSL_INTERNAL_X_VAL(id) \ case #id[0]: \ return FormatConversionCharInternal::id; ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL, ) #undef ABSL_INTERNAL_X_VAL } return FormatConversionCharInternal::kNone; } inline bool FormatConversionCharIsUpper(FormatConversionChar c) { if (c == FormatConversionCharInternal::X || c == FormatConversionCharInternal::F || c == FormatConversionCharInternal::E || c == FormatConversionCharInternal::G || c == FormatConversionCharInternal::A) { return true; } else { return false; } } inline bool FormatConversionCharIsFloat(FormatConversionChar c) { if (c == FormatConversionCharInternal::a || c == FormatConversionCharInternal::e || c == FormatConversionCharInternal::f || c == FormatConversionCharInternal::g || c == FormatConversionCharInternal::A || c == FormatConversionCharInternal::E || c == FormatConversionCharInternal::F || c == FormatConversionCharInternal::G) { return true; } else { return false; } } inline char FormatConversionCharToChar(FormatConversionChar c) { if (c == FormatConversionCharInternal::kNone) { return '\0'; #define ABSL_INTERNAL_X_VAL(e) \ } else if (c == FormatConversionCharInternal::e) { \ return #e[0]; #define ABSL_INTERNAL_X_SEP ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL, ABSL_INTERNAL_X_SEP) } else { return '\0'; } #undef ABSL_INTERNAL_X_VAL #undef ABSL_INTERNAL_X_SEP } inline std::ostream& operator<<(std::ostream& os, FormatConversionChar v) { char c = FormatConversionCharToChar(v); if (!c) c = '?'; return os << c; } struct FormatConversionSpecImplFriend; class FormatConversionSpecImpl { public: bool is_basic() const { return flags_ == Flags::kBasic; } bool has_left_flag() const { return FlagsContains(flags_, Flags::kLeft); } bool has_show_pos_flag() const { return FlagsContains(flags_, Flags::kShowPos); } bool has_sign_col_flag() const { return FlagsContains(flags_, Flags::kSignCol); } bool has_alt_flag() const { return FlagsContains(flags_, Flags::kAlt); } bool has_zero_flag() const { return FlagsContains(flags_, Flags::kZero); } LengthMod length_mod() const { return length_mod_; } FormatConversionChar conversion_char() const { static_assert(offsetof(FormatConversionSpecImpl, conv_) == 0, ""); return conv_; } void set_conversion_char(FormatConversionChar c) { conv_ = c; } int width() const { return width_; } int precision() const { return precision_; } template <typename T> T Wrap() { return T(*this); } private: friend struct str_format_internal::FormatConversionSpecImplFriend; FormatConversionChar conv_ = FormatConversionCharInternal::kNone; Flags flags_; LengthMod length_mod_ = LengthMod::none; int width_; int precision_; }; struct FormatConversionSpecImplFriend final { static void SetFlags(Flags f, FormatConversionSpecImpl* conv) { conv->flags_ = f; } static void SetLengthMod(LengthMod l, FormatConversionSpecImpl* conv) { conv->length_mod_ = l; } static void SetConversionChar(FormatConversionChar c, FormatConversionSpecImpl* conv) { conv->conv_ = c; } static void SetWidth(int w, FormatConversionSpecImpl* conv) { conv->width_ = w; } static void SetPrecision(int p, FormatConversionSpecImpl* conv) { conv->precision_ = p; } static std::string FlagsToString(const FormatConversionSpecImpl& spec) { return str_format_internal::FlagsToString(spec.flags_); } }; constexpr FormatConversionCharSet FormatConversionCharSetUnion( FormatConversionCharSet a) { return a; } template <typename... CharSet> constexpr FormatConversionCharSet FormatConversionCharSetUnion( FormatConversionCharSet a, CharSet... rest) { return static_cast<FormatConversionCharSet>( static_cast<uint64_t>(a) | static_cast<uint64_t>(FormatConversionCharSetUnion(rest...))); } constexpr uint64_t FormatConversionCharToConvInt(FormatConversionChar c) { return uint64_t{1} << (1 + static_cast<uint8_t>(c)); } constexpr uint64_t FormatConversionCharToConvInt(char conv) { return #define ABSL_INTERNAL_CHAR_SET_CASE(c) \ conv == #c[0] \ ? FormatConversionCharToConvInt(FormatConversionCharInternal::c) \ : ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_CHAR_SET_CASE, ) #undef ABSL_INTERNAL_CHAR_SET_CASE conv == '*' ? 1 : 0; } constexpr FormatConversionCharSet FormatConversionCharToConvValue(char conv) { return static_cast<FormatConversionCharSet>( FormatConversionCharToConvInt(conv)); } struct FormatConversionCharSetInternal { #define ABSL_INTERNAL_CHAR_SET_CASE(c) \ static constexpr FormatConversionCharSet c = \ FormatConversionCharToConvValue(#c[0]); ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_CHAR_SET_CASE, ) #undef ABSL_INTERNAL_CHAR_SET_CASE static constexpr FormatConversionCharSet kStar = FormatConversionCharToConvValue('*'); static constexpr FormatConversionCharSet kIntegral = FormatConversionCharSetUnion(d, i, u, o, x, X); static constexpr FormatConversionCharSet kFloating = FormatConversionCharSetUnion(a, e, f, g, A, E, F, G); static constexpr FormatConversionCharSet kNumeric = FormatConversionCharSetUnion(kIntegral, kFloating); static constexpr FormatConversionCharSet kPointer = p; }; constexpr FormatConversionCharSet operator|(FormatConversionCharSet a, FormatConversionCharSet b) { return FormatConversionCharSetUnion(a, b); } constexpr FormatConversionCharSet ToFormatConversionCharSet(char c) { return static_cast<FormatConversionCharSet>( FormatConversionCharToConvValue(c)); } constexpr FormatConversionCharSet ToFormatConversionCharSet( FormatConversionCharSet c) { return c; } template <typename T> void ToFormatConversionCharSet(T) = delete; constexpr bool Contains(FormatConversionCharSet set, char c) { return (static_cast<uint64_t>(set) & static_cast<uint64_t>(FormatConversionCharToConvValue(c))) != 0; } constexpr bool Contains(FormatConversionCharSet set, FormatConversionCharSet c) { return (static_cast<uint64_t>(set) & static_cast<uint64_t>(c)) == static_cast<uint64_t>(c); } constexpr bool Contains(FormatConversionCharSet set, FormatConversionChar c) { return (static_cast<uint64_t>(set) & FormatConversionCharToConvInt(c)) != 0; } inline size_t Excess(size_t used, size_t capacity) { return used < capacity ? capacity - used : 0; } } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/str_format/extension.h" #include <errno.h> #include <algorithm> #include <string> namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { std::string FlagsToString(Flags v) { std::string s; s.append(FlagsContains(v, Flags::kLeft) ? "-" : ""); s.append(FlagsContains(v, Flags::kShowPos) ? "+" : ""); s.append(FlagsContains(v, Flags::kSignCol) ? " " : ""); s.append(FlagsContains(v, Flags::kAlt) ? "#" : ""); s.append(FlagsContains(v, Flags::kZero) ? "0" : ""); return s; } #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL #define ABSL_INTERNAL_X_VAL(id) \ constexpr absl::FormatConversionChar FormatConversionCharInternal::id; ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL, ) #undef ABSL_INTERNAL_X_VAL constexpr absl::FormatConversionChar FormatConversionCharInternal::kNone; #define ABSL_INTERNAL_CHAR_SET_CASE(c) \ constexpr FormatConversionCharSet FormatConversionCharSetInternal::c; ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_CHAR_SET_CASE, ) #undef ABSL_INTERNAL_CHAR_SET_CASE constexpr FormatConversionCharSet FormatConversionCharSetInternal::kStar; constexpr FormatConversionCharSet FormatConversionCharSetInternal::kIntegral; constexpr FormatConversionCharSet FormatConversionCharSetInternal::kFloating; constexpr FormatConversionCharSet FormatConversionCharSetInternal::kNumeric; constexpr FormatConversionCharSet FormatConversionCharSetInternal::kPointer; #endif bool FormatSinkImpl::PutPaddedString(string_view value, int width, int precision, bool left) { size_t space_remaining = 0; if (width >= 0) space_remaining = static_cast<size_t>(width); size_t n = value.size(); if (precision >= 0) n = std::min(n, static_cast<size_t>(precision)); string_view shown(value.data(), n); space_remaining = Excess(shown.size(), space_remaining); if (!left) Append(space_remaining, ' '); Append(shown); if (left) Append(space_remaining, ' '); return true; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/str_format/extension.h" #include <random> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" namespace my_namespace { class UserDefinedType { public: UserDefinedType() = default; void Append(absl::string_view str) { value_.append(str.data(), str.size()); } const std::string& Value() const { return value_; } friend void AbslFormatFlush(UserDefinedType* x, absl::string_view str) { x->Append(str); } private: std::string value_; }; } namespace { std::string MakeRandomString(size_t len) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis('a', 'z'); std::string s(len, '0'); for (char& c : s) { c = dis(gen); } return s; } TEST(FormatExtensionTest, SinkAppendSubstring) { for (size_t chunk_size : {1, 10, 100, 1000, 10000}) { std::string expected, actual; absl::str_format_internal::FormatSinkImpl sink(&actual); for (size_t chunks = 0; chunks < 10; ++chunks) { std::string rand = MakeRandomString(chunk_size); expected += rand; sink.Append(rand); } sink.Flush(); EXPECT_EQ(actual, expected); } } TEST(FormatExtensionTest, SinkAppendChars) { for (size_t chunk_size : {1, 10, 100, 1000, 10000}) { std::string expected, actual; absl::str_format_internal::FormatSinkImpl sink(&actual); for (size_t chunks = 0; chunks < 10; ++chunks) { std::string rand = MakeRandomString(1); expected.append(chunk_size, rand[0]); sink.Append(chunk_size, rand[0]); } sink.Flush(); EXPECT_EQ(actual, expected); } } TEST(FormatExtensionTest, VerifyEnumEquality) { #define X_VAL(id) \ EXPECT_EQ(absl::FormatConversionChar::id, \ absl::str_format_internal::FormatConversionCharInternal::id); ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(X_VAL, ); #undef X_VAL #define X_VAL(id) \ EXPECT_EQ(absl::FormatConversionCharSet::id, \ absl::str_format_internal::FormatConversionCharSetInternal::id); ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(X_VAL, ); #undef X_VAL } TEST(FormatExtensionTest, SetConversionChar) { absl::str_format_internal::FormatConversionSpecImpl spec; EXPECT_EQ(spec.conversion_char(), absl::str_format_internal::FormatConversionCharInternal::kNone); spec.set_conversion_char( absl::str_format_internal::FormatConversionCharInternal::d); EXPECT_EQ(spec.conversion_char(), absl::str_format_internal::FormatConversionCharInternal::d); } }
2,579
#ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_BIND_H_ #define ABSL_STRINGS_INTERNAL_STR_FORMAT_BIND_H_ #include <cassert> #include <cstdio> #include <ostream> #include <string> #include "absl/base/config.h" #include "absl/container/inlined_vector.h" #include "absl/strings/internal/str_format/arg.h" #include "absl/strings/internal/str_format/checker.h" #include "absl/strings/internal/str_format/constexpr_parser.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" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN class UntypedFormatSpec; namespace str_format_internal { class BoundConversion : public FormatConversionSpecImpl { public: const FormatArgImpl* arg() const { return arg_; } void set_arg(const FormatArgImpl* a) { arg_ = a; } private: const FormatArgImpl* arg_; }; class UntypedFormatSpecImpl { public: UntypedFormatSpecImpl() = delete; explicit UntypedFormatSpecImpl(string_view s) : data_(s.data()), size_(s.size()) {} explicit UntypedFormatSpecImpl( const str_format_internal::ParsedFormatBase* pc) : data_(pc), size_(~size_t{}) {} bool has_parsed_conversion() const { return size_ == ~size_t{}; } string_view str() const { assert(!has_parsed_conversion()); return string_view(static_cast<const char*>(data_), size_); } const str_format_internal::ParsedFormatBase* parsed_conversion() const { assert(has_parsed_conversion()); return static_cast<const str_format_internal::ParsedFormatBase*>(data_); } template <typename T> static const UntypedFormatSpecImpl& Extract(const T& s) { return s.spec_; } private: const void* data_; size_t size_; }; template <typename T, FormatConversionCharSet...> struct MakeDependent { using type = T; }; template <FormatConversionCharSet... Args> class FormatSpecTemplate : public MakeDependent<UntypedFormatSpec, Args...>::type { using Base = typename MakeDependent<UntypedFormatSpec, Args...>::type; template <bool res> struct ErrorMaker { constexpr bool operator()(int) const { return res; } }; template <int i, int j> static constexpr bool CheckArity(ErrorMaker<true> SpecifierCount = {}, ErrorMaker<i == j> ParametersPassed = {}) { static_assert(SpecifierCount(i) == ParametersPassed(j), "Number of arguments passed must match the number of " "conversion specifiers."); return true; } template <FormatConversionCharSet specified, FormatConversionCharSet passed, int arg> static constexpr bool CheckMatch( ErrorMaker<Contains(specified, passed)> MismatchedArgumentNumber = {}) { static_assert(MismatchedArgumentNumber(arg), "Passed argument must match specified format."); return true; } template <FormatConversionCharSet... C, size_t... I> static bool CheckMatches(absl::index_sequence<I...>) { bool res[] = {true, CheckMatch<Args, C, I + 1>()...}; (void)res; return true; } public: #ifdef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER FormatSpecTemplate(...) __attribute__((unavailable("Format string is not constexpr."))); template <typename = void> FormatSpecTemplate(const char* s) __attribute__(( enable_if(str_format_internal::EnsureConstexpr(s), "constexpr trap"), unavailable( "Format specified does not match the arguments passed."))); template <typename T = void> FormatSpecTemplate(string_view s) __attribute__((enable_if(str_format_internal::EnsureConstexpr(s), "constexpr trap"))) : Base("to avoid noise in the compiler error") { static_assert(sizeof(T*) == 0, "Format specified does not match the arguments passed."); } FormatSpecTemplate(const char* s) __attribute__((enable_if(ValidFormatImpl<Args...>(s), "bad format trap"))) : Base(s) {} FormatSpecTemplate(string_view s) __attribute__((enable_if(ValidFormatImpl<Args...>(s), "bad format trap"))) : Base(s) {} #else FormatSpecTemplate(const char* s) : Base(s) {} FormatSpecTemplate(string_view s) : Base(s) {} #endif template <FormatConversionCharSet... C> FormatSpecTemplate(const ExtendedParsedFormat<C...>& pc) : Base(&pc) { CheckArity<sizeof...(C), sizeof...(Args)>(); CheckMatches<C...>(absl::make_index_sequence<sizeof...(C)>{}); } }; class Streamable { public: Streamable(const UntypedFormatSpecImpl& format, absl::Span<const FormatArgImpl> args) : format_(format), args_(args.begin(), args.end()) {} std::ostream& Print(std::ostream& os) const; friend std::ostream& operator<<(std::ostream& os, const Streamable& l) { return l.Print(os); } private: const UntypedFormatSpecImpl& format_; absl::InlinedVector<FormatArgImpl, 4> args_; }; std::string Summarize(UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args); bool BindWithPack(const UnboundConversion* props, absl::Span<const FormatArgImpl> pack, BoundConversion* bound); bool FormatUntyped(FormatRawSinkImpl raw_sink, UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args); std::string& AppendPack(std::string* out, UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args); std::string FormatPack(UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args); int FprintF(std::FILE* output, UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args); int SnprintF(char* output, size_t size, UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args); template <typename T> class StreamedWrapper { public: explicit StreamedWrapper(const T& v) : v_(v) {} private: template <typename S> friend ArgConvertResult<FormatConversionCharSetUnion( FormatConversionCharSetInternal::s, FormatConversionCharSetInternal::v)> FormatConvertImpl(const StreamedWrapper<S>& v, FormatConversionSpecImpl conv, FormatSinkImpl* out); const T& v_; }; } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/str_format/bind.h" #include <algorithm> #include <cassert> #include <cerrno> #include <cstddef> #include <cstdio> #include <ios> #include <limits> #include <ostream> #include <sstream> #include <string> #include "absl/base/config.h" #include "absl/base/optimization.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" #include "absl/strings/internal/str_format/output.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { namespace { inline bool BindFromPosition(int position, int* value, absl::Span<const FormatArgImpl> pack) { assert(position > 0); if (static_cast<size_t>(position) > pack.size()) { return false; } return FormatArgImplFriend::ToInt(pack[static_cast<size_t>(position) - 1], value); } class ArgContext { public: explicit ArgContext(absl::Span<const FormatArgImpl> pack) : pack_(pack) {} bool Bind(const UnboundConversion* unbound, BoundConversion* bound); private: absl::Span<const FormatArgImpl> pack_; }; inline bool ArgContext::Bind(const UnboundConversion* unbound, BoundConversion* bound) { const FormatArgImpl* arg = nullptr; int arg_position = unbound->arg_position; if (static_cast<size_t>(arg_position - 1) >= pack_.size()) return false; arg = &pack_[static_cast<size_t>(arg_position - 1)]; if (unbound->flags != Flags::kBasic) { int width = unbound->width.value(); bool force_left = false; if (unbound->width.is_from_arg()) { if (!BindFromPosition(unbound->width.get_from_arg(), &width, pack_)) return false; if (width < 0) { force_left = true; width = -std::max(width, -std::numeric_limits<int>::max()); } } int precision = unbound->precision.value(); if (unbound->precision.is_from_arg()) { if (!BindFromPosition(unbound->precision.get_from_arg(), &precision, pack_)) return false; } FormatConversionSpecImplFriend::SetWidth(width, bound); FormatConversionSpecImplFriend::SetPrecision(precision, bound); if (force_left) { FormatConversionSpecImplFriend::SetFlags(unbound->flags | Flags::kLeft, bound); } else { FormatConversionSpecImplFriend::SetFlags(unbound->flags, bound); } FormatConversionSpecImplFriend::SetLengthMod(unbound->length_mod, bound); } else { FormatConversionSpecImplFriend::SetFlags(unbound->flags, bound); FormatConversionSpecImplFriend::SetWidth(-1, bound); FormatConversionSpecImplFriend::SetPrecision(-1, bound); } FormatConversionSpecImplFriend::SetConversionChar(unbound->conv, bound); bound->set_arg(arg); return true; } template <typename Converter> class ConverterConsumer { public: ConverterConsumer(Converter converter, absl::Span<const FormatArgImpl> pack) : converter_(converter), arg_context_(pack) {} bool Append(string_view s) { converter_.Append(s); return true; } bool ConvertOne(const UnboundConversion& conv, string_view conv_string) { BoundConversion bound; if (!arg_context_.Bind(&conv, &bound)) return false; return converter_.ConvertOne(bound, conv_string); } private: Converter converter_; ArgContext arg_context_; }; template <typename Converter> bool ConvertAll(const UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args, Converter converter) { if (format.has_parsed_conversion()) { return format.parsed_conversion()->ProcessFormat( ConverterConsumer<Converter>(converter, args)); } else { return ParseFormatString(format.str(), ConverterConsumer<Converter>(converter, args)); } } class DefaultConverter { public: explicit DefaultConverter(FormatSinkImpl* sink) : sink_(sink) {} void Append(string_view s) const { sink_->Append(s); } bool ConvertOne(const BoundConversion& bound, string_view ) const { return FormatArgImplFriend::Convert(*bound.arg(), bound, sink_); } private: FormatSinkImpl* sink_; }; class SummarizingConverter { public: explicit SummarizingConverter(FormatSinkImpl* sink) : sink_(sink) {} void Append(string_view s) const { sink_->Append(s); } bool ConvertOne(const BoundConversion& bound, string_view ) const { UntypedFormatSpecImpl spec("%d"); std::ostringstream ss; ss << "{" << Streamable(spec, {*bound.arg()}) << ":" << FormatConversionSpecImplFriend::FlagsToString(bound); if (bound.width() >= 0) ss << bound.width(); if (bound.precision() >= 0) ss << "." << bound.precision(); ss << bound.conversion_char() << "}"; Append(ss.str()); return true; } private: FormatSinkImpl* sink_; }; } bool BindWithPack(const UnboundConversion* props, absl::Span<const FormatArgImpl> pack, BoundConversion* bound) { return ArgContext(pack).Bind(props, bound); } std::string Summarize(const UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args) { typedef SummarizingConverter Converter; std::string out; { FormatSinkImpl sink(&out); if (!ConvertAll(format, args, Converter(&sink))) { return ""; } } return out; } bool FormatUntyped(FormatRawSinkImpl raw_sink, const UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args) { FormatSinkImpl sink(raw_sink); using Converter = DefaultConverter; return ConvertAll(format, args, Converter(&sink)); } std::ostream& Streamable::Print(std::ostream& os) const { if (!FormatUntyped(&os, format_, args_)) os.setstate(std::ios::failbit); return os; } std::string& AppendPack(std::string* out, const UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args) { size_t orig = out->size(); if (ABSL_PREDICT_FALSE(!FormatUntyped(out, format, args))) { out->erase(orig); } return *out; } std::string FormatPack(UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args) { std::string out; if (ABSL_PREDICT_FALSE(!FormatUntyped(&out, format, args))) { out.clear(); } return out; } int FprintF(std::FILE* output, const UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args) { FILERawSink sink(output); if (!FormatUntyped(&sink, format, args)) { errno = EINVAL; return -1; } if (sink.error()) { errno = sink.error(); return -1; } if (sink.count() > static_cast<size_t>(std::numeric_limits<int>::max())) { errno = EFBIG; return -1; } return static_cast<int>(sink.count()); } int SnprintF(char* output, size_t size, const UntypedFormatSpecImpl format, absl::Span<const FormatArgImpl> args) { BufferRawSink sink(output, size ? size - 1 : 0); if (!FormatUntyped(&sink, format, args)) { errno = EINVAL; return -1; } size_t total = sink.total_written(); if (size) output[std::min(total, size - 1)] = 0; return static_cast<int>(total); } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/str_format/bind.h" #include <string.h> #include <limits> #include "gtest/gtest.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { namespace { class FormatBindTest : public ::testing::Test { public: bool Extract(const char *s, UnboundConversion *props, int *next) const { return ConsumeUnboundConversion(s, s + strlen(s), props, next) == s + strlen(s); } }; TEST_F(FormatBindTest, BindSingle) { struct Expectation { int line; const char *fmt; int ok_phases; const FormatArgImpl *arg; int width; int precision; int next_arg; }; const int no = -1; const int ia[] = { 10, 20, 30, 40}; const FormatArgImpl args[] = {FormatArgImpl(ia[0]), FormatArgImpl(ia[1]), FormatArgImpl(ia[2]), FormatArgImpl(ia[3])}; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-field-initializers" const Expectation kExpect[] = { {__LINE__, "d", 2, &args[0], no, no, 2}, {__LINE__, "4d", 2, &args[0], 4, no, 2}, {__LINE__, ".5d", 2, &args[0], no, 5, 2}, {__LINE__, "4.5d", 2, &args[0], 4, 5, 2}, {__LINE__, "*d", 2, &args[1], 10, no, 3}, {__LINE__, ".*d", 2, &args[1], no, 10, 3}, {__LINE__, "*.*d", 2, &args[2], 10, 20, 4}, {__LINE__, "1$d", 2, &args[0], no, no, 0}, {__LINE__, "2$d", 2, &args[1], no, no, 0}, {__LINE__, "3$d", 2, &args[2], no, no, 0}, {__LINE__, "4$d", 2, &args[3], no, no, 0}, {__LINE__, "2$*1$d", 2, &args[1], 10, no, 0}, {__LINE__, "2$*2$d", 2, &args[1], 20, no, 0}, {__LINE__, "2$*3$d", 2, &args[1], 30, no, 0}, {__LINE__, "2$.*1$d", 2, &args[1], no, 10, 0}, {__LINE__, "2$.*2$d", 2, &args[1], no, 20, 0}, {__LINE__, "2$.*3$d", 2, &args[1], no, 30, 0}, {__LINE__, "2$*3$.*1$d", 2, &args[1], 30, 10, 0}, {__LINE__, "2$*2$.*2$d", 2, &args[1], 20, 20, 0}, {__LINE__, "2$*1$.*3$d", 2, &args[1], 10, 30, 0}, {__LINE__, "2$*3$.*1$d", 2, &args[1], 30, 10, 0}, {__LINE__, "1$*d", 0}, {__LINE__, "*2$d", 0}, {__LINE__, "6$d", 1}, {__LINE__, "1$6$d", 0}, {__LINE__, "1$.6$d", 0}, {__LINE__, "1$*6$d", 1}, {__LINE__, "1$.*6$d", 1}, }; #pragma GCC diagnostic pop for (const Expectation &e : kExpect) { SCOPED_TRACE(e.line); SCOPED_TRACE(e.fmt); UnboundConversion props; BoundConversion bound; int ok_phases = 0; int next = 0; if (Extract(e.fmt, &props, &next)) { ++ok_phases; if (BindWithPack(&props, args, &bound)) { ++ok_phases; } } EXPECT_EQ(e.ok_phases, ok_phases); if (e.ok_phases < 2) continue; if (e.arg != nullptr) { EXPECT_EQ(e.arg, bound.arg()); } EXPECT_EQ(e.width, bound.width()); EXPECT_EQ(e.precision, bound.precision()); } } TEST_F(FormatBindTest, WidthUnderflowRegression) { UnboundConversion props; BoundConversion bound; int next = 0; const int args_i[] = {std::numeric_limits<int>::min(), 17}; const FormatArgImpl args[] = {FormatArgImpl(args_i[0]), FormatArgImpl(args_i[1])}; ASSERT_TRUE(Extract("*d", &props, &next)); ASSERT_TRUE(BindWithPack(&props, args, &bound)); EXPECT_EQ(bound.width(), std::numeric_limits<int>::max()); EXPECT_EQ(bound.arg(), args + 1); } TEST_F(FormatBindTest, FormatPack) { struct Expectation { int line; const char *fmt; const char *summary; }; const int ia[] = { 10, 20, 30, 40, -10 }; const FormatArgImpl args[] = {FormatArgImpl(ia[0]), FormatArgImpl(ia[1]), FormatArgImpl(ia[2]), FormatArgImpl(ia[3]), FormatArgImpl(ia[4])}; const Expectation kExpect[] = { {__LINE__, "a%4db%dc", "a{10:4d}b{20:d}c"}, {__LINE__, "a%.4db%dc", "a{10:.4d}b{20:d}c"}, {__LINE__, "a%4.5db%dc", "a{10:4.5d}b{20:d}c"}, {__LINE__, "a%db%4.5dc", "a{10:d}b{20:4.5d}c"}, {__LINE__, "a%db%*.*dc", "a{10:d}b{40:20.30d}c"}, {__LINE__, "a%.*fb", "a{20:.10f}b"}, {__LINE__, "a%1$db%2$*3$.*4$dc", "a{10:d}b{20:30.40d}c"}, {__LINE__, "a%4$db%3$*2$.*1$dc", "a{40:d}b{30:20.10d}c"}, {__LINE__, "a%04ldb", "a{10:04d}b"}, {__LINE__, "a%-#04lldb", "a{10:-#04d}b"}, {__LINE__, "a%1$*5$db", "a{10:-10d}b"}, {__LINE__, "a%1$.*5$db", "a{10:d}b"}, }; for (const Expectation &e : kExpect) { absl::string_view fmt = e.fmt; SCOPED_TRACE(e.line); SCOPED_TRACE(e.fmt); UntypedFormatSpecImpl format(fmt); EXPECT_EQ(e.summary, str_format_internal::Summarize(format, absl::MakeSpan(args))) << "line:" << e.line; } } } } ABSL_NAMESPACE_END }
2,580
#ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_ARG_H_ #define ABSL_STRINGS_INTERNAL_STR_FORMAT_ARG_H_ #include <string.h> #include <wchar.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdio> #include <limits> #include <memory> #include <sstream> #include <string> #include <type_traits> #include <utility> #include "absl/base/config.h" #include "absl/base/optimization.h" #include "absl/meta/type_traits.h" #include "absl/numeric/int128.h" #include "absl/strings/has_absl_stringify.h" #include "absl/strings/internal/str_format/extension.h" #include "absl/strings/string_view.h" #if defined(ABSL_HAVE_STD_STRING_VIEW) #include <string_view> #endif namespace absl { ABSL_NAMESPACE_BEGIN class Cord; class FormatCountCapture; class FormatSink; template <absl::FormatConversionCharSet C> struct FormatConvertResult; class FormatConversionSpec; namespace str_format_internal { template <FormatConversionCharSet C> struct ArgConvertResult { bool value; }; using IntegralConvertResult = ArgConvertResult<FormatConversionCharSetUnion( FormatConversionCharSetInternal::c, FormatConversionCharSetInternal::kNumeric, FormatConversionCharSetInternal::kStar, FormatConversionCharSetInternal::v)>; using FloatingConvertResult = ArgConvertResult<FormatConversionCharSetUnion( FormatConversionCharSetInternal::kFloating, FormatConversionCharSetInternal::v)>; using CharConvertResult = ArgConvertResult<FormatConversionCharSetUnion( FormatConversionCharSetInternal::c, FormatConversionCharSetInternal::kNumeric, FormatConversionCharSetInternal::kStar)>; template <typename T, typename = void> struct HasUserDefinedConvert : std::false_type {}; template <typename T> struct HasUserDefinedConvert<T, void_t<decltype(AbslFormatConvert( std::declval<const T&>(), std::declval<const FormatConversionSpec&>(), std::declval<FormatSink*>()))>> : std::true_type {}; void AbslFormatConvert(); void AbslStringify(); template <typename T> bool ConvertIntArg(T v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<char>(char v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<signed char>(signed char v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<unsigned char>(unsigned char v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<wchar_t>(wchar_t v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<short>(short v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<unsigned short>( unsigned short v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<int>(int v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<unsigned int>(unsigned int v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<long>( long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<unsigned long>(unsigned long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<long long>(long long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); extern template bool ConvertIntArg<unsigned long long>( unsigned long long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); template <typename T> auto FormatConvertImpl(const T& v, FormatConversionSpecImpl conv, FormatSinkImpl* sink) -> decltype(AbslFormatConvert(v, std::declval<const FormatConversionSpec&>(), std::declval<FormatSink*>())) { using FormatConversionSpecT = absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatConversionSpec>; using FormatSinkT = absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatSink>; auto fcs = conv.Wrap<FormatConversionSpecT>(); auto fs = sink->Wrap<FormatSinkT>(); return AbslFormatConvert(v, fcs, &fs); } template <typename T> auto FormatConvertImpl(const T& v, FormatConversionSpecImpl conv, FormatSinkImpl* sink) -> std::enable_if_t<std::is_enum<T>::value && std::is_void<decltype(AbslStringify( std::declval<FormatSink&>(), v))>::value, IntegralConvertResult> { if (conv.conversion_char() == FormatConversionCharInternal::v) { using FormatSinkT = absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatSink>; auto fs = sink->Wrap<FormatSinkT>(); AbslStringify(fs, v); return {true}; } else { return {ConvertIntArg( static_cast<typename std::underlying_type<T>::type>(v), conv, sink)}; } } template <typename T> auto FormatConvertImpl(const T& v, FormatConversionSpecImpl, FormatSinkImpl* sink) -> std::enable_if_t<!std::is_enum<T>::value && !std::is_same<T, absl::Cord>::value && std::is_void<decltype(AbslStringify( std::declval<FormatSink&>(), v))>::value, ArgConvertResult<FormatConversionCharSetInternal::v>> { using FormatSinkT = absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatSink>; auto fs = sink->Wrap<FormatSinkT>(); AbslStringify(fs, v); return {true}; } template <typename T> class StreamedWrapper; struct VoidPtr { VoidPtr() = default; template <typename T, decltype(reinterpret_cast<uintptr_t>(std::declval<T*>())) = 0> VoidPtr(T* ptr) : value(ptr ? reinterpret_cast<uintptr_t>(ptr) : 0) {} uintptr_t value; }; template <FormatConversionCharSet C> constexpr FormatConversionCharSet ExtractCharSet(FormatConvertResult<C>) { return C; } template <FormatConversionCharSet C> constexpr FormatConversionCharSet ExtractCharSet(ArgConvertResult<C>) { return C; } ArgConvertResult<FormatConversionCharSetInternal::p> FormatConvertImpl( VoidPtr v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); using StringConvertResult = ArgConvertResult<FormatConversionCharSetUnion( FormatConversionCharSetInternal::s, FormatConversionCharSetInternal::v)>; StringConvertResult FormatConvertImpl(const std::string& v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); StringConvertResult FormatConvertImpl(const std::wstring& v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); StringConvertResult FormatConvertImpl(string_view v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); #if defined(ABSL_HAVE_STD_STRING_VIEW) StringConvertResult FormatConvertImpl(std::wstring_view v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); #if !defined(ABSL_USES_STD_STRING_VIEW) inline StringConvertResult FormatConvertImpl(std::string_view v, FormatConversionSpecImpl conv, FormatSinkImpl* sink) { return FormatConvertImpl(absl::string_view(v.data(), v.size()), conv, sink); } #endif #endif using StringPtrConvertResult = ArgConvertResult<FormatConversionCharSetUnion( FormatConversionCharSetInternal::s, FormatConversionCharSetInternal::p)>; StringPtrConvertResult FormatConvertImpl(const char* v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); StringPtrConvertResult FormatConvertImpl(const wchar_t* v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); StringPtrConvertResult FormatConvertImpl(std::nullptr_t, FormatConversionSpecImpl conv, FormatSinkImpl* sink); template <class AbslCord, typename std::enable_if<std::is_same< AbslCord, absl::Cord>::value>::type* = nullptr> StringConvertResult FormatConvertImpl(const AbslCord& value, FormatConversionSpecImpl conv, FormatSinkImpl* sink) { bool is_left = conv.has_left_flag(); size_t space_remaining = 0; int width = conv.width(); if (width >= 0) space_remaining = static_cast<size_t>(width); size_t to_write = value.size(); int precision = conv.precision(); if (precision >= 0) to_write = (std::min)(to_write, static_cast<size_t>(precision)); space_remaining = Excess(to_write, space_remaining); if (space_remaining > 0 && !is_left) sink->Append(space_remaining, ' '); for (string_view piece : value.Chunks()) { if (piece.size() > to_write) { piece.remove_suffix(piece.size() - to_write); to_write = 0; } else { to_write -= piece.size(); } sink->Append(piece); if (to_write == 0) { break; } } if (space_remaining > 0 && is_left) sink->Append(space_remaining, ' '); return {true}; } bool ConvertBoolArg(bool v, FormatSinkImpl* sink); FloatingConvertResult FormatConvertImpl(float v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); FloatingConvertResult FormatConvertImpl(double v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); FloatingConvertResult FormatConvertImpl(long double v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); CharConvertResult FormatConvertImpl(char v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); CharConvertResult FormatConvertImpl(wchar_t v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(signed char v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(unsigned char v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(short v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(unsigned short v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(int v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(unsigned v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(unsigned long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(long long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(unsigned long long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(int128 v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); IntegralConvertResult FormatConvertImpl(uint128 v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); template <typename T, enable_if_t<std::is_same<T, bool>::value, int> = 0> IntegralConvertResult FormatConvertImpl(T v, FormatConversionSpecImpl conv, FormatSinkImpl* sink) { if (conv.conversion_char() == FormatConversionCharInternal::v) { return {ConvertBoolArg(v, sink)}; } return FormatConvertImpl(static_cast<int>(v), conv, sink); } template <typename T> typename std::enable_if<std::is_enum<T>::value && !HasUserDefinedConvert<T>::value && !HasAbslStringify<T>::value, IntegralConvertResult>::type FormatConvertImpl(T v, FormatConversionSpecImpl conv, FormatSinkImpl* sink); template <typename T> StringConvertResult FormatConvertImpl(const StreamedWrapper<T>& v, FormatConversionSpecImpl conv, FormatSinkImpl* out) { std::ostringstream oss; oss << v.v_; if (!oss) return {false}; return str_format_internal::FormatConvertImpl(oss.str(), conv, out); } struct FormatCountCaptureHelper { template <class T = int> static ArgConvertResult<FormatConversionCharSetInternal::n> ConvertHelper( const FormatCountCapture& v, FormatConversionSpecImpl conv, FormatSinkImpl* sink) { const absl::enable_if_t<sizeof(T) != 0, FormatCountCapture>& v2 = v; if (conv.conversion_char() != str_format_internal::FormatConversionCharInternal::n) { return {false}; } *v2.p_ = static_cast<int>(sink->size()); return {true}; } }; template <class T = int> ArgConvertResult<FormatConversionCharSetInternal::n> FormatConvertImpl( const FormatCountCapture& v, FormatConversionSpecImpl conv, FormatSinkImpl* sink) { return FormatCountCaptureHelper::ConvertHelper(v, conv, sink); } struct FormatArgImplFriend { template <typename Arg> static bool ToInt(Arg arg, int* out) { return arg.dispatcher_(arg.data_, {}, out); } template <typename Arg> static bool Convert(Arg arg, FormatConversionSpecImpl conv, FormatSinkImpl* out) { return arg.dispatcher_(arg.data_, conv, out); } template <typename Arg> static typename Arg::Dispatcher GetVTablePtrForTest(Arg arg) { return arg.dispatcher_; } }; template <typename Arg> constexpr FormatConversionCharSet ArgumentToConv() { using ConvResult = decltype(str_format_internal::FormatConvertImpl( std::declval<const Arg&>(), std::declval<const FormatConversionSpecImpl&>(), std::declval<FormatSinkImpl*>())); return absl::str_format_internal::ExtractCharSet(ConvResult{}); } class FormatArgImpl { private: enum { kInlinedSpace = 8 }; using VoidPtr = str_format_internal::VoidPtr; union Data { const void* ptr; const volatile void* volatile_ptr; char buf[kInlinedSpace]; }; using Dispatcher = bool (*)(Data, FormatConversionSpecImpl, void* out); template <typename T> struct store_by_value : std::integral_constant<bool, (sizeof(T) <= kInlinedSpace) && (std::is_integral<T>::value || std::is_floating_point<T>::value || std::is_pointer<T>::value || std::is_same<VoidPtr, T>::value)> {}; enum StoragePolicy { ByPointer, ByVolatilePointer, ByValue }; template <typename T> struct storage_policy : std::integral_constant<StoragePolicy, (std::is_volatile<T>::value ? ByVolatilePointer : (store_by_value<T>::value ? ByValue : ByPointer))> { }; template <typename T, typename = void> struct DecayType { static constexpr bool kHasUserDefined = str_format_internal::HasUserDefinedConvert<T>::value || HasAbslStringify<T>::value; using type = typename std::conditional< !kHasUserDefined && std::is_convertible<T, const char*>::value, const char*, typename std::conditional< !kHasUserDefined && std::is_convertible<T, const wchar_t*>::value, const wchar_t*, typename std::conditional< !kHasUserDefined && std::is_convertible<T, VoidPtr>::value, VoidPtr, const T&>::type>::type>::type; }; template <typename T> struct DecayType< T, typename std::enable_if< !str_format_internal::HasUserDefinedConvert<T>::value && !HasAbslStringify<T>::value && std::is_enum<T>::value>::type> { using type = decltype(+typename std::underlying_type<T>::type()); }; public: template <typename T> explicit FormatArgImpl(const T& value) { using D = typename DecayType<T>::type; static_assert( std::is_same<D, const T&>::value || storage_policy<D>::value == ByValue, "Decayed types must be stored by value"); Init(static_cast<D>(value)); } private: friend struct str_format_internal::FormatArgImplFriend; template <typename T, StoragePolicy = storage_policy<T>::value> struct Manager; template <typename T> struct Manager<T, ByPointer> { static Data SetValue(const T& value) { Data data; data.ptr = std::addressof(value); return data; } static const T& Value(Data arg) { return *static_cast<const T*>(arg.ptr); } }; template <typename T> struct Manager<T, ByVolatilePointer> { static Data SetValue(const T& value) { Data data; data.volatile_ptr = &value; return data; } static const T& Value(Data arg) { return *static_cast<const T*>(arg.volatile_ptr); } }; template <typename T> struct Manager<T, ByValue> { static Data SetValue(const T& value) { Data data; memcpy(data.buf, &value, sizeof(value)); return data; } static T Value(Data arg) { T value; memcpy(&value, arg.buf, sizeof(T)); return value; } }; template <typename T> void Init(const T& value) { data_ = Manager<T>::SetValue(value); dispatcher_ = &Dispatch<T>; } template <typename T> static int ToIntVal(const T& val) { using CommonType = typename std::conditional<std::is_signed<T>::value, int64_t, uint64_t>::type; if (static_cast<CommonType>(val) > static_cast<CommonType>((std::numeric_limits<int>::max)())) { return (std::numeric_limits<int>::max)(); } else if (std::is_signed<T>::value && static_cast<CommonType>(val) < static_cast<CommonType>((std::numeric_limits<int>::min)())) { return (std::numeric_limits<int>::min)(); } return static_cast<int>(val); } template <typename T> static bool ToInt(Data arg, int* out, std::true_type , std::false_type) { *out = ToIntVal(Manager<T>::Value(arg)); return true; } template <typename T> static bool ToInt(Data arg, int* out, std::false_type, std::true_type ) { *out = ToIntVal(static_cast<typename std::underlying_type<T>::type>( Manager<T>::Value(arg))); return true; } template <typename T> static bool ToInt(Data, int*, std::false_type, std::false_type) { return false; } template <typename T> static bool Dispatch(Data arg, FormatConversionSpecImpl spec, void* out) { if (ABSL_PREDICT_FALSE(spec.conversion_char() == FormatConversionCharInternal::kNone)) { return ToInt<T>(arg, static_cast<int*>(out), std::is_integral<T>(), std::is_enum<T>()); } if (ABSL_PREDICT_FALSE(!Contains(ArgumentToConv<T>(), spec.conversion_char()))) { return false; } return str_format_internal::FormatConvertImpl( Manager<T>::Value(arg), spec, static_cast<FormatSinkImpl*>(out)) .value; } Data data_; Dispatcher dispatcher_; }; #define ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(T, E) \ E template bool FormatArgImpl::Dispatch<T>(Data, FormatConversionSpecImpl, \ void*) #define ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_NO_WSTRING_VIEW_(...) \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(str_format_internal::VoidPtr, \ __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(bool, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(char, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(signed char, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned char, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(short, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned short, \ __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(int, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned int, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(long, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned long, \ __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(long long, \ __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned long long, \ __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(int128, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(uint128, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(float, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(double, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(long double, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(const char*, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(std::string, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(string_view, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(const wchar_t*, __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(std::wstring, __VA_ARGS__) #if defined(ABSL_HAVE_STD_STRING_VIEW) #define ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_(...) \ ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_NO_WSTRING_VIEW_( \ __VA_ARGS__); \ ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(std::wstring_view, __VA_ARGS__) #else #define ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_(...) \ ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_NO_WSTRING_VIEW_(__VA_ARGS__) #endif ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_(extern); } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/str_format/arg.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <cwchar> #include <string> #include <type_traits> #include "absl/base/config.h" #include "absl/base/optimization.h" #include "absl/container/fixed_array.h" #include "absl/numeric/int128.h" #include "absl/strings/internal/str_format/extension.h" #include "absl/strings/internal/str_format/float_conversion.h" #include "absl/strings/numbers.h" #include "absl/strings/string_view.h" #if defined(ABSL_HAVE_STD_STRING_VIEW) #include <string_view> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { namespace { void ReducePadding(string_view s, size_t *capacity) { *capacity = Excess(s.size(), *capacity); } void ReducePadding(size_t n, size_t *capacity) { *capacity = Excess(n, *capacity); } template <typename T> struct MakeUnsigned : std::make_unsigned<T> {}; template <> struct MakeUnsigned<absl::int128> { using type = absl::uint128; }; template <> struct MakeUnsigned<absl::uint128> { using type = absl::uint128; }; template <typename T> struct IsSigned : std::is_signed<T> {}; template <> struct IsSigned<absl::int128> : std::true_type {}; template <> struct IsSigned<absl::uint128> : std::false_type {}; class IntDigits { public: template <typename T> void PrintAsOct(T v) { static_assert(!IsSigned<T>::value, ""); char *p = storage_ + sizeof(storage_); do { *--p = static_cast<char>('0' + (static_cast<size_t>(v) & 7)); v >>= 3; } while (v); start_ = p; size_ = static_cast<size_t>(storage_ + sizeof(storage_) - p); } template <typename T> void PrintAsDec(T v) { static_assert(std::is_integral<T>::value, ""); start_ = storage_; size_ = static_cast<size_t>(numbers_internal::FastIntToBuffer(v, storage_) - storage_); } void PrintAsDec(int128 v) { auto u = static_cast<uint128>(v); bool add_neg = false; if (v < 0) { add_neg = true; u = uint128{} - u; } PrintAsDec(u, add_neg); } void PrintAsDec(uint128 v, bool add_neg = false) { char *p = storage_ + sizeof(storage_); do { p -= 2; numbers_internal::PutTwoDigits(static_cast<uint32_t>(v % 100), p); v /= 100; } while (v); if (p[0] == '0') { ++p; } if (add_neg) { *--p = '-'; } size_ = static_cast<size_t>(storage_ + sizeof(storage_) - p); start_ = p; } template <typename T> void PrintAsHexLower(T v) { static_assert(!IsSigned<T>::value, ""); char *p = storage_ + sizeof(storage_); do { p -= 2; constexpr const char* table = numbers_internal::kHexTable; std::memcpy(p, table + 2 * (static_cast<size_t>(v) & 0xFF), 2); if (sizeof(T) == 1) break; v >>= 8; } while (v); if (p[0] == '0') { ++p; } start_ = p; size_ = static_cast<size_t>(storage_ + sizeof(storage_) - p); } template <typename T> void PrintAsHexUpper(T v) { static_assert(!IsSigned<T>::value, ""); char *p = storage_ + sizeof(storage_); do { *--p = "0123456789ABCDEF"[static_cast<size_t>(v) & 15]; v >>= 4; } while (v); start_ = p; size_ = static_cast<size_t>(storage_ + sizeof
#include "absl/strings/internal/str_format/arg.h" #include <limits> #include <string> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/strings/str_format.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { namespace { class FormatArgImplTest : public ::testing::Test { public: enum Color { kRed, kGreen, kBlue }; static const char *hi() { return "hi"; } struct X {}; X x_; }; inline FormatConvertResult<FormatConversionCharSet{}> AbslFormatConvert( const FormatArgImplTest::X &, const FormatConversionSpec &, FormatSink *) { return {false}; } TEST_F(FormatArgImplTest, ToInt) { int out = 0; EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(1), &out)); EXPECT_EQ(1, out); EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(-1), &out)); EXPECT_EQ(-1, out); EXPECT_TRUE( FormatArgImplFriend::ToInt(FormatArgImpl(static_cast<char>(64)), &out)); EXPECT_EQ(64, out); EXPECT_TRUE(FormatArgImplFriend::ToInt( FormatArgImpl(static_cast<unsigned long long>(123456)), &out)); EXPECT_EQ(123456, out); EXPECT_TRUE(FormatArgImplFriend::ToInt( FormatArgImpl(static_cast<unsigned long long>( std::numeric_limits<int>::max()) + 1), &out)); EXPECT_EQ(std::numeric_limits<int>::max(), out); EXPECT_TRUE(FormatArgImplFriend::ToInt( FormatArgImpl(static_cast<long long>( std::numeric_limits<int>::min()) - 10), &out)); EXPECT_EQ(std::numeric_limits<int>::min(), out); EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(false), &out)); EXPECT_EQ(0, out); EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(true), &out)); EXPECT_EQ(1, out); EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(2.2), &out)); EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(3.2f), &out)); EXPECT_FALSE(FormatArgImplFriend::ToInt( FormatArgImpl(static_cast<int *>(nullptr)), &out)); EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(hi()), &out)); EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl("hi"), &out)); EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(x_), &out)); EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(kBlue), &out)); EXPECT_EQ(2, out); } extern const char kMyArray[]; TEST_F(FormatArgImplTest, CharArraysDecayToCharPtr) { const char* a = ""; EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(""))); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl("A"))); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl("ABC"))); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(kMyArray))); } extern const wchar_t kMyWCharTArray[]; TEST_F(FormatArgImplTest, WCharTArraysDecayToWCharTPtr) { const wchar_t* a = L""; EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(L""))); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(L"A"))); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(L"ABC"))); EXPECT_EQ( FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)), FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(kMyWCharTArray))); } TEST_F(FormatArgImplTest, OtherPtrDecayToVoidPtr) { auto expected = FormatArgImplFriend::GetVTablePtrForTest( FormatArgImpl(static_cast<void *>(nullptr))); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest( FormatArgImpl(static_cast<int *>(nullptr))), expected); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest( FormatArgImpl(static_cast<volatile int *>(nullptr))), expected); auto p = static_cast<void (*)()>([] {}); EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(p)), expected); } TEST_F(FormatArgImplTest, WorksWithCharArraysOfUnknownSize) { std::string s; FormatSinkImpl sink(&s); FormatConversionSpecImpl conv; FormatConversionSpecImplFriend::SetConversionChar( FormatConversionCharInternal::s, &conv); FormatConversionSpecImplFriend::SetFlags(Flags(), &conv); FormatConversionSpecImplFriend::SetWidth(-1, &conv); FormatConversionSpecImplFriend::SetPrecision(-1, &conv); EXPECT_TRUE( FormatArgImplFriend::Convert(FormatArgImpl(kMyArray), conv, &sink)); sink.Flush(); EXPECT_EQ("ABCDE", s); } const char kMyArray[] = "ABCDE"; TEST_F(FormatArgImplTest, WorksWithWCharTArraysOfUnknownSize) { std::string s; FormatSinkImpl sink(&s); FormatConversionSpecImpl conv; FormatConversionSpecImplFriend::SetConversionChar( FormatConversionCharInternal::s, &conv); FormatConversionSpecImplFriend::SetFlags(Flags(), &conv); FormatConversionSpecImplFriend::SetWidth(-1, &conv); FormatConversionSpecImplFriend::SetPrecision(-1, &conv); EXPECT_TRUE( FormatArgImplFriend::Convert(FormatArgImpl(kMyWCharTArray), conv, &sink)); sink.Flush(); EXPECT_EQ("ABCDE", s); } const wchar_t kMyWCharTArray[] = L"ABCDE"; } } ABSL_NAMESPACE_END }
2,581
#ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_OUTPUT_H_ #define ABSL_STRINGS_INTERNAL_STR_FORMAT_OUTPUT_H_ #include <cstdio> #include <ios> #include <ostream> #include <string> #include "absl/base/port.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { class BufferRawSink { public: BufferRawSink(char* buffer, size_t size) : buffer_(buffer), size_(size) {} size_t total_written() const { return total_written_; } void Write(string_view v); private: char* buffer_; size_t size_; size_t total_written_ = 0; }; class FILERawSink { public: explicit FILERawSink(std::FILE* output) : output_(output) {} void Write(string_view v); size_t count() const { return count_; } int error() const { return error_; } private: std::FILE* output_; int error_ = 0; size_t count_ = 0; }; inline void AbslFormatFlush(std::string* out, string_view s) { out->append(s.data(), s.size()); } inline void AbslFormatFlush(std::ostream* out, string_view s) { out->write(s.data(), static_cast<std::streamsize>(s.size())); } inline void AbslFormatFlush(FILERawSink* sink, string_view v) { sink->Write(v); } inline void AbslFormatFlush(BufferRawSink* sink, string_view v) { sink->Write(v); } template <typename T> auto InvokeFlush(T* out, string_view s) -> decltype(AbslFormatFlush(out, s)) { AbslFormatFlush(out, s); } } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/str_format/output.h" #include <errno.h> #include <cstring> namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { namespace { struct ClearErrnoGuard { ClearErrnoGuard() : old_value(errno) { errno = 0; } ~ClearErrnoGuard() { if (!errno) errno = old_value; } int old_value; }; } void BufferRawSink::Write(string_view v) { size_t to_write = std::min(v.size(), size_); std::memcpy(buffer_, v.data(), to_write); buffer_ += to_write; size_ -= to_write; total_written_ += v.size(); } void FILERawSink::Write(string_view v) { while (!v.empty() && !error_) { ClearErrnoGuard guard; if (size_t result = std::fwrite(v.data(), 1, v.size(), output_)) { count_ += result; v.remove_prefix(result); } else { if (errno == EINTR) { continue; } else if (errno) { error_ = errno; } else if (std::ferror(output_)) { error_ = EBADF; } else { continue; } } } } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/str_format/output.h" #include <sstream> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/cord.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { TEST(InvokeFlush, String) { std::string str = "ABC"; str_format_internal::InvokeFlush(&str, "DEF"); EXPECT_EQ(str, "ABCDEF"); } TEST(InvokeFlush, Stream) { std::stringstream str; str << "ABC"; str_format_internal::InvokeFlush(&str, "DEF"); EXPECT_EQ(str.str(), "ABCDEF"); } TEST(InvokeFlush, Cord) { absl::Cord str("ABC"); str_format_internal::InvokeFlush(&str, "DEF"); EXPECT_EQ(str, "ABCDEF"); } TEST(BufferRawSink, Limits) { char buf[16]; { std::fill(std::begin(buf), std::end(buf), 'x'); str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1); str_format_internal::InvokeFlush(&bufsink, "Hello World237"); EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World237xx"); } { std::fill(std::begin(buf), std::end(buf), 'x'); str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1); str_format_internal::InvokeFlush(&bufsink, "Hello World237237"); EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World2372x"); } { std::fill(std::begin(buf), std::end(buf), 'x'); str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1); str_format_internal::InvokeFlush(&bufsink, "Hello World"); str_format_internal::InvokeFlush(&bufsink, "237"); EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World237xx"); } { std::fill(std::begin(buf), std::end(buf), 'x'); str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1); str_format_internal::InvokeFlush(&bufsink, "Hello World"); str_format_internal::InvokeFlush(&bufsink, "237237"); EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World2372x"); } } } ABSL_NAMESPACE_END }
2,582
#ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_PARSER_H_ #define ABSL_STRINGS_INTERNAL_STR_FORMAT_PARSER_H_ #include <stddef.h> #include <stdlib.h> #include <cassert> #include <cstring> #include <initializer_list> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/config.h" #include "absl/base/optimization.h" #include "absl/strings/internal/str_format/checker.h" #include "absl/strings/internal/str_format/constexpr_parser.h" #include "absl/strings/internal/str_format/extension.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { std::string LengthModToString(LengthMod v); const char* ConsumeUnboundConversionNoInline(const char* p, const char* end, UnboundConversion* conv, int* next_arg); template <typename Consumer> bool ParseFormatString(string_view src, Consumer consumer) { int next_arg = 0; const char* p = src.data(); const char* const end = p + src.size(); while (p != end) { const char* percent = static_cast<const char*>(memchr(p, '%', static_cast<size_t>(end - p))); if (!percent) { return consumer.Append(string_view(p, static_cast<size_t>(end - p))); } if (ABSL_PREDICT_FALSE(!consumer.Append( string_view(p, static_cast<size_t>(percent - p))))) { return false; } if (ABSL_PREDICT_FALSE(percent + 1 >= end)) return false; auto tag = GetTagForChar(percent[1]); if (tag.is_conv()) { if (ABSL_PREDICT_FALSE(next_arg < 0)) { return false; } p = percent + 2; UnboundConversion conv; conv.conv = tag.as_conv(); conv.arg_position = ++next_arg; if (ABSL_PREDICT_FALSE( !consumer.ConvertOne(conv, string_view(percent + 1, 1)))) { return false; } } else if (percent[1] != '%') { UnboundConversion conv; p = ConsumeUnboundConversionNoInline(percent + 1, end, &conv, &next_arg); if (ABSL_PREDICT_FALSE(p == nullptr)) return false; if (ABSL_PREDICT_FALSE(!consumer.ConvertOne( conv, string_view(percent + 1, static_cast<size_t>(p - (percent + 1)))))) { return false; } } else { if (ABSL_PREDICT_FALSE(!consumer.Append("%"))) return false; p = percent + 2; continue; } } return true; } constexpr bool EnsureConstexpr(string_view s) { return s.empty() || s[0] == s[0]; } class ParsedFormatBase { public: explicit ParsedFormatBase( string_view format, bool allow_ignored, std::initializer_list<FormatConversionCharSet> convs); ParsedFormatBase(const ParsedFormatBase& other) { *this = other; } ParsedFormatBase(ParsedFormatBase&& other) { *this = std::move(other); } ParsedFormatBase& operator=(const ParsedFormatBase& other) { if (this == &other) return *this; has_error_ = other.has_error_; items_ = other.items_; size_t text_size = items_.empty() ? 0 : items_.back().text_end; data_.reset(new char[text_size]); memcpy(data_.get(), other.data_.get(), text_size); return *this; } ParsedFormatBase& operator=(ParsedFormatBase&& other) { if (this == &other) return *this; has_error_ = other.has_error_; data_ = std::move(other.data_); items_ = std::move(other.items_); other.items_.clear(); return *this; } template <typename Consumer> bool ProcessFormat(Consumer consumer) const { const char* const base = data_.get(); string_view text(base, 0); for (const auto& item : items_) { const char* const end = text.data() + text.size(); text = string_view(end, static_cast<size_t>((base + item.text_end) - end)); if (item.is_conversion) { if (!consumer.ConvertOne(item.conv, text)) return false; } else { if (!consumer.Append(text)) return false; } } return !has_error_; } bool has_error() const { return has_error_; } private: bool MatchesConversions( bool allow_ignored, std::initializer_list<FormatConversionCharSet> convs) const; struct ParsedFormatConsumer; struct ConversionItem { bool is_conversion; size_t text_end; UnboundConversion conv; }; bool has_error_; std::unique_ptr<char[]> data_; std::vector<ConversionItem> items_; }; template <FormatConversionCharSet... C> class ExtendedParsedFormat : public str_format_internal::ParsedFormatBase { public: explicit ExtendedParsedFormat(string_view format) #ifdef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER __attribute__(( enable_if(str_format_internal::EnsureConstexpr(format), "Format string is not constexpr."), enable_if(str_format_internal::ValidFormatImpl<C...>(format), "Format specified does not match the template arguments."))) #endif : ExtendedParsedFormat(format, false) { } static std::unique_ptr<ExtendedParsedFormat> New(string_view format) { return New(format, false); } static std::unique_ptr<ExtendedParsedFormat> NewAllowIgnored( string_view format) { return New(format, true); } private: static std::unique_ptr<ExtendedParsedFormat> New(string_view format, bool allow_ignored) { std::unique_ptr<ExtendedParsedFormat> conv( new ExtendedParsedFormat(format, allow_ignored)); if (conv->has_error()) return nullptr; return conv; } ExtendedParsedFormat(string_view s, bool allow_ignored) : ParsedFormatBase(s, allow_ignored, {C...}) {} }; } ABSL_NAMESPACE_END } #endif #include "absl/strings/internal/str_format/parser.h" #include <assert.h> #include <string.h> #include <wchar.h> #include <cctype> #include <cstdint> #include <algorithm> #include <initializer_list> #include <limits> #include <ostream> #include <string> #include <unordered_set> namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { constexpr ConvTag ConvTagHolder::value[256]; ABSL_ATTRIBUTE_NOINLINE const char* ConsumeUnboundConversionNoInline( const char* p, const char* end, UnboundConversion* conv, int* next_arg) { return ConsumeUnboundConversion(p, end, conv, next_arg); } std::string LengthModToString(LengthMod v) { switch (v) { case LengthMod::h: return "h"; case LengthMod::hh: return "hh"; case LengthMod::l: return "l"; case LengthMod::ll: return "ll"; case LengthMod::L: return "L"; case LengthMod::j: return "j"; case LengthMod::z: return "z"; case LengthMod::t: return "t"; case LengthMod::q: return "q"; case LengthMod::none: return ""; } return ""; } struct ParsedFormatBase::ParsedFormatConsumer { explicit ParsedFormatConsumer(ParsedFormatBase *parsedformat) : parsed(parsedformat), data_pos(parsedformat->data_.get()) {} bool Append(string_view s) { if (s.empty()) return true; size_t text_end = AppendText(s); if (!parsed->items_.empty() && !parsed->items_.back().is_conversion) { parsed->items_.back().text_end = text_end; } else { parsed->items_.push_back({false, text_end, {}}); } return true; } bool ConvertOne(const UnboundConversion &conv, string_view s) { size_t text_end = AppendText(s); parsed->items_.push_back({true, text_end, conv}); return true; } size_t AppendText(string_view s) { memcpy(data_pos, s.data(), s.size()); data_pos += s.size(); return static_cast<size_t>(data_pos - parsed->data_.get()); } ParsedFormatBase *parsed; char* data_pos; }; ParsedFormatBase::ParsedFormatBase( string_view format, bool allow_ignored, std::initializer_list<FormatConversionCharSet> convs) : data_(format.empty() ? nullptr : new char[format.size()]) { has_error_ = !ParseFormatString(format, ParsedFormatConsumer(this)) || !MatchesConversions(allow_ignored, convs); } bool ParsedFormatBase::MatchesConversions( bool allow_ignored, std::initializer_list<FormatConversionCharSet> convs) const { std::unordered_set<int> used; auto add_if_valid_conv = [&](int pos, char c) { if (static_cast<size_t>(pos) > convs.size() || !Contains(convs.begin()[pos - 1], c)) return false; used.insert(pos); return true; }; for (const ConversionItem &item : items_) { if (!item.is_conversion) continue; auto &conv = item.conv; if (conv.precision.is_from_arg() && !add_if_valid_conv(conv.precision.get_from_arg(), '*')) return false; if (conv.width.is_from_arg() && !add_if_valid_conv(conv.width.get_from_arg(), '*')) return false; if (!add_if_valid_conv(conv.arg_position, FormatConversionCharToChar(conv.conv))) return false; } return used.size() == convs.size() || allow_ignored; } } ABSL_NAMESPACE_END }
#include "absl/strings/internal/str_format/parser.h" #include <string.h> #include <algorithm> #include <initializer_list> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/macros.h" #include "absl/strings/internal/str_format/constexpr_parser.h" #include "absl/strings/internal/str_format/extension.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { namespace { using testing::Pair; TEST(LengthModTest, Names) { struct Expectation { int line; LengthMod mod; const char *name; }; const Expectation kExpect[] = { {__LINE__, LengthMod::none, "" }, {__LINE__, LengthMod::h, "h" }, {__LINE__, LengthMod::hh, "hh"}, {__LINE__, LengthMod::l, "l" }, {__LINE__, LengthMod::ll, "ll"}, {__LINE__, LengthMod::L, "L" }, {__LINE__, LengthMod::j, "j" }, {__LINE__, LengthMod::z, "z" }, {__LINE__, LengthMod::t, "t" }, {__LINE__, LengthMod::q, "q" }, }; EXPECT_EQ(ABSL_ARRAYSIZE(kExpect), 10); for (auto e : kExpect) { SCOPED_TRACE(e.line); EXPECT_EQ(e.name, LengthModToString(e.mod)); } } TEST(ConversionCharTest, Names) { struct Expectation { FormatConversionChar id; char name; }; const Expectation kExpect[] = { #define X(c) {FormatConversionCharInternal::c, #c[0]} X(c), X(s), X(d), X(i), X(o), X(u), X(x), X(X), X(f), X(F), X(e), X(E), X(g), X(G), X(a), X(A), X(n), X(p), #undef X {FormatConversionCharInternal::kNone, '\0'}, }; for (auto e : kExpect) { SCOPED_TRACE(e.name); FormatConversionChar v = e.id; EXPECT_EQ(e.name, FormatConversionCharToChar(v)); } } class ConsumeUnboundConversionTest : public ::testing::Test { public: std::pair<string_view, string_view> Consume(string_view src) { int next = 0; o = UnboundConversion(); const char* p = ConsumeUnboundConversion( src.data(), src.data() + src.size(), &o, &next); if (!p) return {{}, src}; return {string_view(src.data(), p - src.data()), string_view(p, src.data() + src.size() - p)}; } bool Run(const char *fmt, bool force_positional = false) { int next = force_positional ? -1 : 0; o = UnboundConversion(); return ConsumeUnboundConversion(fmt, fmt + strlen(fmt), &o, &next) == fmt + strlen(fmt); } UnboundConversion o; }; TEST_F(ConsumeUnboundConversionTest, ConsumeSpecification) { struct Expectation { int line; string_view src; string_view out; string_view src_post; }; const Expectation kExpect[] = { {__LINE__, "", "", "" }, {__LINE__, "b", "", "b" }, {__LINE__, "ba", "", "ba"}, {__LINE__, "l", "", "l" }, {__LINE__, "d", "d", "" }, {__LINE__, "v", "v", "" }, {__LINE__, "d ", "d", " " }, {__LINE__, "dd", "d", "d" }, {__LINE__, "d9", "d", "9" }, {__LINE__, "dzz", "d", "zz"}, {__LINE__, "3v", "", "3v"}, {__LINE__, "hv", "", "hv"}, {__LINE__, "1$v", "1$v", ""}, {__LINE__, "1$*2$d", "1$*2$d", "" }, {__LINE__, "0-14.3hhd", "0-14.3hhd", ""}, {__LINE__, " 0-+#14.3hhd", " 0-+#14.3hhd", ""}, }; for (const auto& e : kExpect) { SCOPED_TRACE(e.line); EXPECT_THAT(Consume(e.src), Pair(e.out, e.src_post)); } } TEST_F(ConsumeUnboundConversionTest, BasicConversion) { EXPECT_FALSE(Run("")); EXPECT_FALSE(Run("z")); EXPECT_FALSE(Run("dd")); EXPECT_TRUE(Run("d")); EXPECT_EQ('d', FormatConversionCharToChar(o.conv)); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_LT(o.precision.value(), 0); EXPECT_EQ(1, o.arg_position); } TEST_F(ConsumeUnboundConversionTest, ArgPosition) { EXPECT_TRUE(Run("d")); EXPECT_EQ(1, o.arg_position); EXPECT_TRUE(Run("3$d")); EXPECT_EQ(3, o.arg_position); EXPECT_TRUE(Run("1$d")); EXPECT_EQ(1, o.arg_position); EXPECT_TRUE(Run("1$d", true)); EXPECT_EQ(1, o.arg_position); EXPECT_TRUE(Run("123$d")); EXPECT_EQ(123, o.arg_position); EXPECT_TRUE(Run("123$d", true)); EXPECT_EQ(123, o.arg_position); EXPECT_TRUE(Run("10$d")); EXPECT_EQ(10, o.arg_position); EXPECT_TRUE(Run("10$d", true)); EXPECT_EQ(10, o.arg_position); EXPECT_FALSE(Run("0$d")); EXPECT_FALSE(Run("0$d", true)); EXPECT_FALSE(Run("1$*0$d")); EXPECT_FALSE(Run("1$.*0$d")); EXPECT_FALSE(Run("01$p")); EXPECT_FALSE(Run("01$p", true)); EXPECT_FALSE(Run("1$*01$p")); EXPECT_FALSE(Run("1$.*01$p")); } TEST_F(ConsumeUnboundConversionTest, WidthAndPrecision) { EXPECT_TRUE(Run("14d")); EXPECT_EQ('d', FormatConversionCharToChar(o.conv)); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_EQ(14, o.width.value()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_LT(o.precision.value(), 0); EXPECT_TRUE(Run("14.d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(14, o.width.value()); EXPECT_EQ(0, o.precision.value()); EXPECT_TRUE(Run(".d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(0, o.precision.value()); EXPECT_TRUE(Run(".5d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(5, o.precision.value()); EXPECT_TRUE(Run(".0d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(0, o.precision.value()); EXPECT_TRUE(Run("14.5d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(14, o.width.value()); EXPECT_EQ(5, o.precision.value()); EXPECT_TRUE(Run("*.*d")); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(1, o.width.get_from_arg()); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(2, o.precision.get_from_arg()); EXPECT_EQ(3, o.arg_position); EXPECT_TRUE(Run("*d")); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(1, o.width.get_from_arg()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_LT(o.precision.value(), 0); EXPECT_EQ(2, o.arg_position); EXPECT_TRUE(Run(".*d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_LT(o.width.value(), 0); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(1, o.precision.get_from_arg()); EXPECT_EQ(2, o.arg_position); EXPECT_FALSE(Run("*23$.*34$d")); EXPECT_TRUE(Run("12$*23$.*34$d")); EXPECT_EQ(12, o.arg_position); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(23, o.width.get_from_arg()); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(34, o.precision.get_from_arg()); EXPECT_TRUE(Run("2$*5$.*9$d")); EXPECT_EQ(2, o.arg_position); EXPECT_TRUE(o.width.is_from_arg()); EXPECT_EQ(5, o.width.get_from_arg()); EXPECT_TRUE(o.precision.is_from_arg()); EXPECT_EQ(9, o.precision.get_from_arg()); EXPECT_FALSE(Run(".*0$d")) << "no arg 0"; EXPECT_TRUE(Run("999999999.999999999d")); EXPECT_FALSE(o.width.is_from_arg()); EXPECT_EQ(999999999, o.width.value()); EXPECT_FALSE(o.precision.is_from_arg()); EXPECT_EQ(999999999, o.precision.value()); EXPECT_FALSE(Run("1000000000.999999999d")); EXPECT_FALSE(Run("999999999.1000000000d")); EXPECT_FALSE(Run("9999999999d")); EXPECT_FALSE(Run(".9999999999d")); } TEST_F(ConsumeUnboundConversionTest, Flags) { static const char kAllFlags[] = "-+ #0"; static const int kNumFlags = ABSL_ARRAYSIZE(kAllFlags) - 1; for (int rev = 0; rev < 2; ++rev) { for (int i = 0; i < 1 << kNumFlags; ++i) { std::string fmt; for (int k = 0; k < kNumFlags; ++k) if ((i >> k) & 1) fmt += kAllFlags[k]; if (rev == 1) { std::reverse(fmt.begin(), fmt.end()); } fmt += 'd'; SCOPED_TRACE(fmt); EXPECT_TRUE(Run(fmt.c_str())); EXPECT_EQ(fmt.find('-') == std::string::npos, !FlagsContains(o.flags, Flags::kLeft)); EXPECT_EQ(fmt.find('+') == std::string::npos, !FlagsContains(o.flags, Flags::kShowPos)); EXPECT_EQ(fmt.find(' ') == std::string::npos, !FlagsContains(o.flags, Flags::kSignCol)); EXPECT_EQ(fmt.find('#') == std::string::npos, !FlagsContains(o.flags, Flags::kAlt)); EXPECT_EQ(fmt.find('0') == std::string::npos, !FlagsContains(o.flags, Flags::kZero)); } } } TEST_F(ConsumeUnboundConversionTest, BasicFlag) { for (const char* fmt : {"d", "llx", "G", "1$X"}) { SCOPED_TRACE(fmt); EXPECT_TRUE(Run(fmt)); EXPECT_EQ(o.flags, Flags::kBasic); } for (const char* fmt : {"3d", ".llx", "-G", "1$#X", "lc"}) { SCOPED_TRACE(fmt); EXPECT_TRUE(Run(fmt)); EXPECT_NE(o.flags, Flags::kBasic); } } TEST_F(ConsumeUnboundConversionTest, LengthMod) { EXPECT_TRUE(Run("d")); EXPECT_EQ(LengthMod::none, o.length_mod); EXPECT_TRUE(Run("hd")); EXPECT_EQ(LengthMod::h, o.length_mod); EXPECT_TRUE(Run("hhd")); EXPECT_EQ(LengthMod::hh, o.length_mod); EXPECT_TRUE(Run("ld")); EXPECT_EQ(LengthMod::l, o.length_mod); EXPECT_TRUE(Run("lld")); EXPECT_EQ(LengthMod::ll, o.length_mod); EXPECT_TRUE(Run("Lf")); EXPECT_EQ(LengthMod::L, o.length_mod); EXPECT_TRUE(Run("qf")); EXPECT_EQ(LengthMod::q, o.length_mod); EXPECT_TRUE(Run("jd")); EXPECT_EQ(LengthMod::j, o.length_mod); EXPECT_TRUE(Run("zd")); EXPECT_EQ(LengthMod::z, o.length_mod); EXPECT_TRUE(Run("td")); EXPECT_EQ(LengthMod::t, o.length_mod); } 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 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 += FormatConversionCharToChar(conv.conv); *out += "}"; return true; } }; std::string SummarizeParsedFormat(const ParsedFormatBase& pc) { std::string out; if (!pc.ProcessFormat(SummarizeConsumer(&out))) out += "!"; return out; } class ParsedFormatTest : public testing::Test {}; TEST_F(ParsedFormatTest, ValueSemantics) { ParsedFormatBase p1({}, true, {}); EXPECT_EQ("", SummarizeParsedFormat(p1)); ParsedFormatBase p2 = p1; EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p2)); p1 = ParsedFormatBase("hello%s", true, {FormatConversionCharSetInternal::s}); EXPECT_EQ("[hello]{s:1$s}", SummarizeParsedFormat(p1)); ParsedFormatBase p3 = p1; EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p3)); using std::swap; swap(p1, p2); EXPECT_EQ("", SummarizeParsedFormat(p1)); EXPECT_EQ("[hello]{s:1$s}", SummarizeParsedFormat(p2)); swap(p1, p2); p2 = p1; EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p2)); } struct ExpectParse { const char* in; std::initializer_list<FormatConversionCharSet> conv_set; const char* out; }; TEST_F(ParsedFormatTest, Parsing) { const ExpectParse kExpect[] = { {"", {}, ""}, {"ab", {}, "[ab]"}, {"a%d", {FormatConversionCharSetInternal::d}, "[a]{d:1$d}"}, {"a%+d", {FormatConversionCharSetInternal::d}, "[a]{+d:1$d}"}, {"a% d", {FormatConversionCharSetInternal::d}, "[a]{ d:1$d}"}, {"a%b %d", {}, "[a]!"}, }; for (const auto& e : kExpect) { SCOPED_TRACE(e.in); EXPECT_EQ(e.out, SummarizeParsedFormat(ParsedFormatBase(e.in, false, e.conv_set))); } } TEST_F(ParsedFormatTest, ParsingFlagOrder) { const ExpectParse kExpect[] = { {"a%+ 0d", {FormatConversionCharSetInternal::d}, "[a]{+ 0d:1$d}"}, {"a%+0 d", {FormatConversionCharSetInternal::d}, "[a]{+0 d:1$d}"}, {"a%0+ d", {FormatConversionCharSetInternal::d}, "[a]{0+ d:1$d}"}, {"a% +0d", {FormatConversionCharSetInternal::d}, "[a]{ +0d:1$d}"}, {"a%0 +d", {FormatConversionCharSetInternal::d}, "[a]{0 +d:1$d}"}, {"a% 0+d", {FormatConversionCharSetInternal::d}, "[a]{ 0+d:1$d}"}, {"a%+ 0+d", {FormatConversionCharSetInternal::d}, "[a]{+ 0+d:1$d}"}, }; for (const auto& e : kExpect) { SCOPED_TRACE(e.in); EXPECT_EQ(e.out, SummarizeParsedFormat(ParsedFormatBase(e.in, false, e.conv_set))); } } } } ABSL_NAMESPACE_END }
2,583
#ifndef ABSL_NUMERIC_INT128_H_ #define ABSL_NUMERIC_INT128_H_ #include <cassert> #include <cmath> #include <cstdint> #include <cstring> #include <iosfwd> #include <limits> #include <string> #include <utility> #include "absl/base/config.h" #include "absl/base/macros.h" #include "absl/base/port.h" #include "absl/types/compare.h" #if defined(_MSC_VER) #define ABSL_INTERNAL_WCHAR_T __wchar_t #if defined(_M_X64) && !defined(_M_ARM64EC) #include <intrin.h> #pragma intrinsic(_umul128) #endif #else #define ABSL_INTERNAL_WCHAR_T wchar_t #endif namespace absl { ABSL_NAMESPACE_BEGIN class int128; class #if defined(ABSL_HAVE_INTRINSIC_INT128) alignas(unsigned __int128) #endif uint128 { public: uint128() = default; constexpr uint128(int v); constexpr uint128(unsigned int v); constexpr uint128(long v); constexpr uint128(unsigned long v); constexpr uint128(long long v); constexpr uint128(unsigned long long v); #ifdef ABSL_HAVE_INTRINSIC_INT128 constexpr uint128(__int128 v); constexpr uint128(unsigned __int128 v); #endif constexpr uint128(int128 v); explicit uint128(float v); explicit uint128(double v); explicit uint128(long double v); uint128& operator=(int v); uint128& operator=(unsigned int v); uint128& operator=(long v); uint128& operator=(unsigned long v); uint128& operator=(long long v); uint128& operator=(unsigned long long v); #ifdef ABSL_HAVE_INTRINSIC_INT128 uint128& operator=(__int128 v); uint128& operator=(unsigned __int128 v); #endif uint128& operator=(int128 v); constexpr explicit operator bool() const; constexpr explicit operator char() const; constexpr explicit operator signed char() const; constexpr explicit operator unsigned char() const; constexpr explicit operator char16_t() const; constexpr explicit operator char32_t() const; constexpr explicit operator ABSL_INTERNAL_WCHAR_T() const; constexpr explicit operator short() const; constexpr explicit operator unsigned short() const; constexpr explicit operator int() const; constexpr explicit operator unsigned int() const; constexpr explicit operator long() const; constexpr explicit operator unsigned long() const; constexpr explicit operator long long() const; constexpr explicit operator unsigned long long() const; #ifdef ABSL_HAVE_INTRINSIC_INT128 constexpr explicit operator __int128() const; constexpr explicit operator unsigned __int128() const; #endif explicit operator float() const; explicit operator double() const; explicit operator long double() const; uint128& operator+=(uint128 other); uint128& operator-=(uint128 other); uint128& operator*=(uint128 other); uint128& operator/=(uint128 other); uint128& operator%=(uint128 other); uint128 operator++(int); uint128 operator--(int); uint128& operator<<=(int); uint128& operator>>=(int); uint128& operator&=(uint128 other); uint128& operator|=(uint128 other); uint128& operator^=(uint128 other); uint128& operator++(); uint128& operator--(); friend constexpr uint64_t Uint128Low64(uint128 v); friend constexpr uint64_t Uint128High64(uint128 v); friend constexpr uint128 MakeUint128(uint64_t high, uint64_t low); friend constexpr uint128 Uint128Max(); template <typename H> friend H AbslHashValue(H h, uint128 v) { return H::combine(std::move(h), Uint128High64(v), Uint128Low64(v)); } template <typename Sink> friend void AbslStringify(Sink& sink, uint128 v) { sink.Append(v.ToString()); } private: constexpr uint128(uint64_t high, uint64_t low); std::string ToString() const; #if defined(ABSL_IS_LITTLE_ENDIAN) uint64_t lo_; uint64_t hi_; #elif defined(ABSL_IS_BIG_ENDIAN) uint64_t hi_; uint64_t lo_; #else #error "Unsupported byte order: must be little-endian or big-endian." #endif }; std::ostream& operator<<(std::ostream& os, uint128 v); constexpr uint128 Uint128Max() { return uint128((std::numeric_limits<uint64_t>::max)(), (std::numeric_limits<uint64_t>::max)()); } ABSL_NAMESPACE_END } namespace std { template <> class numeric_limits<absl::uint128> { public: static constexpr bool is_specialized = true; static constexpr bool is_signed = false; static constexpr bool is_integer = true; static constexpr bool is_exact = true; static constexpr bool has_infinity = false; static constexpr bool has_quiet_NaN = false; static constexpr bool has_signaling_NaN = false; ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING static constexpr float_denorm_style has_denorm = denorm_absent; ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING static constexpr bool has_denorm_loss = false; static constexpr float_round_style round_style = round_toward_zero; static constexpr bool is_iec559 = false; static constexpr bool is_bounded = true; static constexpr bool is_modulo = true; static constexpr int digits = 128; static constexpr int digits10 = 38; static constexpr int max_digits10 = 0; static constexpr int radix = 2; static constexpr int min_exponent = 0; static constexpr int min_exponent10 = 0; static constexpr int max_exponent = 0; static constexpr int max_exponent10 = 0; #ifdef ABSL_HAVE_INTRINSIC_INT128 static constexpr bool traps = numeric_limits<unsigned __int128>::traps; #else static constexpr bool traps = numeric_limits<uint64_t>::traps; #endif static constexpr bool tinyness_before = false; static constexpr absl::uint128(min)() { return 0; } static constexpr absl::uint128 lowest() { return 0; } static constexpr absl::uint128(max)() { return absl::Uint128Max(); } static constexpr absl::uint128 epsilon() { return 0; } static constexpr absl::uint128 round_error() { return 0; } static constexpr absl::uint128 infinity() { return 0; } static constexpr absl::uint128 quiet_NaN() { return 0; } static constexpr absl::uint128 signaling_NaN() { return 0; } static constexpr absl::uint128 denorm_min() { return 0; } }; } namespace absl { ABSL_NAMESPACE_BEGIN class int128 { public: int128() = default; constexpr int128(int v); constexpr int128(unsigned int v); constexpr int128(long v); constexpr int128(unsigned long v); constexpr int128(long long v); constexpr int128(unsigned long long v); #ifdef ABSL_HAVE_INTRINSIC_INT128 constexpr int128(__int128 v); constexpr explicit int128(unsigned __int128 v); #endif constexpr explicit int128(uint128 v); explicit int128(float v); explicit int128(double v); explicit int128(long double v); int128& operator=(int v); int128& operator=(unsigned int v); int128& operator=(long v); int128& operator=(unsigned long v); int128& operator=(long long v); int128& operator=(unsigned long long v); #ifdef ABSL_HAVE_INTRINSIC_INT128 int128& operator=(__int128 v); #endif constexpr explicit operator bool() const; constexpr explicit operator char() const; constexpr explicit operator signed char() const; constexpr explicit operator unsigned char() const; constexpr explicit operator char16_t() const; constexpr explicit operator char32_t() const; constexpr explicit operator ABSL_INTERNAL_WCHAR_T() const; constexpr explicit operator short() const; constexpr explicit operator unsigned short() const; constexpr explicit operator int() const; constexpr explicit operator unsigned int() const; constexpr explicit operator long() const; constexpr explicit operator unsigned long() const; constexpr explicit operator long long() const; constexpr explicit operator unsigned long long() const; #ifdef ABSL_HAVE_INTRINSIC_INT128 constexpr explicit operator __int128() const; constexpr explicit operator unsigned __int128() const; #endif explicit operator float() const; explicit operator double() const; explicit operator long double() const; int128& operator+=(int128 other); int128& operator-=(int128 other); int128& operator*=(int128 other); int128& operator/=(int128 other); int128& operator%=(int128 other); int128 operator++(int); int128 operator--(int); int128& operator++(); int128& operator--(); int128& operator&=(int128 other); int128& operator|=(int128 other); int128& operator^=(int128 other); int128& operator<<=(int amount); int128& operator>>=(int amount); friend constexpr uint64_t Int128Low64(int128 v); friend constexpr int64_t Int128High64(int128 v); friend constexpr int128 MakeInt128(int64_t high, uint64_t low); friend constexpr int128 Int128Max(); friend constexpr int128 Int128Min(); template <typename H> friend H AbslHashValue(H h, int128 v) { return H::combine(std::move(h), Int128High64(v), Int128Low64(v)); } template <typename Sink> friend void AbslStringify(Sink& sink, int128 v) { sink.Append(v.ToString()); } private: constexpr int128(int64_t high, uint64_t low); std::string ToString() const; #if defined(ABSL_HAVE_INTRINSIC_INT128) __int128 v_; #else #if defined(ABSL_IS_LITTLE_ENDIAN) uint64_t lo_; int64_t hi_; #elif defined(ABSL_IS_BIG_ENDIAN) int64_t hi_; uint64_t lo_; #else #error "Unsupported byte order: must be little-endian or big-endian." #endif #endif }; std::ostream& operator<<(std::ostream& os, int128 v); constexpr int128 Int128Max() { return int128((std::numeric_limits<int64_t>::max)(), (std::numeric_limits<uint64_t>::max)()); } constexpr int128 Int128Min() { return int128((std::numeric_limits<int64_t>::min)(), 0); } ABSL_NAMESPACE_END } namespace std { template <> class numeric_limits<absl::int128> { public: static constexpr bool is_specialized = true; static constexpr bool is_signed = true; static constexpr bool is_integer = true; static constexpr bool is_exact = true; static constexpr bool has_infinity = false; static constexpr bool has_quiet_NaN = false; static constexpr bool has_signaling_NaN = false; ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING static constexpr float_denorm_style has_denorm = denorm_absent; ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING static constexpr bool has_denorm_loss = false; static constexpr float_round_style round_style = round_toward_zero; static constexpr bool is_iec559 = false; static constexpr bool is_bounded = true; static constexpr bool is_modulo = false; static constexpr int digits = 127; static constexpr int digits10 = 38; static constexpr int max_digits10 = 0; static constexpr int radix = 2; static constexpr int min_exponent = 0; static constexpr int min_exponent10 = 0; static constexpr int max_exponent = 0; static constexpr int max_exponent10 = 0; #ifdef ABSL_HAVE_INTRINSIC_INT128 static constexpr bool traps = numeric_limits<__int128>::traps; #else static constexpr bool traps = numeric_limits<uint64_t>::traps; #endif static constexpr bool tinyness_before = false; static constexpr absl::int128(min)() { return absl::Int128Min(); } static constexpr absl::int128 lowest() { return absl::Int128Min(); } static constexpr absl::int128(max)() { return absl::Int128Max(); } static constexpr absl::int128 epsilon() { return 0; } static constexpr absl::int128 round_error() { return 0; } static constexpr absl::int128 infinity() { return 0; } static constexpr absl::int128 quiet_NaN() { return 0; } static constexpr absl::int128 signaling_NaN() { return 0; } static constexpr absl::int128 denorm_min() { return 0; } }; } namespace absl { ABSL_NAMESPACE_BEGIN constexpr uint128 MakeUint128(uint64_t high, uint64_t low) { return uint128(high, low); } inline uint128& uint128::operator=(int v) { return *this = uint128(v); } inline uint128& uint128::operator=(unsigned int v) { return *this = uint128(v); } inline uint128& uint128::operator=(long v) { return *this = uint128(v); } inline uint128& uint128::operator=(unsigned long v) { return *this = uint128(v); } inline uint128& uint128::operator=(long long v) { return *this = uint128(v); } inline uint128& uint128::operator=(unsigned long long v) { return *this = uint128(v); } #ifdef ABSL_HAVE_INTRINSIC_INT128 inline uint128& uint128::operator=(__int128 v) { return *this = uint128(v); } inline uint128& uint128::operator=(unsigned __int128 v) { return *this = uint128(v); } #endif inline uint128& uint128::operator=(int128 v) { return *this = uint128(v); } constexpr uint128 operator<<(uint128 lhs, int amount); constexpr uint128 operator>>(uint128 lhs, int amount); constexpr uint128 operator+(uint128 lhs, uint128 rhs); constexpr uint128 operator-(uint128 lhs, uint128 rhs); uint128 operator*(uint128 lhs, uint128 rhs); uint128 operator/(uint128 lhs, uint128 rhs); uint128 operator%(uint128 lhs, uint128 rhs); inline uint128& uint128::operator<<=(int amount) { *this = *this << amount; return *this; } inline uint128& uint128::operator>>=(int amount) { *this = *this >> amount; return *this; } inline uint128& uint128::operator+=(uint128 other) { *this = *this + other; return *this; } inline uint128& uint128::operator-=(uint128 other) { *this = *this - other; return *this; } inline uint128& uint128::operator*=(uint128 other) { *this = *this * other; return *this; } inline uint128& uint128::operator/=(uint128 other) { *this = *this / other; return *this; } inline uint128& uint128::operator%=(uint128 other) { *this = *this % other; return *this; } constexpr uint64_t Uint128Low64(uint128 v) { return v.lo_; } constexpr uint64_t Uint128High64(uint128 v) { return v.hi_; } #if defined(ABSL_IS_LITTLE_ENDIAN) constexpr uint128::uint128(uint64_t high, uint64_t low) : lo_{low}, hi_{high} {} constexpr uint128::uint128(int v) : lo_{static_cast<uint64_t>(v)}, hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0} {} constexpr uint128::uint128(long v) : lo_{static_cast<uint64_t>(v)}, hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0} {} constexpr uint128::uint128(long long v) : lo_{static_cast<uint64_t>(v)}, hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0} {} constexpr uint128::uint128(unsigned int v) : lo_{v}, hi_{0} {} constexpr uint128::uint128(unsigned long v) : lo_{v}, hi_{0} {} constexpr uint128::uint128(unsigned long long v) : lo_{v}, hi_{0} {} #ifdef ABSL_HAVE_INTRINSIC_INT128 constexpr uint128::uint128(__int128 v) : lo_{static_cast<uint64_t>(v & ~uint64_t{0})}, hi_{static_cast<uint64_t>(static_cast<unsigned __int128>(v) >> 64)} {} constexpr uint128::uint128(unsigned __int128 v) : lo_{static_cast<uint64_t>(v & ~uint64_t{0})}, hi_{static_cast<uint64_t>(v >> 64)} {} #endif constexpr uint128::uint128(int128 v) : lo_{Int128Low64(v)}, hi_{static_cast<uint64_t>(Int128High64(v))} {} #elif defined(ABSL_IS_BIG_ENDIAN) constexpr uint128::uint128(uint64_t high, uint64_t low) : hi_{high}, lo_{low} {} constexpr uint128::uint128(int v) : hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0}, lo_{static_cast<uint64_t>(v)} {} constexpr uint128::uint128(long v) : hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0}, lo_{static_cast<uint64_t>(v)} {} constexpr uint128::uint128(long long v) : hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0}, lo_{static_cast<uint64_t>(v)} {} constexpr uint128::uint128(unsigned int v) : hi_{0}, lo_{v} {} constexpr uint128::uint128(unsigned long v) : hi_{0}, lo_{v} {} constexpr uint128::uint128(unsigned long long v) : hi_{0}, lo_{v} {} #ifdef ABSL_HAVE_INTRINSIC_INT128 constexpr uint128::uint128(__int128 v) : hi_{static_cast<uint64_t>(static_cast<unsigned __int128>(v) >> 64)}, lo_{static_cast<uint64_t>(v & ~uint64_t{0})} {} constexpr uint128::uint128(unsigned __int128 v) : hi_{static_cast<uint64_t>(v >> 64)}, lo_{static_cast<uint64_t>(v & ~uint64_t{0})} {} #endif constexpr uint128::uint128(int128 v) : hi_{static_cast<uint64_t>(Int128High64(v))}, lo_{Int128Low64(v)} {} #else #error "Unsupported byte order: must be little-endian or big-endian." #endif constexpr uint128::operator bool() const { return lo_ || hi_; } constexpr uint128::operator char() const { return static_cast<char>(lo_); } constexpr uint128::operator signed char() const { return static_cast<signed char>(lo_); } constexpr uint128::operator unsigned char() const { return static_cast<unsigned char>(lo_); } constexpr uint128::operator char16_t() const { return static_cast<char16_t>(lo_); } constexpr uint128::operator char32_t() const { return static_cast<char32_t>(lo_); } constexpr uint128::operator ABSL_INTERNAL_WCHAR_T() const { return static_cast<ABSL_INTERNAL_WCHAR_T>(lo_); } constexpr uint128::operator short() const { return static_cast<short>(lo_); } constexpr uint128::operator unsigned short() const { return static_cast<unsigned short>(lo_); } constexpr uint128::operator int() const { return static_cast<int>(lo_); } constexpr uint128::operator unsigned int() const { return static_cast<unsigned int>(lo_); } constexpr uint128::operator long() const { return static_cast<long>(lo_); } constexpr uint128::operator unsigned long() const { return static_cast<unsigned long>(lo_); } constexpr uint128::operator long long() const { return static_cast<long long>(lo_); } constexpr uint128::operator unsigned long long() const { return static_cast<unsigned long long>(lo_); } #ifdef ABSL_HAVE_INTRINSIC_INT128 constexpr uint128::operator __int128() const { return (static_cast<__int128>(hi_) << 64) + lo_; } constexpr uint128::operator unsigned __int128() const { return (static_cast<unsigned __int128>(hi_) << 64) + lo_; } #endif inline uint128::operator float() const { return static_cast<float>(lo_) + std::ldexp(static_cast<float>(hi_), 64); } inline uint128::operator double() const { return static_cast<double>(lo_) + std::ldexp(static_cast<double>(hi_), 64); } inline uint128::operator long double() const { return static_cast<long double>(lo_) + std::ldexp(static_cast<long double>(hi_), 64); } constexpr bool operator==(uint128 lhs, uint128 rhs) { #if defined(ABSL_HAVE_INTRINSIC_INT128) return static_cast<unsigned __int128>(lhs) == static_cast<unsigned __int128>(rhs); #else return (Uint128Low64(lhs) == Uint128Low64(rhs) && Uint128High64(lhs) == Uint128High64(rhs)); #endif } constexpr bool operator!=(uint128 lhs, uint128 rhs) { return !(lhs == rhs); } constexpr bool operator<(uint128 lhs, uint128 rhs) { #ifdef ABSL_HAVE_INTRINSIC_INT128 return static_cast<unsigned __int128>(lhs) < static_cast<unsigned __int128>(rhs); #else return (Uint128High64(lhs) == Uint128High64(rhs)) ? (Uint128Low64(lhs) < Uint128Low64(rhs)) : (Uint128High64(lhs) < Uint128High64(rhs)); #endif } constexpr bool operator>(uint128 lhs, uint128 rhs) { return rhs < lhs; } constexpr bool operator<=(uint128 lhs, uint128 rhs) { return !(rhs < lhs); } constexpr bool operator>=(uint128 lhs, uint128 rhs) { return !(lhs < rhs); } #ifdef __cpp_impl_three_way_comparison constexpr absl::strong_ordering operator<=>(uint128 lhs, uint128 rhs) { #if defined(ABSL_HAVE_INTRINSIC_INT128) if (auto lhs_128 = static_cast<unsigned __int128>(lhs), rhs_128 = static_cast<unsigned __int128>(rhs); lhs_128 < rhs_128) { return absl::strong_ordering::less; } else if (lhs_128 > rhs_128) { return absl::strong_ordering::greater; } else { return absl::strong_ordering::equal; } #else if (uint64_t lhs_high = Uint128High64(lhs), rhs_high = Uint128High64(rhs); lhs_high < rhs_high) { return absl::strong_ordering::less; } else if (lhs_high > rhs_high) { return absl::strong_ordering::greater; } else if (uint64_t lhs_low = Uint128Low64(lhs), rhs_low = Uint128Low64(rhs); lhs_low < rhs_low) { return absl::strong_ordering::less; } else if (lhs_low > rhs_low) { return absl::strong_ordering::greater; } else { return absl::strong_ordering::equal; } #endif } #endif constexpr inline uint128 operator+(uint128 val) { return val; } constexpr inline int128 operator+(int128 val) { return val; } constexpr uint128 operator-(uint128 val) { #if defined(ABSL_HAVE_INTRINSIC_INT128) return -static_cast<unsigned __int128>(val); #else return MakeUint128( ~Uint128High64(val) + static_cast<unsigned long>(Uint128Low64(val) == 0), ~Uint128Low64(val) + 1); #endif } constexpr inline bool operator!(uint128 val) { #if defined(ABSL_HAVE_INTRINSIC_INT128) return !static_cast<unsigned __int128>(val); #else return !Uint128High64(val) && !Uint128Low64(val); #endif } constexpr inline uint128 operator~(uint128 val) { #if defined(ABSL_HAVE_INTRINSIC_INT128) return ~static_cast<unsigned __int128>(val); #else return MakeUint128(~Uint128High64(val), ~Uint128Low64(val)); #endif } constexpr inline uint128 operator|(uint128 lhs, uint128 rhs) { #if defined(ABSL_HAVE_INTRINSIC_INT128) return static_cast<unsigned __int128>(lhs) | static_cast<unsigned __int128>(rhs); #else return MakeUint128(Uint128High64(lhs) | Uint128High64(rhs), Uint128Low64(lhs) | Uint128Low64(rhs)); #endif } constexpr inline uint128 operator&(uint128 lhs, uint128 rhs) { #if defined(ABSL_HAVE_INTRINSIC_INT128) return static_cast<unsigned __int128>(lhs) & static_cast<unsigned __int128>(rhs); #else return MakeUint128(Uint128High64(lhs) & Uint128High64(rhs), Uint128Low64(lhs) & Uint128Low64(rhs)); #endif } constexpr inline uint128 operator^(uint128 lhs, uint128 rhs) { #if defined(ABSL_HAVE_INTRINSIC_INT128) return static_cast<unsigned __int128>(lhs) ^ static_cast<unsigned __int128>(rhs); #else return MakeUint128(Uint128High64(lhs) ^ Uint128High64(rhs), Uint128Low64(lhs) ^ Uint128Low64(rhs)); #endif } inline uint128& uint128::operator|=(uint128 other) { *this = *this | other; return *this; } inline uint128& uint128::operator&=(uint128 other) { *this = *this & other; return *this; } inline uint128& uint128::operator^=(uint128 other) { *this = *this ^ other; return *this; } constexpr uint128 operator<<(uint128 lhs, int amount) { #ifdef ABSL_HAVE_INTRINSIC_INT128 return static_cast<unsigned __int128>(lhs) << amount; #else return amount >= 64 ? MakeUint128(Uint128Low64(lhs) << (amount - 64), 0) : amount == 0 ? lhs : MakeUint128((Uint128High64(lhs) << amount) | (Uint128Low64(lhs) >> (64 - amount)), Uint128Low64(lhs) << amount); #endif } constexpr uint128 operator>>(uint128 lhs, int amount) { #ifdef ABSL_HAVE_INTRINSIC_INT128 return
#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
2,584
#ifndef ABSL_SYNCHRONIZATION_BLOCKING_COUNTER_H_ #define ABSL_SYNCHRONIZATION_BLOCKING_COUNTER_H_ #include <atomic> #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN class BlockingCounter { public: explicit BlockingCounter(int initial_count); BlockingCounter(const BlockingCounter&) = delete; BlockingCounter& operator=(const BlockingCounter&) = delete; bool DecrementCount(); void Wait(); private: Mutex lock_; std::atomic<int> count_; int num_waiting_ ABSL_GUARDED_BY(lock_); bool done_ ABSL_GUARDED_BY(lock_); }; ABSL_NAMESPACE_END } #endif #include "absl/synchronization/blocking_counter.h" #include <atomic> #include "absl/base/internal/raw_logging.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { bool IsDone(void *arg) { return *reinterpret_cast<bool *>(arg); } } BlockingCounter::BlockingCounter(int initial_count) : count_(initial_count), num_waiting_(0), done_{initial_count == 0 ? true : false} { ABSL_RAW_CHECK(initial_count >= 0, "BlockingCounter initial_count negative"); } bool BlockingCounter::DecrementCount() { int count = count_.fetch_sub(1, std::memory_order_acq_rel) - 1; ABSL_RAW_CHECK(count >= 0, "BlockingCounter::DecrementCount() called too many times"); if (count == 0) { MutexLock l(&lock_); done_ = true; return true; } return false; } void BlockingCounter::Wait() { MutexLock l(&this->lock_); ABSL_RAW_CHECK(num_waiting_ == 0, "multiple threads called Wait()"); num_waiting_++; this->lock_.Await(Condition(IsDone, &this->done_)); } ABSL_NAMESPACE_END }
#include "absl/synchronization/blocking_counter.h" #include <thread> #include <vector> #include "gtest/gtest.h" #include "absl/time/clock.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { void PauseAndDecreaseCounter(BlockingCounter* counter, int* done) { absl::SleepFor(absl::Seconds(1)); *done = 1; counter->DecrementCount(); } TEST(BlockingCounterTest, BasicFunctionality) { const int num_workers = 10; BlockingCounter counter(num_workers); std::vector<std::thread> workers; std::vector<int> done(num_workers, 0); workers.reserve(num_workers); for (int k = 0; k < num_workers; k++) { workers.emplace_back( [&counter, &done, k] { PauseAndDecreaseCounter(&counter, &done[k]); }); } counter.Wait(); for (int k = 0; k < num_workers; k++) { EXPECT_EQ(1, done[k]); } for (std::thread& w : workers) { w.join(); } } TEST(BlockingCounterTest, WaitZeroInitialCount) { BlockingCounter counter(0); counter.Wait(); } #if GTEST_HAS_DEATH_TEST TEST(BlockingCounterTest, WaitNegativeInitialCount) { EXPECT_DEATH(BlockingCounter counter(-1), "BlockingCounter initial_count negative"); } #endif } ABSL_NAMESPACE_END }
2,585
#ifndef ABSL_SYNCHRONIZATION_BARRIER_H_ #define ABSL_SYNCHRONIZATION_BARRIER_H_ #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN class Barrier { public: explicit Barrier(int num_threads) : num_to_block_(num_threads), num_to_exit_(num_threads) {} Barrier(const Barrier&) = delete; Barrier& operator=(const Barrier&) = delete; bool Block(); private: Mutex lock_; int num_to_block_ ABSL_GUARDED_BY(lock_); int num_to_exit_ ABSL_GUARDED_BY(lock_); }; ABSL_NAMESPACE_END } #endif #include "absl/synchronization/barrier.h" #include "absl/base/internal/raw_logging.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN static bool IsZero(void *arg) { return 0 == *reinterpret_cast<int *>(arg); } bool Barrier::Block() { MutexLock l(&this->lock_); this->num_to_block_--; if (this->num_to_block_ < 0) { ABSL_RAW_LOG( FATAL, "Block() called too many times. num_to_block_=%d out of total=%d", this->num_to_block_, this->num_to_exit_); } this->lock_.Await(Condition(IsZero, &this->num_to_block_)); this->num_to_exit_--; ABSL_RAW_CHECK(this->num_to_exit_ >= 0, "barrier underflow"); return this->num_to_exit_ == 0; } ABSL_NAMESPACE_END }
#include "absl/synchronization/barrier.h" #include <thread> #include <vector> #include "gtest/gtest.h" #include "absl/synchronization/mutex.h" #include "absl/time/clock.h" TEST(Barrier, SanityTest) { constexpr int kNumThreads = 10; absl::Barrier* barrier = new absl::Barrier(kNumThreads); absl::Mutex mutex; int counter = 0; auto thread_func = [&] { if (barrier->Block()) { delete barrier; } absl::MutexLock lock(&mutex); ++counter; }; std::vector<std::thread> threads; for (int i = 0; i < kNumThreads - 1; ++i) { threads.push_back(std::thread(thread_func)); } absl::SleepFor(absl::Seconds(1)); { absl::MutexLock lock(&mutex); EXPECT_EQ(counter, 0); } threads.push_back(std::thread(thread_func)); for (auto& thread : threads) { thread.join(); } absl::MutexLock lock(&mutex); EXPECT_EQ(counter, kNumThreads); }
2,586