ID
stringlengths
36
36
Language
stringclasses
1 value
Repository Name
stringclasses
13 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
13
116
Code
stringlengths
0
278k
Unit Test - (Ground Truth)
stringlengths
78
663k
Code Url
stringlengths
91
198
Test Code Url
stringlengths
93
203
Commit Hash
stringclasses
13 values
6869083b-75c0-4e08-a074-4c5908c73712
cpp
google/googletest
sample2
googletest/samples/sample2.cc
googletest/samples/sample2_unittest.cc
#include "sample2.h" #include <string.h> const char* MyString::CloneCString(const char* a_c_string) { if (a_c_string == nullptr) return nullptr; const size_t len = strlen(a_c_string); char* const clone = new char[len + 1]; memcpy(clone, a_c_string, len + 1); return clone; } void MyString::Set(const char* a_c_string) { const char* const temp = MyString::CloneCString(a_c_string); delete[] c_string_; c_string_ = temp; }
#include "sample2.h" #include "gtest/gtest.h" namespace { TEST(MyString, DefaultConstructor) { const MyString s; EXPECT_STREQ(nullptr, s.c_string()); EXPECT_EQ(0u, s.Length()); } const char kHelloString[] = "Hello, world!"; TEST(MyString, ConstructorFromCString) { const MyString s(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length()); } TEST(MyString, CopyConstructor) { const MyString s1(kHelloString); const MyString s2 = s1; EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString)); } TEST(MyString, Set) { MyString s; s.Set(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); s.Set(s.c_string()); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); s.Set(nullptr); EXPECT_STREQ(nullptr, s.c_string()); } }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/samples/sample2.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/samples/sample2_unittest.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
05ca717a-710e-4112-add2-ca73d6c6071f
cpp
google/googletest
sample1
googletest/samples/sample1.cc
googletest/samples/sample1_unittest.cc
#include "sample1.h" int Factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } bool IsPrime(int n) { if (n <= 1) return false; if (n % 2 == 0) return n == 2; for (int i = 3;; i += 2) { if (i > n / i) break; if (n % i == 0) return false; } return true; }
#include "sample1.h" #include <limits.h> #include "gtest/gtest.h" namespace { TEST(FactorialTest, Negative) { EXPECT_EQ(1, Factorial(-5)); EXPECT_EQ(1, Factorial(-1)); EXPECT_GT(Factorial(-10), 0); } TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); } TEST(FactorialTest, Positive) { EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(2, Factorial(2)); EXPECT_EQ(6, Factorial(3)); EXPECT_EQ(40320, Factorial(8)); } TEST(IsPrimeTest, Negative) { EXPECT_FALSE(IsPrime(-1)); EXPECT_FALSE(IsPrime(-2)); EXPECT_FALSE(IsPrime(INT_MIN)); } TEST(IsPrimeTest, Trivial) { EXPECT_FALSE(IsPrime(0)); EXPECT_FALSE(IsPrime(1)); EXPECT_TRUE(IsPrime(2)); EXPECT_TRUE(IsPrime(3)); } TEST(IsPrimeTest, Positive) { EXPECT_FALSE(IsPrime(4)); EXPECT_TRUE(IsPrime(5)); EXPECT_FALSE(IsPrime(6)); EXPECT_TRUE(IsPrime(23)); } }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/samples/sample1.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/samples/sample1_unittest.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
f5bec509-da94-4e49-bc7e-4fa9a774cd5b
cpp
google/googletest
sample4
googletest/samples/sample4.cc
googletest/samples/sample4_unittest.cc
#include "sample4.h" #include <stdio.h> int Counter::Increment() { return counter_++; } int Counter::Decrement() { if (counter_ == 0) { return counter_; } else { return counter_--; } } void Counter::Print() const { printf("%d", counter_); }
#include "sample4.h" #include "gtest/gtest.h" namespace { TEST(Counter, Increment) { Counter c; EXPECT_EQ(0, c.Decrement()); EXPECT_EQ(0, c.Increment()); EXPECT_EQ(1, c.Increment()); EXPECT_EQ(2, c.Increment()); EXPECT_EQ(3, c.Decrement()); } }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/samples/sample4.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/samples/sample4_unittest.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
348ae442-7632-4acb-8891-c07bad76ebb1
cpp
google/googletest
gtest
googletest/src/gtest.cc
googletest/test/gtest_unittest.cc
#include "gtest/gtest.h" #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> #include <chrono> #include <cmath> #include <csignal> #include <cstdint> #include <cstdlib> #include <cstring> #include <initializer_list> #include <iomanip> #include <ios> #include <iostream> #include <iterator> #include <limits> #include <list> #include <map> #include <ostream> #include <set> #include <sstream> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-assertion-result.h" #include "gtest/gtest-spi.h" #include "gtest/internal/custom/gtest.h" #include "gtest/internal/gtest-port.h" #ifdef GTEST_OS_LINUX #include <fcntl.h> #include <limits.h> #include <sched.h> #include <strings.h> #include <sys/mman.h> #include <sys/time.h> #include <unistd.h> #include <string> #elif defined(GTEST_OS_ZOS) #include <sys/time.h> #include <strings.h> #elif defined(GTEST_OS_WINDOWS_MOBILE) #include <windows.h> #undef min #elif defined(GTEST_OS_WINDOWS) #include <windows.h> #undef min #ifdef _MSC_VER #include <crtdbg.h> #endif #include <io.h> #include <sys/stat.h> #include <sys/timeb.h> #include <sys/types.h> #ifdef GTEST_OS_WINDOWS_MINGW #include <sys/time.h> #endif #else #include <sys/time.h> #include <unistd.h> #endif #if GTEST_HAS_EXCEPTIONS #include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #endif #include "src/gtest-internal-inl.h" #ifdef GTEST_OS_WINDOWS #define vsnprintf _vsnprintf #endif #ifdef GTEST_OS_MAC #ifndef GTEST_OS_IOS #include <crt_externs.h> #endif #endif #ifdef GTEST_HAS_ABSL #include "absl/container/flat_hash_set.h" #include "absl/debugging/failure_signal_handler.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #endif #if defined(__has_builtin) #define GTEST_HAS_BUILTIN(x) __has_builtin(x) #else #define GTEST_HAS_BUILTIN(x) 0 #endif #if defined(GTEST_HAS_ABSL) && !defined(GTEST_NO_ABSL_FLAGS) #define GTEST_HAS_ABSL_FLAGS #endif namespace testing { using internal::CountIf; using internal::ForEach; using internal::GetElementOr; using internal::Shuffle; static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest, const char* , const char* , const TestPartResultArray& results, TestPartResult::Type type, const std::string& substr) { const std::string expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" << " Actual: " << results.size() << " failures"; for (int i = 0; i < results.size(); i++) { msg << "\n" << results.GetTestPartResult(i); } return AssertionFailure() << msg; } const TestPartResult& r = results.GetTestPartResult(0); if (r.type() != type) { return AssertionFailure() << "Expected: " << expected << "\n" << " Actual:\n" << r; } if (strstr(r.message(), substr.c_str()) == nullptr) { return AssertionFailure() << "Expected: " << expected << " containing \"" << substr << "\"\n" << " Actual:\n" << r; } return AssertionSuccess(); } SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr) : results_(results), type_(type), substr_(substr) {} SingleFailureChecker::~SingleFailureChecker() { EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->current_test_result()->AddTestPartResult(result); unit_test_->listeners()->repeater()->OnTestPartResult(result); } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); } TestPartResultReporterInterface* UnitTestImpl::GetGlobalTestPartResultReporter() { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); return global_test_part_result_reporter_; } void UnitTestImpl::SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter) { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); global_test_part_result_reporter_ = reporter; } TestPartResultReporterInterface* UnitTestImpl::GetTestPartResultReporterForCurrentThread() { return per_thread_test_part_result_reporter_.get(); } void UnitTestImpl::SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter) { per_thread_test_part_result_reporter_.set(reporter); } int UnitTestImpl::successful_test_suite_count() const { return CountIf(test_suites_, TestSuitePassed); } int UnitTestImpl::failed_test_suite_count() const { return CountIf(test_suites_, TestSuiteFailed); } int UnitTestImpl::total_test_suite_count() const { return static_cast<int>(test_suites_.size()); } int UnitTestImpl::test_suite_to_run_count() const { return CountIf(test_suites_, ShouldRunTestSuite); } int UnitTestImpl::successful_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count); } int UnitTestImpl::skipped_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count); } int UnitTestImpl::failed_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count); } int UnitTestImpl::reportable_disabled_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_disabled_test_count); } int UnitTestImpl::disabled_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count); } int UnitTestImpl::reportable_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count); } int UnitTestImpl::total_test_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count); } int UnitTestImpl::test_to_run_count() const { return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count); } std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { return os_stack_trace_getter()->CurrentStackTrace( static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1 ); } class Timer { public: Timer() : start_(clock::now()) {} TimeInMillis Elapsed() { return std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - start_) .count(); } private: #if defined(_NEWLIB_VERSION) && !defined(CLOCK_MONOTONIC) using clock = std::chrono::system_clock; #else using clock = std::chrono::steady_clock; #endif clock::time_point start_; }; TimeInMillis GetTimeInMillis() { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now() - std::chrono::system_clock::from_time_t(0)) .count(); } #ifdef GTEST_OS_WINDOWS_MOBILE LPCWSTR String::AnsiToUtf16(const char* ansi) { if (!ansi) return nullptr; const int length = strlen(ansi); const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return nullptr; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, 0, nullptr, nullptr); char* ansi = new char[ansi_length + 1]; WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr, nullptr); ansi[ansi_length] = 0; return ansi; } #endif bool String::CStringEquals(const char* lhs, const char* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return strcmp(lhs, rhs) == 0; } #if GTEST_HAS_STD_WSTRING static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { for (size_t i = 0; i != length;) { if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; } } } #endif void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { ::std::vector< ::std::string> parsed; ::std::string::size_type pos = 0; while (::testing::internal::AlwaysTrue()) { const ::std::string::size_type colon = str.find(delimiter, pos); if (colon == ::std::string::npos) { parsed.push_back(str.substr(pos)); break; } else { parsed.push_back(str.substr(pos, colon - pos)); pos = colon + 1; } } dest->swap(parsed); } } Message::Message() : ss_(new ::std::stringstream) { *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); } Message& Message::operator<<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } Message& Message::operator<<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING Message& Message::operator<<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif std::string Message::GetString() const { return internal::StringStreamToString(ss_.get()); } namespace internal { namespace edit_distance { std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left, const std::vector<size_t>& right) { std::vector<std::vector<double> > costs( left.size() + 1, std::vector<double>(right.size() + 1)); std::vector<std::vector<EditType> > best_move( left.size() + 1, std::vector<EditType>(right.size() + 1)); for (size_t l_i = 0; l_i < costs.size(); ++l_i) { costs[l_i][0] = static_cast<double>(l_i); best_move[l_i][0] = kRemove; } for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { costs[0][r_i] = static_cast<double>(r_i); best_move[0][r_i] = kAdd; } for (size_t l_i = 0; l_i < left.size(); ++l_i) { for (size_t r_i = 0; r_i < right.size(); ++r_i) { if (left[l_i] == right[r_i]) { costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; best_move[l_i + 1][r_i + 1] = kMatch; continue; } const double add = costs[l_i + 1][r_i]; const double remove = costs[l_i][r_i + 1]; const double replace = costs[l_i][r_i]; if (add < remove && add < replace) { costs[l_i + 1][r_i + 1] = add + 1; best_move[l_i + 1][r_i + 1] = kAdd; } else if (remove < add && remove < replace) { costs[l_i + 1][r_i + 1] = remove + 1; best_move[l_i + 1][r_i + 1] = kRemove; } else { costs[l_i + 1][r_i + 1] = replace + 1.00001; best_move[l_i + 1][r_i + 1] = kReplace; } } } std::vector<EditType> best_path; for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { EditType move = best_move[l_i][r_i]; best_path.push_back(move); l_i -= move != kAdd; r_i -= move != kRemove; } std::reverse(best_path.begin(), best_path.end()); return best_path; } namespace { class InternalStrings { public: size_t GetId(const std::string& str) { IdMap::iterator it = ids_.find(str); if (it != ids_.end()) return it->second; size_t id = ids_.size(); return ids_[str] = id; } private: typedef std::map<std::string, size_t> IdMap; IdMap ids_; }; } std::vector<EditType> CalculateOptimalEdits( const std::vector<std::string>& left, const std::vector<std::string>& right) { std::vector<size_t> left_ids, right_ids; { InternalStrings intern_table; for (size_t i = 0; i < left.size(); ++i) { left_ids.push_back(intern_table.GetId(left[i])); } for (size_t i = 0; i < right.size(); ++i) { right_ids.push_back(intern_table.GetId(right[i])); } } return CalculateOptimalEdits(left_ids, right_ids); } namespace { class Hunk { public: Hunk(size_t left_start, size_t right_start) : left_start_(left_start), right_start_(right_start), adds_(), removes_(), common_() {} void PushLine(char edit, const char* line) { switch (edit) { case ' ': ++common_; FlushEdits(); hunk_.push_back(std::make_pair(' ', line)); break; case '-': ++removes_; hunk_removes_.push_back(std::make_pair('-', line)); break; case '+': ++adds_; hunk_adds_.push_back(std::make_pair('+', line)); break; } } void PrintTo(std::ostream* os) { PrintHeader(os); FlushEdits(); for (std::list<std::pair<char, const char*> >::const_iterator it = hunk_.begin(); it != hunk_.end(); ++it) { *os << it->first << it->second << "\n"; } } bool has_edits() const { return adds_ || removes_; } private: void FlushEdits() { hunk_.splice(hunk_.end(), hunk_removes_); hunk_.splice(hunk_.end(), hunk_adds_); } void PrintHeader(std::ostream* ss) const { *ss << "@@ "; if (removes_) { *ss << "-" << left_start_ << "," << (removes_ + common_); } if (removes_ && adds_) { *ss << " "; } if (adds_) { *ss << "+" << right_start_ << "," << (adds_ + common_); } *ss << " @@\n"; } size_t left_start_, right_start_; size_t adds_, removes_, common_; std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_; }; } std::string CreateUnifiedDiff(const std::vector<std::string>& left, const std::vector<std::string>& right, size_t context) { const std::vector<EditType> edits = CalculateOptimalEdits(left, right); size_t l_i = 0, r_i = 0, edit_i = 0; std::stringstream ss; while (edit_i < edits.size()) { while (edit_i < edits.size() && edits[edit_i] == kMatch) { ++l_i; ++r_i; ++edit_i; } const size_t prefix_context = std::min(l_i, context); Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); for (size_t i = prefix_context; i > 0; --i) { hunk.PushLine(' ', left[l_i - i].c_str()); } size_t n_suffix = 0; for (; edit_i < edits.size(); ++edit_i) { if (n_suffix >= context) { auto it = edits.begin() + static_cast<int>(edit_i); while (it != edits.end() && *it == kMatch) ++it; if (it == edits.end() || static_cast<size_t>(it - edits.begin()) - edit_i >= context) { break; } } EditType edit = edits[edit_i]; n_suffix = edit == kMatch ? n_suffix + 1 : 0; if (edit == kMatch || edit == kRemove || edit == kReplace) { hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); } if (edit == kAdd || edit == kReplace) { hunk.PushLine('+', right[r_i].c_str()); } l_i += edit != kAdd; r_i += edit != kRemove; } if (!hunk.has_edits()) { break; } hunk.PrintTo(&ss); } return ss.str(); } } namespace { std::vector<std::string> SplitEscapedString(const std::string& str) { std::vector<std::string> lines; size_t start = 0, end = str.size(); if (end > 2 && str[0] == '"' && str[end - 1] == '"') { ++start; --end; } bool escaped = false; for (size_t i = start; i + 1 < end; ++i) { if (escaped) { escaped = false; if (str[i] == 'n') { lines.push_back(str.substr(start, i - start - 1)); start = i + 1; } } else { escaped = str[i] == '\\'; } } lines.push_back(str.substr(start, end - start)); return lines; } } AssertionResult EqFailure(const char* lhs_expression, const char* rhs_expression, const std::string& lhs_value, const std::string& rhs_value, bool ignoring_case) { Message msg; msg << "Expected equality of these values:"; msg << "\n " << lhs_expression; if (lhs_value != lhs_expression) { msg << "\n Which is: " << lhs_value; } msg << "\n " << rhs_expression; if (rhs_value != rhs_expression) { msg << "\n Which is: " << rhs_value; } if (ignoring_case) { msg << "\nIgnoring case"; } if (!lhs_value.empty() && !rhs_value.empty()) { const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value); const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value); if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { msg << "\nWith diff:\n" << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); } } return AssertionFailure() << msg; } std::string GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); const double min_abs = std::min(fabs(val1), fabs(val2)); const double epsilon = nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs; if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 && abs_error < epsilon) { return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", where\n" << expr1 << " evaluates to " << val1 << ",\n" << expr2 << " evaluates to " << val2 << ".\nThe abs_error parameter " << abs_error_expr << " evaluates to " << abs_error << " which is smaller than the minimum distance between doubles for " "numbers of this magnitude which is " << epsilon << ", thus making this EXPECT_NEAR check equivalent to " "EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead."; } return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << expr1 << " evaluates to " << val1 << ",\n" << expr2 << " evaluates to " << val2 << ", and\n" << abs_error_expr << " evaluates to " << abs_error << "."; } template <typename RawType> AssertionResult FloatingPointLE(const char* expr1, const char* expr2, RawType val1, RawType val2) { if (val1 < val2) { return AssertionSuccess(); } const FloatingPoint<RawType> lhs(val1), rhs(val2); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } ::std::stringstream val1_ss; val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val1; ::std::stringstream val2_ss; val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val2; return AssertionFailure() << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" << " Actual: " << StringStreamToString(&val1_ss) << " vs " << StringStreamToString(&val2_ss); } } AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2) { return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); } AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2) { return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); } namespace internal { AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), true); } AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } } namespace { bool IsSubstringPred(const char* needle, const char* haystack) { if (needle == nullptr || haystack == nullptr) return needle == haystack; return strstr(haystack, needle) != nullptr; } bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { if (needle == nullptr || haystack == nullptr) return needle == haystack; return wcsstr(haystack, needle) != nullptr; } template <typename StringType> bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } template <typename StringType> AssertionResult IsSubstringImpl(bool expected_to_be_substring, const char* needle_expr, const char* haystack_expr, const StringType& needle, const StringType& haystack) { if (IsSubstringPred(needle, haystack) == expected_to_be_substring) return AssertionSuccess(); const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; return AssertionFailure() << "Value of: " << needle_expr << "\n" << " Actual: " << begin_string_quote << needle << "\"\n" << "Expected: " << (expected_to_be_substring ? "" : "not ") << "a substring of " << haystack_expr << "\n" << "Which is: " << begin_string_quote << haystack << "\""; } } AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif namespace internal { #ifdef GTEST_OS_WINDOWS namespace { AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_TV_TITLE) const char error_text[] = ""; #else const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; char error_text[kBufSize] = {'\0'}; DWORD message_length = ::FormatMessageA(kFlags, 0, static_cast<DWORD>(hr), 0, error_text, kBufSize, nullptr); for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } #endif const std::string error_hex("0x" + String::FormatHexInt(hr)); return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" << " Actual: " << error_hex << " " << error_text << "\n"; } } AssertionResult IsHRESULTSuccess(const char* expr, long hr) { if (SUCCEEDED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "succeeds", hr); } AssertionResult IsHRESULTFailure(const char* expr, long hr) { if (FAILED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "fails", hr); } #endif constexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1; constexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1; constexpr uint32_t kMaxCodePoint3 = (static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1; constexpr uint32_t kMaxCodePoint4 = (static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1; inline uint32_t ChopLowBits(uint32_t* bits, int n) { const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1); *bits >>= n; return low_bits; } std::string CodePointToUtf8(uint32_t code_point) { if (code_point > kMaxCodePoint4) { return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")"; } char str[5]; if (code_point <= kMaxCodePoint1) { str[1] = '\0'; str[0] = static_cast<char>(code_point); } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); str[0] = static_cast<char>(0xC0 | code_point); } else if (code_point <= kMaxCodePoint3) { str[3] = '\0'; str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); str[0] = static_cast<char>(0xE0 | code_point); } else { str[4] = '\0'; str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); str[0] = static_cast<char>(0xF0 | code_point); } return str; } inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; } inline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second) { const auto first_u = static_cast<uint32_t>(first); const auto second_u = static_cast<uint32_t>(second); const uint32_t mask = (1 << 10) - 1; return (sizeof(wchar_t) == 2) ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000 : first_u; } std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { uint32_t unicode_code_point; if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast<uint32_t>(str[i]); } stream << CodePointToUtf8(unicode_code_point); } return StringStreamToString(&stream); } std::string String::ShowWideCString(const wchar_t* wide_c_str) { if (wide_c_str == nullptr) return "(null)"; return internal::WideStringToUtf8(wide_c_str, -1); } bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return wcscmp(lhs, rhs) == 0; } AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2); } bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; return posix::StrCaseCmp(lhs, rhs) == 0; } bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == nullptr) return rhs == nullptr; if (rhs == nullptr) return false; #ifdef GTEST_OS_WINDOWS return _wcsicmp(lhs, rhs) == 0; #elif defined(GTEST_OS_LINUX) && !defined(GTEST_OS_LINUX_ANDROID) return wcscasecmp(lhs, rhs) == 0; #else wint_t left, right; do { left = towlower(static_cast<wint_t>(*lhs++)); right = towlower(static_cast<wint_t>(*rhs++)); } while (left && left == right); return left == right; #endif } bool String::EndsWithCaseInsensitive(const std::string& str, const std::string& suffix) { const size_t str_len = str.length(); const size_t suffix_len = suffix.length(); return (str_len >= suffix_len) && CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, suffix.c_str()); } std::string String::FormatIntWidth2(int value) { return FormatIntWidthN(value, 2); } std::string String::FormatIntWidthN(int value, int width) { std::stringstream ss; ss << std::setfill('0') << std::setw(width) << value; return ss.str(); } std::string String::FormatHexUInt32(uint32_t value) { std::stringstream ss; ss << std::hex << std::uppercase << value; return ss.str(); } std::string String::FormatHexInt(int value) { return FormatHexUInt32(static_cast<uint32_t>(value)); } std::string String::FormatByte(unsigned char value) { std::stringstream ss; ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase << static_cast<unsigned int>(value); return ss.str(); } std::string StringStreamToString(::std::stringstream* ss) { const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); std::string result; result.reserve(static_cast<size_t>(2 * (end - start))); for (const char* ch = start; ch != end; ++ch) { if (*ch == '\0') { result += "\\0"; } else { result += *ch; } } return result; } std::string AppendUserMessage(const std::string& gtest_msg, const Message& user_msg) { const std::string user_msg_string = user_msg.GetString(); if (user_msg_string.empty()) { return gtest_msg; } if (gtest_msg.empty()) { return user_msg_string; } return gtest_msg + "\n" + user_msg_string; } } TestResult::TestResult() : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} TestResult::~TestResult() = default; const TestPartResult& TestResult::GetTestPartResult(int i) const { if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(static_cast<size_t>(i)); } const TestProperty& TestResult::GetTestProperty(int i) const { if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(static_cast<size_t>(i)); } void TestResult::ClearTestPartResults() { test_part_results_.clear(); } void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { test_part_results_.push_back(test_part_result); } void TestResult::RecordProperty(const std::string& xml_element, const TestProperty& test_property) { if (!ValidateTestProperty(xml_element, test_property)) { return; } internal::MutexLock lock(&test_properties_mutex_); const std::vector<TestProperty>::iterator property_with_matching_key = std::find_if(test_properties_.begin(), test_properties_.end(), internal::TestPropertyKeyIs(test_property.key())); if (property_with_matching_key == test_properties_.end()) { test_properties_.push_back(test_property); return; } property_with_matching_key->SetValue(test_property.value()); } static const char* const kReservedTestSuitesAttributes[] = { "disabled", "errors", "failures", "name", "random_seed", "tests", "time", "timestamp"}; static const char* const kReservedTestSuiteAttributes[] = { "disabled", "errors", "failures", "name", "tests", "time", "timestamp", "skipped"}; static const char* const kReservedTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param", "file", "line"}; static const char* const kReservedOutputTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param", "file", "line", "result", "timestamp"}; template <size_t kSize> std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { return std::vector<std::string>(array, array + kSize); } static std::vector<std::string> GetReservedAttributesForElement( const std::string& xml_element) { if (xml_element == "testsuites") { return ArrayAsVector(kReservedTestSuitesAttributes); } else if (xml_element == "testsuite") { return ArrayAsVector(kReservedTestSuiteAttributes); } else if (xml_element == "testcase") { return ArrayAsVector(kReservedTestCaseAttributes); } else { GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; } return std::vector<std::string>(); } #if GTEST_HAS_FILE_SYSTEM static std::vector<std::string> GetReservedOutputAttributesForElement( const std::string& xml_element) { if (xml_element == "testsuites") { return ArrayAsVector(kReservedTestSuitesAttributes); } else if (xml_element == "testsuite") { return ArrayAsVector(kReservedTestSuiteAttributes); } else if (xml_element == "testcase") { return ArrayAsVector(kReservedOutputTestCaseAttributes); } else { GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; } return std::vector<std::string>(); } #endif static std::string FormatWordList(const std::vector<std::string>& words) { Message word_list; for (size_t i = 0; i < words.size(); ++i) { if (i > 0 && words.size() > 2) { word_list << ", "; } if (i == words.size() - 1) { word_list << "and "; } word_list << "'" << words[i] << "'"; } return word_list.GetString(); } static bool ValidateTestPropertyName( const std::string& property_name, const std::vector<std::string>& reserved_names) { if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != reserved_names.end()) { ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name << " (" << FormatWordList(reserved_names) << " are reserved by " << GTEST_NAME_ << ")"; return false; } return true; } bool TestResult::ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property) { return ValidateTestPropertyName(test_property.key(), GetReservedAttributesForElement(xml_element)); } void TestResult::Clear() { test_part_results_.clear(); test_properties_.clear(); death_test_count_ = 0; elapsed_time_ = 0; } static bool TestPartSkipped(const TestPartResult& result) { return result.skipped(); } bool TestResult::Skipped() const { return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0; } bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { if (GetTestPartResult(i).failed()) return true; } return false; } static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } int TestResult::total_part_count() const { return static_cast<int>(test_part_results_.size()); } int TestResult::test_property_count() const { return static_cast<int>(test_properties_.size()); } Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {} Test::~Test() = default; void Test::SetUp() {} void Test::TearDown() {} void Test::RecordProperty(const std::string& key, const std::string& value) { UnitTest::GetInstance()->RecordProperty(key, value); } namespace internal { void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message) { UnitTest::GetInstance()->AddTestPartResult( result_type, nullptr, -1, message, ""); } } bool Test::HasSameFixtureClass() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); const TestSuite* const test_suite = impl->current_test_suite(); const TestInfo* const first_test_info = test_suite->test_info_list()[0]; const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; const char* const first_test_name = first_test_info->name(); const TestInfo* const this_test_info = impl->current_test_info(); const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; const char* const this_test_name = this_test_info->name(); if (this_fixture_id != first_fixture_id) { const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); if (first_is_TEST || this_is_TEST) { const char* const TEST_name = first_is_TEST ? first_test_name : this_test_name; const char* const TEST_F_name = first_is_TEST ? this_test_name : first_test_name; ADD_FAILURE() << "All tests in the same test suite must use the same test fixture\n" << "class, so mixing TEST_F and TEST in the same test suite is\n" << "illegal. In test suite " << this_test_info->test_suite_name() << ",\n" << "test " << TEST_F_name << " is defined using TEST_F but\n" << "test " << TEST_name << " is defined using TEST. You probably\n" << "want to change the TEST to TEST_F or move it to another test\n" << "case."; } else { ADD_FAILURE() << "All tests in the same test suite must use the same test fixture\n" << "class. However, in test suite " << this_test_info->test_suite_name() << ",\n" << "you defined test " << first_test_name << " and test " << this_test_name << "\n" << "using two different test fixture classes. This can happen if\n" << "the two classes are from different namespaces or translation\n" << "units and have the same name. You should probably rename one\n" << "of the classes to put the tests into different test suites."; } return false; } return true; } namespace internal { #if GTEST_HAS_EXCEPTIONS static std::string FormatCxxExceptionMessage(const char* description, const char* location) { Message message; if (description != nullptr) { message << "C++ exception with description \"" << description << "\""; } else { message << "Unknown C++ exception"; } message << " thrown in " << location << "."; return message.GetString(); } static std::string PrintTestPartResultToString( const TestPartResult& test_part_result); GoogleTestFailureException::GoogleTestFailureException( const TestPartResult& failure) : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} #endif template <class T, typename Result> Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(), const char* location) { #if GTEST_HAS_SEH __try { return (object->*method)(); } __except (internal::UnitTestOptions::GTestProcessSEH( GetExceptionCode(), location)) { return static_cast<Result>(0); } #else (void)location; return (object->*method)(); #endif } template <class T, typename Result> Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(), const char* location) { if (internal::GetUnitTestImpl()->catch_exceptions()) { #if GTEST_HAS_EXCEPTIONS try { return HandleSehExceptionsInMethodIfSupported(object, method, location); } catch (const AssertionException&) { } catch (const internal::GoogleTestFailureException&) { throw; } catch (const std::exception& e) { internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(e.what(), location)); } catch (...) { internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(nullptr, location)); } return static_cast<Result>(0); #else return HandleSehExceptionsInMethodIfSupported(object, method, location); #endif } else { return (object->*method)(); } } } void Test::Run() { if (!HasSameFixtureClass()) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); if (!HasFatalFailure() && !IsSkipped()) { impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody, "the test body"); } impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown, "TearDown()"); } bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); } bool Test::HasNonfatalFailure() { return internal::GetUnitTestImpl() ->current_test_result() ->HasNonfatalFailure(); } bool Test::IsSkipped() { return internal::GetUnitTestImpl()->current_test_result()->Skipped(); } TestInfo::TestInfo(std::string a_test_suite_name, std::string a_name, const char* a_type_param, const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : test_suite_name_(std::move(a_test_suite_name)), name_(std::move(a_name)), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), value_param_(a_value_param ? new std::string(a_value_param) : nullptr), location_(std::move(a_code_location)), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), matches_filter_(false), is_in_another_shard_(false), factory_(factory), result_() {} TestInfo::~TestInfo() { delete factory_; } namespace internal { TestInfo* MakeAndRegisterTestInfo( std::string test_suite_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = new TestInfo(std::move(test_suite_name), name, type_param, value_param, std::move(code_location), fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } void ReportInvalidTestSuiteType(const char* test_suite_name, const CodeLocation& code_location) { Message errors; errors << "Attempted redefinition of test suite " << test_suite_name << ".\n" << "All tests in the same test suite must use the same test fixture\n" << "class. However, in test suite " << test_suite_name << ", you tried\n" << "to define a test using a fixture class different from the one\n" << "used earlier. This can happen if the two fixture classes are\n" << "from different namespaces and have the same name. You should\n" << "probably rename one of the classes to put the tests into different\n" << "test suites."; GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(), code_location.line) << " " << errors.GetString(); } void UnitTestImpl::RegisterParameterizedTests() { if (!parameterized_tests_registered_) { parameterized_test_registry_.RegisterTests(); type_parameterized_test_registry_.CheckForInstantiations(); parameterized_tests_registered_ = true; } } } void TestInfo::Run() { TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); if (!should_run_) { if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*this); return; } UnitTest::GetInstance()->set_current_test_info(this); repeater->OnTestStart(*this); result_.set_start_timestamp(internal::GetTimeInMillis()); internal::Timer timer; UnitTest::GetInstance()->UponLeavingGTest(); Test* const test = internal::HandleExceptionsInMethodIfSupported( factory_, &internal::TestFactoryBase::CreateTest, "the test fixture's constructor"); if (!Test::HasFatalFailure() && !Test::IsSkipped()) { test->Run(); } if (test != nullptr) { UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); } result_.set_elapsed_time(timer.Elapsed()); repeater->OnTestEnd(*this); UnitTest::GetInstance()->set_current_test_info(nullptr); } void TestInfo::Skip() { if (!should_run_) return; UnitTest::GetInstance()->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); repeater->OnTestStart(*this); const TestPartResult test_part_result = TestPartResult(TestPartResult::kSkip, this->file(), this->line(), ""); internal::GetUnitTestImpl() ->GetTestPartResultReporterForCurrentThread() ->ReportTestPartResult(test_part_result); repeater->OnTestEnd(*this); UnitTest::GetInstance()->set_current_test_info(nullptr); } int TestSuite::successful_test_count() const { return CountIf(test_info_list_, TestPassed); } int TestSuite::skipped_test_count() const { return CountIf(test_info_list_, TestSkipped); } int TestSuite::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } int TestSuite::reportable_disabled_test_count() const { return CountIf(test_info_list_, TestReportableDisabled); } int TestSuite::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } int TestSuite::reportable_test_count() const { return CountIf(test_info_list_, TestReportable); } int TestSuite::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); } int TestSuite::total_test_count() const { return static_cast<int>(test_info_list_.size()); } TestSuite::TestSuite(const std::string& a_name, const char* a_type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) : name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : nullptr), set_up_tc_(set_up_tc), tear_down_tc_(tear_down_tc), should_run_(false), start_timestamp_(0), elapsed_time_(0) {} TestSuite::~TestSuite() { ForEach(test_info_list_, internal::Delete<TestInfo>); } const TestInfo* TestSuite::GetTestInfo(int i) const { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)]; } TestInfo* TestSuite::GetMutableTestInfo(int i) { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)]; } void TestSuite::AddTestInfo(TestInfo* test_info) { test_info_list_.push_back(test_info); test_indices_.push_back(static_cast<int>(test_indices_.size())); } void TestSuite::Run() { if (!should_run_) return; UnitTest::GetInstance()->set_current_test_suite(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); std::stable_sort(test_info_list_.begin(), test_info_list_.end(), [](const TestInfo* const a, const TestInfo* const b) { if (const int result = std::strcmp(a->file(), b->file())) { return result < 0; } return a->line() < b->line(); }); repeater->OnTestSuiteStart(*this); #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ repeater->OnTestCaseStart(*this); #endif UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); const bool skip_all = ad_hoc_test_result().Failed() || ad_hoc_test_result().Skipped(); start_timestamp_ = internal::GetTimeInMillis(); internal::Timer timer; for (int i = 0; i < total_test_count(); i++) { if (skip_all) { GetMutableTestInfo(i)->Skip(); } else { GetMutableTestInfo(i)->Run(); } if (GTEST_FLAG_GET(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) { for (int j = i + 1; j < total_test_count(); j++) { GetMutableTestInfo(j)->Skip(); } break; } } elapsed_time_ = timer.Elapsed(); UnitTest::GetInstance()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()"); repeater->OnTestSuiteEnd(*this); #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ repeater->OnTestCaseEnd(*this); #endif UnitTest::GetInstance()->set_current_test_suite(nullptr); } void TestSuite::Skip() { if (!should_run_) return; UnitTest::GetInstance()->set_current_test_suite(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); repeater->OnTestSuiteStart(*this); #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ repeater->OnTestCaseStart(*this); #endif for (int i = 0; i < total_test_count(); i++) { GetMutableTestInfo(i)->Skip(); } repeater->OnTestSuiteEnd(*this); #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ repeater->OnTestCaseEnd(*this); #endif UnitTest::GetInstance()->set_current_test_suite(nullptr); } void TestSuite::ClearResult() { ad_hoc_test_result_.Clear(); ForEach(test_info_list_, TestInfo::ClearTestResult); } void TestSuite::ShuffleTests(internal::Random* random) { Shuffle(random, &test_indices_); } void TestSuite::UnshuffleTests() { for (size_t i = 0; i < test_indices_.size(); i++) { test_indices_[i] = static_cast<int>(i); } } static std::string FormatCountableNoun(int count, const char* singular_form, const char* plural_form) { return internal::StreamableToString(count) + " " + (count == 1 ? singular_form : plural_form); } static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } static std::string FormatTestSuiteCount(int test_suite_count) { return FormatCountableNoun(test_suite_count, "test suite", "test suites"); } static const char* TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSkip: return "Skipped\n"; case TestPartResult::kSuccess: return "Success"; case TestPartResult::kNonFatalFailure: case TestPartResult::kFatalFailure: #ifdef _MSC_VER return "error: "; #else return "Failure\n"; #endif default: return "Unknown result type"; } } namespace internal { namespace { enum class GTestColor { kDefault, kRed, kGreen, kYellow }; } static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { return (Message() << internal::FormatFileLocation( test_part_result.file_name(), test_part_result.line_number()) << " " << TestPartResultTypeToString(test_part_result.type()) << test_part_result.message()) .GetString(); } static void PrintTestPartResult(const TestPartResult& test_part_result) { const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) ::OutputDebugStringA(result.c_str()); ::OutputDebugStringA("\n"); #endif } #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ !defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \ !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW) static WORD GetColorAttribute(GTestColor color) { switch (color) { case GTestColor::kRed: return FOREGROUND_RED; case GTestColor::kGreen: return FOREGROUND_GREEN; case GTestColor::kYellow: return FOREGROUND_RED | FOREGROUND_GREEN; default: return 0; } } static int GetBitOffset(WORD color_mask) { if (color_mask == 0) return 0; int bitOffset = 0; while ((color_mask & 1) == 0) { color_mask >>= 1; ++bitOffset; } return bitOffset; } static WORD GetNewColor(GTestColor color, WORD old_color_attrs) { static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY; static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; const WORD existing_bg = old_color_attrs & background_mask; WORD new_color = GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY; static const int bg_bitOffset = GetBitOffset(background_mask); static const int fg_bitOffset = GetBitOffset(foreground_mask); if (((new_color & background_mask) >> bg_bitOffset) == ((new_color & foreground_mask) >> fg_bitOffset)) { new_color ^= FOREGROUND_INTENSITY; } return new_color; } #else static const char* GetAnsiColorCode(GTestColor color) { switch (color) { case GTestColor::kRed: return "1"; case GTestColor::kGreen: return "2"; case GTestColor::kYellow: return "3"; default: assert(false); return "9"; } } #endif bool ShouldUseColor(bool stdout_is_tty) { std::string c = GTEST_FLAG_GET(color); const char* const gtest_color = c.c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) return stdout_is_tty; #else const char* const term = posix::GetEnv("TERM"); const bool term_supports_color = term != nullptr && (String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-kitty") || String::CStringEquals(term, "alacritty") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "tmux") || String::CStringEquals(term, "rxvt-unicode") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin") || String::EndsWithCaseInsensitive(term, "-256color")); return stdout_is_tty && term_supports_color; #endif } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CStringEquals(gtest_color, "1"); } GTEST_ATTRIBUTE_PRINTF_(2, 3) static void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); const bool use_color = in_color_mode && (color != GTestColor::kDefault); if (!use_color) { vprintf(fmt, args); va_end(args); return; } #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MOBILE) && \ !defined(GTEST_OS_WINDOWS_GAMES) && !defined(GTEST_OS_WINDOWS_PHONE) && \ !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_MINGW) const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO buffer_info; GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); const WORD old_color_attrs = buffer_info.wAttributes; const WORD new_color = GetNewColor(color, old_color_attrs); fflush(stdout); SetConsoleTextAttribute(stdout_handle, new_color); vprintf(fmt, args); fflush(stdout); SetConsoleTextAttribute(stdout_handle, old_color_attrs); #else printf("\033[0;3%sm", GetAnsiColorCode(color)); vprintf(fmt, args); printf("\033[m"); #endif va_end(args); } static const char kTypeParamLabel[] = "TypeParam"; static const char kValueParamLabel[] = "GetParam()"; static void PrintFullTestCommentIfPresent(const TestInfo& test_info) { const char* const type_param = test_info.type_param(); const char* const value_param = test_info.value_param(); if (type_param != nullptr || value_param != nullptr) { printf(", where "); if (type_param != nullptr) { printf("%s = %s", kTypeParamLabel, type_param); if (value_param != nullptr) printf(" and "); } if (value_param != nullptr) { printf("%s = %s", kValueParamLabel, value_param); } } } class PrettyUnitTestResultPrinter : public TestEventListener { public: PrettyUnitTestResultPrinter() = default; static void PrintTestName(const char* test_suite, const char* test) { printf("%s.%s", test_suite, test); } void OnTestProgramStart(const UnitTest& ) override {} void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; void OnEnvironmentsSetUpEnd(const UnitTest& ) override {} #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseStart(const TestCase& test_case) override; #else void OnTestSuiteStart(const TestSuite& test_suite) override; #endif void OnTestStart(const TestInfo& test_info) override; void OnTestDisabled(const TestInfo& test_info) override; void OnTestPartResult(const TestPartResult& result) override; void OnTestEnd(const TestInfo& test_info) override; #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseEnd(const TestCase& test_case) override; #else void OnTestSuiteEnd(const TestSuite& test_suite) override; #endif void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; void OnEnvironmentsTearDownEnd(const UnitTest& ) override {} void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; void OnTestProgramEnd(const UnitTest& ) override {} private: static void PrintFailedTests(const UnitTest& unit_test); static void PrintFailedTestSuites(const UnitTest& unit_test); static void PrintSkippedTests(const UnitTest& unit_test); }; void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { if (GTEST_FLAG_GET(repeat) != 1) printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); std::string f = GTEST_FLAG_GET(filter); const char* const filter = f.c_str(); if (!String::CStringEquals(filter, kUniversalFilter)) { ColoredPrintf(GTestColor::kYellow, "Note: %s filter = %s\n", GTEST_NAME_, filter); } if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); ColoredPrintf(GTestColor::kYellow, "Note: This is test shard %d of %s.\n", static_cast<int>(shard_index) + 1, internal::posix::GetEnv(kTestTotalShards)); } if (GTEST_FLAG_GET(shuffle)) { ColoredPrintf(GTestColor::kYellow, "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); } ColoredPrintf(GTestColor::kGreen, "[==========] "); printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( const UnitTest& ) { ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("Global test environment set-up.\n"); fflush(stdout); } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("%s from %s", counts.c_str(), test_case.name()); if (test_case.type_param() == nullptr) { printf("\n"); } else { printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); } fflush(stdout); } #else void PrettyUnitTestResultPrinter::OnTestSuiteStart( const TestSuite& test_suite) { const std::string counts = FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("%s from %s", counts.c_str(), test_suite.name()); if (test_suite.type_param() == nullptr) { printf("\n"); } else { printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param()); } fflush(stdout); } #endif void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(GTestColor::kGreen, "[ RUN ] "); PrintTestName(test_info.test_suite_name(), test_info.name()); printf("\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestDisabled(const TestInfo& test_info) { ColoredPrintf(GTestColor::kYellow, "[ DISABLED ] "); PrintTestName(test_info.test_suite_name(), test_info.name()); printf("\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { switch (result.type()) { case TestPartResult::kSuccess: return; default: PrintTestPartResult(result); fflush(stdout); } } void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { if (test_info.result()->Passed()) { ColoredPrintf(GTestColor::kGreen, "[ OK ] "); } else if (test_info.result()->Skipped()) { ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); } else { ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); } PrintTestName(test_info.test_suite_name(), test_info.name()); if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms)\n", internal::StreamableToString(test_info.result()->elapsed_time()) .c_str()); } else { printf("\n"); } fflush(stdout); } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { if (!GTEST_FLAG_GET(print_time)) return; const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(), internal::StreamableToString(test_case.elapsed_time()).c_str()); fflush(stdout); } #else void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) { if (!GTEST_FLAG_GET(print_time)) return; const std::string counts = FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(), internal::StreamableToString(test_suite.elapsed_time()).c_str()); fflush(stdout); } #endif void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( const UnitTest& ) { ColoredPrintf(GTestColor::kGreen, "[----------] "); printf("Global test environment tear-down\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { const int failed_test_count = unit_test.failed_test_count(); ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite& test_suite = *unit_test.GetTestSuite(i); if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) { continue; } for (int j = 0; j < test_suite.total_test_count(); ++j) { const TestInfo& test_info = *test_suite.GetTestInfo(j); if (!test_info.should_run() || !test_info.result()->Failed()) { continue; } ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); printf("%s.%s", test_suite.name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); printf("\n"); } } printf("\n%2d FAILED %s\n", failed_test_count, failed_test_count == 1 ? "TEST" : "TESTS"); } void PrettyUnitTestResultPrinter::PrintFailedTestSuites( const UnitTest& unit_test) { int suite_failure_count = 0; for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite& test_suite = *unit_test.GetTestSuite(i); if (!test_suite.should_run()) { continue; } if (test_suite.ad_hoc_test_result().Failed()) { ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); printf("%s: SetUpTestSuite or TearDownTestSuite\n", test_suite.name()); ++suite_failure_count; } } if (suite_failure_count > 0) { printf("\n%2d FAILED TEST %s\n", suite_failure_count, suite_failure_count == 1 ? "SUITE" : "SUITES"); } } void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) { const int skipped_test_count = unit_test.skipped_test_count(); if (skipped_test_count == 0) { return; } for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { const TestSuite& test_suite = *unit_test.GetTestSuite(i); if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) { continue; } for (int j = 0; j < test_suite.total_test_count(); ++j) { const TestInfo& test_info = *test_suite.GetTestInfo(j); if (!test_info.should_run() || !test_info.result()->Skipped()) { continue; } ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); printf("%s.%s", test_suite.name(), test_info.name()); printf("\n"); } } } void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int ) { ColoredPrintf(GTestColor::kGreen, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } printf("\n"); ColoredPrintf(GTestColor::kGreen, "[ PASSED ] "); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); const int skipped_test_count = unit_test.skipped_test_count(); if (skipped_test_count > 0) { ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str()); PrintSkippedTests(unit_test); } if (!unit_test.Passed()) { PrintFailedTests(unit_test); PrintFailedTestSuites(unit_test); } int num_disabled = unit_test.reportable_disabled_test_count(); if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) { if (unit_test.Passed()) { printf("\n"); } ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); } fflush(stdout); } class BriefUnitTestResultPrinter : public TestEventListener { public: BriefUnitTestResultPrinter() = default; static void PrintTestName(const char* test_suite, const char* test) { printf("%s.%s", test_suite, test); } void OnTestProgramStart(const UnitTest& ) override {} void OnTestIterationStart(const UnitTest& , int ) override {} void OnEnvironmentsSetUpStart(const UnitTest& ) override {} void OnEnvironmentsSetUpEnd(const UnitTest& ) override {} #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseStart(const TestCase& ) override {} #else void OnTestSuiteStart(const TestSuite& ) override {} #endif void OnTestStart(const TestInfo& ) override {} void OnTestDisabled(const TestInfo& ) override {} void OnTestPartResult(const TestPartResult& result) override; void OnTestEnd(const TestInfo& test_info) override; #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseEnd(const TestCase& ) override {} #else void OnTestSuiteEnd(const TestSuite& ) override {} #endif void OnEnvironmentsTearDownStart(const UnitTest& ) override {} void OnEnvironmentsTearDownEnd(const UnitTest& ) override {} void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; void OnTestProgramEnd(const UnitTest& ) override {} }; void BriefUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { switch (result.type()) { case TestPartResult::kSuccess: return; default: PrintTestPartResult(result); fflush(stdout); } } void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { if (test_info.result()->Failed()) { ColoredPrintf(GTestColor::kRed, "[ FAILED ] "); PrintTestName(test_info.test_suite_name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms)\n", internal::StreamableToString(test_info.result()->elapsed_time()) .c_str()); } else { printf("\n"); } fflush(stdout); } } void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int ) { ColoredPrintf(GTestColor::kGreen, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); if (GTEST_FLAG_GET(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } printf("\n"); ColoredPrintf(GTestColor::kGreen, "[ PASSED ] "); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); const int skipped_test_count = unit_test.skipped_test_count(); if (skipped_test_count > 0) { ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] "); printf("%s.\n", FormatTestCount(skipped_test_count).c_str()); } int num_disabled = unit_test.reportable_disabled_test_count(); if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) { if (unit_test.Passed()) { printf("\n"); } ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); } fflush(stdout); } class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} ~TestEventRepeater() override; void Append(TestEventListener* listener); TestEventListener* Release(TestEventListener* listener); bool forwarding_enabled() const { return forwarding_enabled_; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } void OnTestProgramStart(const UnitTest& parameter) override; void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; void OnEnvironmentsSetUpStart(const UnitTest& parameter) override; void OnEnvironmentsSetUpEnd(const UnitTest& parameter) override; #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseStart(const TestSuite& parameter) override; #endif void OnTestSuiteStart(const TestSuite& parameter) override; void OnTestStart(const TestInfo& parameter) override; void OnTestDisabled(const TestInfo& parameter) override; void OnTestPartResult(const TestPartResult& parameter) override; void OnTestEnd(const TestInfo& parameter) override; #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ void OnTestCaseEnd(const TestCase& parameter) override; #endif void OnTestSuiteEnd(const TestSuite& parameter) override; void OnEnvironmentsTearDownStart(const UnitTest& parameter) override; void OnEnvironmentsTearDownEnd(const UnitTest& parameter) override; void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; void OnTestProgramEnd(const UnitTest& parameter) override; private: bool forwarding_enabled_; std::vector<TestEventListener*> listeners_; TestEventRepeater(const TestEventRepeater&) = delete; TestEventRepeater& operator=(const TestEventRepeater&) = delete; }; TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete<TestEventListener>); } void TestEventRepeater::Append(TestEventListener* listener) { listeners_.push_back(listener); } TestEventListener* TestEventRepeater::Release(TestEventListener* listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { listeners_.erase(listeners_.begin() + static_cast<int>(i)); return listener; } } return nullptr; } #define GTEST_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (size_t i = 0; i < listeners_.size(); i++) { \ listeners_[i]->Name(parameter); \ } \ } \ } #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (size_t i = listeners_.size(); i != 0; i--) { \ listeners_[i - 1]->Name(parameter); \ } \ } \ } GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite) #endif GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite) GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) GTEST_REPEATER_METHOD_(OnTestDisabled, TestInfo) GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite) #endif GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite) GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) #undef GTEST_REPEATER_METHOD_ #undef GTEST_REVERSE_REPEATER_METHOD_ void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (size_t i = 0; i < listeners_.size(); i++) { listeners_[i]->OnTestIterationStart(unit_test, iteration); } } } void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (size_t i = listeners_.size(); i > 0; i--) { listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration); } } } #if GTEST_HAS_FILE_SYSTEM class XmlUnitTestResultPrinter : public EmptyTestEventListener { public: explicit XmlUnitTestResultPrinter(const char* output_file); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites); static void PrintXmlTestsList(std::ostream* stream, const std::vector<TestSuite*>& test_suites); private: static bool IsNormalizableWhitespace(unsigned char c) { return c == '\t' || c == '\n' || c == '\r'; } static bool IsValidXmlCharacter(unsigned char c) { return IsNormalizableWhitespace(c) || c >= 0x20; } static std::string EscapeXml(const std::string& str, bool is_attribute); static std::string RemoveInvalidXmlCharacters(const std::string& str); static std::string EscapeXmlAttribute(const std::string& str) { return EscapeXml(str, true); } static std::string EscapeXmlText(const char* str) { return EscapeXml(str, false); } static void OutputXmlAttribute(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value); static void OutputXmlCDataSection(::std::ostream* stream, const char* data); static void OutputXmlTestSuiteForTestResult(::std::ostream* stream, const TestResult& result); static void OutputXmlTestResult(::std::ostream* stream, const TestResult& result); static void OutputXmlTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info); static void PrintXmlTestSuite(::std::ostream* stream, const TestSuite& test_suite); static void PrintXmlUnitTest(::std::ostream* stream, const UnitTest& unit_test); static std::string TestPropertiesAsXmlAttributes(const TestResult& result); static void OutputXmlTestProperties(std::ostream* stream, const TestResult& result); const std::string output_file_; XmlUnitTestResultPrinter(const XmlUnitTestResultPrinter&) = delete; XmlUnitTestResultPrinter& operator=(const XmlUnitTestResultPrinter&) = delete; }; XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.empty()) { GTEST_LOG_(FATAL) << "XML output file may not be null"; } } void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int ) { FILE* xmlout = OpenFileForWriting(output_file_); std::stringstream stream; PrintXmlUnitTest(&stream, unit_test); fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } void XmlUnitTestResultPrinter::ListTestsMatchingFilter( const std::vector<TestSuite*>& test_suites) { FILE* xmlout = OpenFileForWriting(output_file_); std::stringstream stream; PrintXmlTestsList(&stream, test_suites); fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str, bool is_attribute) { Message m; for (size_t i = 0; i < str.size(); ++i) { const char ch = str[i]; switch (ch) { case '<': m << "&lt;"; break; case '>': m << "&gt;"; break; case '&': m << "&amp;"; break; case '\'': if (is_attribute) m << "&apos;"; else m << '\''; break; case '"': if (is_attribute) m << "&quot;"; else m << '"'; break; default: if (IsValidXmlCharacter(static_cast<unsigned char>(ch))) { if (is_attribute && IsNormalizableWhitespace(static_cast<unsigned char>(ch))) m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch)) << ";"; else m << ch; } break; } } return m.GetString(); } std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( const std::string& str) { std::string output; output.reserve(str.size()); for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) if (IsValidXmlCharacter(static_cast<unsigned char>(*it))) output.push_back(*it); return output; } std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { ::std::stringstream ss; ss << std::fixed << std::setprecision( ms % 1000 == 0 ? 0 : (ms % 100 == 0 ? 1 : (ms % 10 == 0 ? 2 : 3))) << std::showpoint; ss << (static_cast<double>(ms) * 1e-3); return ss.str(); } static bool PortableLocaltime(time_t seconds, struct tm* out) { #if defined(_MSC_VER) return localtime_s(out, &seconds) == 0; #elif defined(__MINGW32__) || defined(__MINGW64__) struct tm* tm_ptr = localtime(&seconds); if (tm_ptr == nullptr) return false; *out = *tm_ptr; return true; #elif defined(__STDC_LIB_EXT1__) return localtime_s(&seconds, out) != nullptr; #else return localtime_r(&seconds, out) != nullptr; #endif } std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { struct tm time_struct; if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) return ""; return StreamableToString(time_struct.tm_year + 1900) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_sec) + "." + String::FormatIntWidthN(static_cast<int>(ms % 1000), 3); } void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { const char* segment = data; *stream << "<![CDATA["; for (;;) { const char* const next_segment = strstr(segment, "]]>"); if (next_segment != nullptr) { stream->write(segment, static_cast<std::streamsize>(next_segment - segment)); *stream << "]]>]]&gt;<![CDATA["; segment = next_segment + strlen("]]>"); } else { *stream << segment; break; } } *stream << "]]>"; } void XmlUnitTestResultPrinter::OutputXmlAttribute( std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Attribute " << name << " is not allowed for element <" << element_name << ">."; *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; } void XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult( ::std::ostream* stream, const TestResult& result) { *stream << " <testsuite"; OutputXmlAttribute(stream, "testsuite", "name", "NonTestSuiteFailure"); OutputXmlAttribute(stream, "testsuite", "tests", "1"); OutputXmlAttribute(stream, "testsuite", "failures", "1"); OutputXmlAttribute(stream, "testsuite", "disabled", "0"); OutputXmlAttribute(stream, "testsuite", "skipped", "0"); OutputXmlAttribute(stream, "testsuite", "errors", "0"); OutputXmlAttribute(stream, "testsuite", "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); OutputXmlAttribute( stream, "testsuite", "timestamp", FormatEpochTimeInMillisAsIso8601(result.start_timestamp())); *stream << ">"; *stream << " <testcase"; OutputXmlAttribute(stream, "testcase", "name", ""); OutputXmlAttribute(stream, "testcase", "status", "run"); OutputXmlAttribute(stream, "testcase", "result", "completed"); OutputXmlAttribute(stream, "testcase", "classname", ""); OutputXmlAttribute(stream, "testcase", "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); OutputXmlAttribute( stream, "testcase", "timestamp", FormatEpochTimeInMillisAsIso8601(result.start_timestamp())); OutputXmlTestResult(stream, result); *stream << " </testsuite>\n"; } void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); const std::string kTestsuite = "testcase"; if (test_info.is_in_another_shard()) { return; } *stream << " <testcase"; OutputXmlAttribute(stream, kTestsuite, "name", test_info.name()); if (test_info.value_param() != nullptr) { OutputXmlAttribute(stream, kTestsuite, "value_param", test_info.value_param()); } if (test_info.type_param() != nullptr) { OutputXmlAttribute(stream, kTestsuite, "type_param", test_info.type_param()); } OutputXmlAttribute(stream, kTestsuite, "file", test_info.file()); OutputXmlAttribute(stream, kTestsuite, "line", StreamableToString(test_info.line())); if (GTEST_FLAG_GET(list_tests)) { *stream << " />\n"; return; } OutputXmlAttribute(stream, kTestsuite, "status", test_info.should_run() ? "run" : "notrun"); OutputXmlAttribute(stream, kTestsuite, "result", test_info.should_run() ? (result.Skipped() ? "skipped" : "completed") : "suppressed"); OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); OutputXmlAttribute( stream, kTestsuite, "timestamp", FormatEpochTimeInMillisAsIso8601(result.start_timestamp())); OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name); OutputXmlTestResult(stream, result); } void XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream, const TestResult& result) { int failures = 0; int skips = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.failed()) { if (++failures == 1 && skips == 0) { *stream << ">\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string summary = location + "\n" + part.summary(); *stream << " <failure message=\"" << EscapeXmlAttribute(summary) << "\" type=\"\">"; const std::string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); *stream << "</failure>\n"; } else if (part.skipped()) { if (++skips == 1 && failures == 0) { *stream << ">\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string summary = location + "\n" + part.summary(); *stream << " <skipped message=\"" << EscapeXmlAttribute(summary.c_str()) << "\">"; const std::string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); *stream << "</skipped>\n"; } } if (failures == 0 && skips == 0 && result.test_property_count() == 0) { *stream << " />\n"; } else { if (failures == 0 && skips == 0) { *stream << ">\n"; } OutputXmlTestProperties(stream, result); *stream << " </testcase>\n"; } } void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream, const TestSuite& test_suite) { const std::string kTestsuite = "testsuite"; *stream << " <" << kTestsuite; OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name()); OutputXmlAttribute(stream, kTestsuite, "tests", StreamableToString(test_suite.reportable_test_count())); if (!GTEST_FLAG_GET(list_tests)) { OutputXmlAttribute(stream, kTestsuite, "failures", StreamableToString(test_suite.failed_test_count())); OutputXmlAttribute( stream, kTestsuite, "disabled", StreamableToString(test_suite.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuite, "skipped", StreamableToString(test_suite.skipped_test_count())); OutputXmlAttribute(stream, kTestsuite, "errors", "0"); OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(test_suite.elapsed_time())); OutputXmlAttribute( stream, kTestsuite, "timestamp", FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp())); *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result()); } *stream << ">\n"; for (int i = 0; i < test_suite.total_test_count(); ++i) { if (test_suite.GetTestInfo(i)->is_reportable()) OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); } *stream << " </" << kTestsuite << ">\n"; } void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, const UnitTest& unit_test) { const std::string kTestsuites = "testsuites"; *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; *stream << "<" << kTestsuites; OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(unit_test.reportable_test_count())); OutputXmlAttribute(stream, kTestsuites, "failures", StreamableToString(unit_test.failed_test_count())); OutputXmlAttribute( stream, kTestsuites, "disabled", StreamableToString(unit_test.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuites, "errors", "0"); OutputXmlAttribute(stream, kTestsuites, "time", FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); OutputXmlAttribute( stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); if (GTEST_FLAG_GET(shuffle)) { OutputXmlAttribute(stream, kTestsuites, "random_seed", StreamableToString(unit_test.random_seed())); } *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i)); } if (unit_test.ad_hoc_test_result().Failed()) { OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); } *stream << "</" << kTestsuites << ">\n"; } void XmlUnitTestResultPrinter::PrintXmlTestsList( std::ostream* stream, const std::vector<TestSuite*>& test_suites) { const std::string kTestsuites = "testsuites"; *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; *stream << "<" << kTestsuites; int total_tests = 0; for (auto test_suite : test_suites) { total_tests += test_suite->total_test_count(); } OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(total_tests)); OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; for (auto test_suite : test_suites) { PrintXmlTestSuite(stream, *test_suite); } *stream << "</" << kTestsuites << ">\n"; } std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( const TestResult& result) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << " " << property.key() << "=" << "\"" << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } void XmlUnitTestResultPrinter::OutputXmlTestProperties( std::ostream* stream, const TestResult& result) { const std::string kProperties = "properties"; const std::string kProperty = "property"; if (result.test_property_count() <= 0) { return; } *stream << " <" << kProperties << ">\n"; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); *stream << " <" << kProperty; *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\""; *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\""; *stream << "/>\n"; } *stream << " </" << kProperties << ">\n"; } #endif #if GTEST_HAS_FILE_SYSTEM class JsonUnitTestResultPrinter : public EmptyTestEventListener { public: explicit JsonUnitTestResultPrinter(const char* output_file); void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; static void PrintJsonTestList(::std::ostream* stream, const std::vector<TestSuite*>& test_suites); private: static std::string EscapeJson(const std::string& str); static void OutputJsonKey(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value, const std::string& indent, bool comma = true); static void OutputJsonKey(std::ostream* stream, const std::string& element_name, const std::string& name, int value, const std::string& indent, bool comma = true); static void OutputJsonTestSuiteForTestResult(::std::ostream* stream, const TestResult& result); static void OutputJsonTestResult(::std::ostream* stream, const TestResult& result); static void OutputJsonTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info); static void PrintJsonTestSuite(::std::ostream* stream, const TestSuite& test_suite); static void PrintJsonUnitTest(::std::ostream* stream, const UnitTest& unit_test); static std::string TestPropertiesAsJson(const TestResult& result, const std::string& indent); const std::string output_file_; JsonUnitTestResultPrinter(const JsonUnitTestResultPrinter&) = delete; JsonUnitTestResultPrinter& operator=(const JsonUnitTestResultPrinter&) = delete; }; JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.empty()) { GTEST_LOG_(FATAL) << "JSON output file may not be null"; } } void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int ) { FILE* jsonout = OpenFileForWriting(output_file_); std::stringstream stream; PrintJsonUnitTest(&stream, unit_test); fprintf(jsonout, "%s", StringStreamToString(&stream).c_str()); fclose(jsonout); } std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) { Message m; for (size_t i = 0; i < str.size(); ++i) { const char ch = str[i]; switch (ch) { case '\\': case '"': case '/': m << '\\' << ch; break; case '\b': m << "\\b"; break; case '\t': m << "\\t"; break; case '\n': m << "\\n"; break; case '\f': m << "\\f"; break; case '\r': m << "\\r"; break; default: if (ch < ' ') { m << "\\u00" << String::FormatByte(static_cast<unsigned char>(ch)); } else { m << ch; } break; } } return m.GetString(); } static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) { ::std::stringstream ss; ss << (static_cast<double>(ms) * 1e-3) << "s"; return ss.str(); } static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { struct tm time_struct; if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) return ""; return StreamableToString(time_struct.tm_year + 1900) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_sec) + "Z"; } static inline std::string Indent(size_t width) { return std::string(width, ' '); } void JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value, const std::string& indent, bool comma) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Key \"" << name << "\" is not allowed for value \"" << element_name << "\"."; *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\""; if (comma) *stream << ",\n"; } void JsonUnitTestResultPrinter::OutputJsonKey( std::ostream* stream, const std::string& element_name, const std::string& name, int value, const std::string& indent, bool comma) { const std::vector<std::string>& allowed_names = GetReservedOutputAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Key \"" << name << "\" is not allowed for value \"" << element_name << "\"."; *stream << indent << "\"" << name << "\": " << StreamableToString(value); if (comma) *stream << ",\n"; } void JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult( ::std::ostream* stream, const TestResult& result) { *stream << Indent(4) << "{\n"; OutputJsonKey(stream, "testsuite", "name", "NonTestSuiteFailure", Indent(6)); OutputJsonKey(stream, "testsuite", "tests", 1, Indent(6)); if (!GTEST_FLAG_GET(list_tests)) { OutputJsonKey(stream, "testsuite", "failures", 1, Indent(6)); OutputJsonKey(stream, "testsuite", "disabled", 0, Indent(6)); OutputJsonKey(stream, "testsuite", "skipped", 0, Indent(6)); OutputJsonKey(stream, "testsuite", "errors", 0, Indent(6)); OutputJsonKey(stream, "testsuite", "time", FormatTimeInMillisAsDuration(result.elapsed_time()), Indent(6)); OutputJsonKey(stream, "testsuite", "timestamp", FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()), Indent(6)); } *stream << Indent(6) << "\"testsuite\": [\n"; *stream << Indent(8) << "{\n"; OutputJsonKey(stream, "testcase", "name", "", Indent(10)); OutputJsonKey(stream, "testcase", "status", "RUN", Indent(10)); OutputJsonKey(stream, "testcase", "result", "COMPLETED", Indent(10)); OutputJsonKey(stream, "testcase", "timestamp", FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()), Indent(10)); OutputJsonKey(stream, "testcase", "time", FormatTimeInMillisAsDuration(result.elapsed_time()), Indent(10)); OutputJsonKey(stream, "testcase", "classname", "", Indent(10), false); *stream << TestPropertiesAsJson(result, Indent(10)); OutputJsonTestResult(stream, result); *stream << "\n" << Indent(6) << "]\n" << Indent(4) << "}"; } void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, const char* test_suite_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); const std::string kTestsuite = "testcase"; const std::string kIndent = Indent(10); *stream << Indent(8) << "{\n"; OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent); if (test_info.value_param() != nullptr) { OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(), kIndent); } if (test_info.type_param() != nullptr) { OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), kIndent); } OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); if (GTEST_FLAG_GET(list_tests)) { *stream << "\n" << Indent(8) << "}"; return; } else { *stream << ",\n"; } OutputJsonKey(stream, kTestsuite, "status", test_info.should_run() ? "RUN" : "NOTRUN", kIndent); OutputJsonKey(stream, kTestsuite, "result", test_info.should_run() ? (result.Skipped() ? "SKIPPED" : "COMPLETED") : "SUPPRESSED", kIndent); OutputJsonKey(stream, kTestsuite, "timestamp", FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()), kIndent); OutputJsonKey(stream, kTestsuite, "time", FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent); OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent, false); *stream << TestPropertiesAsJson(result, kIndent); OutputJsonTestResult(stream, result); } void JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream, const TestResult& result) { const std::string kIndent = Indent(10); { int failures = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.failed()) { *stream << ",\n"; if (++failures == 1) { *stream << kIndent << "\"" << "failures" << "\": [\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string message = EscapeJson(location + "\n" + part.message()); *stream << kIndent << " {\n" << kIndent << " \"failure\": \"" << message << "\",\n" << kIndent << " \"type\": \"\"\n" << kIndent << " }"; } } if (failures > 0) *stream << "\n" << kIndent << "]"; } { int skipped = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.skipped()) { *stream << ",\n"; if (++skipped == 1) { *stream << kIndent << "\"" << "skipped" << "\": [\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string message = EscapeJson(location + "\n" + part.message()); *stream << kIndent << " {\n" << kIndent << " \"message\": \"" << message << "\"\n" << kIndent << " }"; } } if (skipped > 0) *stream << "\n" << kIndent << "]"; } *stream << "\n" << Indent(8) << "}"; } void JsonUnitTestResultPrinter::PrintJsonTestSuite( std::ostream* stream, const TestSuite& test_suite) { const std::string kTestsuite = "testsuite"; const std::string kIndent = Indent(6); *stream << Indent(4) << "{\n"; OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent); OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(), kIndent); if (!GTEST_FLAG_GET(list_tests)) { OutputJsonKey(stream, kTestsuite, "failures", test_suite.failed_test_count(), kIndent); OutputJsonKey(stream, kTestsuite, "disabled", test_suite.reportable_disabled_test_count(), kIndent); OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent); OutputJsonKey( stream, kTestsuite, "timestamp", FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()), kIndent); OutputJsonKey(stream, kTestsuite, "time", FormatTimeInMillisAsDuration(test_suite.elapsed_time()), kIndent, false); *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent) << ",\n"; } *stream << kIndent << "\"" << kTestsuite << "\": [\n"; bool comma = false; for (int i = 0; i < test_suite.total_test_count(); ++i) { if (test_suite.GetTestInfo(i)->is_reportable()) { if (comma) { *stream << ",\n"; } else { comma = true; } OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); } } *stream << "\n" << kIndent << "]\n" << Indent(4) << "}"; } void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, const UnitTest& unit_test) { const std::string kTestsuites = "testsuites"; const std::string kIndent = Indent(2); *stream << "{\n"; OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(), kIndent); OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(), kIndent); OutputJsonKey(stream, kTestsuites, "disabled", unit_test.reportable_disabled_test_count(), kIndent); OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent); if (GTEST_FLAG_GET(shuffle)) { OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(), kIndent); } OutputJsonKey(stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()), kIndent); OutputJsonKey(stream, kTestsuites, "time", FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent, false); *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent) << ",\n"; OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); *stream << kIndent << "\"" << kTestsuites << "\": [\n"; bool comma = false; for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) { if (comma) { *stream << ",\n"; } else { comma = true; } PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i)); } } if (unit_test.ad_hoc_test_result().Failed()) { if (comma) { *stream << ",\n"; } OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result()); } *stream << "\n" << kIndent << "]\n" << "}\n"; } void JsonUnitTestResultPrinter::PrintJsonTestList( std::ostream* stream, const std::vector<TestSuite*>& test_suites) { const std::string kTestsuites = "testsuites"; const std::string kIndent = Indent(2); *stream << "{\n"; int total_tests = 0; for (auto test_suite : test_suites) { total_tests += test_suite->total_test_count(); } OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent); OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); *stream << kIndent << "\"" << kTestsuites << "\": [\n"; for (size_t i = 0; i < test_suites.size(); ++i) { if (i != 0) { *stream << ",\n"; } PrintJsonTestSuite(stream, *test_suites[i]); } *stream << "\n" << kIndent << "]\n" << "}\n"; } std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( const TestResult& result, const std::string& indent) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << ",\n" << indent << "\"" << property.key() << "\": " << "\"" << EscapeJson(property.value()) << "\""; } return attributes.GetString(); } #endif #if GTEST_CAN_STREAM_RESULTS_ std::string StreamingListener::UrlEncode(const char* str) { std::string result; result.reserve(strlen(str) + 1); for (char ch = *str; ch != '\0'; ch = *++str) { switch (ch) { case '%': case '=': case '&': case '\n': result.push_back('%'); result.append(String::FormatByte(static_cast<unsigned char>(ch))); break; default: result.push_back(ch); break; } } return result; } void StreamingListener::SocketWriter::MakeConnection() { GTEST_CHECK_(sockfd_ == -1) << "MakeConnection() can't be called when there is already a connection."; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; addrinfo* servinfo = nullptr; const int error_num = getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); if (error_num != 0) { GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " << gai_strerror(error_num); } for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr; cur_addr = cur_addr->ai_next) { sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); if (sockfd_ != -1) { if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { close(sockfd_); sockfd_ = -1; } } } freeaddrinfo(servinfo); if (sockfd_ == -1) { GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " << host_name_ << ":" << port_num_; } } #endif const char* const OsStackTraceGetterInterface::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) GTEST_LOCK_EXCLUDED_(mutex_) { #ifdef GTEST_HAS_ABSL std::string result; if (max_depth <= 0) { return result; } max_depth = std::min(max_depth, kMaxStackTraceDepth); std::vector<void*> raw_stack(max_depth); const int raw_stack_size = absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1); void* caller_frame = nullptr; { MutexLock lock(&mutex_); caller_frame = caller_frame_; } for (int i = 0; i < raw_stack_size; ++i) { if (raw_stack[i] == caller_frame && !GTEST_FLAG_GET(show_internal_stack_frames)) { absl::StrAppend(&result, kElidedFramesMarker, "\n"); break; } char tmp[1024]; const char* symbol = "(unknown)"; if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) { symbol = tmp; } char line[1024]; snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol); result += line; } return result; #else static_cast<void>(max_depth); static_cast<void>(skip_count); return ""; #endif } void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { #ifdef GTEST_HAS_ABSL void* caller_frame = nullptr; if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) { caller_frame = nullptr; } MutexLock lock(&mutex_); caller_frame_ = caller_frame; #endif } #ifdef GTEST_HAS_DEATH_TEST class ScopedPrematureExitFile { public: explicit ScopedPrematureExitFile(const char* premature_exit_filepath) : premature_exit_filepath_( premature_exit_filepath ? premature_exit_filepath : "") { if (!premature_exit_filepath_.empty()) { FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w"); fwrite("0", 1, 1, pfile); fclose(pfile); } } ~ScopedPrematureExitFile() { #ifndef GTEST_OS_ESP8266 if (!premature_exit_filepath_.empty()) { int retval = remove(premature_exit_filepath_.c_str()); if (retval) { GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \"" << premature_exit_filepath_ << "\" with error " << retval; } } #endif } private: const std::string premature_exit_filepath_; ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete; ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete; }; #endif } TestEventListeners::TestEventListeners() : repeater_(new internal::TestEventRepeater()), default_result_printer_(nullptr), default_xml_generator_(nullptr) {} TestEventListeners::~TestEventListeners() { delete repeater_; } void TestEventListeners::Append(TestEventListener* listener) { repeater_->Append(listener); } TestEventListener* TestEventListeners::Release(TestEventListener* listener) { if (listener == default_result_printer_) default_result_printer_ = nullptr; else if (listener == default_xml_generator_) default_xml_generator_ = nullptr; return repeater_->Release(listener); } TestEventListener* TestEventListeners::repeater() { return repeater_; } void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { if (default_result_printer_ != listener) { delete Release(default_result_printer_); default_result_printer_ = listener; if (listener != nullptr) Append(listener); } } void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { if (default_xml_generator_ != listener) { delete Release(default_xml_generator_); default_xml_generator_ = listener; if (listener != nullptr) Append(listener); } } bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } void TestEventListeners::SuppressEventForwarding(bool suppress) { repeater_->set_forwarding_enabled(!suppress); } UnitTest* UnitTest::GetInstance() { #if defined(__BORLANDC__) static UnitTest* const instance = new UnitTest; return instance; #else static UnitTest instance; return &instance; #endif } int UnitTest::successful_test_suite_count() const { return impl()->successful_test_suite_count(); } int UnitTest::failed_test_suite_count() const { return impl()->failed_test_suite_count(); } int UnitTest::total_test_suite_count() const { return impl()->total_test_suite_count(); } int UnitTest::test_suite_to_run_count() const { return impl()->test_suite_to_run_count(); } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ int UnitTest::successful_test_case_count() const { return impl()->successful_test_suite_count(); } int UnitTest::failed_test_case_count() const { return impl()->failed_test_suite_count(); } int UnitTest::total_test_case_count() const { return impl()->total_test_suite_count(); } int UnitTest::test_case_to_run_count() const { return impl()->test_suite_to_run_count(); } #endif int UnitTest::successful_test_count() const { return impl()->successful_test_count(); } int UnitTest::skipped_test_count() const { return impl()->skipped_test_count(); } int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } int UnitTest::reportable_disabled_test_count() const { return impl()->reportable_disabled_test_count(); } int UnitTest::disabled_test_count() const { return impl()->disabled_test_count(); } int UnitTest::reportable_test_count() const { return impl()->reportable_test_count(); } int UnitTest::total_test_count() const { return impl()->total_test_count(); } int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } internal::TimeInMillis UnitTest::start_timestamp() const { return impl()->start_timestamp(); } internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } bool UnitTest::Passed() const { return impl()->Passed(); } bool UnitTest::Failed() const { return impl()->Failed(); } const TestSuite* UnitTest::GetTestSuite(int i) const { return impl()->GetTestSuite(i); } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } #endif const TestResult& UnitTest::ad_hoc_test_result() const { return *impl()->ad_hoc_test_result(); } TestSuite* UnitTest::GetMutableTestSuite(int i) { return impl()->GetMutableSuiteCase(i); } void UnitTest::UponLeavingGTest() { impl()->os_stack_trace_getter()->UponLeavingGTest(); } void UnitTest::set_current_test_suite(TestSuite* a_current_test_suite) { internal::MutexLock lock(&mutex_); impl_->set_current_test_suite(a_current_test_suite); } void UnitTest::set_current_test_info(TestInfo* a_current_test_info) { internal::MutexLock lock(&mutex_); impl_->set_current_test_info(a_current_test_info); } TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } Environment* UnitTest::AddEnvironment(Environment* env) { if (env == nullptr) { return nullptr; } impl_->environments().push_back(env); return env; } void UnitTest::AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; internal::MutexLock lock(&mutex_); if (!impl_->gtest_trace_stack().empty()) { msg << "\n" << GTEST_NAME_ << " trace:"; for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) << " " << trace.message; } } if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) { msg << internal::kStackTraceMarker << os_stack_trace; } else { msg << "\n"; } const TestPartResult result = TestPartResult( result_type, file_name, line_number, msg.GetString().c_str()); impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult( result); if (result_type != TestPartResult::kSuccess && result_type != TestPartResult::kSkip) { if (GTEST_FLAG_GET(break_on_failure)) { #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_PHONE) && \ !defined(GTEST_OS_WINDOWS_RT) DebugBreak(); #elif (!defined(__native_client__)) && \ ((defined(__clang__) || defined(__GNUC__)) && \ (defined(__x86_64__) || defined(__i386__))) asm("int3"); #elif GTEST_HAS_BUILTIN(__builtin_trap) __builtin_trap(); #elif defined(SIGTRAP) raise(SIGTRAP); #else *static_cast<volatile int*>(nullptr) = 1; #endif } else if (GTEST_FLAG_GET(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS throw internal::GoogleTestFailureException(result); #else exit(1); #endif } } } void UnitTest::RecordProperty(const std::string& key, const std::string& value) { impl_->RecordProperty(TestProperty(key, value)); } int UnitTest::Run() { #ifdef GTEST_HAS_DEATH_TEST const bool in_death_test_child_process = !GTEST_FLAG_GET(internal_run_death_test).empty(); const internal::ScopedPrematureExitFile premature_exit_file( in_death_test_child_process ? nullptr : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); #else const bool in_death_test_child_process = false; #endif impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions)); #ifdef GTEST_OS_WINDOWS if (impl()->catch_exceptions() || in_death_test_child_process) { #if !defined(GTEST_OS_WINDOWS_MOBILE) && !defined(GTEST_OS_WINDOWS_PHONE) && \ !defined(GTEST_OS_WINDOWS_RT) && !defined(GTEST_OS_WINDOWS_GAMES) SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #endif #if (defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW)) && \ !defined(GTEST_OS_WINDOWS_MOBILE) _set_error_mode(_OUT_TO_STDERR); #endif #if defined(_MSC_VER) && !defined(GTEST_OS_WINDOWS_MOBILE) if (!GTEST_FLAG_GET(break_on_failure)) _set_abort_behavior( 0x0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); if (!IsDebuggerPresent()) { (void)_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); } #endif } #else (void)in_death_test_child_process; #endif return internal::HandleExceptionsInMethodIfSupported( impl(), &internal::UnitTestImpl::RunAllTests, "auxiliary test code (environments or event listeners)") ? 0 : 1; } #if GTEST_HAS_FILE_SYSTEM const char* UnitTest::original_working_dir() const { return impl_->original_working_dir_.c_str(); } #endif const TestSuite* UnitTest::current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_suite(); } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ const TestCase* UnitTest::current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_suite(); } #endif const TestInfo* UnitTest::current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_info(); } int UnitTest::random_seed() const { return impl_->random_seed(); } internal::ParameterizedTestSuiteRegistry& UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { return impl_->parameterized_test_registry(); } UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); } UnitTest::~UnitTest() { delete impl_; } void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().push_back(trace); } void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : parent_(parent), GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 ) default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_reporter_( &default_global_test_part_result_reporter_), per_thread_test_part_result_reporter_( &default_per_thread_test_part_result_reporter_), parameterized_test_registry_(), parameterized_tests_registered_(false), last_death_test_suite_(-1), current_test_suite_(nullptr), current_test_info_(nullptr), ad_hoc_test_result_(), os_stack_trace_getter_(nullptr), post_flag_parse_init_performed_(false), random_seed_(0), random_(0), start_timestamp_(0), elapsed_time_(0), #ifdef GTEST_HAS_DEATH_TEST death_test_factory_(new DefaultDeathTestFactory), #endif catch_exceptions_(false) { listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); } UnitTestImpl::~UnitTestImpl() { ForEach(test_suites_, internal::Delete<TestSuite>); ForEach(environments_, internal::Delete<Environment>); delete os_stack_trace_getter_; } void UnitTestImpl::RecordProperty(const TestProperty& test_property) { std::string xml_element; TestResult* test_result; if (current_test_info_ != nullptr) { xml_element = "testcase"; test_result = &(current_test_info_->result_); } else if (current_test_suite_ != nullptr) { xml_element = "testsuite"; test_result = &(current_test_suite_->ad_hoc_test_result_); } else { xml_element = "testsuites"; test_result = &ad_hoc_test_result_; } test_result->RecordProperty(xml_element, test_property); } #ifdef GTEST_HAS_DEATH_TEST void UnitTestImpl::SuppressTestEventsIfInSubprocess() { if (internal_run_death_test_flag_ != nullptr) listeners()->SuppressEventForwarding(true); } #endif void UnitTestImpl::ConfigureXmlOutput() { const std::string& output_format = UnitTestOptions::GetOutputFormat(); #if GTEST_HAS_FILE_SYSTEM if (output_format == "xml") { listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (output_format == "json") { listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (!output_format.empty()) { GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \"" << output_format << "\" ignored."; } #else if (!output_format.empty()) { GTEST_LOG_(ERROR) << "ERROR: alternative output formats require " << "GTEST_HAS_FILE_SYSTEM to be enabled"; } #endif } #if GTEST_CAN_STREAM_RESULTS_ void UnitTestImpl::ConfigureStreamingOutput() { const std::string& target = GTEST_FLAG_GET(stream_result_to); if (!target.empty()) { const size_t pos = target.find(':'); if (pos != std::string::npos) { listeners()->Append( new StreamingListener(target.substr(0, pos), target.substr(pos + 1))); } else { GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target << "\" ignored."; } } } #endif void UnitTestImpl::PostFlagParsingInit() { if (!post_flag_parse_init_performed_) { post_flag_parse_init_performed_ = true; #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); #endif #ifdef GTEST_HAS_DEATH_TEST InitDeathTestSubprocessControlInfo(); SuppressTestEventsIfInSubprocess(); #endif RegisterParameterizedTests(); ConfigureXmlOutput(); if (GTEST_FLAG_GET(brief)) { listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter); } #if GTEST_CAN_STREAM_RESULTS_ ConfigureStreamingOutput(); #endif #ifdef GTEST_HAS_ABSL if (GTEST_FLAG_GET(install_failure_signal_handler)) { absl::FailureSignalHandlerOptions options; absl::InstallFailureSignalHandler(options); } #endif } } TestSuite* UnitTestImpl::GetTestSuite( const std::string& test_suite_name, const char* type_param, internal::SetUpTestSuiteFunc set_up_tc, internal::TearDownTestSuiteFunc tear_down_tc) { if (!test_suites_.empty() && (*test_suites_.rbegin())->name_ == test_suite_name) { return *test_suites_.rbegin(); } auto item_it = test_suites_by_name_.find(test_suite_name); if (item_it != test_suites_by_name_.end()) { return item_it->second; } auto* const new_test_suite = new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc); test_suites_by_name_.emplace(test_suite_name, new_test_suite); const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter); if (death_test_suite_filter.MatchesName(test_suite_name)) { ++last_death_test_suite_; test_suites_.insert(test_suites_.begin() + last_death_test_suite_, new_test_suite); } else { test_suites_.push_back(new_test_suite); } test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size())); return new_test_suite; } static void SetUpEnvironment(Environment* env) { env->SetUp(); } static void TearDownEnvironment(Environment* env) { env->TearDown(); } bool UnitTestImpl::RunAllTests() { const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); if (g_help_flag) return true; PostFlagParsingInit(); #if GTEST_HAS_FILE_SYSTEM internal::WriteToShardStatusFileIfNeeded(); #endif bool in_subprocess_for_death_test = false; #ifdef GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_ != nullptr); #if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); } #endif #endif const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, in_subprocess_for_death_test); const bool has_tests_to_run = FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL : IGNORE_SHARDING_PROTOCOL) > 0; if (GTEST_FLAG_GET(list_tests)) { ListTestsMatchingFilter(); return true; } random_seed_ = GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed)); bool failed = false; TestEventListener* repeater = listeners()->repeater(); start_timestamp_ = GetTimeInMillis(); repeater->OnTestProgramStart(*parent_); const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat); const bool gtest_repeat_forever = repeat < 0; const bool recreate_environments_when_repeating = GTEST_FLAG_GET(recreate_environments_when_repeating) || gtest_repeat_forever; for (int i = 0; gtest_repeat_forever || i != repeat; i++) { ClearNonAdHocTestResult(); Timer timer; if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) { random()->Reseed(static_cast<uint32_t>(random_seed_)); ShuffleTests(); } repeater->OnTestIterationStart(*parent_, i); if (has_tests_to_run) { if (i == 0 || recreate_environments_when_repeating) { repeater->OnEnvironmentsSetUpStart(*parent_); ForEach(environments_, SetUpEnvironment); repeater->OnEnvironmentsSetUpEnd(*parent_); } if (Test::IsSkipped()) { TestResult& test_result = *internal::GetUnitTestImpl()->current_test_result(); for (int j = 0; j < test_result.total_part_count(); ++j) { const TestPartResult& test_part_result = test_result.GetTestPartResult(j); if (test_part_result.type() == TestPartResult::kSkip) { const std::string& result = test_part_result.message(); printf("%s\n", result.c_str()); } } fflush(stdout); } else if (!Test::HasFatalFailure()) { for (int test_index = 0; test_index < total_test_suite_count(); test_index++) { GetMutableSuiteCase(test_index)->Run(); if (GTEST_FLAG_GET(fail_fast) && GetMutableSuiteCase(test_index)->Failed()) { for (int j = test_index + 1; j < total_test_suite_count(); j++) { GetMutableSuiteCase(j)->Skip(); } break; } } } else if (Test::HasFatalFailure()) { for (int test_index = 0; test_index < total_test_suite_count(); test_index++) { GetMutableSuiteCase(test_index)->Skip(); } } if (i == repeat - 1 || recreate_environments_when_repeating) { repeater->OnEnvironmentsTearDownStart(*parent_); std::for_each(environments_.rbegin(), environments_.rend(), TearDownEnvironment); repeater->OnEnvironmentsTearDownEnd(*parent_); } } elapsed_time_ = timer.Elapsed(); repeater->OnTestIterationEnd(*parent_, i); if (!Passed()) { failed = true; } UnshuffleTests(); if (GTEST_FLAG_GET(shuffle)) { random_seed_ = GetNextRandomSeed(random_seed_); } } repeater->OnTestProgramEnd(*parent_); bool delete_environment_on_teardown = true; if (delete_environment_on_teardown) { ForEach(environments_, internal::Delete<Environment>); environments_.clear(); } if (!gtest_is_initialized_before_run_all_tests) { ColoredPrintf( GTestColor::kRed, "\nIMPORTANT NOTICE - DO NOT IGNORE:\n" "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_ "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_ " will start to enforce the valid usage. " "Please fix it ASAP, or IT WILL START TO FAIL.\n"); } return !failed; } #if GTEST_HAS_FILE_SYSTEM void WriteToShardStatusFileIfNeeded() { const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); if (test_shard_file != nullptr) { FILE* const file = posix::FOpen(test_shard_file, "w"); if (file == nullptr) { ColoredPrintf(GTestColor::kRed, "Could not write to the test shard status file \"%s\" " "specified by the %s environment variable.\n", test_shard_file, kTestShardStatusFile); fflush(stdout); exit(EXIT_FAILURE); } fclose(file); } } #endif bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; } const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1); const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1); if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards << " unset.\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards << " = " << total_shards << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { const Message msg = Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < " << kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(GTestColor::kRed, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } return total_shards > 1; } int32_t Int32FromEnvOrDie(const char* var, int32_t default_val) { const char* str_val = posix::GetEnv(var); if (str_val == nullptr) { return default_val; } int32_t result; if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); } return result; } bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { return (test_id % total_shards) == shard_index; } int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestTotalShards, -1) : -1; const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestShardIndex, -1) : -1; const PositiveAndNegativeUnitTestFilter gtest_flag_filter( GTEST_FLAG_GET(filter)); const UnitTestFilter disable_test_filter(kDisableTestFilter); int num_runnable_tests = 0; int num_selected_tests = 0; for (auto* test_suite : test_suites_) { const std::string& test_suite_name = test_suite->name_; test_suite->set_should_run(false); for (TestInfo* test_info : test_suite->test_info_list()) { const std::string& test_name = test_info->name_; const bool is_disabled = disable_test_filter.MatchesName(test_suite_name) || disable_test_filter.MatchesName(test_name); test_info->is_disabled_ = is_disabled; const bool matches_filter = gtest_flag_filter.MatchesTest(test_suite_name, test_name); test_info->matches_filter_ = matches_filter; const bool is_runnable = (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) && matches_filter; const bool is_in_another_shard = shard_tests != IGNORE_SHARDING_PROTOCOL && !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests); test_info->is_in_another_shard_ = is_in_another_shard; const bool is_selected = is_runnable && !is_in_another_shard; num_runnable_tests += is_runnable; num_selected_tests += is_selected; test_info->should_run_ = is_selected; test_suite->set_should_run(test_suite->should_run() || is_selected); } } return num_selected_tests; } static void PrintOnOneLine(const char* str, int max_length) { if (str != nullptr) { for (int i = 0; *str != '\0'; ++str) { if (i >= max_length) { printf("..."); break; } if (*str == '\n') { printf("\\n"); i += 2; } else { printf("%c", *str); ++i; } } } } void UnitTestImpl::ListTestsMatchingFilter() { const int kMaxParamLength = 250; for (auto* test_suite : test_suites_) { bool printed_test_suite_name = false; for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { const TestInfo* const test_info = test_suite->test_info_list()[j]; if (test_info->matches_filter_) { if (!printed_test_suite_name) { printed_test_suite_name = true; printf("%s.", test_suite->name()); if (test_suite->type_param() != nullptr) { printf(" # %s = ", kTypeParamLabel); PrintOnOneLine(test_suite->type_param(), kMaxParamLength); } printf("\n"); } printf(" %s", test_info->name()); if (test_info->value_param() != nullptr) { printf(" # %s = ", kValueParamLabel); PrintOnOneLine(test_info->value_param(), kMaxParamLength); } printf("\n"); } } } fflush(stdout); #if GTEST_HAS_FILE_SYSTEM const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml" || output_format == "json") { FILE* fileout = OpenFileForWriting(UnitTestOptions::GetAbsolutePathToOutputFile()); std::stringstream stream; if (output_format == "xml") { XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) .PrintXmlTestsList(&stream, test_suites_); } else if (output_format == "json") { JsonUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) .PrintJsonTestList(&stream, test_suites_); } fprintf(fileout, "%s", StringStreamToString(&stream).c_str()); fclose(fileout); } #endif } void UnitTestImpl::set_os_stack_trace_getter( OsStackTraceGetterInterface* getter) { if (os_stack_trace_getter_ != getter) { delete os_stack_trace_getter_; os_stack_trace_getter_ = getter; } } OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { if (os_stack_trace_getter_ == nullptr) { #ifdef GTEST_OS_STACK_TRACE_GETTER_ os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; #else os_stack_trace_getter_ = new OsStackTraceGetter; #endif } return os_stack_trace_getter_; } TestResult* UnitTestImpl::current_test_result() { if (current_test_info_ != nullptr) { return &current_test_info_->result_; } if (current_test_suite_ != nullptr) { return &current_test_suite_->ad_hoc_test_result_; } return &ad_hoc_test_result_; } void UnitTestImpl::ShuffleTests() { ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_); ShuffleRange(random(), last_death_test_suite_ + 1, static_cast<int>(test_suites_.size()), &test_suite_indices_); for (auto& test_suite : test_suites_) { test_suite->ShuffleTests(random()); } } void UnitTestImpl::UnshuffleTests() { for (size_t i = 0; i < test_suites_.size(); i++) { test_suites_[i]->UnshuffleTests(); test_suite_indices_[i] = static_cast<int>(i); } } GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string GetCurrentOsStackTraceExceptTop(int skip_count) { return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); } namespace { class ClassUniqueToAlwaysTrue {}; } bool IsTrue(bool condition) { return condition; } bool AlwaysTrue() { #if GTEST_HAS_EXCEPTIONS if (IsTrue(false)) throw ClassUniqueToAlwaysTrue(); #endif return true; } bool SkipPrefix(const char* prefix, const char** pstr) { const size_t prefix_len = strlen(prefix); if (strncmp(*pstr, prefix, prefix_len) == 0) { *pstr += prefix_len; return true; } return false; } static const char* ParseFlagValue(const char* str, const char* flag_name, bool def_optional) { if (str == nullptr || flag_name == nullptr) return nullptr; const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag_name; const size_t flag_len = flag_str.length(); if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; const char* flag_end = str + flag_len; if (def_optional && (flag_end[0] == '\0')) { return flag_end; } if (flag_end[0] != '=') return nullptr; return flag_end + 1; } static bool ParseFlag(const char* str, const char* flag_name, bool* value) { const char* const value_str = ParseFlagValue(str, flag_name, true); if (value_str == nullptr) return false; *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } bool ParseFlag(const char* str, const char* flag_name, int32_t* value) { const char* const value_str = ParseFlagValue(str, flag_name, false); if (value_str == nullptr) return false; return ParseInt32(Message() << "The value of flag --" << flag_name, value_str, value); } template <typename String> static bool ParseFlag(const char* str, const char* flag_name, String* value) { const char* const value_str = ParseFlagValue(str, flag_name, false); if (value_str == nullptr) return false; *value = value_str; return true; } static bool HasGoogleTestFlagPrefix(const char* str) { return (SkipPrefix("--", &str) || SkipPrefix("-", &str) || SkipPrefix("/", &str)) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); } static void PrintColorEncoded(const char* str) { GTestColor color = GTestColor::kDefault; for (;;) { const char* p = strchr(str, '@'); if (p == nullptr) { ColoredPrintf(color, "%s", str); return; } ColoredPrintf(color, "%s", std::string(str, p).c_str()); const char ch = p[1]; str = p + 2; if (ch == '@') { ColoredPrintf(color, "@"); } else if (ch == 'D') { color = GTestColor::kDefault; } else if (ch == 'R') { color = GTestColor::kRed; } else if (ch == 'G') { color = GTestColor::kGreen; } else if (ch == 'Y') { color = GTestColor::kYellow; } else { --str; } } } static const char kColorEncodedHelpMessage[] = "This program contains tests written using " GTEST_NAME_ ". You can use the\n" "following command line flags to control its behavior:\n" "\n" "Test Selection:\n" " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" " List the names of all tests instead of running them. The name of\n" " TEST(Foo, Bar) is \"Foo.Bar\".\n" " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSITIVE_PATTERNS" "[@G-@YNEGATIVE_PATTERNS]@D\n" " Run only the tests whose name matches one of the positive patterns " "but\n" " none of the negative patterns. '?' matches any single character; " "'*'\n" " matches any substring; ':' separates two patterns.\n" " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" " Run all disabled tests too.\n" "\n" "Test Execution:\n" " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" " Run the tests repeatedly; use a negative count to repeat forever.\n" " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" " Randomize tests' orders on every iteration.\n" " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" " Random number seed to use for shuffling test orders (between 1 and\n" " 99999, or 0 to use a seed based on the current time).\n" " @G--" GTEST_FLAG_PREFIX_ "recreate_environments_when_repeating@D\n" " Sets up and tears down the global test environment on each repeat\n" " of the test.\n" "\n" "Test Output:\n" " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" " Enable/disable colored output. The default is @Gauto@D.\n" " @G--" GTEST_FLAG_PREFIX_ "brief=1@D\n" " Only print test failures.\n" " @G--" GTEST_FLAG_PREFIX_ "print_time=0@D\n" " Don't print the elapsed time of each test.\n" " @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" " Generate a JSON or XML report in the given directory or with the " "given\n" " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" #if GTEST_CAN_STREAM_RESULTS_ " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " Stream test results to the given server.\n" #endif "\n" "Assertion Behavior:\n" #if defined(GTEST_HAS_DEATH_TEST) && !defined(GTEST_OS_WINDOWS) " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" #endif " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " Turn assertion failures into debugger break-points.\n" " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" " Turn assertion failures into C++ exceptions for use by an external\n" " test framework.\n" " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" " Do not report exceptions as test failures. Instead, allow them\n" " to crash the program or throw a pop-up (on Windows).\n" "\n" "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " "the corresponding\n" "environment variable of a flag (all letters in upper-case). For example, " "to\n" "disable colored text output, you can either specify " "@G--" GTEST_FLAG_PREFIX_ "color=no@D or set\n" "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" "\n" "For more information, please read the " GTEST_NAME_ " documentation at\n" "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" "(not one in your own code or tests), please report it to\n" "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; static bool ParseGoogleTestFlag(const char* const arg) { #define GTEST_INTERNAL_PARSE_FLAG(flag_name) \ do { \ auto value = GTEST_FLAG_GET(flag_name); \ if (ParseFlag(arg, #flag_name, &value)) { \ GTEST_FLAG_SET(flag_name, value); \ return true; \ } \ } while (false) GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests); GTEST_INTERNAL_PARSE_FLAG(break_on_failure); GTEST_INTERNAL_PARSE_FLAG(catch_exceptions); GTEST_INTERNAL_PARSE_FLAG(color); GTEST_INTERNAL_PARSE_FLAG(death_test_style); GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork); GTEST_INTERNAL_PARSE_FLAG(fail_fast); GTEST_INTERNAL_PARSE_FLAG(filter); GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test); GTEST_INTERNAL_PARSE_FLAG(list_tests); GTEST_INTERNAL_PARSE_FLAG(output); GTEST_INTERNAL_PARSE_FLAG(brief); GTEST_INTERNAL_PARSE_FLAG(print_time); GTEST_INTERNAL_PARSE_FLAG(print_utf8); GTEST_INTERNAL_PARSE_FLAG(random_seed); GTEST_INTERNAL_PARSE_FLAG(repeat); GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating); GTEST_INTERNAL_PARSE_FLAG(shuffle); GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth); GTEST_INTERNAL_PARSE_FLAG(stream_result_to); GTEST_INTERNAL_PARSE_FLAG(throw_on_failure); return false; } #if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM static void LoadFlagsFromFile(const std::string& path) { FILE* flagfile = posix::FOpen(path.c_str(), "r"); if (!flagfile) { GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG_GET(flagfile) << "\""; } std::string contents(ReadEntireFile(flagfile)); posix::FClose(flagfile); std::vector<std::string> lines; SplitString(contents, '\n', &lines); for (size_t i = 0; i < lines.size(); ++i) { if (lines[i].empty()) continue; if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true; } } #endif template <typename CharType> void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { std::string flagfile_value; for (int i = 1; i < *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); using internal::ParseFlag; bool remove_flag = false; if (ParseGoogleTestFlag(arg)) { remove_flag = true; #if GTEST_USE_OWN_FLAGFILE_FLAG_ && GTEST_HAS_FILE_SYSTEM } else if (ParseFlag(arg, "flagfile", &flagfile_value)) { GTEST_FLAG_SET(flagfile, flagfile_value); LoadFlagsFromFile(flagfile_value); remove_flag = true; #endif } else if (arg_string == "--help" || HasGoogleTestFlagPrefix(arg)) { g_help_flag = true; } if (remove_flag) { for (int j = i + 1; j < *argc; ++j) { argv[j - 1] = argv[j]; } (*argc)--; argv[*argc] = nullptr; i--; } } if (g_help_flag) { PrintColorEncoded(kColorEncodedHelpMessage); } } void ParseGoogleTestFlagsOnly(int* argc, char** argv) { #ifdef GTEST_HAS_ABSL_FLAGS if (*argc <= 0) return; std::vector<char*> positional_args; std::vector<absl::UnrecognizedFlag> unrecognized_flags; absl::ParseAbseilFlagsOnly(*argc, argv, positional_args, unrecognized_flags); absl::flat_hash_set<absl::string_view> unrecognized; for (const auto& flag : unrecognized_flags) { unrecognized.insert(flag.flag_name); } absl::flat_hash_set<char*> positional; for (const auto& arg : positional_args) { positional.insert(arg); } int out_pos = 1; int in_pos = 1; for (; in_pos < *argc; ++in_pos) { char* arg = argv[in_pos]; absl::string_view arg_str(arg); if (absl::ConsumePrefix(&arg_str, "--")) { if (unrecognized.contains(arg_str)) { argv[out_pos++] = argv[in_pos]; continue; } } if (arg_str.empty()) { ++in_pos; break; } if (positional.contains(arg)) { argv[out_pos++] = arg; } } while (in_pos < *argc) { argv[out_pos++] = argv[in_pos++]; } *argc = out_pos; argv[out_pos] = nullptr; #else ParseGoogleTestFlagsOnlyImpl(argc, argv); #endif #ifdef GTEST_OS_MAC #ifndef GTEST_OS_IOS if (*_NSGetArgv() == argv) { *_NSGetArgc() = *argc; } #endif #endif } void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } template <typename CharType> void InitGoogleTestImpl(int* argc, CharType** argv) { if (GTestIsInitialized()) return; if (*argc <= 0) return; g_argvs.clear(); for (int i = 0; i != *argc; i++) { g_argvs.push_back(StreamableToString(argv[i])); } #ifdef GTEST_HAS_ABSL absl::InitializeSymbolizer(g_argvs[0].c_str()); #ifdef GTEST_HAS_ABSL_FLAGS absl::SetProgramUsageMessage(absl::StrReplaceAll( kColorEncodedHelpMessage, {{"@D", ""}, {"@R", ""}, {"@G", ""}, {"@Y", ""}, {"@@", "@"}})); #endif #endif ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } } void InitGoogleTest(int* argc, char** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else internal::InitGoogleTestImpl(argc, argv); #endif } void InitGoogleTest(int* argc, wchar_t** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else internal::InitGoogleTestImpl(argc, argv); #endif } void InitGoogleTest() { int argc = 1; const auto arg0 = "dummy"; char* argv0 = const_cast<char*>(arg0); char** argv = &argv0; #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); #else internal::InitGoogleTestImpl(&argc, argv); #endif } #if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) || \ !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_) static std::string GetDirFromEnv( std::initializer_list<const char*> environment_variables, const char* fallback, char separator) { for (const char* variable_name : environment_variables) { const char* value = internal::posix::GetEnv(variable_name); if (value != nullptr && value[0] != '\0') { if (value[strlen(value) - 1] != separator) { return std::string(value).append(1, separator); } return value; } } return fallback; } #endif std::string TempDir() { #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) return GTEST_CUSTOM_TEMPDIR_FUNCTION_(); #elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE) return GetDirFromEnv({"TEST_TMPDIR", "TEMP"}, "\\temp\\", '\\'); #elif defined(GTEST_OS_LINUX_ANDROID) return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/data/local/tmp/", '/'); #else return GetDirFromEnv({"TEST_TMPDIR", "TMPDIR"}, "/tmp/", '/'); #endif } #if GTEST_HAS_FILE_SYSTEM && !defined(GTEST_CUSTOM_SRCDIR_FUNCTION_) static std::string GetCurrentExecutableDirectory() { internal::FilePath argv_0(internal::GetArgvs()[0]); return argv_0.RemoveFileName().string(); } #endif #if GTEST_HAS_FILE_SYSTEM std::string SrcDir() { #if defined(GTEST_CUSTOM_SRCDIR_FUNCTION_) return GTEST_CUSTOM_SRCDIR_FUNCTION_(); #elif defined(GTEST_OS_WINDOWS) || defined(GTEST_OS_WINDOWS_MOBILE) return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(), '\\'); #elif defined(GTEST_OS_LINUX_ANDROID) return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(), '/'); #else return GetDirFromEnv({"TEST_SRCDIR"}, GetCurrentExecutableDirectory().c_str(), '/'); #endif } #endif void ScopedTrace::PushTrace(const char* file, int line, std::string message) { internal::TraceInfo trace; trace.file = file; trace.line = line; trace.message.swap(message); UnitTest::GetInstance()->PushGTestTrace(trace); } ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { UnitTest::GetInstance()->PopGTestTrace(); } }
#include "gtest/gtest.h" TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { bool dummy = GTEST_FLAG_GET(also_run_disabled_tests) || GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) || GTEST_FLAG_GET(color) != "unknown" || GTEST_FLAG_GET(fail_fast) || GTEST_FLAG_GET(filter) != "unknown" || GTEST_FLAG_GET(list_tests) || GTEST_FLAG_GET(output) != "unknown" || GTEST_FLAG_GET(brief) || GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) || GTEST_FLAG_GET(repeat) > 0 || GTEST_FLAG_GET(recreate_environments_when_repeating) || GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) || GTEST_FLAG_GET(stack_trace_depth) > 0 || GTEST_FLAG_GET(stream_result_to) != "unknown" || GTEST_FLAG_GET(throw_on_failure); EXPECT_TRUE(dummy || !dummy); } #include <limits.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <cstdint> #include <map> #include <memory> #include <ostream> #include <set> #include <stdexcept> #include <string> #include <type_traits> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest-spi.h" #include "src/gtest-internal-inl.h" struct ConvertibleGlobalType { template < class T, std::enable_if_t< false, std::enable_if_t<std::is_constructible<T>::value, int>> = 0> operator T() const; }; void operator<<(ConvertibleGlobalType&, int); static_assert(sizeof(decltype(std::declval<ConvertibleGlobalType&>() << 1)(*)()) > 0, "error in operator<< overload resolution"); namespace testing { namespace internal { #if GTEST_CAN_STREAM_RESULTS_ class StreamingListenerTest : public Test { public: class FakeSocketWriter : public StreamingListener::AbstractSocketWriter { public: void Send(const std::string& message) override { output_ += message; } std::string output_; }; StreamingListenerTest() : fake_sock_writer_(new FakeSocketWriter), streamer_(fake_sock_writer_), test_info_obj_("FooTest", "Bar", nullptr, nullptr, CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {} protected: std::string* output() { return &(fake_sock_writer_->output_); } FakeSocketWriter* const fake_sock_writer_; StreamingListener streamer_; UnitTest unit_test_; TestInfo test_info_obj_; }; TEST_F(StreamingListenerTest, OnTestProgramEnd) { *output() = ""; streamer_.OnTestProgramEnd(unit_test_); EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output()); } TEST_F(StreamingListenerTest, OnTestIterationEnd) { *output() = ""; streamer_.OnTestIterationEnd(unit_test_, 42); EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestSuiteStart) { *output() = ""; streamer_.OnTestSuiteStart(TestSuite("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output()); } TEST_F(StreamingListenerTest, OnTestSuiteEnd) { *output() = ""; streamer_.OnTestSuiteEnd(TestSuite("FooTest", "Bar", nullptr, nullptr)); EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestStart) { *output() = ""; streamer_.OnTestStart(test_info_obj_); EXPECT_EQ("event=TestStart&name=Bar\n", *output()); } TEST_F(StreamingListenerTest, OnTestEnd) { *output() = ""; streamer_.OnTestEnd(test_info_obj_); EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestPartResult) { *output() = ""; streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%")); EXPECT_EQ( "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n", *output()); } #endif class TestEventListenersAccessor { public: static TestEventListener* GetRepeater(TestEventListeners* listeners) { return listeners->repeater(); } static void SetDefaultResultPrinter(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultResultPrinter(listener); } static void SetDefaultXmlGenerator(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultXmlGenerator(listener); } static bool EventForwardingEnabled(const TestEventListeners& listeners) { return listeners.EventForwardingEnabled(); } static void SuppressEventForwarding(TestEventListeners* listeners) { listeners->SuppressEventForwarding(true); } }; class UnitTestRecordPropertyTestHelper : public Test { protected: UnitTestRecordPropertyTestHelper() {} void UnitTestRecordProperty(const char* key, const std::string& value) { unit_test_.RecordProperty(key, value); } UnitTest unit_test_; }; } } using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; using testing::DoubleLE; using testing::EmptyTestEventListener; using testing::Environment; using testing::FloatLE; using testing::IsNotSubstring; using testing::IsSubstring; using testing::kMaxStackTraceDepth; using testing::Message; using testing::ScopedFakeTestPartResultReporter; using testing::StaticAssertTypeEq; using testing::Test; using testing::TestEventListeners; using testing::TestInfo; using testing::TestPartResult; using testing::TestPartResultArray; using testing::TestProperty; using testing::TestResult; using testing::TimeInMillis; using testing::UnitTest; using testing::internal::AlwaysFalse; using testing::internal::AlwaysTrue; using testing::internal::AppendUserMessage; using testing::internal::ArrayAwareFind; using testing::internal::ArrayEq; using testing::internal::CodePointToUtf8; using testing::internal::CopyArray; using testing::internal::CountIf; using testing::internal::EqFailure; using testing::internal::FloatingPoint; using testing::internal::ForEach; using testing::internal::FormatEpochTimeInMillisAsIso8601; using testing::internal::FormatTimeInMillisAsSeconds; using testing::internal::GetElementOr; using testing::internal::GetNextRandomSeed; using testing::internal::GetRandomSeedFromFlag; using testing::internal::GetTestTypeId; using testing::internal::GetTimeInMillis; using testing::internal::GetTypeId; using testing::internal::GetUnitTestImpl; using testing::internal::GTestFlagSaver; using testing::internal::HasDebugStringAndShortDebugString; using testing::internal::Int32FromEnvOrDie; using testing::internal::IsContainer; using testing::internal::IsContainerTest; using testing::internal::IsNotContainer; using testing::internal::kMaxRandomSeed; using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::NativeArray; using testing::internal::ParseFlag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; using testing::internal::Shuffle; using testing::internal::ShuffleRange; using testing::internal::SkipPrefix; using testing::internal::StreamableToString; using testing::internal::String; using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; using testing::internal::WideStringToUtf8; using testing::internal::edit_distance::CalculateOptimalEdits; using testing::internal::edit_distance::CreateUnifiedDiff; using testing::internal::edit_distance::EditType; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif #ifdef GTEST_IS_THREADSAFE using testing::internal::ThreadWithParam; #endif class TestingVector : public std::vector<int> {}; ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) { os << "{ "; for (size_t i = 0; i < vector.size(); i++) { os << vector[i] << " "; } os << "}"; return os; } namespace { TEST(GetRandomSeedFromFlagTest, HandlesZero) { const int seed = GetRandomSeedFromFlag(0); EXPECT_LE(1, seed); EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) { EXPECT_EQ(1, GetRandomSeedFromFlag(1)); EXPECT_EQ(2, GetRandomSeedFromFlag(2)); EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetRandomSeedFromFlag(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) { const int seed1 = GetRandomSeedFromFlag(-1); EXPECT_LE(1, seed1); EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed)); const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1); EXPECT_LE(1, seed2); EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed)); } TEST(GetNextRandomSeedTest, WorksForValidInput) { EXPECT_EQ(2, GetNextRandomSeed(1)); EXPECT_EQ(3, GetNextRandomSeed(2)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetNextRandomSeed(kMaxRandomSeed - 1)); EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed)); } static void ClearCurrentTestPartResults() { TestResultAccessor::ClearTestPartResults( GetUnitTestImpl()->current_test_result()); } TEST(GetTypeIdTest, ReturnsSameValueForSameType) { EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>()); EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>()); } class SubClassOfTest : public Test {}; class AnotherSubClassOfTest : public Test {}; TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>()); EXPECT_NE(GetTypeId<int>(), GetTypeId<char>()); EXPECT_NE(GetTypeId<int>(), GetTestTypeId()); EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>()); } TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); } using ::testing::internal::CanonicalizeForStdLibVersioning; TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) { EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_")); EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo")); EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x")); EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x")); EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x")); } TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) { EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_")); EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_")); EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__google::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_")); } TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { EXPECT_EQ("0.", FormatTimeInMillisAsSeconds(0)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) { EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3)); EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10)); EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200)); EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200)); EXPECT_EQ("3.", FormatTimeInMillisAsSeconds(3000)); EXPECT_EQ("10.", FormatTimeInMillisAsSeconds(10000)); EXPECT_EQ("100.", FormatTimeInMillisAsSeconds(100000)); EXPECT_EQ("123.456", FormatTimeInMillisAsSeconds(123456)); EXPECT_EQ("1234567.89", FormatTimeInMillisAsSeconds(1234567890)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); EXPECT_EQ("-3.", FormatTimeInMillisAsSeconds(-3000)); EXPECT_EQ("-10.", FormatTimeInMillisAsSeconds(-10000)); EXPECT_EQ("-100.", FormatTimeInMillisAsSeconds(-100000)); EXPECT_EQ("-123.456", FormatTimeInMillisAsSeconds(-123456)); EXPECT_EQ("-1234567.89", FormatTimeInMillisAsSeconds(-1234567890)); } #if !defined(__EMSCRIPTEN__) class FormatEpochTimeInMillisAsIso8601Test : public Test { public: static const TimeInMillis kMillisPerSec = 1000; private: void SetUp() override { saved_tz_.reset(); GTEST_DISABLE_MSC_DEPRECATED_PUSH_() if (const char* tz = getenv("TZ")) { saved_tz_ = std::make_unique<std::string>(tz); } GTEST_DISABLE_MSC_DEPRECATED_POP_() SetTimeZone("UTC+00"); } void TearDown() override { SetTimeZone(saved_tz_ != nullptr ? saved_tz_->c_str() : nullptr); saved_tz_.reset(); } static void SetTimeZone(const char* time_zone) { #if defined(_MSC_VER) || defined(GTEST_OS_WINDOWS_MINGW) const std::string env_var = std::string("TZ=") + (time_zone ? time_zone : ""); _putenv(env_var.c_str()); GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 ) tzset(); GTEST_DISABLE_MSC_WARNINGS_POP_() #else #if defined(GTEST_OS_LINUX_ANDROID) && __ANDROID_API__ < 21 setenv("TZ", "UTC", 1); tzset(); #endif if (time_zone) { setenv(("TZ"), time_zone, 1); } else { unsetenv("TZ"); } tzset(); #endif } std::unique_ptr<std::string> saved_tz_; }; const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec; TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { EXPECT_EQ("2011-10-31T18:52:42.000", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) { EXPECT_EQ("2011-10-31T18:52:42.234", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { EXPECT_EQ("2011-09-03T05:07:02.000", FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) { EXPECT_EQ("2011-09-28T17:08:22.000", FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00.000", FormatEpochTimeInMillisAsIso8601(0)); } #endif #ifdef __BORLANDC__ #pragma option push -w-ccc -w-rch #endif TEST(NullLiteralTest, LHSAllowsNullLiterals) { EXPECT_EQ(0, static_cast<void*>(nullptr)); ASSERT_EQ(0, static_cast<void*>(nullptr)); EXPECT_EQ(NULL, static_cast<void*>(nullptr)); ASSERT_EQ(NULL, static_cast<void*>(nullptr)); EXPECT_EQ(nullptr, static_cast<void*>(nullptr)); ASSERT_EQ(nullptr, static_cast<void*>(nullptr)); const int* const p = nullptr; EXPECT_EQ(0, p); ASSERT_EQ(0, p); EXPECT_EQ(NULL, p); ASSERT_EQ(NULL, p); EXPECT_EQ(nullptr, p); ASSERT_EQ(nullptr, p); } struct ConvertToAll { template <typename T> operator T() const { return T(); } }; struct ConvertToPointer { template <class T> operator T*() const { return nullptr; } }; struct ConvertToAllButNoPointers { template <typename T, typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0> operator T() const { return T(); } }; struct MyType {}; inline bool operator==(MyType const&, MyType const&) { return true; } TEST(NullLiteralTest, ImplicitConversion) { EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr)); #if !defined(__GNUC__) || defined(__clang__) EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr)); #endif EXPECT_EQ(ConvertToAll{}, MyType{}); EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{}); } #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic error "-Wzero-as-null-pointer-constant" #endif #endif TEST(NullLiteralTest, NoConversionNoWarning) { EXPECT_EQ(0, 0); ASSERT_EQ(0, 0); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __BORLANDC__ #pragma option pop #endif TEST(CodePointToUtf8Test, CanEncodeNul) { EXPECT_EQ("", CodePointToUtf8(L'\0')); } TEST(CodePointToUtf8Test, CanEncodeAscii) { EXPECT_EQ("a", CodePointToUtf8(L'a')); EXPECT_EQ("Z", CodePointToUtf8(L'Z')); EXPECT_EQ("&", CodePointToUtf8(L'&')); EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F')); } TEST(CodePointToUtf8Test, CanEncode8To11Bits) { EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3')); EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576))); } TEST(CodePointToUtf8Test, CanEncode12To16Bits) { EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3))); EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D))); } #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(CodePointToUtf8Test, CanEncode17To21Bits) { EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3')); EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400')); EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634')); } TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD')); } #endif TEST(WideStringToUtf8Test, CanEncodeNul) { EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeAscii) { EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncode8To11Bits) { EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); const wchar_t s[] = {0x576, '\0'}; EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); } TEST(WideStringToUtf8Test, CanEncode12To16Bits) { const wchar_t s1[] = {0x8D3, '\0'}; EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); const wchar_t s2[] = {0xC74D, '\0'}; EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); } TEST(WideStringToUtf8Test, StopsOnNulCharacter) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); } TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); } #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, CanEncode17To21Bits) { EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", WideStringToUtf8(L"\xABCDFF", -1).c_str()); } #else TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { const wchar_t s[] = {0xD801, 0xDC00, '\0'}; EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); } TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { const wchar_t s1[] = {0xD800, '\0'}; EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); const wchar_t s2[] = {0xD800, 'M', '\0'}; EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\0'}; EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); } #endif #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = {0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; EXPECT_STREQ( "\xF4\x88\x98\xB4" "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93" "\xF4\x88\x98\xB4", WideStringToUtf8(s, -1).c_str()); } #else TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = {0xC74D, '\n', 0x576, 0x8D3, '\0'}; EXPECT_STREQ( "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", WideStringToUtf8(s, -1).c_str()); } #endif TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { testing::internal::Random random(42); EXPECT_DEATH_IF_SUPPORTED(random.Generate(0), "Cannot generate a number in the range \\[0, 0\\)"); EXPECT_DEATH_IF_SUPPORTED( random.Generate(testing::internal::Random::kMaxRange + 1), "Generation of a number in \\[0, 2147483649\\) was requested, " "but this can only generate numbers in \\[0, 2147483648\\)"); } TEST(RandomTest, GeneratesNumbersWithinRange) { constexpr uint32_t kRange = 10000; testing::internal::Random random(12345); for (int i = 0; i < 10; i++) { EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; } testing::internal::Random random2(testing::internal::Random::kMaxRange); for (int i = 0; i < 10; i++) { EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i; } } TEST(RandomTest, RepeatsWhenReseeded) { constexpr int kSeed = 123; constexpr int kArraySize = 10; constexpr uint32_t kRange = 10000; uint32_t values[kArraySize]; testing::internal::Random random(kSeed); for (int i = 0; i < kArraySize; i++) { values[i] = random.Generate(kRange); } random.Reseed(kSeed); for (int i = 0; i < kArraySize; i++) { EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i; } } static bool IsPositive(int n) { return n > 0; } TEST(ContainerUtilityTest, CountIf) { std::vector<int> v; EXPECT_EQ(0, CountIf(v, IsPositive)); v.push_back(-1); v.push_back(0); EXPECT_EQ(0, CountIf(v, IsPositive)); v.push_back(2); v.push_back(-10); v.push_back(10); EXPECT_EQ(2, CountIf(v, IsPositive)); } static int g_sum = 0; static void Accumulate(int n) { g_sum += n; } TEST(ContainerUtilityTest, ForEach) { std::vector<int> v; g_sum = 0; ForEach(v, Accumulate); EXPECT_EQ(0, g_sum); g_sum = 0; v.push_back(1); ForEach(v, Accumulate); EXPECT_EQ(1, g_sum); g_sum = 0; v.push_back(20); v.push_back(300); ForEach(v, Accumulate); EXPECT_EQ(321, g_sum); } TEST(ContainerUtilityTest, GetElementOr) { std::vector<char> a; EXPECT_EQ('x', GetElementOr(a, 0, 'x')); a.push_back('a'); a.push_back('b'); EXPECT_EQ('a', GetElementOr(a, 0, 'x')); EXPECT_EQ('b', GetElementOr(a, 1, 'x')); EXPECT_EQ('x', GetElementOr(a, -2, 'x')); EXPECT_EQ('x', GetElementOr(a, 2, 'x')); } TEST(ContainerUtilityDeathTest, ShuffleRange) { std::vector<int> a; a.push_back(0); a.push_back(1); a.push_back(2); testing::internal::Random random(1); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, -1, 1, &a), "Invalid shuffle range start -1: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 4, 4, &a), "Invalid shuffle range start 4: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 2, &a), "Invalid shuffle range finish 2: must be in range \\[3, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 4, &a), "Invalid shuffle range finish 4: must be in range \\[3, 3\\]"); } class VectorShuffleTest : public Test { protected: static const size_t kVectorSize = 20; VectorShuffleTest() : random_(1) { for (int i = 0; i < static_cast<int>(kVectorSize); i++) { vector_.push_back(i); } } static bool VectorIsCorrupt(const TestingVector& vector) { if (kVectorSize != vector.size()) { return true; } bool found_in_vector[kVectorSize] = {false}; for (size_t i = 0; i < vector.size(); i++) { const int e = vector[i]; if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) { return true; } found_in_vector[e] = true; } return false; } static bool VectorIsNotCorrupt(const TestingVector& vector) { return !VectorIsCorrupt(vector); } static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) { for (int i = begin; i < end; i++) { if (i != vector[static_cast<size_t>(i)]) { return true; } } return false; } static bool RangeIsUnshuffled(const TestingVector& vector, int begin, int end) { return !RangeIsShuffled(vector, begin, end); } static bool VectorIsShuffled(const TestingVector& vector) { return RangeIsShuffled(vector, 0, static_cast<int>(vector.size())); } static bool VectorIsUnshuffled(const TestingVector& vector) { return !VectorIsShuffled(vector); } testing::internal::Random random_; TestingVector vector_; }; const size_t VectorShuffleTest::kVectorSize; TEST_F(VectorShuffleTest, HandlesEmptyRange) { ShuffleRange(&random_, 0, 0, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); } TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) { ShuffleRange(&random_, 0, 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); } TEST_F(VectorShuffleTest, ShufflesEntireVector) { Shuffle(&random_, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_; EXPECT_NE(0, vector_[0]); EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]); } TEST_F(VectorShuffleTest, ShufflesStartOfVector) { const int kRangeSize = kVectorSize / 2; ShuffleRange(&random_, 0, kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, static_cast<int>(kVectorSize)); } TEST_F(VectorShuffleTest, ShufflesEndOfVector) { const int kRangeSize = kVectorSize / 2; ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, static_cast<int>(kVectorSize)); } TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { const int kRangeSize = static_cast<int>(kVectorSize) / 3; ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize, static_cast<int>(kVectorSize)); } TEST_F(VectorShuffleTest, ShufflesRepeatably) { TestingVector vector2; for (size_t i = 0; i < kVectorSize; i++) { vector2.push_back(static_cast<int>(i)); } random_.Reseed(1234); Shuffle(&random_, &vector_); random_.Reseed(1234); Shuffle(&random_, &vector2); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector2); for (size_t i = 0; i < kVectorSize; i++) { EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i; } } TEST(AssertHelperTest, AssertHelperIsSmall) { EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*)); } TEST(StringTest, EndsWithCaseInsensitive) { EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR")); EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar")); EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "")); EXPECT_TRUE(String::EndsWithCaseInsensitive("", "")); EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo")); EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo")); EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo")); } static const wchar_t* const kNull = nullptr; TEST(StringTest, CaseInsensitiveWideCStringEquals) { EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"")); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar")); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull)); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); } #ifdef GTEST_OS_WINDOWS TEST(StringTest, ShowWideCString) { EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str()); EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); } #ifdef GTEST_OS_WINDOWS_MOBILE TEST(StringTest, AnsiAndUtf16Null) { EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); } TEST(StringTest, AnsiAndUtf16ConvertBasic) { const char* ansi = String::Utf16ToAnsi(L"str"); EXPECT_STREQ("str", ansi); delete[] ansi; const WCHAR* utf16 = String::AnsiToUtf16("str"); EXPECT_EQ(0, wcsncmp(L"str", utf16, 3)); delete[] utf16; } TEST(StringTest, AnsiAndUtf16ConvertPathChars) { const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); EXPECT_STREQ(".:\\ \"*?", ansi); delete[] ansi; const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3)); delete[] utf16; } #endif #endif TEST(TestPropertyTest, StringValue) { TestProperty property("key", "1"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("1", property.value()); } TEST(TestPropertyTest, ReplaceStringValue) { TestProperty property("key", "1"); EXPECT_STREQ("1", property.value()); property.SetValue("2"); EXPECT_STREQ("2", property.value()); } static void AddFatalFailure() { FAIL() << "Expected fatal failure."; } static void AddNonfatalFailure() { ADD_FAILURE() << "Expected non-fatal failure."; } class ScopedFakeTestPartResultReporterTest : public Test { public: enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; static void AddFailure(FailureMode failure) { if (failure == FATAL_FAILURE) { AddFatalFailure(); } else { AddNonfatalFailure(); } } }; TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) { TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter( ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, &results); AddFailure(NONFATAL_FAILURE); AddFailure(FATAL_FAILURE); } EXPECT_EQ(2, results.size()); EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); } TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter(&results); AddFailure(NONFATAL_FAILURE); } EXPECT_EQ(1, results.size()); } #ifdef GTEST_IS_THREADSAFE class ScopedFakeTestPartResultReporterWithThreadsTest : public ScopedFakeTestPartResultReporterTest { protected: static void AddFailureInOtherThread(FailureMode failure) { ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr); thread.Join(); } }; TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest, InterceptsTestFailuresInAllThreads) { TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter( ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results); AddFailure(NONFATAL_FAILURE); AddFailure(FATAL_FAILURE); AddFailureInOtherThread(NONFATAL_FAILURE); AddFailureInOtherThread(FATAL_FAILURE); } EXPECT_EQ(4, results.size()); EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed()); } #endif typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest; TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure."); } TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) { EXPECT_FATAL_FAILURE(AddFatalFailure(), ::std::string("Expected fatal failure.")); } TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(), "Expected fatal failure."); } #ifdef __BORLANDC__ #pragma option push -w-ccc #endif int NonVoidFunction() { EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); return 0; } TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) { NonVoidFunction(); } void DoesNotAbortHelper(bool* aborted) { EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); *aborted = false; } #ifdef __BORLANDC__ #pragma option pop #endif TEST_F(ExpectFatalFailureTest, DoesNotAbort) { bool aborted = true; DoesNotAbortHelper(&aborted); EXPECT_FALSE(aborted); } static int global_var = 0; #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE( { GTEST_USE_UNPROTECTED_COMMA_; AddFatalFailure(); }, ""); #endif EXPECT_FATAL_FAILURE_ON_ALL_THREADS( { GTEST_USE_UNPROTECTED_COMMA_; AddFatalFailure(); }, ""); } typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure."); } TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), ::std::string("Expected non-fatal failure.")); } TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(), "Expected non-fatal failure."); } TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { EXPECT_NONFATAL_FAILURE( { GTEST_USE_UNPROTECTED_COMMA_; AddNonfatalFailure(); }, ""); EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( { GTEST_USE_UNPROTECTED_COMMA_; AddNonfatalFailure(); }, ""); } #ifdef GTEST_IS_THREADSAFE typedef ScopedFakeTestPartResultReporterWithThreadsTest ExpectFailureWithThreadsTest; TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) { EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE), "Expected fatal failure."); } TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) { EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure."); } #endif TEST(TestPropertyTest, ConstructorWorks) { const TestProperty property("key", "value"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("value", property.value()); } TEST(TestPropertyTest, SetValue) { TestProperty property("key", "value_1"); EXPECT_STREQ("key", property.key()); property.SetValue("value_2"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("value_2", property.value()); } class TestResultTest : public Test { protected: typedef std::vector<TestPartResult> TPRVector; TestPartResult *pr1, *pr2; TestResult *r0, *r1, *r2; void SetUp() override { pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"); pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc", -1, "Failure!"); r0 = new TestResult(); r1 = new TestResult(); r2 = new TestResult(); TPRVector* results1 = const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1)); TPRVector* results2 = const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2)); results1->push_back(*pr1); results2->push_back(*pr1); results2->push_back(*pr2); } void TearDown() override { delete pr1; delete pr2; delete r0; delete r1; delete r2; } static void CompareTestPartResult(const TestPartResult& expected, const TestPartResult& actual) { EXPECT_EQ(expected.type(), actual.type()); EXPECT_STREQ(expected.file_name(), actual.file_name()); EXPECT_EQ(expected.line_number(), actual.line_number()); EXPECT_STREQ(expected.summary(), actual.summary()); EXPECT_STREQ(expected.message(), actual.message()); EXPECT_EQ(expected.passed(), actual.passed()); EXPECT_EQ(expected.failed(), actual.failed()); EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed()); EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed()); } }; TEST_F(TestResultTest, total_part_count) { ASSERT_EQ(0, r0->total_part_count()); ASSERT_EQ(1, r1->total_part_count()); ASSERT_EQ(2, r2->total_part_count()); } TEST_F(TestResultTest, Passed) { ASSERT_TRUE(r0->Passed()); ASSERT_TRUE(r1->Passed()); ASSERT_FALSE(r2->Passed()); } TEST_F(TestResultTest, Failed) { ASSERT_FALSE(r0->Failed()); ASSERT_FALSE(r1->Failed()); ASSERT_TRUE(r2->Failed()); } typedef TestResultTest TestResultDeathTest; TEST_F(TestResultDeathTest, GetTestPartResult) { CompareTestPartResult(*pr1, r2->GetTestPartResult(0)); CompareTestPartResult(*pr2, r2->GetTestPartResult(1)); EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), ""); EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), ""); } TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) { TestResult test_result; ASSERT_EQ(0, test_result.test_property_count()); } TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) { TestResult test_result; TestProperty property("key_1", "1"); TestResultAccessor::RecordProperty(&test_result, "testcase", property); ASSERT_EQ(1, test_result.test_property_count()); const TestProperty& actual_property = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property.key()); EXPECT_STREQ("1", actual_property.value()); } TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) { TestResult test_result; TestProperty property_1("key_1", "1"); TestProperty property_2("key_2", "2"); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2); ASSERT_EQ(2, test_result.test_property_count()); const TestProperty& actual_property_1 = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property_1.key()); EXPECT_STREQ("1", actual_property_1.value()); const TestProperty& actual_property_2 = test_result.GetTestProperty(1); EXPECT_STREQ("key_2", actual_property_2.key()); EXPECT_STREQ("2", actual_property_2.value()); } TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) { TestResult test_result; TestProperty property_1_1("key_1", "1"); TestProperty property_2_1("key_2", "2"); TestProperty property_1_2("key_1", "12"); TestProperty property_2_2("key_2", "22"); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2); ASSERT_EQ(2, test_result.test_property_count()); const TestProperty& actual_property_1 = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property_1.key()); EXPECT_STREQ("12", actual_property_1.value()); const TestProperty& actual_property_2 = test_result.GetTestProperty(1); EXPECT_STREQ("key_2", actual_property_2.key()); EXPECT_STREQ("22", actual_property_2.value()); } TEST(TestResultPropertyTest, GetTestProperty) { TestResult test_result; TestProperty property_1("key_1", "1"); TestProperty property_2("key_2", "2"); TestProperty property_3("key_3", "3"); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2); TestResultAccessor::RecordProperty(&test_result, "testcase", property_3); const TestProperty& fetched_property_1 = test_result.GetTestProperty(0); const TestProperty& fetched_property_2 = test_result.GetTestProperty(1); const TestProperty& fetched_property_3 = test_result.GetTestProperty(2); EXPECT_STREQ("key_1", fetched_property_1.key()); EXPECT_STREQ("1", fetched_property_1.value()); EXPECT_STREQ("key_2", fetched_property_2.key()); EXPECT_STREQ("2", fetched_property_2.value()); EXPECT_STREQ("key_3", fetched_property_3.key()); EXPECT_STREQ("3", fetched_property_3.value()); EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), ""); EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), ""); } class GTestFlagSaverTest : public Test { protected: static void SetUpTestSuite() { saver_ = new GTestFlagSaver; GTEST_FLAG_SET(also_run_disabled_tests, false); GTEST_FLAG_SET(break_on_failure, false); GTEST_FLAG_SET(catch_exceptions, false); GTEST_FLAG_SET(death_test_use_fork, false); GTEST_FLAG_SET(color, "auto"); GTEST_FLAG_SET(fail_fast, false); GTEST_FLAG_SET(filter, ""); GTEST_FLAG_SET(list_tests, false); GTEST_FLAG_SET(output, ""); GTEST_FLAG_SET(brief, false); GTEST_FLAG_SET(print_time, true); GTEST_FLAG_SET(random_seed, 0); GTEST_FLAG_SET(repeat, 1); GTEST_FLAG_SET(recreate_environments_when_repeating, true); GTEST_FLAG_SET(shuffle, false); GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth); GTEST_FLAG_SET(stream_result_to, ""); GTEST_FLAG_SET(throw_on_failure, false); } static void TearDownTestSuite() { delete saver_; saver_ = nullptr; } void VerifyAndModifyFlags() { EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests)); EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure)); EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions)); EXPECT_STREQ("auto", GTEST_FLAG_GET(color).c_str()); EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork)); EXPECT_FALSE(GTEST_FLAG_GET(fail_fast)); EXPECT_STREQ("", GTEST_FLAG_GET(filter).c_str()); EXPECT_FALSE(GTEST_FLAG_GET(list_tests)); EXPECT_STREQ("", GTEST_FLAG_GET(output).c_str()); EXPECT_FALSE(GTEST_FLAG_GET(brief)); EXPECT_TRUE(GTEST_FLAG_GET(print_time)); EXPECT_EQ(0, GTEST_FLAG_GET(random_seed)); EXPECT_EQ(1, GTEST_FLAG_GET(repeat)); EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating)); EXPECT_FALSE(GTEST_FLAG_GET(shuffle)); EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth)); EXPECT_STREQ("", GTEST_FLAG_GET(stream_result_to).c_str()); EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure)); GTEST_FLAG_SET(also_run_disabled_tests, true); GTEST_FLAG_SET(break_on_failure, true); GTEST_FLAG_SET(catch_exceptions, true); GTEST_FLAG_SET(color, "no"); GTEST_FLAG_SET(death_test_use_fork, true); GTEST_FLAG_SET(fail_fast, true); GTEST_FLAG_SET(filter, "abc"); GTEST_FLAG_SET(list_tests, true); GTEST_FLAG_SET(output, "xml:foo.xml"); GTEST_FLAG_SET(brief, true); GTEST_FLAG_SET(print_time, false); GTEST_FLAG_SET(random_seed, 1); GTEST_FLAG_SET(repeat, 100); GTEST_FLAG_SET(recreate_environments_when_repeating, false); GTEST_FLAG_SET(shuffle, true); GTEST_FLAG_SET(stack_trace_depth, 1); GTEST_FLAG_SET(stream_result_to, "localhost:1234"); GTEST_FLAG_SET(throw_on_failure, true); } private: static GTestFlagSaver* saver_; }; GTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr; TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); } TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); } static void SetEnv(const char* name, const char* value) { #ifdef GTEST_OS_WINDOWS_MOBILE return; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) static std::map<std::string, std::string*> added_env; std::string* prev_env = NULL; if (added_env.find(name) != added_env.end()) { prev_env = added_env[name]; } added_env[name] = new std::string((Message() << name << "=" << value).GetString()); putenv(const_cast<char*>(added_env[name]->c_str())); delete prev_env; #elif defined(GTEST_OS_WINDOWS) _putenv((Message() << name << "=" << value).GetString().c_str()); #else if (*value == '\0') { unsetenv(name); } else { setenv(name, value, 1); } #endif } #ifndef GTEST_OS_WINDOWS_MOBILE using testing::internal::Int32FromGTestEnv; TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", ""); EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); } #if !defined(GTEST_GET_INT32_FROM_ENV_) TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321"); EXPECT_EQ(20, Int32FromGTestEnv("temp", 20)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321"); EXPECT_EQ(30, Int32FromGTestEnv("temp", 30)); } TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1"); EXPECT_EQ(40, Int32FromGTestEnv("temp", 40)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X"); EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); } #endif TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123"); EXPECT_EQ(123, Int32FromGTestEnv("temp", 0)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321"); EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0)); } #endif TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { int32_t value = 123; EXPECT_FALSE(ParseFlag("--a=100", "b", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseFlag("a=100", "a", &value)); EXPECT_EQ(123, value); } TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); int32_t value = 123; EXPECT_FALSE(ParseFlag("--abc=12345678987654321", "abc", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseFlag("--abc=-12345678987654321", "abc", &value)); EXPECT_EQ(123, value); } TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); int32_t value = 123; EXPECT_FALSE(ParseFlag("--abc=A1", "abc", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseFlag("--abc=12X", "abc", &value)); EXPECT_EQ(123, value); } TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { int32_t value = 123; EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); EXPECT_EQ(456, value); EXPECT_TRUE(ParseFlag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value)); EXPECT_EQ(-789, value); } #ifndef GTEST_OS_WINDOWS_MOBILE TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123"); EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123"); EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); } #endif TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); EXPECT_DEATH_IF_SUPPORTED( Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); EXPECT_DEATH_IF_SUPPORTED( Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4)); } class ShouldShardTest : public testing::Test { protected: void SetUp() override { index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX"; total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL"; } void TearDown() override { SetEnv(index_var_, ""); SetEnv(total_var_, ""); } const char* index_var_; const char* total_var_; }; TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) { SetEnv(index_var_, ""); SetEnv(total_var_, ""); EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) { SetEnv(index_var_, "0"); SetEnv(total_var_, "1"); EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } #ifndef GTEST_OS_WINDOWS_MOBILE TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) { SetEnv(index_var_, "4"); SetEnv(total_var_, "22"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); SetEnv(index_var_, "8"); SetEnv(total_var_, "9"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); SetEnv(index_var_, "0"); SetEnv(total_var_, "9"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } #endif typedef ShouldShardTest ShouldShardDeathTest; TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) { SetEnv(index_var_, "4"); SetEnv(total_var_, "4"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, "4"); SetEnv(total_var_, "-2"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, "5"); SetEnv(total_var_, ""); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, ""); SetEnv(total_var_, "5"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); } TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { const int num_tests = 17; const int num_shards = 5; for (int test_id = 0; test_id < num_tests; test_id++) { int prev_selected_shard_index = -1; for (int shard_index = 0; shard_index < num_shards; shard_index++) { if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) { if (prev_selected_shard_index < 0) { prev_selected_shard_index = shard_index; } else { ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " << shard_index << " are both selected to run test " << test_id; } } } } for (int shard_index = 0; shard_index < num_shards; shard_index++) { int num_tests_on_shard = 0; for (int test_id = 0; test_id < num_tests; test_id++) { num_tests_on_shard += ShouldRunTestOnShard(num_shards, shard_index, test_id); } EXPECT_GE(num_tests_on_shard, num_tests / num_shards); } } TEST(UnitTestTest, CanGetOriginalWorkingDir) { ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr); EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), ""); } TEST(UnitTestTest, ReturnsPlausibleTimestamp) { EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp()); EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis()); } void ExpectNonFatalFailureRecordingPropertyWithReservedKey( const TestResult& test_result, const char* key) { EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key"); ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key << "' recorded unexpectedly."; } void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( const char* key) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(test_info != nullptr); ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(), key); } void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( const char* key) { const testing::TestSuite* test_suite = UnitTest::GetInstance()->current_test_suite(); ASSERT_TRUE(test_suite != nullptr); ExpectNonFatalFailureRecordingPropertyWithReservedKey( test_suite->ad_hoc_test_result(), key); } void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( const char* key) { ExpectNonFatalFailureRecordingPropertyWithReservedKey( UnitTest::GetInstance()->ad_hoc_test_result(), key); } class UnitTestRecordPropertyTest : public testing::internal::UnitTestRecordPropertyTestHelper { public: static void SetUpTestSuite() { ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "disabled"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "errors"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "failures"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "tests"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite( "time"); Test::RecordProperty("test_case_key_1", "1"); const testing::TestSuite* test_suite = UnitTest::GetInstance()->current_test_suite(); ASSERT_TRUE(test_suite != nullptr); ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count()); EXPECT_STREQ("test_case_key_1", test_suite->ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("1", test_suite->ad_hoc_test_result().GetTestProperty(0).value()); } }; TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) { UnitTestRecordProperty("key_1", "1"); ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count()); EXPECT_STREQ("key_1", unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); } TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) { UnitTestRecordProperty("key_1", "1"); UnitTestRecordProperty("key_2", "2"); ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count()); EXPECT_STREQ("key_1", unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); EXPECT_STREQ("key_2", unit_test_.ad_hoc_test_result().GetTestProperty(1).key()); EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value()); } TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) { UnitTestRecordProperty("key_1", "1"); UnitTestRecordProperty("key_2", "2"); UnitTestRecordProperty("key_1", "12"); UnitTestRecordProperty("key_2", "22"); ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count()); EXPECT_STREQ("key_1", unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("12", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); EXPECT_STREQ("key_2", unit_test_.ad_hoc_test_result().GetTestProperty(1).key()); EXPECT_STREQ("22", unit_test_.ad_hoc_test_result().GetTestProperty(1).value()); } TEST_F(UnitTestRecordPropertyTest, AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) { ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "value_param"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "type_param"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("status"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest("time"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "classname"); } TEST_F(UnitTestRecordPropertyTest, AddRecordWithReservedKeysGeneratesCorrectPropertyList) { EXPECT_NONFATAL_FAILURE( Test::RecordProperty("name", "1"), "'classname', 'name', 'status', 'time', 'type_param', 'value_param'," " 'file', and 'line' are reserved"); } class UnitTestRecordPropertyTestEnvironment : public Environment { public: void TearDown() override { ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "tests"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "failures"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "disabled"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "errors"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "timestamp"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "time"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite( "random_seed"); } }; GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static Environment* record_property_env = AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment); bool IsEven(int n) { return (n % 2) == 0; } struct IsEvenFunctor { bool operator()(int n) { return IsEven(n); } }; AssertionResult AssertIsEven(const char* expr, int n) { if (IsEven(n)) { return AssertionSuccess(); } Message msg; msg << expr << " evaluates to " << n << ", which is not even."; return AssertionFailure(msg); } AssertionResult ResultIsEven(int n) { if (IsEven(n)) return AssertionSuccess() << n << " is even"; else return AssertionFailure() << n << " is odd"; } AssertionResult ResultIsEvenNoExplanation(int n) { if (IsEven(n)) return AssertionSuccess(); else return AssertionFailure() << n << " is odd"; } struct AssertIsEvenFunctor { AssertionResult operator()(const char* expr, int n) { return AssertIsEven(expr, n); } }; bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); } struct SumIsEven3Functor { bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); } }; AssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3, const char* e4, int n1, int n2, int n3, int n4) { const int sum = n1 + n2 + n3 + n4; if (IsEven(sum)) { return AssertionSuccess(); } Message msg; msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum << ", which is not even."; return AssertionFailure(msg); } struct AssertSumIsEven5Functor { AssertionResult operator()(const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, int n1, int n2, int n3, int n4, int n5) { const int sum = n1 + n2 + n3 + n4 + n5; if (IsEven(sum)) { return AssertionSuccess(); } Message msg; msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5 << ") evaluates to " << sum << ", which is not even."; return AssertionFailure(msg); } }; TEST(Pred1Test, WithoutFormat) { EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!"; ASSERT_PRED1(IsEven, 4); EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(IsEven, 5) << "This failure is expected."; }, "This failure is expected."); EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false"); } TEST(Pred1Test, WithFormat) { EXPECT_PRED_FORMAT1(AssertIsEven, 2); ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) << "This failure is UNEXPECTED!"; const int n = 5; EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), "n evaluates to 5, which is not even."); EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; }, "This failure is expected."); } TEST(Pred1Test, SingleEvaluationOnFailure) { static int n = 0; EXPECT_PRED1(IsEven, n++); EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) << "This failure is expected."; }, "This failure is expected."); EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; } TEST(PredTest, WithoutFormat) { ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!"; EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8); const int n1 = 1; const int n2 = 2; EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; }, "This failure is expected."); EXPECT_FATAL_FAILURE( { ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); }, "evaluates to false"); } TEST(PredTest, WithFormat) { ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) << "This failure is UNEXPECTED!"; EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); const int n1 = 1; const int n2 = 2; const int n3 = 4; const int n4 = 6; EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); }, "evaluates to 13, which is not even."); EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) << "This failure is expected."; }, "This failure is expected."); } TEST(PredTest, SingleEvaluationOnFailure) { int n1 = 0; int n2 = 0; EXPECT_PRED2(SumIsEven2, n1++, n2++); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; n1 = n2 = 0; int n3 = 0; int n4 = 0; int n5 = 0; ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++) << "This failure is UNEXPECTED!"; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once."; n1 = n2 = n3 = 0; EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) << "This failure is expected."; }, "This failure is expected."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; n1 = n2 = n3 = n4 = 0; EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); }, "evaluates to 1, which is not even."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; } TEST(PredTest, ExpectPredEvalFailure) { std::set<int> set_a = {2, 1, 3, 4, 5}; std::set<int> set_b = {0, 4, 8}; const auto compare_sets = [](std::set<int>, std::set<int>) { return false; }; EXPECT_NONFATAL_FAILURE( EXPECT_PRED2(compare_sets, set_a, set_b), "compare_sets(set_a, set_b) evaluates to false, where\nset_a evaluates " "to { 1, 2, 3, 4, 5 }\nset_b evaluates to { 0, 4, 8 }"); } bool IsPositive(double x) { return x > 0; } template <typename T> bool IsNegative(T x) { return x < 0; } template <typename T1, typename T2> bool GreaterThan(T1 x1, T2 x2) { return x1 > x2; } TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { EXPECT_PRED1((bool (*)(int))(IsPositive), 5); ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); } TEST(PredicateAssertionTest, AcceptsTemplateFunction) { EXPECT_PRED1(IsNegative<int>, -5); ASSERT_PRED2((GreaterThan<int, int>), 5, 0); } AssertionResult IsPositiveFormat(const char* , int n) { return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } AssertionResult IsPositiveFormat(const char* , double x) { return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template <typename T> AssertionResult IsNegativeFormat(const char* , T x) { return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template <typename T1, typename T2> AssertionResult EqualsFormat(const char* , const char* , const T1& x1, const T2& x2) { return x1 == x2 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) { EXPECT_PRED_FORMAT1(IsPositiveFormat, 5); ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0); } TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { EXPECT_PRED_FORMAT1(IsNegativeFormat, -5); ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); } TEST(StringAssertionTest, ASSERT_STREQ) { const char* const p1 = "good"; ASSERT_STREQ(p1, p1); const char p2[] = "good"; ASSERT_STREQ(p1, p2); EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), " \"bad\"\n \"good\""); } TEST(StringAssertionTest, ASSERT_STREQ_Null) { ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr); EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, "non-null"), "non-null"); } TEST(StringAssertionTest, ASSERT_STREQ_Null2) { EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", nullptr), "non-null"); } TEST(StringAssertionTest, ASSERT_STRNE) { ASSERT_STRNE("hi", "Hi"); ASSERT_STRNE("Hi", nullptr); ASSERT_STRNE(nullptr, "Hi"); ASSERT_STRNE("", nullptr); ASSERT_STRNE(nullptr, ""); ASSERT_STRNE("", "Hi"); ASSERT_STRNE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\""); } TEST(StringAssertionTest, ASSERT_STRCASEEQ) { ASSERT_STRCASEEQ("hi", "Hi"); ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr); ASSERT_STRCASEEQ("", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case"); } TEST(StringAssertionTest, ASSERT_STRCASENE) { ASSERT_STRCASENE("hi1", "Hi2"); ASSERT_STRCASENE("Hi", nullptr); ASSERT_STRCASENE(nullptr, "Hi"); ASSERT_STRCASENE("", nullptr); ASSERT_STRCASENE(nullptr, ""); ASSERT_STRCASENE("", "Hi"); ASSERT_STRCASENE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)"); } TEST(StringAssertionTest, STREQ_Wide) { ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr); ASSERT_STREQ(L"", L""); EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", nullptr), "non-null"); EXPECT_STREQ(L"Hi", L"Hi"); EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc"); EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc"); EXPECT_NONFATAL_FAILURE( { EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure"; }, "Expected failure"); } TEST(StringAssertionTest, STRNE_Wide) { EXPECT_NONFATAL_FAILURE( { EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr); }, ""); EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\""); ASSERT_STRNE(L"non-null", nullptr); EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\""); EXPECT_STRNE(L"abc", L"Abc"); EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc"); ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen"; } TEST(IsSubstringTest, ReturnsCorrectResultForCString) { EXPECT_FALSE(IsSubstring("", "", nullptr, "a")); EXPECT_FALSE(IsSubstring("", "", "b", nullptr)); EXPECT_FALSE(IsSubstring("", "", "needle", "haystack")); EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(nullptr), nullptr)); EXPECT_TRUE(IsSubstring("", "", "needle", "two needles")); } TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { EXPECT_FALSE(IsSubstring("", "", kNull, L"a")); EXPECT_FALSE(IsSubstring("", "", L"b", kNull)); EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); EXPECT_TRUE( IsSubstring("", "", static_cast<const wchar_t*>(nullptr), nullptr)); EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); } TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { EXPECT_STREQ( "Value of: needle_expr\n" " Actual: \"needle\"\n" "Expected: a substring of haystack_expr\n" "Which is: \"haystack\"", IsSubstring("needle_expr", "haystack_expr", "needle", "haystack") .failure_message()); } TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); } #if GTEST_HAS_STD_WSTRING TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles")); EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack"))); } TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { EXPECT_STREQ( "Value of: needle_expr\n" " Actual: L\"needle\"\n" "Expected: a substring of haystack_expr\n" "Which is: L\"haystack\"", IsSubstring("needle_expr", "haystack_expr", ::std::wstring(L"needle"), L"haystack") .failure_message()); } #endif TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) { EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack")); EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles")); } TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack")); EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles")); } TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { EXPECT_STREQ( "Value of: needle_expr\n" " Actual: L\"needle\"\n" "Expected: not a substring of haystack_expr\n" "Which is: L\"two needles\"", IsNotSubstring("needle_expr", "haystack_expr", L"needle", L"two needles") .failure_message()); } TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); } TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { EXPECT_STREQ( "Value of: needle_expr\n" " Actual: \"needle\"\n" "Expected: not a substring of haystack_expr\n" "Which is: \"two needles\"", IsNotSubstring("needle_expr", "haystack_expr", ::std::string("needle"), "two needles") .failure_message()); } #if GTEST_HAS_STD_WSTRING TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) { EXPECT_FALSE( IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles")); EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack"))); } #endif template <typename RawType> class FloatingPointTest : public Test { protected: struct TestValues { RawType close_to_positive_zero; RawType close_to_negative_zero; RawType further_from_negative_zero; RawType close_to_one; RawType further_from_one; RawType infinity; RawType close_to_infinity; RawType further_from_infinity; RawType nan1; RawType nan2; }; typedef typename testing::internal::FloatingPoint<RawType> Floating; typedef typename Floating::Bits Bits; void SetUp() override { const uint32_t max_ulps = Floating::kMaxUlps; const Bits zero_bits = Floating(0).bits(); values_.close_to_positive_zero = Floating::ReinterpretBits(zero_bits + max_ulps / 2); values_.close_to_negative_zero = -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2); values_.further_from_negative_zero = -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2); const Bits one_bits = Floating(1).bits(); values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); values_.further_from_one = Floating::ReinterpretBits(one_bits + max_ulps + 1); values_.infinity = Floating::Infinity(); const Bits infinity_bits = Floating(values_.infinity).bits(); values_.close_to_infinity = Floating::ReinterpretBits(infinity_bits - max_ulps); values_.further_from_infinity = Floating::ReinterpretBits(infinity_bits - max_ulps - 1); values_.nan1 = Floating::ReinterpretBits( Floating::kExponentBitMask | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1); values_.nan2 = Floating::ReinterpretBits( Floating::kExponentBitMask | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200); } void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } static TestValues values_; }; template <typename RawType> typename FloatingPointTest<RawType>::TestValues FloatingPointTest<RawType>::values_; typedef FloatingPointTest<float> FloatTest; TEST_F(FloatTest, Size) { TestSize(); } TEST_F(FloatTest, Zeros) { EXPECT_FLOAT_EQ(0.0, -0.0); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5"); } TEST_F(FloatTest, AlmostZeros) { static const FloatTest::TestValues& v = this->values_; EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero); EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero); EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_FATAL_FAILURE( { ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero); }, "v.further_from_negative_zero"); } TEST_F(FloatTest, SmallDiff) { EXPECT_FLOAT_EQ(1.0, values_.close_to_one); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one), "values_.further_from_one"); } TEST_F(FloatTest, LargeDiff) { EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0"); } TEST_F(FloatTest, Infinity) { EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1), "values_.nan1"); } TEST_F(FloatTest, NaN) { static const FloatTest::TestValues& v = this->values_; EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity"); } TEST_F(FloatTest, Reflexive) { EXPECT_FLOAT_EQ(0.0, 0.0); EXPECT_FLOAT_EQ(1.0, 1.0); ASSERT_FLOAT_EQ(values_.infinity, values_.infinity); } TEST_F(FloatTest, Commutative) { EXPECT_FLOAT_EQ(values_.close_to_one, 1.0); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0), "1.0"); } TEST_F(FloatTest, EXPECT_NEAR) { EXPECT_NEAR(-1.0f, -1.1f, 0.2f); EXPECT_NEAR(2.0f, 3.0f, 1.0f); EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f), "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); } TEST_F(FloatTest, ASSERT_NEAR) { ASSERT_NEAR(-1.0f, -1.1f, 0.2f); ASSERT_NEAR(2.0f, 3.0f, 1.0f); EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f), "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); } TEST_F(FloatTest, FloatLESucceeds) { EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f); } TEST_F(FloatTest, FloatLEFails) { EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f), "(2.0f) <= (1.0f)"); EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); }, "(values_.further_from_one) <= (1.0f)"); EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); }, "(-values_.infinity) <= (values_.nan1)"); EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); } typedef FloatingPointTest<double> DoubleTest; TEST_F(DoubleTest, Size) { TestSize(); } TEST_F(DoubleTest, Zeros) { EXPECT_DOUBLE_EQ(0.0, -0.0); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0"); } TEST_F(DoubleTest, AlmostZeros) { static const DoubleTest::TestValues& v = this->values_; EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero); EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero); EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_FATAL_FAILURE( { ASSERT_DOUBLE_EQ(v.close_to_positive_zero, v.further_from_negative_zero); }, "v.further_from_negative_zero"); } TEST_F(DoubleTest, SmallDiff) { EXPECT_DOUBLE_EQ(1.0, values_.close_to_one); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one), "values_.further_from_one"); } TEST_F(DoubleTest, LargeDiff) { EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0"); } TEST_F(DoubleTest, Infinity) { EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), "values_.nan1"); } TEST_F(DoubleTest, NaN) { static const DoubleTest::TestValues& v = this->values_; EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity"); } TEST_F(DoubleTest, Reflexive) { EXPECT_DOUBLE_EQ(0.0, 0.0); EXPECT_DOUBLE_EQ(1.0, 1.0); ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); } TEST_F(DoubleTest, Commutative) { EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0), "1.0"); } TEST_F(DoubleTest, EXPECT_NEAR) { EXPECT_NEAR(-1.0, -1.1, 0.2); EXPECT_NEAR(2.0, 3.0, 1.0); EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); EXPECT_NONFATAL_FAILURE( EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0), "The abs_error parameter 1.0 evaluates to 1 which is smaller than the " "minimum distance between doubles for numbers of this magnitude which is " "512"); } TEST_F(DoubleTest, ASSERT_NEAR) { ASSERT_NEAR(-1.0, -1.1, 0.2); ASSERT_NEAR(2.0, 3.0, 1.0); EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); } TEST_F(DoubleTest, DoubleLESucceeds) { EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0); } TEST_F(DoubleTest, DoubleLEFails) { EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0), "(2.0) <= (1.0)"); EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); }, "(values_.further_from_one) <= (1.0)"); EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); }, " (-values_.infinity) <= (values_.nan1)"); EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); } TEST(DisabledTest, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Disabled test should not be run."; } TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); } TEST(DISABLED_TestSuite, TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } TEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } class DisabledTestsTest : public Test { protected: static void SetUpTestSuite() { FAIL() << "Unexpected failure: All tests disabled in test case. " "SetUpTestSuite() should not be called."; } static void TearDownTestSuite() { FAIL() << "Unexpected failure: All tests disabled in test case. " "TearDownTestSuite() should not be called."; } }; TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) { FAIL() << "Unexpected failure: Disabled test should not be run."; } TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { FAIL() << "Unexpected failure: Disabled test should not be run."; } template <typename T> class TypedTest : public Test {}; typedef testing::Types<int, double> NumericTypes; TYPED_TEST_SUITE(TypedTest, NumericTypes); TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; } template <typename T> class DISABLED_TypedTest : public Test {}; TYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes); TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; } template <typename T> class TypedTestP : public Test {}; TYPED_TEST_SUITE_P(TypedTestP); TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } REGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun); INSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes); template <typename T> class DISABLED_TypedTestP : public Test {}; TYPED_TEST_SUITE_P(DISABLED_TypedTestP); TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } REGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun); INSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes); class SingleEvaluationTest : public Test { public: static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); } static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); } protected: SingleEvaluationTest() { p1_ = s1_; p2_ = s2_; a_ = 0; b_ = 0; } static const char* const s1_; static const char* const s2_; static const char* p1_; static const char* p2_; static int a_; static int b_; }; const char* const SingleEvaluationTest::s1_ = "01234"; const char* const SingleEvaluationTest::s2_ = "abcde"; const char* SingleEvaluationTest::p1_; const char* SingleEvaluationTest::p2_; int SingleEvaluationTest::a_; int SingleEvaluationTest::b_; TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) { EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(), "p2_++"); EXPECT_EQ(s1_ + 1, p1_); EXPECT_EQ(s2_ + 1, p2_); } TEST_F(SingleEvaluationTest, ASSERT_STR) { EXPECT_STRNE(p1_++, p2_++); EXPECT_EQ(s1_ + 1, p1_); EXPECT_EQ(s2_ + 1, p2_); EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case"); EXPECT_EQ(s1_ + 2, p1_); EXPECT_EQ(s2_ + 2, p2_); } TEST_F(SingleEvaluationTest, FailedASSERT_NE) { EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(), "(a_++) != (b_++)"); EXPECT_EQ(1, a_); EXPECT_EQ(1, b_); } TEST_F(SingleEvaluationTest, OtherCases) { EXPECT_TRUE(0 == a_++); EXPECT_EQ(1, a_); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++"); EXPECT_EQ(2, a_); EXPECT_GT(a_++, b_++); EXPECT_EQ(3, a_); EXPECT_EQ(1, b_); EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)"); EXPECT_EQ(4, a_); EXPECT_EQ(2, b_); ASSERT_TRUE(0 < a_++); EXPECT_EQ(5, a_); ASSERT_GT(a_++, b_++); EXPECT_EQ(6, a_); EXPECT_EQ(3, b_); } #if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_RTTI #define ERROR_DESC "std::runtime_error" #else #define ERROR_DESC "an std::exception-derived error" #endif void ThrowAnInteger() { throw 1; } void ThrowRuntimeError(const char* what) { throw std::runtime_error(what); } TEST_F(SingleEvaluationTest, ExceptionTests) { EXPECT_THROW( { a_++; ThrowAnInteger(); }, int); EXPECT_EQ(1, a_); EXPECT_NONFATAL_FAILURE(EXPECT_THROW( { a_++; ThrowAnInteger(); }, bool), "throws a different type"); EXPECT_EQ(2, a_); EXPECT_NONFATAL_FAILURE(EXPECT_THROW( { a_++; ThrowRuntimeError("A description"); }, bool), "throws " ERROR_DESC " with description \"A description\""); EXPECT_EQ(3, a_); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing"); EXPECT_EQ(4, a_); EXPECT_NO_THROW(a_++); EXPECT_EQ(5, a_); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ a_++; ThrowAnInteger(); }), "it throws"); EXPECT_EQ(6, a_); EXPECT_ANY_THROW({ a_++; ThrowAnInteger(); }); EXPECT_EQ(7, a_); EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't"); EXPECT_EQ(8, a_); } #endif class NoFatalFailureTest : public Test { protected: void Succeeds() {} void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; } void Fails() { FAIL() << "some fatal failure"; } void DoAssertNoFatalFailureOnFails() { ASSERT_NO_FATAL_FAILURE(Fails()); ADD_FAILURE() << "should not reach here."; } void DoExpectNoFatalFailureOnFails() { EXPECT_NO_FATAL_FAILURE(Fails()); ADD_FAILURE() << "other failure"; } }; TEST_F(NoFatalFailureTest, NoFailure) { EXPECT_NO_FATAL_FAILURE(Succeeds()); ASSERT_NO_FATAL_FAILURE(Succeeds()); } TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), "some non-fatal failure"); EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), "some non-fatal failure"); } TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures); DoAssertNoFatalFailureOnFails(); } ASSERT_EQ(2, gtest_failures.size()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", gtest_failures.GetTestPartResult(1).message()); } TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures); DoExpectNoFatalFailureOnFails(); } ASSERT_EQ(3, gtest_failures.size()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(2).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", gtest_failures.GetTestPartResult(1).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure", gtest_failures.GetTestPartResult(2).message()); } TEST_F(NoFatalFailureTest, MessageIsStreamable) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures); EXPECT_NO_FATAL_FAILURE([] { FAIL() << "foo"; }()) << "my message"; } ASSERT_EQ(2, gtest_failures.size()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message", gtest_failures.GetTestPartResult(1).message()); } std::string EditsToString(const std::vector<EditType>& edits) { std::string out; for (size_t i = 0; i < edits.size(); ++i) { static const char kEdits[] = " +-/"; out.append(1, kEdits[edits[i]]); } return out; } std::vector<size_t> CharsToIndices(const std::string& str) { std::vector<size_t> out; for (size_t i = 0; i < str.size(); ++i) { out.push_back(static_cast<size_t>(str[i])); } return out; } std::vector<std::string> CharsToLines(const std::string& str) { std::vector<std::string> out; for (size_t i = 0; i < str.size(); ++i) { out.push_back(str.substr(i, 1)); } return out; } TEST(EditDistance, TestSuites) { struct Case { int line; const char* left; const char* right; const char* expected_edits; const char* expected_diff; }; static const Case kCases[] = { {__LINE__, "A", "A", " ", ""}, {__LINE__, "ABCDE", "ABCDE", " ", ""}, {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"}, {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"}, {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"}, {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"}, {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"}, {__LINE__, "ABCD", "abcd", " "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"}, {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +", "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"}, {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ", "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"}, {__LINE__, "ABCDE", "BCDCD", "- +/", "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"}, {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++", "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n" "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"}, {}}; for (const Case* c = kCases; c->left; ++c) { EXPECT_TRUE(c->expected_edits == EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), CharsToIndices(c->right)))) << "Left <" << c->left << "> Right <" << c->right << "> Edits <" << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), CharsToIndices(c->right))) << ">"; EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))) << "Left <" << c->left << "> Right <" << c->right << "> Diff <" << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right)) << ">"; } } TEST(AssertionTest, EqFailure) { const std::string foo_val("5"), bar_val("6"); const std::string msg1( EqFailure("foo", "bar", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " foo\n" " Which is: 5\n" " bar\n" " Which is: 6", msg1.c_str()); const std::string msg2( EqFailure("foo", "6", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " foo\n" " Which is: 5\n" " 6", msg2.c_str()); const std::string msg3( EqFailure("5", "bar", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " 5\n" " bar\n" " Which is: 6", msg3.c_str()); const std::string msg4( EqFailure("5", "6", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " 5\n" " 6", msg4.c_str()); const std::string msg5( EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true) .failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " foo\n" " Which is: \"x\"\n" " bar\n" " Which is: \"y\"\n" "Ignoring case", msg5.c_str()); } TEST(AssertionTest, EqFailureWithDiff) { const std::string left( "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15"); const std::string right( "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14"); const std::string msg1( EqFailure("left", "right", left, right, false).failure_message()); EXPECT_STREQ( "Expected equality of these values:\n" " left\n" " Which is: " "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n" " right\n" " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n" "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n" "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n", msg1.c_str()); } TEST(AssertionTest, AppendUserMessage) { const std::string foo("foo"); Message msg; EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str()); msg << "bar"; EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str()); } #ifdef __BORLANDC__ #pragma option push -w-ccc -w-rch #endif TEST(AssertionTest, ASSERT_TRUE) { ASSERT_TRUE(2 > 1); EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1"); } TEST(AssertionTest, AssertTrueWithAssertionResult) { ASSERT_TRUE(ResultIsEven(2)); #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)), "Value of: ResultIsEven(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); #endif ASSERT_TRUE(ResultIsEvenNoExplanation(2)); EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)), "Value of: ResultIsEvenNoExplanation(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); } TEST(AssertionTest, ASSERT_FALSE) { ASSERT_FALSE(2 < 1); EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1), "Value of: 2 > 1\n" " Actual: true\n" "Expected: false"); } TEST(AssertionTest, AssertFalseWithAssertionResult) { ASSERT_FALSE(ResultIsEven(3)); #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)), "Value of: ResultIsEven(2)\n" " Actual: true (2 is even)\n" "Expected: false"); #endif ASSERT_FALSE(ResultIsEvenNoExplanation(3)); EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)), "Value of: ResultIsEvenNoExplanation(2)\n" " Actual: true\n" "Expected: false"); } #ifdef __BORLANDC__ #pragma option pop #endif TEST(ExpectTest, ASSERT_EQ_Double) { ASSERT_EQ(5.6, 5.6); EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1"); } TEST(AssertionTest, ASSERT_EQ) { ASSERT_EQ(5, 2 + 3); EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), "Expected equality of these values:\n" " 5\n" " 2*3\n" " Which is: 6"); } TEST(AssertionTest, ASSERT_EQ_NULL) { const char* p = nullptr; ASSERT_EQ(nullptr, p); static int n = 0; EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), " &n\n Which is:"); } TEST(ExpectTest, ASSERT_EQ_0) { int n = 0; ASSERT_EQ(0, n); EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), " 0\n 5.6"); } TEST(AssertionTest, ASSERT_NE) { ASSERT_NE(6, 7); EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'), "Expected: ('a') != ('a'), " "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); } TEST(AssertionTest, ASSERT_LE) { ASSERT_LE(2, 3); ASSERT_LE(2, 2); EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); } TEST(AssertionTest, ASSERT_LT) { ASSERT_LT(2, 3); EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); } TEST(AssertionTest, ASSERT_GE) { ASSERT_GE(2, 1); ASSERT_GE(2, 2); EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); } TEST(AssertionTest, ASSERT_GT) { ASSERT_GT(2, 1); EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); } #if GTEST_HAS_EXCEPTIONS void ThrowNothing() {} TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowAnInteger(), int); #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of type bool.\n" " Actual: it throws a different type."); EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowRuntimeError("A description"), std::logic_error), "Expected: ThrowRuntimeError(\"A description\") " "throws an exception of type std::logic_error.\n " "Actual: it throws " ERROR_DESC " " "with description \"A description\"."); #endif EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" " Actual: it throws nothing."); } TEST(AssertionTest, ASSERT_NO_THROW) { ASSERT_NO_THROW(ThrowNothing()); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an exception." "\n Actual: it throws."); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError("A description")), "Expected: ThrowRuntimeError(\"A description\") " "doesn't throw an exception.\n " "Actual: it throws " ERROR_DESC " " "with description \"A description\"."); } TEST(AssertionTest, ASSERT_ANY_THROW) { ASSERT_ANY_THROW(ThrowAnInteger()); EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't."); } #endif TEST(AssertionTest, AssertPrecedence) { ASSERT_EQ(1 < 2, true); bool false_value = false; ASSERT_EQ(true && false_value, false); } void TestEq1(int x) { ASSERT_EQ(1, x); } TEST(AssertionTest, NonFixtureSubroutine) { EXPECT_FATAL_FAILURE(TestEq1(2), " x\n Which is: 2"); } class Uncopyable { public: explicit Uncopyable(int a_value) : value_(a_value) {} int value() const { return value_; } bool operator==(const Uncopyable& rhs) const { return value() == rhs.value(); } private: Uncopyable(const Uncopyable&); int value_; }; ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) { return os << value.value(); } bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; } void TestAssertNonPositive() { Uncopyable y(-1); ASSERT_PRED1(IsPositiveUncopyable, y); } void TestAssertEqualsUncopyable() { Uncopyable x(5); Uncopyable y(-1); ASSERT_EQ(x, y); } TEST(AssertionTest, AssertWorksWithUncopyableObject) { Uncopyable x(5); ASSERT_PRED1(IsPositiveUncopyable, x); ASSERT_EQ(x, x); EXPECT_FATAL_FAILURE( TestAssertNonPositive(), "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), "Expected equality of these values:\n" " x\n Which is: 5\n y\n Which is: -1"); } TEST(AssertionTest, ExpectWorksWithUncopyableObject) { Uncopyable x(5); EXPECT_PRED1(IsPositiveUncopyable, x); Uncopyable y(-1); EXPECT_NONFATAL_FAILURE( EXPECT_PRED1(IsPositiveUncopyable, y), "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_EQ(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "Expected equality of these values:\n" " x\n Which is: 5\n y\n Which is: -1"); } enum NamedEnum { kE1 = 0, kE2 = 1 }; TEST(AssertionTest, NamedEnum) { EXPECT_EQ(kE1, kE1); EXPECT_LT(kE1, kE2); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1"); } #if !defined(__SUNPRO_CC) && !defined(__HP_aCC) enum { kCaseA = -1, #ifdef GTEST_OS_LINUX kCaseB = testing::internal::kMaxBiggestInt, #else kCaseB = INT_MAX, #endif kCaseC = 42 }; TEST(AssertionTest, AnonymousEnum) { #ifdef GTEST_OS_LINUX EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB)); #endif EXPECT_EQ(kCaseA, kCaseA); EXPECT_NE(kCaseA, kCaseB); EXPECT_LT(kCaseA, kCaseB); EXPECT_LE(kCaseA, kCaseB); EXPECT_GT(kCaseB, kCaseA); EXPECT_GE(kCaseA, kCaseA); EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)"); EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42"); ASSERT_EQ(kCaseA, kCaseA); ASSERT_NE(kCaseA, kCaseB); ASSERT_LT(kCaseA, kCaseB); ASSERT_LE(kCaseA, kCaseB); ASSERT_GT(kCaseB, kCaseA); ASSERT_GE(kCaseA, kCaseA); #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), " kCaseB\n Which is: "); EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: 42"); #endif EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "\n Which is: -1"); } #endif #ifdef GTEST_OS_WINDOWS static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; } static HRESULT OkHRESULTSuccess() { return S_OK; } static HRESULT FalseHRESULTSuccess() { return S_FALSE; } TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { EXPECT_HRESULT_SUCCEEDED(S_OK); EXPECT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { ASSERT_HRESULT_SUCCEEDED(S_OK); ASSERT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { EXPECT_HRESULT_FAILED(E_UNEXPECTED); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), "Expected: (OkHRESULTSuccess()) fails.\n" " Actual: 0x0"); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), "Expected: (FalseHRESULTSuccess()) fails.\n" " Actual: 0x1"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { ASSERT_HRESULT_FAILED(E_UNEXPECTED); #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), "Expected: (OkHRESULTSuccess()) fails.\n" " Actual: 0x0"); #endif EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), "Expected: (FalseHRESULTSuccess()) fails.\n" " Actual: 0x1"); } TEST(HRESULTAssertionTest, Streaming) { EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", "expected failure"); #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", "expected failure"); #endif EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure"); } #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdangling-else" #pragma GCC diagnostic ignored "-Wempty-body" #pragma GCC diagnostic ignored "-Wpragmas" #endif TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) ASSERT_TRUE(false) << "This should never be executed; " "It's a compilation test only."; if (AlwaysTrue()) EXPECT_FALSE(false); else ; if (AlwaysFalse()) ASSERT_LT(1, 3); if (AlwaysFalse()) ; else EXPECT_GT(3, 2) << ""; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #if GTEST_HAS_EXCEPTIONS TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { int n = 0; EXPECT_THROW(throw 1, int); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw n, const char*), ""); EXPECT_NO_THROW(n++); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); EXPECT_ANY_THROW(throw 1); EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), ""); } TEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) { EXPECT_THROW(throw std::exception(), std::exception); } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdangling-else" #pragma GCC diagnostic ignored "-Wempty-body" #pragma GCC diagnostic ignored "-Wpragmas" #endif TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool); if (AlwaysTrue()) EXPECT_THROW(ThrowAnInteger(), int); else ; if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger()); if (AlwaysTrue()) EXPECT_NO_THROW(ThrowNothing()); else ; if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing()); if (AlwaysTrue()) EXPECT_ANY_THROW(ThrowAnInteger()); else ; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdangling-else" #pragma GCC diagnostic ignored "-Wempty-body" #pragma GCC diagnostic ignored "-Wpragmas" #endif TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. " << "It's a compilation test only."; else ; if (AlwaysFalse()) ASSERT_NO_FATAL_FAILURE(FAIL()) << ""; else ; if (AlwaysTrue()) EXPECT_NO_FATAL_FAILURE(SUCCEED()); else ; if (AlwaysFalse()) ; else ASSERT_NO_FATAL_FAILURE(SUCCEED()); } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif TEST(AssertionSyntaxTest, WorksWithSwitch) { switch (0) { case 1: break; default: ASSERT_TRUE(true); } switch (0) case 0: EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; switch (0) { case 1: default: ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler"; } switch (0) case 0: EXPECT_NE(1, 2); } #if GTEST_HAS_EXCEPTIONS void ThrowAString() { throw "std::string"; } TEST(AssertionSyntaxTest, WorksWithConst) { ASSERT_THROW(ThrowAString(), const char*); EXPECT_THROW(ThrowAString(), const char*); } #endif } namespace testing { TEST(SuccessfulAssertionTest, SUCCEED) { SUCCEED(); SUCCEED() << "OK"; EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count()); } TEST(SuccessfulAssertionTest, EXPECT) { EXPECT_TRUE(true); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } TEST(SuccessfulAssertionTest, EXPECT_STR) { EXPECT_STREQ("", ""); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } TEST(SuccessfulAssertionTest, ASSERT) { ASSERT_TRUE(true); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } TEST(SuccessfulAssertionTest, ASSERT_STR) { ASSERT_STREQ("", ""); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } } namespace { TEST(AssertionWithMessageTest, EXPECT) { EXPECT_EQ(1, 1) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.", "Expected failure #1"); EXPECT_LE(1, 2) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.", "Expected failure #2."); EXPECT_GE(1, 0) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.", "Expected failure #3."); EXPECT_STREQ("1", "1") << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.", "Expected failure #4."); EXPECT_STRCASEEQ("a", "A") << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.", "Expected failure #5."); EXPECT_FLOAT_EQ(1, 1) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.", "Expected failure #6."); EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed."; } TEST(AssertionWithMessageTest, ASSERT) { ASSERT_EQ(1, 1) << "This should succeed."; ASSERT_NE(1, 2) << "This should succeed."; ASSERT_LE(1, 2) << "This should succeed."; ASSERT_LT(1, 2) << "This should succeed."; ASSERT_GE(1, 0) << "This should succeed."; EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.", "Expected failure."); } TEST(AssertionWithMessageTest, ASSERT_STR) { ASSERT_STREQ("1", "1") << "This should succeed."; ASSERT_STRNE("1", "2") << "This should succeed."; ASSERT_STRCASEEQ("a", "A") << "This should succeed."; EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.", "Expected failure."); } TEST(AssertionWithMessageTest, ASSERT_FLOATING) { ASSERT_FLOAT_EQ(1, 1) << "This should succeed."; ASSERT_DOUBLE_EQ(1, 1) << "This should succeed."; EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << "Expect failure.", "Expect failure."); } TEST(AssertionWithMessageTest, ASSERT_FALSE) { ASSERT_FALSE(false) << "This shouldn't fail."; EXPECT_FATAL_FAILURE( { ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 << " evaluates to " << true; }, "Expected failure"); } TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); } TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; } TEST(AssertionWithMessageTest, ASSERT_TRUE) { ASSERT_TRUE(true) << "This should succeed."; ASSERT_TRUE(true) << true; EXPECT_FATAL_FAILURE( { ASSERT_TRUE(false) << static_cast<const char*>(nullptr) << static_cast<char*>(nullptr); }, "(null)(null)"); } #ifdef GTEST_OS_WINDOWS TEST(AssertionWithMessageTest, WideStringMessage) { EXPECT_NONFATAL_FAILURE( { EXPECT_TRUE(false) << L"This failure is expected.\x8119"; }, "This failure is expected."); EXPECT_FATAL_FAILURE( { ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120"; }, "This failure is expected too."); } #endif TEST(ExpectTest, EXPECT_TRUE) { EXPECT_TRUE(true) << "Intentional success"; EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.", "Intentional failure #1."); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.", "Intentional failure #2."); EXPECT_TRUE(2 > 1); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1), "Value of: 2 < 1\n" " Actual: false\n" "Expected: true"); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3"); } TEST(ExpectTest, ExpectTrueWithAssertionResult) { EXPECT_TRUE(ResultIsEven(2)); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)), "Value of: ResultIsEven(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); EXPECT_TRUE(ResultIsEvenNoExplanation(2)); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)), "Value of: ResultIsEvenNoExplanation(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); } TEST(ExpectTest, EXPECT_FALSE) { EXPECT_FALSE(2 < 1); EXPECT_FALSE(false) << "Intentional success"; EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.", "Intentional failure #1."); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.", "Intentional failure #2."); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1), "Value of: 2 > 1\n" " Actual: true\n" "Expected: false"); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3"); } TEST(ExpectTest, ExpectFalseWithAssertionResult) { EXPECT_FALSE(ResultIsEven(3)); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)), "Value of: ResultIsEven(2)\n" " Actual: true (2 is even)\n" "Expected: false"); EXPECT_FALSE(ResultIsEvenNoExplanation(3)); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)), "Value of: ResultIsEvenNoExplanation(2)\n" " Actual: true\n" "Expected: false"); } #ifdef __BORLANDC__ #pragma option pop #endif TEST(ExpectTest, EXPECT_EQ) { EXPECT_EQ(5, 2 + 3); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), "Expected equality of these values:\n" " 5\n" " 2*3\n" " Which is: 6"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3"); } TEST(ExpectTest, EXPECT_EQ_Double) { EXPECT_EQ(5.6, 5.6); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1"); } TEST(ExpectTest, EXPECT_EQ_NULL) { const char* p = nullptr; EXPECT_EQ(nullptr, p); int n = 0; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), " &n\n Which is:"); } TEST(ExpectTest, EXPECT_EQ_0) { int n = 0; EXPECT_EQ(0, n); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), " 0\n 5.6"); } TEST(ExpectTest, EXPECT_NE) { EXPECT_NE(6, 7); EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), "Expected: ('a') != ('a'), " "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2"); char* const p0 = nullptr; EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0"); void* pv1 = (void*)0x1234; char* const p1 = reinterpret_cast<char*>(pv1); EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1"); } TEST(ExpectTest, EXPECT_LE) { EXPECT_LE(2, 3); EXPECT_LE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)"); } TEST(ExpectTest, EXPECT_LT) { EXPECT_LT(2, 3); EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)"); } TEST(ExpectTest, EXPECT_GE) { EXPECT_GE(2, 1); EXPECT_GE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)"); } TEST(ExpectTest, EXPECT_GT) { EXPECT_GT(2, 1); EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)"); } #if GTEST_HAS_EXCEPTIONS TEST(ExpectTest, EXPECT_THROW) { EXPECT_THROW(ThrowAnInteger(), int); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of " "type bool.\n Actual: it throws a different type."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW(ThrowRuntimeError("A description"), std::logic_error), "Expected: ThrowRuntimeError(\"A description\") " "throws an exception of type std::logic_error.\n " "Actual: it throws " ERROR_DESC " " "with description \"A description\"."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" " Actual: it throws nothing."); } TEST(ExpectTest, EXPECT_NO_THROW) { EXPECT_NO_THROW(ThrowNothing()); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an " "exception.\n Actual: it throws."); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError("A description")), "Expected: ThrowRuntimeError(\"A description\") " "doesn't throw an exception.\n " "Actual: it throws " ERROR_DESC " " "with description \"A description\"."); } TEST(ExpectTest, EXPECT_ANY_THROW) { EXPECT_ANY_THROW(ThrowAnInteger()); EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't."); } #endif TEST(ExpectTest, ExpectPrecedence) { EXPECT_EQ(1 < 2, true); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), " true && false\n Which is: false"); } TEST(StreamableToStringTest, Scalar) { EXPECT_STREQ("5", StreamableToString(5).c_str()); } TEST(StreamableToStringTest, Pointer) { int n = 0; int* p = &n; EXPECT_STRNE("(null)", StreamableToString(p).c_str()); } TEST(StreamableToStringTest, NullPointer) { int* p = nullptr; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } TEST(StreamableToStringTest, CString) { EXPECT_STREQ("Foo", StreamableToString("Foo").c_str()); } TEST(StreamableToStringTest, NullCString) { char* p = nullptr; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } TEST(StreamableTest, string) { static const std::string str( "This failure message is a std::string, and is expected."); EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str()); } TEST(StreamableTest, stringWithEmbeddedNUL) { static const char char_array_with_nul[] = "Here's a NUL\0 and some more string"; static const std::string string_with_nul( char_array_with_nul, sizeof(char_array_with_nul) - 1); EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, "Here's a NUL\\0 and some more string"); } TEST(StreamableTest, NULChar) { EXPECT_FATAL_FAILURE( { FAIL() << "A NUL" << '\0' << " and some more string"; }, "A NUL\\0 and some more string"); } TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); } TEST(StreamableTest, NullCharPtr) { EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), "(null)"); } TEST(StreamableTest, BasicIoManip) { EXPECT_FATAL_FAILURE( { FAIL() << "Line 1." << std::endl << "A NUL char " << std::ends << std::flush << " in line 2."; }, "Line 1.\nA NUL char \\0 in line 2."); } void AddFailureHelper(bool* aborted) { *aborted = true; ADD_FAILURE() << "Intentional failure."; *aborted = false; } TEST(MacroTest, ADD_FAILURE) { bool aborted = true; EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure."); EXPECT_FALSE(aborted); } TEST(MacroTest, ADD_FAILURE_AT) { EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!"); EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed"); } TEST(MacroTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL(), "Failed"); EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", "Intentional failure."); } TEST(MacroTest, GTEST_FAIL_AT) { EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42) << "Wrong!", "Wrong!"); EXPECT_FATAL_FAILURE(GTEST_FAIL_AT("foo.cc", 42), "Failed"); } TEST(MacroTest, SUCCEED) { SUCCEED(); SUCCEED() << "Explicit success."; } TEST(EqAssertionTest, Bool) { EXPECT_EQ(true, true); EXPECT_FATAL_FAILURE( { bool false_value = false; ASSERT_EQ(false_value, true); }, " false_value\n Which is: false\n true"); } TEST(EqAssertionTest, Int) { ASSERT_EQ(32, 32); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), " 32\n 33"); } TEST(EqAssertionTest, Time_T) { EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0)); EXPECT_FATAL_FAILURE( ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234"); } TEST(EqAssertionTest, Char) { ASSERT_EQ('z', 'z'); const char ch = 'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), " ch\n Which is: 'b'"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), " ch\n Which is: 'b'"); } TEST(EqAssertionTest, WideChar) { EXPECT_EQ(L'b', L'b'); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), "Expected equality of these values:\n" " L'\0'\n" " Which is: L'\0' (0, 0x0)\n" " L'x'\n" " Which is: L'x' (120, 0x78)"); static wchar_t wchar; wchar = L'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar"); wchar = 0x8119; EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar), " wchar\n Which is: L'"); } TEST(EqAssertionTest, StdString) { ASSERT_EQ("Test", ::std::string("Test")); static const ::std::string str1("A * in the middle"); static const ::std::string str2(str1); EXPECT_EQ(str1, str2); EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\""); char* const p1 = const_cast<char*>("foo"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1"); static ::std::string str3(str1); str3.at(2) = '\0'; EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), " str3\n Which is: \"A \\0 in the middle\""); } #if GTEST_HAS_STD_WSTRING TEST(EqAssertionTest, StdWideString) { const ::std::wstring wstr1(L"A * in the middle"); const ::std::wstring wstr2(wstr1); ASSERT_EQ(wstr1, wstr2); const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\0'}; EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\0'}; EXPECT_NONFATAL_FAILURE( { EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); }, "kTestX8120"); ::std::wstring wstr3(wstr1); wstr3.at(2) = L'\0'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3"); EXPECT_FATAL_FAILURE( { ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar")); }, ""); } #endif TEST(EqAssertionTest, CharPointer) { char* const p0 = nullptr; void* pv1 = (void*)0x1234; void* pv2 = (void*)0xABC0; char* const p1 = reinterpret_cast<char*>(pv1); char* const p2 = reinterpret_cast<char*>(pv2); ASSERT_EQ(p1, p1); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:"); EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234), reinterpret_cast<char*>(0xABC0)), "ABC0"); } TEST(EqAssertionTest, WideCharPointer) { wchar_t* const p0 = nullptr; void* pv1 = (void*)0x1234; void* pv2 = (void*)0xABC0; wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1); wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2); EXPECT_EQ(p0, p0); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), " p2\n Which is:"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), " p2\n Which is:"); void* pv3 = (void*)0x1234; void* pv4 = (void*)0xABC0; const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3); const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4"); } TEST(EqAssertionTest, OtherPointer) { ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr)); EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr), reinterpret_cast<const int*>(0x1234)), "0x1234"); } class UnprintableChar { public: explicit UnprintableChar(char ch) : char_(ch) {} bool operator==(const UnprintableChar& rhs) const { return char_ == rhs.char_; } bool operator!=(const UnprintableChar& rhs) const { return char_ != rhs.char_; } bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; } bool operator<=(const UnprintableChar& rhs) const { return char_ <= rhs.char_; } bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; } bool operator>=(const UnprintableChar& rhs) const { return char_ >= rhs.char_; } private: char char_; }; TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) { const UnprintableChar x('x'), y('y'); ASSERT_EQ(x, x); EXPECT_NE(x, y); ASSERT_LT(x, y); EXPECT_LE(x, y); ASSERT_GT(y, x); EXPECT_GE(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>"); EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>"); #ifndef __BORLANDC__ EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')), "1-byte object <78>"); EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), "1-byte object <78>"); #endif EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), "1-byte object <79>"); EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), "1-byte object <78>"); EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), "1-byte object <79>"); } class Foo { public: Foo() = default; private: int Bar() const { return 1; } FRIEND_TEST(FRIEND_TEST_Test, TEST); FRIEND_TEST(FRIEND_TEST_Test2, TEST_F); }; TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); } class FRIEND_TEST_Test2 : public Test { protected: Foo foo; }; TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); } class TestLifeCycleTest : public Test { protected: TestLifeCycleTest() { count_++; } ~TestLifeCycleTest() override { count_--; } int count() const { return count_; } private: static int count_; }; int TestLifeCycleTest::count_ = 0; TEST_F(TestLifeCycleTest, Test1) { ASSERT_EQ(1, count()); } TEST_F(TestLifeCycleTest, Test2) { ASSERT_EQ(1, count()); } } TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) { AssertionResult r1 = AssertionSuccess(); AssertionResult r2 = r1; r1 << "abc"; AssertionResult r3 = r1; EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1)); EXPECT_STREQ("abc", r1.message()); } TEST(AssertionResultTest, ConstructionWorks) { AssertionResult r1 = AssertionSuccess(); EXPECT_TRUE(r1); EXPECT_STREQ("", r1.message()); AssertionResult r2 = AssertionSuccess() << "abc"; EXPECT_TRUE(r2); EXPECT_STREQ("abc", r2.message()); AssertionResult r3 = AssertionFailure(); EXPECT_FALSE(r3); EXPECT_STREQ("", r3.message()); AssertionResult r4 = AssertionFailure() << "def"; EXPECT_FALSE(r4); EXPECT_STREQ("def", r4.message()); AssertionResult r5 = AssertionFailure(Message() << "ghi"); EXPECT_FALSE(r5); EXPECT_STREQ("ghi", r5.message()); } TEST(AssertionResultTest, NegationWorks) { AssertionResult r1 = AssertionSuccess() << "abc"; EXPECT_FALSE(!r1); EXPECT_STREQ("abc", (!r1).message()); AssertionResult r2 = AssertionFailure() << "def"; EXPECT_TRUE(!r2); EXPECT_STREQ("def", (!r2).message()); } TEST(AssertionResultTest, StreamingWorks) { AssertionResult r = AssertionSuccess(); r << "abc" << 'd' << 0 << true; EXPECT_STREQ("abcd0true", r.message()); } TEST(AssertionResultTest, CanStreamOstreamManipulators) { AssertionResult r = AssertionSuccess(); r << "Data" << std::endl << std::flush << std::ends << "Will be visible"; EXPECT_STREQ("Data\n\\0Will be visible", r.message()); } TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) { struct ExplicitlyConvertibleToBool { explicit operator bool() const { return value; } bool value; }; ExplicitlyConvertibleToBool v1 = {false}; ExplicitlyConvertibleToBool v2 = {true}; EXPECT_FALSE(v1); EXPECT_TRUE(v2); } struct ConvertibleToAssertionResult { operator AssertionResult() const { return AssertionResult(true); } }; TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) { ConvertibleToAssertionResult obj; EXPECT_TRUE(obj); } class Base { public: explicit Base(int an_x) : x_(an_x) {} int x() const { return x_; } private: int x_; }; std::ostream& operator<<(std::ostream& os, const Base& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const Base* pointer) { return os << "(" << pointer->x() << ")"; } TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { Message msg; Base a(1); msg << a << &a; EXPECT_STREQ("1(1)", msg.GetString().c_str()); } namespace { class MyTypeInUnnamedNameSpace : public Base { public: explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {} }; std::ostream& operator<<(std::ostream& os, const MyTypeInUnnamedNameSpace& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const MyTypeInUnnamedNameSpace* pointer) { return os << "(" << pointer->x() << ")"; } } TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) { Message msg; MyTypeInUnnamedNameSpace a(1); msg << a << &a; EXPECT_STREQ("1(1)", msg.GetString().c_str()); } namespace namespace1 { class MyTypeInNameSpace1 : public Base { public: explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {} }; std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) { return os << "(" << pointer->x() << ")"; } } TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { Message msg; namespace1::MyTypeInNameSpace1 a(1); msg << a << &a; EXPECT_STREQ("1(1)", msg.GetString().c_str()); } namespace namespace2 { class MyTypeInNameSpace2 : public ::Base { public: explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {} }; } std::ostream& operator<<(std::ostream& os, const namespace2::MyTypeInNameSpace2& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const namespace2::MyTypeInNameSpace2* pointer) { return os << "(" << pointer->x() << ")"; } TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) { Message msg; namespace2::MyTypeInNameSpace2 a(1); msg << a << &a; EXPECT_STREQ("1(1)", msg.GetString().c_str()); } TEST(MessageTest, NullPointers) { Message msg; char* const p1 = nullptr; unsigned char* const p2 = nullptr; int* p3 = nullptr; double* p4 = nullptr; bool* p5 = nullptr; Message* p6 = nullptr; msg << p1 << p2 << p3 << p4 << p5 << p6; ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str()); } TEST(MessageTest, WideStrings) { const wchar_t* const_wstr = nullptr; EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str()); wchar_t* wstr = nullptr; EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str()); const_wstr = L"abc\x8119"; EXPECT_STREQ("abc\xe8\x84\x99", (Message() << const_wstr).GetString().c_str()); wstr = const_cast<wchar_t*>(const_wstr); EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str()); } namespace testing { class TestInfoTest : public Test { protected: static const TestInfo* GetTestInfo(const char* test_name) { const TestSuite* const test_suite = GetUnitTestImpl()->GetTestSuite("TestInfoTest", "", nullptr, nullptr); for (int i = 0; i < test_suite->total_test_count(); ++i) { const TestInfo* const test_info = test_suite->GetTestInfo(i); if (strcmp(test_name, test_info->name()) == 0) return test_info; } return nullptr; } static const TestResult* GetTestResult(const TestInfo* test_info) { return test_info->result(); } }; TEST_F(TestInfoTest, Names) { const TestInfo* const test_info = GetTestInfo("Names"); ASSERT_STREQ("TestInfoTest", test_info->test_suite_name()); ASSERT_STREQ("Names", test_info->name()); } TEST_F(TestInfoTest, result) { const TestInfo* const test_info = GetTestInfo("result"); ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); } #define VERIFY_CODE_LOCATION \ const int expected_line = __LINE__ - 1; \ const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \ ASSERT_TRUE(test_info); \ EXPECT_STREQ(__FILE__, test_info->file()); \ EXPECT_EQ(expected_line, test_info->line()) TEST(CodeLocationForTEST, Verify) { VERIFY_CODE_LOCATION; } class CodeLocationForTESTF : public Test {}; TEST_F(CodeLocationForTESTF, Verify) { VERIFY_CODE_LOCATION; } class CodeLocationForTESTP : public TestWithParam<int> {}; TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; } INSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0)); template <typename T> class CodeLocationForTYPEDTEST : public Test {}; TYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int); TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { VERIFY_CODE_LOCATION; } template <typename T> class CodeLocationForTYPEDTESTP : public Test {}; TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP); TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) { VERIFY_CODE_LOCATION; } REGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify); INSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int); #undef VERIFY_CODE_LOCATION #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ class SetUpTestCaseTest : public Test { protected: static void SetUpTestCase() { printf("Setting up the test case . . .\n"); shared_resource_ = "123"; counter_++; EXPECT_EQ(1, counter_); } static void TearDownTestCase() { printf("Tearing down the test case . . .\n"); counter_--; EXPECT_EQ(0, counter_); shared_resource_ = nullptr; } void SetUp() override { EXPECT_EQ(1, counter_); } static int counter_; static const char* shared_resource_; }; int SetUpTestCaseTest::counter_ = 0; const char* SetUpTestCaseTest::shared_resource_ = nullptr; TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); } TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } #endif class SetUpTestSuiteTest : public Test { protected: static void SetUpTestSuite() { printf("Setting up the test suite . . .\n"); shared_resource_ = "123"; counter_++; EXPECT_EQ(1, counter_); } static void TearDownTestSuite() { printf("Tearing down the test suite . . .\n"); counter_--; EXPECT_EQ(0, counter_); shared_resource_ = nullptr; } void SetUp() override { EXPECT_EQ(1, counter_); } static int counter_; static const char* shared_resource_; }; int SetUpTestSuiteTest::counter_ = 0; const char* SetUpTestSuiteTest::shared_resource_ = nullptr; TEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) { EXPECT_STRNE(nullptr, shared_resource_); } TEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) { EXPECT_STREQ("123", shared_resource_); } struct Flags { Flags() : also_run_disabled_tests(false), break_on_failure(false), catch_exceptions(false), death_test_use_fork(false), fail_fast(false), filter(""), list_tests(false), output(""), brief(false), print_time(true), random_seed(0), repeat(1), recreate_environments_when_repeating(true), shuffle(false), stack_trace_depth(kMaxStackTraceDepth), stream_result_to(""), throw_on_failure(false) {} static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) { Flags flags; flags.also_run_disabled_tests = also_run_disabled_tests; return flags; } static Flags BreakOnFailure(bool break_on_failure) { Flags flags; flags.break_on_failure = break_on_failure; return flags; } static Flags CatchExceptions(bool catch_exceptions) { Flags flags; flags.catch_exceptions = catch_exceptions; return flags; } static Flags DeathTestUseFork(bool death_test_use_fork) { Flags flags; flags.death_test_use_fork = death_test_use_fork; return flags; } static Flags FailFast(bool fail_fast) { Flags flags; flags.fail_fast = fail_fast; return flags; } static Flags Filter(const char* filter) { Flags flags; flags.filter = filter; return flags; } static Flags ListTests(bool list_tests) { Flags flags; flags.list_tests = list_tests; return flags; } static Flags Output(const char* output) { Flags flags; flags.output = output; return flags; } static Flags Brief(bool brief) { Flags flags; flags.brief = brief; return flags; } static Flags PrintTime(bool print_time) { Flags flags; flags.print_time = print_time; return flags; } static Flags RandomSeed(int32_t random_seed) { Flags flags; flags.random_seed = random_seed; return flags; } static Flags Repeat(int32_t repeat) { Flags flags; flags.repeat = repeat; return flags; } static Flags RecreateEnvironmentsWhenRepeating( bool recreate_environments_when_repeating) { Flags flags; flags.recreate_environments_when_repeating = recreate_environments_when_repeating; return flags; } static Flags Shuffle(bool shuffle) { Flags flags; flags.shuffle = shuffle; return flags; } static Flags StackTraceDepth(int32_t stack_trace_depth) { Flags flags; flags.stack_trace_depth = stack_trace_depth; return flags; } static Flags StreamResultTo(const char* stream_result_to) { Flags flags; flags.stream_result_to = stream_result_to; return flags; } static Flags ThrowOnFailure(bool throw_on_failure) { Flags flags; flags.throw_on_failure = throw_on_failure; return flags; } bool also_run_disabled_tests; bool break_on_failure; bool catch_exceptions; bool death_test_use_fork; bool fail_fast; const char* filter; bool list_tests; const char* output; bool brief; bool print_time; int32_t random_seed; int32_t repeat; bool recreate_environments_when_repeating; bool shuffle; int32_t stack_trace_depth; const char* stream_result_to; bool throw_on_failure; }; class ParseFlagsTest : public Test { protected: void SetUp() override { GTEST_FLAG_SET(also_run_disabled_tests, false); GTEST_FLAG_SET(break_on_failure, false); GTEST_FLAG_SET(catch_exceptions, false); GTEST_FLAG_SET(death_test_use_fork, false); GTEST_FLAG_SET(fail_fast, false); GTEST_FLAG_SET(filter, ""); GTEST_FLAG_SET(list_tests, false); GTEST_FLAG_SET(output, ""); GTEST_FLAG_SET(brief, false); GTEST_FLAG_SET(print_time, true); GTEST_FLAG_SET(random_seed, 0); GTEST_FLAG_SET(repeat, 1); GTEST_FLAG_SET(recreate_environments_when_repeating, true); GTEST_FLAG_SET(shuffle, false); GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth); GTEST_FLAG_SET(stream_result_to, ""); GTEST_FLAG_SET(throw_on_failure, false); } template <typename CharType> static void AssertStringArrayEq(int size1, CharType** array1, int size2, CharType** array2) { ASSERT_EQ(size1, size2) << " Array sizes different."; for (int i = 0; i != size1; i++) { ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; } } static void CheckFlags(const Flags& expected) { EXPECT_EQ(expected.also_run_disabled_tests, GTEST_FLAG_GET(also_run_disabled_tests)); EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure)); EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions)); EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG_GET(death_test_use_fork)); EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast)); EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str()); EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests)); EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str()); EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief)); EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time)); EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed)); EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat)); EXPECT_EQ(expected.recreate_environments_when_repeating, GTEST_FLAG_GET(recreate_environments_when_repeating)); EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle)); EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth)); EXPECT_STREQ(expected.stream_result_to, GTEST_FLAG_GET(stream_result_to).c_str()); EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure)); } template <typename CharType> static void TestParsingFlags(int argc1, const CharType** argv1, int argc2, const CharType** argv2, const Flags& expected, bool should_print_help) { const bool saved_help_flag = ::testing::internal::g_help_flag; ::testing::internal::g_help_flag = false; #if GTEST_HAS_STREAM_REDIRECTION CaptureStdout(); #endif internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); #if GTEST_HAS_STREAM_REDIRECTION const std::string captured_stdout = GetCapturedStdout(); #endif CheckFlags(expected); AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2); EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); #if GTEST_HAS_STREAM_REDIRECTION const char* const expected_help_fragment = "This program contains tests written using"; if (should_print_help) { EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout); } else { EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment, captured_stdout); } #endif ::testing::internal::g_help_flag = saved_help_flag; } #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1, \ sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected, \ should_print_help) }; TEST_F(ParseFlagsTest, Empty) { const char* argv[] = {nullptr}; const char* argv2[] = {nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } TEST_F(ParseFlagsTest, NoFlag) { const char* argv[] = {"foo.exe", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } TEST_F(ParseFlagsTest, FailFast) { const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false); } TEST_F(ParseFlagsTest, FilterEmpty) { const char* argv[] = {"foo.exe", "--gtest_filter=", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false); } TEST_F(ParseFlagsTest, FilterNonEmpty) { const char* argv[] = {"foo.exe", "--gtest_filter=abc", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); } TEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) { const char* argv[] = {"foo.exe", "--gtest_break_on_failure", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } TEST_F(ParseFlagsTest, BreakOnFailureFalse_0) { const char* argv[] = {"foo.exe", "--gtest_break_on_failure=0", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } TEST_F(ParseFlagsTest, BreakOnFailureFalse_f) { const char* argv[] = {"foo.exe", "--gtest_break_on_failure=f", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } TEST_F(ParseFlagsTest, BreakOnFailureFalse_F) { const char* argv[] = {"foo.exe", "--gtest_break_on_failure=F", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } TEST_F(ParseFlagsTest, BreakOnFailureTrue) { const char* argv[] = {"foo.exe", "--gtest_break_on_failure=1", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } TEST_F(ParseFlagsTest, CatchExceptions) { const char* argv[] = {"foo.exe", "--gtest_catch_exceptions", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false); } TEST_F(ParseFlagsTest, DeathTestUseFork) { const char* argv[] = {"foo.exe", "--gtest_death_test_use_fork", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false); } TEST_F(ParseFlagsTest, DuplicatedFlags) { const char* argv[] = {"foo.exe", "--gtest_filter=a", "--gtest_filter=b", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false); } TEST_F(ParseFlagsTest, UnrecognizedFlag) { const char* argv[] = {"foo.exe", "--gtest_break_on_failure", "bar", "--gtest_filter=b", nullptr}; const char* argv2[] = {"foo.exe", "bar", nullptr}; Flags flags; flags.break_on_failure = true; flags.filter = "b"; GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false); } TEST_F(ParseFlagsTest, ListTestsFlag) { const char* argv[] = {"foo.exe", "--gtest_list_tests", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } TEST_F(ParseFlagsTest, ListTestsTrue) { const char* argv[] = {"foo.exe", "--gtest_list_tests=1", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } TEST_F(ParseFlagsTest, ListTestsFalse) { const char* argv[] = {"foo.exe", "--gtest_list_tests=0", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } TEST_F(ParseFlagsTest, ListTestsFalse_f) { const char* argv[] = {"foo.exe", "--gtest_list_tests=f", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } TEST_F(ParseFlagsTest, ListTestsFalse_F) { const char* argv[] = {"foo.exe", "--gtest_list_tests=F", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } TEST_F(ParseFlagsTest, OutputXml) { const char* argv[] = {"foo.exe", "--gtest_output=xml", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false); } TEST_F(ParseFlagsTest, OutputXmlFile) { const char* argv[] = {"foo.exe", "--gtest_output=xml:file", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false); } TEST_F(ParseFlagsTest, OutputXmlDirectory) { const char* argv[] = {"foo.exe", "--gtest_output=xml:directory/path/", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"), false); } TEST_F(ParseFlagsTest, BriefFlag) { const char* argv[] = {"foo.exe", "--gtest_brief", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false); } TEST_F(ParseFlagsTest, BriefFlagTrue) { const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false); } TEST_F(ParseFlagsTest, BriefFlagFalse) { const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false); } TEST_F(ParseFlagsTest, PrintTimeFlag) { const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } TEST_F(ParseFlagsTest, PrintTimeTrue) { const char* argv[] = {"foo.exe", "--gtest_print_time=1", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } TEST_F(ParseFlagsTest, PrintTimeFalse) { const char* argv[] = {"foo.exe", "--gtest_print_time=0", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } TEST_F(ParseFlagsTest, PrintTimeFalse_f) { const char* argv[] = {"foo.exe", "--gtest_print_time=f", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } TEST_F(ParseFlagsTest, PrintTimeFalse_F) { const char* argv[] = {"foo.exe", "--gtest_print_time=F", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } TEST_F(ParseFlagsTest, RandomSeed) { const char* argv[] = {"foo.exe", "--gtest_random_seed=1000", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false); } TEST_F(ParseFlagsTest, Repeat) { const char* argv[] = {"foo.exe", "--gtest_repeat=1000", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); } TEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) { const char* argv[] = { "foo.exe", "--gtest_recreate_environments_when_repeating=0", nullptr, }; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_( argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false); } TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) { const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), false); } TEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) { const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=1", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), false); } TEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) { const char* argv[] = {"foo.exe", "--gtest_also_run_disabled_tests=0", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false), false); } TEST_F(ParseFlagsTest, ShuffleWithoutValue) { const char* argv[] = {"foo.exe", "--gtest_shuffle", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } TEST_F(ParseFlagsTest, ShuffleFalse_0) { const char* argv[] = {"foo.exe", "--gtest_shuffle=0", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false); } TEST_F(ParseFlagsTest, ShuffleTrue) { const char* argv[] = {"foo.exe", "--gtest_shuffle=1", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } TEST_F(ParseFlagsTest, StackTraceDepth) { const char* argv[] = {"foo.exe", "--gtest_stack_trace_depth=5", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); } TEST_F(ParseFlagsTest, StreamResultTo) { const char* argv[] = {"foo.exe", "--gtest_stream_result_to=localhost:1234", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StreamResultTo("localhost:1234"), false); } TEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) { const char* argv[] = {"foo.exe", "--gtest_throw_on_failure", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } TEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) { const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=0", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false); } TEST_F(ParseFlagsTest, ThrowOnFailureTrue) { const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } TEST_F(ParseFlagsTest, FilterBad) { const char* argv[] = {"foo.exe", "--gtest_filter", nullptr}; const char* argv2[] = {"foo.exe", "--gtest_filter", nullptr}; #if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST) EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true), testing::ExitedWithCode(1), "ERROR: Missing the value for the flag 'gtest_filter'"); #elif !defined(GTEST_HAS_ABSL) GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); #else static_cast<void>(argv); static_cast<void>(argv2); #endif } TEST_F(ParseFlagsTest, OutputEmpty) { const char* argv[] = {"foo.exe", "--gtest_output", nullptr}; const char* argv2[] = {"foo.exe", "--gtest_output", nullptr}; #if defined(GTEST_HAS_ABSL) && defined(GTEST_HAS_DEATH_TEST) EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true), testing::ExitedWithCode(1), "ERROR: Missing the value for the flag 'gtest_output'"); #elif !defined(GTEST_HAS_ABSL) GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true); #else static_cast<void>(argv); static_cast<void>(argv2); #endif } #ifdef GTEST_HAS_ABSL TEST_F(ParseFlagsTest, AbseilPositionalFlags) { const char* argv[] = {"foo.exe", "--gtest_throw_on_failure=1", "--", "--other_flag", nullptr}; const char* argv2[] = {"foo.exe", "--other_flag", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } #endif TEST_F(ParseFlagsTest, UnrecognizedFlags) { const char* argv[] = {"foo.exe", "--gtest_filter=abcd", "--other_flag", nullptr}; const char* argv2[] = {"foo.exe", "--other_flag", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abcd"), false); } #ifdef GTEST_OS_WINDOWS TEST_F(ParseFlagsTest, WideStrings) { const wchar_t* argv[] = {L"foo.exe", L"--gtest_filter=Foo*", L"--gtest_list_tests=1", L"--gtest_break_on_failure", L"--non_gtest_flag", NULL}; const wchar_t* argv2[] = {L"foo.exe", L"--non_gtest_flag", NULL}; Flags expected_flags; expected_flags.break_on_failure = true; expected_flags.filter = "Foo*"; expected_flags.list_tests = true; GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } #endif #if GTEST_USE_OWN_FLAGFILE_FLAG_ class FlagfileTest : public ParseFlagsTest { public: void SetUp() override { ParseFlagsTest::SetUp(); testdata_path_.Set(internal::FilePath( testing::TempDir() + internal::GetCurrentExecutableName().string() + "_flagfile_test")); testing::internal::posix::RmDir(testdata_path_.c_str()); EXPECT_TRUE(testdata_path_.CreateFolder()); } void TearDown() override { testing::internal::posix::RmDir(testdata_path_.c_str()); ParseFlagsTest::TearDown(); } internal::FilePath CreateFlagfile(const char* contents) { internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName( testdata_path_, internal::FilePath("unique"), "txt")); FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w"); fprintf(f, "%s", contents); fclose(f); return file_path; } private: internal::FilePath testdata_path_; }; TEST_F(FlagfileTest, Empty) { internal::FilePath flagfile_path(CreateFlagfile("")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } TEST_F(FlagfileTest, FilterNonEmpty) { internal::FilePath flagfile_path( CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; const char* argv2[] = {"foo.exe", nullptr}; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); } TEST_F(FlagfileTest, SeveralFlags) { internal::FilePath flagfile_path( CreateFlagfile("--" GTEST_FLAG_PREFIX_ "filter=abc\n" "--" GTEST_FLAG_PREFIX_ "break_on_failure\n" "--" GTEST_FLAG_PREFIX_ "list_tests")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr}; const char* argv2[] = {"foo.exe", nullptr}; Flags expected_flags; expected_flags.break_on_failure = true; expected_flags.filter = "abc"; expected_flags.list_tests = true; GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } #endif class CurrentTestInfoTest : public Test { protected: static void SetUpTestSuite() { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == nullptr) << "There should be no tests running at this point."; } static void TearDownTestSuite() { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == nullptr) << "There should be no tests running at this point."; } }; TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) << "Expected the name of the currently running test suite."; EXPECT_STREQ("WorksForFirstTestInATestSuite", test_info->name()) << "Expected the name of the currently running test."; } TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(nullptr != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_suite_name()) << "Expected the name of the currently running test suite."; EXPECT_STREQ("WorksForSecondTestInATestSuite", test_info->name()) << "Expected the name of the currently running test."; } } namespace my_namespace { namespace testing { class Test {}; class Message {}; class AssertionResult {}; TEST(NestedTestingNamespaceTest, Success) { EXPECT_EQ(1, 1) << "This shouldn't fail."; } TEST(NestedTestingNamespaceTest, Failure) { EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.", "This failure is expected."); } } } class ProtectedFixtureMethodsTest : public Test { protected: void SetUp() override { Test::SetUp(); } void TearDown() override { Test::TearDown(); } }; TEST(StreamingAssertionsTest, Unconditional) { SUCCEED() << "expected success"; EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure"); } #ifdef __BORLANDC__ #pragma option push -w-ccc -w-rch #endif TEST(StreamingAssertionsTest, Truth) { EXPECT_TRUE(true) << "unexpected failure"; ASSERT_TRUE(true) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, Truth2) { EXPECT_FALSE(false) << "unexpected failure"; ASSERT_FALSE(false) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure", "expected failure"); } #ifdef __BORLANDC__ #pragma option pop #endif TEST(StreamingAssertionsTest, IntegerEquals) { EXPECT_EQ(1, 1) << "unexpected failure"; ASSERT_EQ(1, 1) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, IntegerLessThan) { EXPECT_LT(1, 2) << "unexpected failure"; ASSERT_LT(1, 2) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsEqual) { EXPECT_STREQ("foo", "foo") << "unexpected failure"; ASSERT_STREQ("foo", "foo") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsNotEqual) { EXPECT_STRNE("foo", "bar") << "unexpected failure"; ASSERT_STRNE("foo", "bar") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) { EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure"; ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) { EXPECT_STRCASENE("foo", "bar") << "unexpected failure"; ASSERT_STRCASENE("foo", "bar") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, FloatingPointEquals) { EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure", "expected failure"); } #if GTEST_HAS_EXCEPTIONS TEST(StreamingAssertionsTest, Throw) { EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, NoThrow) { EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, AnyThrow) { EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure", "expected failure"); } #endif TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { GTEST_FLAG_SET(color, "yes"); SetEnv("TERM", "xterm"); EXPECT_TRUE(ShouldUseColor(true)); EXPECT_TRUE(ShouldUseColor(false)); SetEnv("TERM", "dumb"); EXPECT_TRUE(ShouldUseColor(true)); EXPECT_TRUE(ShouldUseColor(false)); } TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { SetEnv("TERM", "dumb"); GTEST_FLAG_SET(color, "True"); EXPECT_TRUE(ShouldUseColor(false)); GTEST_FLAG_SET(color, "t"); EXPECT_TRUE(ShouldUseColor(false)); GTEST_FLAG_SET(color, "1"); EXPECT_TRUE(ShouldUseColor(false)); } TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { GTEST_FLAG_SET(color, "no"); SetEnv("TERM", "xterm"); EXPECT_FALSE(ShouldUseColor(true)); EXPECT_FALSE(ShouldUseColor(false)); SetEnv("TERM", "dumb"); EXPECT_FALSE(ShouldUseColor(true)); EXPECT_FALSE(ShouldUseColor(false)); } TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { SetEnv("TERM", "xterm"); GTEST_FLAG_SET(color, "F"); EXPECT_FALSE(ShouldUseColor(true)); GTEST_FLAG_SET(color, "0"); EXPECT_FALSE(ShouldUseColor(true)); GTEST_FLAG_SET(color, "unknown"); EXPECT_FALSE(ShouldUseColor(true)); } TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { GTEST_FLAG_SET(color, "auto"); SetEnv("TERM", "xterm"); EXPECT_FALSE(ShouldUseColor(false)); EXPECT_TRUE(ShouldUseColor(true)); } TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { GTEST_FLAG_SET(color, "auto"); #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) SetEnv("TERM", "dumb"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", ""); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "xterm"); EXPECT_TRUE(ShouldUseColor(true)); #else SetEnv("TERM", "dumb"); EXPECT_FALSE(ShouldUseColor(true)); SetEnv("TERM", "emacs"); EXPECT_FALSE(ShouldUseColor(true)); SetEnv("TERM", "vt100"); EXPECT_FALSE(ShouldUseColor(true)); SetEnv("TERM", "xterm-mono"); EXPECT_FALSE(ShouldUseColor(true)); SetEnv("TERM", "xterm"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "xterm-color"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "xterm-kitty"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "alacritty"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "xterm-256color"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "screen"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "screen-256color"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "tmux"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "tmux-256color"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "rxvt-unicode"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "rxvt-unicode-256color"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "linux"); EXPECT_TRUE(ShouldUseColor(true)); SetEnv("TERM", "cygwin"); EXPECT_TRUE(ShouldUseColor(true)); #endif } GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy1 = StaticAssertTypeEq<bool, bool>(); GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED static bool dummy2 = StaticAssertTypeEq<const int, const int>(); template <typename T> class StaticAssertTypeEqTestHelper { public: StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); } }; TEST(StaticAssertTypeEqTest, WorksInClass) { StaticAssertTypeEqTestHelper<bool>(); } typedef int IntAlias; TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) { StaticAssertTypeEq<int, IntAlias>(); StaticAssertTypeEq<int*, IntAlias*>(); } TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) { EXPECT_FALSE(HasNonfatalFailure()); } static void FailFatally() { FAIL(); } TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) { FailFatally(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_FALSE(has_nonfatal_failure); } TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { FailFatally(); ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } static bool HasNonfatalFailureHelper() { return testing::Test::HasNonfatalFailure(); } TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) { EXPECT_FALSE(HasNonfatalFailureHelper()); } TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) { ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailureHelper(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) { EXPECT_FALSE(HasFailure()); } TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) { FailFatally(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { ADD_FAILURE(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { FailFatally(); ADD_FAILURE(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } static bool HasFailureHelper() { return testing::Test::HasFailure(); } TEST(HasFailureTest, WorksOutsideOfTestBody) { EXPECT_FALSE(HasFailureHelper()); } TEST(HasFailureTest, WorksOutsideOfTestBody2) { ADD_FAILURE(); const bool has_failure = HasFailureHelper(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } class TestListener : public EmptyTestEventListener { public: TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {} TestListener(int* on_start_counter, bool* is_destroyed) : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {} ~TestListener() override { if (is_destroyed_) *is_destroyed_ = true; } protected: void OnTestProgramStart(const UnitTest& ) override { if (on_start_counter_ != nullptr) (*on_start_counter_)++; } private: int* on_start_counter_; bool* is_destroyed_; }; TEST(TestEventListenersTest, ConstructionWorks) { TestEventListeners listeners; EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr); EXPECT_TRUE(listeners.default_result_printer() == nullptr); EXPECT_TRUE(listeners.default_xml_generator() == nullptr); } TEST(TestEventListenersTest, DestructionWorks) { bool default_result_printer_is_destroyed = false; bool default_xml_printer_is_destroyed = false; bool extra_listener_is_destroyed = false; TestListener* default_result_printer = new TestListener(nullptr, &default_result_printer_is_destroyed); TestListener* default_xml_printer = new TestListener(nullptr, &default_xml_printer_is_destroyed); TestListener* extra_listener = new TestListener(nullptr, &extra_listener_is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, default_result_printer); TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, default_xml_printer); listeners.Append(extra_listener); } EXPECT_TRUE(default_result_printer_is_destroyed); EXPECT_TRUE(default_xml_printer_is_destroyed); EXPECT_TRUE(extra_listener_is_destroyed); } TEST(TestEventListenersTest, Append) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; listeners.Append(listener); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } EXPECT_TRUE(is_destroyed); } class SequenceTestingListener : public EmptyTestEventListener { public: SequenceTestingListener(std::vector<std::string>* vector, const char* id) : vector_(vector), id_(id) {} protected: void OnTestProgramStart(const UnitTest& ) override { vector_->push_back(GetEventDescription("OnTestProgramStart")); } void OnTestProgramEnd(const UnitTest& ) override { vector_->push_back(GetEventDescription("OnTestProgramEnd")); } void OnTestIterationStart(const UnitTest& , int ) override { vector_->push_back(GetEventDescription("OnTestIterationStart")); } void OnTestIterationEnd(const UnitTest& , int ) override { vector_->push_back(GetEventDescription("OnTestIterationEnd")); } private: std::string GetEventDescription(const char* method) { Message message; message << id_ << "." << method; return message.GetString(); } std::vector<std::string>* vector_; const char* const id_; SequenceTestingListener(const SequenceTestingListener&) = delete; SequenceTestingListener& operator=(const SequenceTestingListener&) = delete; }; TEST(EventListenerTest, AppendKeepsOrder) { std::vector<std::string> vec; TestEventListeners listeners; listeners.Append(new SequenceTestingListener(&vec, "1st")); listeners.Append(new SequenceTestingListener(&vec, "2nd")); listeners.Append(new SequenceTestingListener(&vec, "3rd")); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramEnd(*UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str()); EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestIterationStart(*UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestIterationEnd(*UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str()); EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str()); } TEST(TestEventListenersTest, Release) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; listeners.Append(listener); EXPECT_EQ(listener, listeners.Release(listener)); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_TRUE(listeners.Release(listener) == nullptr); } EXPECT_EQ(0, on_start_counter); EXPECT_FALSE(is_destroyed); delete listener; } TEST(EventListenerTest, SuppressEventForwarding) { int on_start_counter = 0; TestListener* listener = new TestListener(&on_start_counter, nullptr); TestEventListeners listeners; listeners.Append(listener); ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::SuppressEventForwarding(&listeners); ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprocesses) { EXPECT_DEATH_IF_SUPPORTED( { GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( *GetUnitTestImpl()->listeners())) << "expected failure"; }, "expected failure"); } TEST(EventListenerTest, default_result_printer) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); EXPECT_EQ(listener, listeners.default_result_printer()); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr); EXPECT_TRUE(listeners.default_result_printer() == nullptr); EXPECT_TRUE(is_destroyed); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_TRUE(listeners.default_result_printer() == nullptr); EXPECT_FALSE(is_destroyed); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } EXPECT_FALSE(is_destroyed); delete listener; } TEST(EventListenerTest, default_xml_generator) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestEventListeners listeners; TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); EXPECT_EQ(listener, listeners.default_xml_generator()); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr); EXPECT_TRUE(listeners.default_xml_generator() == nullptr); EXPECT_TRUE(is_destroyed); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_TRUE(listeners.default_xml_generator() == nullptr); EXPECT_FALSE(is_destroyed); TestEventListenersAccessor::GetRepeater(&listeners) ->OnTestProgramStart(*UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } EXPECT_FALSE(is_destroyed); delete listener; } GTEST_TEST(AlternativeNameTest, Works) { GTEST_SUCCEED() << "OK"; EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure", "An expected failure"); GTEST_ASSERT_EQ(0, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_NE(0, 1); GTEST_ASSERT_NE(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_LE(0, 0); GTEST_ASSERT_LE(0, 1); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_LT(0, 1); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_GE(0, 0); GTEST_ASSERT_GE(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure", "An expected failure"); GTEST_ASSERT_GT(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure", "An expected failure"); } class ConversionHelperBase {}; class ConversionHelperDerived : public ConversionHelperBase {}; struct HasDebugStringMethods { std::string DebugString() const { return ""; } std::string ShortDebugString() const { return ""; } }; struct InheritsDebugStringMethods : public HasDebugStringMethods {}; struct WrongTypeDebugStringMethod { std::string DebugString() const { return ""; } int ShortDebugString() const { return 1; } }; struct NotConstDebugStringMethod { std::string DebugString() { return ""; } std::string ShortDebugString() const { return ""; } }; struct MissingDebugStringMethod { std::string DebugString() { return ""; } }; struct IncompleteType; TEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) { static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value, "const_true"); static_assert( HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value, "const_true"); static_assert(HasDebugStringAndShortDebugString< const InheritsDebugStringMethods>::value, "const_true"); static_assert( !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value, "const_false"); static_assert( !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value, "const_false"); static_assert( !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value, "const_false"); static_assert(!HasDebugStringAndShortDebugString<IncompleteType>::value, "const_false"); static_assert(!HasDebugStringAndShortDebugString<int>::value, "const_false"); } TEST(HasDebugStringAndShortDebugStringTest, ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) { EXPECT_TRUE( HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value); } TEST(HasDebugStringAndShortDebugStringTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) { EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value); EXPECT_FALSE( HasDebugStringAndShortDebugString<const ConversionHelperBase>::value); } template <typename T1, typename T2> void TestGTestRemoveReferenceAndConst() { static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value, "GTEST_REMOVE_REFERENCE_AND_CONST_ failed."); } TEST(RemoveReferenceToConstTest, Works) { TestGTestRemoveReferenceAndConst<int, int>(); TestGTestRemoveReferenceAndConst<double, double&>(); TestGTestRemoveReferenceAndConst<char, const char>(); TestGTestRemoveReferenceAndConst<char, const char&>(); TestGTestRemoveReferenceAndConst<const char*, const char*>(); } template <typename T1, typename T2> void TestGTestReferenceToConst() { static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value, "GTEST_REFERENCE_TO_CONST_ failed."); } TEST(GTestReferenceToConstTest, Works) { TestGTestReferenceToConst<const char&, char>(); TestGTestReferenceToConst<const int&, const int>(); TestGTestReferenceToConst<const double&, double>(); TestGTestReferenceToConst<const std::string&, const std::string&>(); } class NonContainer {}; TEST(IsContainerTestTest, WorksForNonContainer) { EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0))); } TEST(IsContainerTestTest, WorksForContainer) { EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0))); EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::map<int, double>>(0))); } struct ConstOnlyContainerWithPointerIterator { using const_iterator = int*; const_iterator begin() const; const_iterator end() const; }; struct ConstOnlyContainerWithClassIterator { struct const_iterator { const int& operator*() const; const_iterator& operator++(); }; const_iterator begin() const; const_iterator end() const; }; TEST(IsContainerTestTest, ConstOnlyContainer) { EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0))); EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0))); } struct AHashTable { typedef void hasher; }; struct NotReallyAHashTable { typedef void hasher; typedef void reverse_iterator; }; TEST(IsHashTable, Basic) { EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value); EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value); EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value); EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value); } TEST(ArrayEqTest, WorksForDegeneratedArrays) { EXPECT_TRUE(ArrayEq(5, 5L)); EXPECT_FALSE(ArrayEq('a', 0)); } TEST(ArrayEqTest, WorksForOneDimensionalArrays) { const int a[] = {0, 1}; long b[] = {0, 1}; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); b[0] = 2; EXPECT_FALSE(ArrayEq(a, b)); EXPECT_FALSE(ArrayEq(a, 1, b)); } TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { const char a[][3] = {"hi", "lo"}; const char b[][3] = {"hi", "lo"}; const char c[][3] = {"hi", "li"}; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); EXPECT_FALSE(ArrayEq(a, c)); EXPECT_FALSE(ArrayEq(a, 2, c)); } TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { const char a[] = "hello"; EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o')); EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x')); } TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { int a[][2] = {{0, 1}, {2, 3}, {4, 5}}; const int b[2] = {2, 3}; EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); const int c[2] = {6, 7}; EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); } TEST(CopyArrayTest, WorksForDegeneratedArrays) { int n = 0; CopyArray('a', &n); EXPECT_EQ('a', n); } TEST(CopyArrayTest, WorksForOneDimensionalArrays) { const char a[3] = "hi"; int b[3]; #ifndef __BORLANDC__ CopyArray(a, &b); EXPECT_TRUE(ArrayEq(a, b)); #endif int c[3]; CopyArray(a, 3, c); EXPECT_TRUE(ArrayEq(a, c)); } TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { const int a[2][3] = {{0, 1, 2}, {3, 4, 5}}; int b[2][3]; #ifndef __BORLANDC__ CopyArray(a, &b); EXPECT_TRUE(ArrayEq(a, b)); #endif int c[2][3]; CopyArray(a, 2, c); EXPECT_TRUE(ArrayEq(a, c)); } TEST(NativeArrayTest, ConstructorFromArrayWorks) { const int a[3] = {0, 1, 2}; NativeArray<int> na(a, 3, RelationToSourceReference()); EXPECT_EQ(3U, na.size()); EXPECT_EQ(a, na.begin()); } TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) { typedef int Array[2]; Array* a = new Array[1]; (*a)[0] = 0; (*a)[1] = 1; NativeArray<int> na(*a, 2, RelationToSourceCopy()); EXPECT_NE(*a, na.begin()); delete[] a; EXPECT_EQ(0, na.begin()[0]); EXPECT_EQ(1, na.begin()[1]); } TEST(NativeArrayTest, TypeMembersAreCorrect) { StaticAssertTypeEq<char, NativeArray<char>::value_type>(); StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>(); StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>(); StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>(); } TEST(NativeArrayTest, MethodsWork) { const int a[3] = {0, 1, 2}; NativeArray<int> na(a, 3, RelationToSourceCopy()); ASSERT_EQ(3U, na.size()); EXPECT_EQ(3, na.end() - na.begin()); NativeArray<int>::const_iterator it = na.begin(); EXPECT_EQ(0, *it); ++it; EXPECT_EQ(1, *it); it++; EXPECT_EQ(2, *it); ++it; EXPECT_EQ(na.end(), it); EXPECT_TRUE(na == na); NativeArray<int> na2(a, 3, RelationToSourceReference()); EXPECT_TRUE(na == na2); const int b1[3] = {0, 1, 1}; const int b2[4] = {0, 1, 2, 3}; EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference())); EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy())); } TEST(NativeArrayTest, WorksForTwoDimensionalArray) { const char a[2][3] = {"hi", "lo"}; NativeArray<char[3]> na(a, 2, RelationToSourceReference()); ASSERT_EQ(2U, na.size()); EXPECT_EQ(a, na.begin()); } TEST(ElemFromList, Basic) { using testing::internal::ElemFromList; EXPECT_TRUE( (std::is_same<int, ElemFromList<0, int, double, char>::type>::value)); EXPECT_TRUE( (std::is_same<double, ElemFromList<1, int, double, char>::type>::value)); EXPECT_TRUE( (std::is_same<char, ElemFromList<2, int, double, char>::type>::value)); EXPECT_TRUE(( std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int, char, int, int, int, int>::type>::value)); } TEST(FlatTuple, Basic) { using testing::internal::FlatTuple; FlatTuple<int, double, const char*> tuple = {}; EXPECT_EQ(0, tuple.Get<0>()); EXPECT_EQ(0.0, tuple.Get<1>()); EXPECT_EQ(nullptr, tuple.Get<2>()); tuple = FlatTuple<int, double, const char*>( testing::internal::FlatTupleConstructTag{}, 7, 3.2, "Foo"); EXPECT_EQ(7, tuple.Get<0>()); EXPECT_EQ(3.2, tuple.Get<1>()); EXPECT_EQ(std::string("Foo"), tuple.Get<2>()); tuple.Get<1>() = 5.1; EXPECT_EQ(5.1, tuple.Get<1>()); } namespace { std::string AddIntToString(int i, const std::string& s) { return s + std::to_string(i); } } TEST(FlatTuple, Apply) { using testing::internal::FlatTuple; FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{}, 5, "Hello"}; EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool { return i == static_cast<int>(s.size()); })); EXPECT_EQ(tuple.Apply(AddIntToString), "Hello5"); tuple.Apply([](int& i, std::string& s) { ++i; s += s; }); EXPECT_EQ(tuple.Get<0>(), 6); EXPECT_EQ(tuple.Get<1>(), "HelloHello"); } struct ConstructionCounting { ConstructionCounting() { ++default_ctor_calls; } ~ConstructionCounting() { ++dtor_calls; } ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; } ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; } ConstructionCounting& operator=(const ConstructionCounting&) { ++copy_assignment_calls; return *this; } ConstructionCounting& operator=(ConstructionCounting&&) noexcept { ++move_assignment_calls; return *this; } static void Reset() { default_ctor_calls = 0; dtor_calls = 0; copy_ctor_calls = 0; move_ctor_calls = 0; copy_assignment_calls = 0; move_assignment_calls = 0; } static int default_ctor_calls; static int dtor_calls; static int copy_ctor_calls; static int move_ctor_calls; static int copy_assignment_calls; static int move_assignment_calls; }; int ConstructionCounting::default_ctor_calls = 0; int ConstructionCounting::dtor_calls = 0; int ConstructionCounting::copy_ctor_calls = 0; int ConstructionCounting::move_ctor_calls = 0; int ConstructionCounting::copy_assignment_calls = 0; int ConstructionCounting::move_assignment_calls = 0; TEST(FlatTuple, ConstructorCalls) { using testing::internal::FlatTuple; ConstructionCounting::Reset(); { FlatTuple<ConstructionCounting> tuple; } EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1); EXPECT_EQ(ConstructionCounting::dtor_calls, 1); EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); ConstructionCounting::Reset(); { ConstructionCounting elem; FlatTuple<ConstructionCounting> tuple{ testing::internal::FlatTupleConstructTag{}, elem}; } EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1); EXPECT_EQ(ConstructionCounting::dtor_calls, 2); EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1); EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); ConstructionCounting::Reset(); { FlatTuple<ConstructionCounting> tuple{ testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}}; } EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1); EXPECT_EQ(ConstructionCounting::dtor_calls, 2); EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1); EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); ConstructionCounting::Reset(); { FlatTuple<ConstructionCounting> tuple; ConstructionCounting elem; tuple.Get<0>() = elem; } EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2); EXPECT_EQ(ConstructionCounting::dtor_calls, 2); EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1); EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0); ConstructionCounting::Reset(); { FlatTuple<ConstructionCounting> tuple; tuple.Get<0>() = ConstructionCounting{}; } EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2); EXPECT_EQ(ConstructionCounting::dtor_calls, 2); EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0); EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0); EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1); ConstructionCounting::Reset(); } TEST(FlatTuple, ManyTypes) { using testing::internal::FlatTuple; #define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int, #define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8 #define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16 #define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32 #define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64 #define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128 FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple; tuple.Get<0>() = 7; tuple.Get<99>() = 17; tuple.Get<256>() = 1000; EXPECT_EQ(7, tuple.Get<0>()); EXPECT_EQ(17, tuple.Get<99>()); EXPECT_EQ(1000, tuple.Get<256>()); } TEST(SkipPrefixTest, SkipsWhenPrefixMatches) { const char* const str = "hello"; const char* p = str; EXPECT_TRUE(SkipPrefix("", &p)); EXPECT_EQ(str, p); p = str; EXPECT_TRUE(SkipPrefix("hell", &p)); EXPECT_EQ(str + 4, p); } TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { const char* const str = "world"; const char* p = str; EXPECT_FALSE(SkipPrefix("W", &p)); EXPECT_EQ(str, p); p = str; EXPECT_FALSE(SkipPrefix("world!", &p)); EXPECT_EQ(str, p); } TEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) { const testing::TestResult& test_result = testing::UnitTest::GetInstance()->ad_hoc_test_result(); EXPECT_FALSE(test_result.Failed()); } class DynamicUnitTestFixture : public testing::Test {}; class DynamicTest : public DynamicUnitTestFixture { void TestBody() override { EXPECT_TRUE(true); } }; auto* dynamic_test = testing::RegisterTest( "DynamicUnitTestFixture", "DynamicTest", "TYPE", "VALUE", __FILE__, __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; }); TEST(RegisterTest, WasRegistered) { const auto& unittest = testing::UnitTest::GetInstance(); for (int i = 0; i < unittest->total_test_suite_count(); ++i) { auto* tests = unittest->GetTestSuite(i); if (tests->name() != std::string("DynamicUnitTestFixture")) continue; for (int j = 0; j < tests->total_test_count(); ++j) { if (tests->GetTestInfo(j)->name() != std::string("DynamicTest")) continue; EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), "VALUE"); EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), "TYPE"); return; } } FAIL() << "Didn't find the test!"; } TEST(PatternGlobbingTest, MatchesFilterLinearRuntime) { std::string name(100, 'a'); name.push_back('b'); std::string pattern; for (int i = 0; i < 100; ++i) { pattern.append("a*"); } pattern.push_back('b'); EXPECT_TRUE( testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str())); } TEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) { const std::string name = "aaaa"; EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*")); EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "a*:")); EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab")); EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:")); EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, "ab:a*")); } TEST(PatternGlobbingTest, MatchesFilterEdgeCases) { EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("", "*a")); EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "*")); EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter("a", "")); EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter("", "")); }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/src/gtest.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/test/gtest_unittest.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
51c740cd-a235-4e14-b923-bec2dec16ca6
cpp
google/googletest
gtest_main
googletest/src/gtest_main.cc
googletest/test/gtest_main_unittest.cc
#include <cstdio> #include "gtest/gtest.h" #if defined(GTEST_OS_ESP8266) || defined(GTEST_OS_ESP32) || \ (defined(GTEST_OS_NRF52) && defined(ARDUINO)) #ifdef GTEST_OS_ESP8266 extern "C" { #endif void setup() { testing::InitGoogleTest(); } void loop() { RUN_ALL_TESTS(); } #ifdef GTEST_OS_ESP8266 } #endif #elif defined(GTEST_OS_QURT) GTEST_API_ int main() { printf("Running main() from %s\n", __FILE__); testing::InitGoogleTest(); return RUN_ALL_TESTS(); } #else GTEST_API_ int main(int argc, char **argv) { printf("Running main() from %s\n", __FILE__); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #endif
#include "gtest/gtest.h" namespace { TEST(GTestMainTest, ShouldSucceed) {} }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/src/gtest_main.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/test/gtest_main_unittest.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
3e7cdd1d-f8d7-4034-8f45-062e29e11fb3
cpp
google/googletest
gtest-typed-test
googletest/src/gtest-typed-test.cc
googletest/test/gtest-typed-test_test.cc
#include "gtest/gtest-typed-test.h" #include <set> #include <string> #include <vector> #include "gtest/gtest.h" namespace testing { namespace internal { static const char* SkipSpaces(const char* str) { while (IsSpace(*str)) str++; return str; } static std::vector<std::string> SplitIntoTestNames(const char* src) { std::vector<std::string> name_vec; src = SkipSpaces(src); for (; src != nullptr; src = SkipComma(src)) { name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); } return name_vec; } const char* TypedTestSuitePState::VerifyRegisteredTestNames( const char* test_suite_name, const char* file, int line, const char* registered_tests) { RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line)); typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests); Message errors; std::set<std::string> tests; for (std::vector<std::string>::const_iterator name_it = name_vec.begin(); name_it != name_vec.end(); ++name_it) { const std::string& name = *name_it; if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; continue; } if (registered_tests_.count(name) != 0) { tests.insert(name); } else { errors << "No test named " << name << " can be found in this test suite.\n"; } } for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } } const std::string& errors_str = errors.GetString(); if (!errors_str.empty()) { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); posix::Abort(); } return registered_tests; } } }
#include "test/gtest-typed-test_test.h" #include <set> #include <string> #include <type_traits> #include <vector> #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 ) using testing::Test; template <typename T> class CommonTest : public Test { public: static void SetUpTestSuite() { shared_ = new T(5); } static void TearDownTestSuite() { delete shared_; shared_ = nullptr; } protected: typedef std::vector<T> Vector; typedef std::set<int> IntSet; CommonTest() : value_(1) {} ~CommonTest() override { EXPECT_EQ(3, value_); } void SetUp() override { EXPECT_EQ(1, value_); value_++; } void TearDown() override { EXPECT_EQ(2, value_); value_++; } T value_; static T* shared_; }; template <typename T> T* CommonTest<T>::shared_ = nullptr; using testing::Types; typedef Types<char, int> TwoTypes; TYPED_TEST_SUITE(CommonTest, TwoTypes); TYPED_TEST(CommonTest, ValuesAreCorrect) { EXPECT_EQ(5, *TestFixture::shared_); typename TestFixture::Vector empty; EXPECT_EQ(0U, empty.size()); typename TestFixture::IntSet empty2; EXPECT_EQ(0U, empty2.size()); EXPECT_EQ(2, this->value_); } TYPED_TEST(CommonTest, ValuesAreStillCorrect) { ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); EXPECT_EQ(static_cast<TypeParam>(2), this->value_); } template <typename T> class TypedTest1 : public Test {}; TYPED_TEST_SUITE(TypedTest1, int); TYPED_TEST(TypedTest1, A) {} template <typename T> class TypedTest2 : public Test {}; TYPED_TEST_SUITE(TypedTest2, Types<int>); TYPED_TEST(TypedTest2, A) {} namespace library1 { template <typename T> class NumericTest : public Test {}; typedef Types<int, long> NumericTypes; TYPED_TEST_SUITE(NumericTest, NumericTypes); TYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } } template <typename T> class TypedTestWithNames : public Test {}; class TypedTestNames { public: template <typename T> static std::string GetName(int i) { if (std::is_same<T, char>::value) { return std::string("char") + ::testing::PrintToString(i); } if (std::is_same<T, int>::value) { return std::string("int") + ::testing::PrintToString(i); } } }; TYPED_TEST_SUITE(TypedTestWithNames, TwoTypes, TypedTestNames); TYPED_TEST(TypedTestWithNames, TestSuiteName) { if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "TypedTestWithNames/char0"); } if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "TypedTestWithNames/int1"); } } using testing::Types; using testing::internal::TypedTestSuitePState; class TypedTestSuitePStateTest : public Test { protected: void SetUp() override { state_.AddTestName("foo.cc", 0, "FooTest", "A"); state_.AddTestName("foo.cc", 0, "FooTest", "B"); state_.AddTestName("foo.cc", 0, "FooTest", "C"); } TypedTestSuitePState state_; }; TEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) { const char* tests = "A, B, C"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } TEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) { const char* tests = "A,C, B"; EXPECT_EQ(tests, state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, tests)); } using TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest; TEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, A, C"), "foo\\.cc.1.?: Test A is listed more than once\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C, D"), "foo\\.cc.1.?: No test named D can be found in this test suite\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) { EXPECT_DEATH_IF_SUPPORTED( state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, C"), "foo\\.cc.1.?: You forgot to list test B\\."); } TEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) { state_.VerifyRegisteredTestNames("Suite", "foo.cc", 1, "A, B, C"); EXPECT_DEATH_IF_SUPPORTED( state_.AddTestName("foo.cc", 2, "FooTest", "D"), "foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P" "\\(FooTest, \\.\\.\\.\\)\\."); } template <typename T> class DerivedTest : public CommonTest<T> {}; TYPED_TEST_SUITE_P(DerivedTest); TYPED_TEST_P(DerivedTest, ValuesAreCorrect) { EXPECT_EQ(5, *TestFixture::shared_); EXPECT_EQ(2, this->value_); } TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) { ASSERT_TRUE(this->shared_ != nullptr); EXPECT_EQ(5, *this->shared_); EXPECT_EQ(2, this->value_); } REGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect, ValuesAreStillCorrect); typedef Types<short, long> MyTwoTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes); template <typename T> class TypeParametrizedTestWithNames : public Test {}; TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames); TYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) { if (std::is_same<TypeParam, char>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "CustomName/TypeParametrizedTestWithNames/parChar0"); } if (std::is_same<TypeParam, int>::value) { EXPECT_STREQ(::testing::UnitTest::GetInstance() ->current_test_info() ->test_suite_name(), "CustomName/TypeParametrizedTestWithNames/parInt1"); } } REGISTER_TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames, TestSuiteName); class TypeParametrizedTestNames { public: template <typename T> static std::string GetName(int i) { if (std::is_same<T, char>::value) { return std::string("parChar") + ::testing::PrintToString(i); } if (std::is_same<T, int>::value) { return std::string("parInt") + ::testing::PrintToString(i); } } }; INSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames, TwoTypes, TypeParametrizedTestNames); template <typename T> class TypedTestP1 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP1); using IntAfterTypedTestSuiteP = int; TYPED_TEST_P(TypedTestP1, A) {} TYPED_TEST_P(TypedTestP1, B) {} using IntBeforeRegisterTypedTestSuiteP = int; REGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B); template <typename T> class TypedTestP2 : public Test {}; TYPED_TEST_SUITE_P(TypedTestP2); TYPED_TEST_P(TypedTestP2, A) {} REGISTER_TYPED_TEST_SUITE_P(TypedTestP2, A); IntAfterTypedTestSuiteP after = 0; IntBeforeRegisterTypedTestSuiteP before = 0; INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP1, int); INSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP2, Types<int>); INSTANTIATE_TYPED_TEST_SUITE_P(Double, TypedTestP2, Types<double>); typedef Types<std::vector<double>, std::set<char> > MyContainers; INSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers); namespace library2 { template <typename T> class NumericTest : public Test {}; TYPED_TEST_SUITE_P(NumericTest); TYPED_TEST_P(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); } TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) { EXPECT_LT(TypeParam(0), TypeParam(1)); } REGISTER_TYPED_TEST_SUITE_P(NumericTest, DefaultIsZero, ZeroIsLessThanOne); typedef Types<int, double> NumericTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes); static const char* GetTestName() { return testing::UnitTest::GetInstance()->current_test_info()->name(); } template <typename T> class TrimmedTest : public Test {}; TYPED_TEST_SUITE_P(TrimmedTest); TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); } TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); } REGISTER_TYPED_TEST_SUITE_P(TrimmedTest, Test1, Test2, Test3, Test4, Test5); template <typename T1, typename T2> struct MyPair {}; typedef Types<int, double, MyPair<int, int> > TrimTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes); } GTEST_DISABLE_MSC_WARNINGS_POP_()
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/src/gtest-typed-test.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/test/gtest-typed-test_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
9d63bd8b-9c7a-4345-b260-6a298972320a
cpp
google/googletest
gmock-internal-utils
googlemock/src/gmock-internal-utils.cc
googlemock/test/gmock-internal-utils_test.cc
#include "gmock/internal/gmock-internal-utils.h" #include <ctype.h> #include <array> #include <cctype> #include <cstdint> #include <cstring> #include <iostream> #include <ostream> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { namespace internal { GTEST_API_ std::string JoinAsKeyValueTuple( const std::vector<const char*>& names, const Strings& values) { GTEST_CHECK_(names.size() == values.size()); if (values.empty()) { return ""; } const auto build_one = [&](const size_t i) { return std::string(names[i]) + ": " + values[i]; }; std::string result = "(" + build_one(0); for (size_t i = 1; i < values.size(); i++) { result += ", "; result += build_one(i); } result += ")"; return result; } GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) { std::string result; char prev_char = '\0'; for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { const bool starts_new_word = IsUpper(*p) || (!IsAlpha(prev_char) && IsLower(*p)) || (!IsDigit(prev_char) && IsDigit(*p)); if (IsAlNum(*p)) { if (starts_new_word && !result.empty()) result += ' '; result += ToLower(*p); } } return result; } class GoogleTestFailureReporter : public FailureReporterInterface { public: void ReportFailure(FailureType type, const char* file, int line, const std::string& message) override { AssertHelper(type == kFatal ? TestPartResult::kFatalFailure : TestPartResult::kNonFatalFailure, file, line, message.c_str()) = Message(); if (type == kFatal) { posix::Abort(); } } }; GTEST_API_ FailureReporterInterface* GetFailureReporter() { static FailureReporterInterface* const failure_reporter = new GoogleTestFailureReporter(); return failure_reporter; } static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); GTEST_API_ bool LogIsVisible(LogSeverity severity) { if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) { return true; } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) { return false; } else { return severity == kWarning; } } GTEST_API_ void Log(LogSeverity severity, const std::string& message, int stack_frames_to_skip) { if (!LogIsVisible(severity)) return; MutexLock l(&g_log_mutex); if (severity == kWarning) { std::cout << "\nGMOCK WARNING:"; } if (message.empty() || message[0] != '\n') { std::cout << "\n"; } std::cout << message; if (stack_frames_to_skip >= 0) { #ifdef NDEBUG const int actual_to_skip = 0; #else const int actual_to_skip = stack_frames_to_skip + 1; #endif if (!message.empty() && *message.rbegin() != '\n') { std::cout << "\n"; } std::cout << "Stack trace:\n" << ::testing::internal::GetCurrentOsStackTraceExceptTop( actual_to_skip); } std::cout << ::std::flush; } GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); } GTEST_API_ void IllegalDoDefault(const char* file, int line) { internal::Assert( false, file, line, "You are using DoDefault() inside a composite action like " "DoAll() or WithArgs(). This is not supported for technical " "reasons. Please instead spell out the default action, or " "assign the default action to an Action variable and use " "the variable in various places."); } constexpr char UndoWebSafeEncoding(char c) { return c == '-' ? '+' : c == '_' ? '/' : c; } constexpr char UnBase64Impl(char c, const char* const base64, char carry) { return *base64 == 0 ? static_cast<char>(65) : *base64 == c ? carry : UnBase64Impl(c, base64 + 1, static_cast<char>(carry + 1)); } template <size_t... I> constexpr std::array<char, 256> UnBase64Impl(std::index_sequence<I...>, const char* const base64) { return { {UnBase64Impl(UndoWebSafeEncoding(static_cast<char>(I)), base64, 0)...}}; } constexpr std::array<char, 256> UnBase64(const char* const base64) { return UnBase64Impl(std::make_index_sequence<256>{}, base64); } static constexpr char kBase64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64); bool Base64Unescape(const std::string& encoded, std::string* decoded) { decoded->clear(); size_t encoded_len = encoded.size(); decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4)); int bit_pos = 0; char dst = 0; for (int src : encoded) { if (std::isspace(src) || src == '=') { continue; } char src_bin = kUnBase64[static_cast<size_t>(src)]; if (src_bin >= 64) { decoded->clear(); return false; } if (bit_pos == 0) { dst |= static_cast<char>(src_bin << 2); bit_pos = 6; } else { dst |= static_cast<char>(src_bin >> (bit_pos - 2)); decoded->push_back(dst); dst = static_cast<char>(src_bin << (10 - bit_pos)); bit_pos = (bit_pos + 6) % 8; } } return true; } } }
#include "gmock/internal/gmock-internal-utils.h" #include <stdlib.h> #include <cstdint> #include <map> #include <memory> #include <sstream> #include <string> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ #ifdef GTEST_OS_CYGWIN #include <sys/types.h> #endif namespace proto2 { class Message; } namespace testing { namespace internal { namespace { TEST(JoinAsKeyValueTupleTest, JoinsEmptyTuple) { EXPECT_EQ("", JoinAsKeyValueTuple({}, Strings())); } TEST(JoinAsKeyValueTupleTest, JoinsOneTuple) { EXPECT_EQ("(a: 1)", JoinAsKeyValueTuple({"a"}, {"1"})); } TEST(JoinAsKeyValueTupleTest, JoinsTwoTuple) { EXPECT_EQ("(a: 1, b: 2)", JoinAsKeyValueTuple({"a", "b"}, {"1", "2"})); } TEST(JoinAsKeyValueTupleTest, JoinsTenTuple) { EXPECT_EQ( "(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10)", JoinAsKeyValueTuple({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}, {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"})); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) { EXPECT_EQ("", ConvertIdentifierNameToWords("")); EXPECT_EQ("", ConvertIdentifierNameToWords("_")); EXPECT_EQ("", ConvertIdentifierNameToWords("__")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) { EXPECT_EQ("1", ConvertIdentifierNameToWords("_1")); EXPECT_EQ("2", ConvertIdentifierNameToWords("2_")); EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_")); EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) { EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) { EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123")); EXPECT_EQ("chapter 11 section 1", ConvertIdentifierNameToWords("_Chapter11Section_1_")); } TEST(GetRawPointerTest, WorksForSmartPointers) { const char* const raw_p1 = new const char('a'); const std::unique_ptr<const char> p1(raw_p1); EXPECT_EQ(raw_p1, GetRawPointer(p1)); double* const raw_p2 = new double(2.5); const std::shared_ptr<double> p2(raw_p2); EXPECT_EQ(raw_p2, GetRawPointer(p2)); } TEST(GetRawPointerTest, WorksForRawPointers) { int* p = nullptr; EXPECT_TRUE(nullptr == GetRawPointer(p)); int n = 1; EXPECT_EQ(&n, GetRawPointer(&n)); } TEST(GetRawPointerTest, WorksForStdReferenceWrapper) { int n = 1; EXPECT_EQ(&n, GetRawPointer(std::ref(n))); EXPECT_EQ(&n, GetRawPointer(std::cref(n))); } class Base {}; class Derived : public Base {}; TEST(KindOfTest, Bool) { EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool)); } TEST(KindOfTest, Integer) { EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); #if defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) || defined(GTEST_OS_CYGWIN) EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); #endif } TEST(KindOfTest, FloatingPoint) { EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); } TEST(KindOfTest, Other) { EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**)); EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); } TEST(LosslessArithmeticConvertibleTest, BoolToBool) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, BoolToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value)); EXPECT_TRUE( (LosslessArithmeticConvertible<bool, unsigned long>::value)); } TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) { EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToBool) { EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short, uint64_t>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<short, uint64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<signed char, unsigned int>::value)); EXPECT_TRUE( (LosslessArithmeticConvertible<unsigned char, unsigned char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long, unsigned long>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<unsigned char, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value)); EXPECT_FALSE( (LosslessArithmeticConvertible<short, long double>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) { EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value)); EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value)); EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value)); GTEST_INTENTIONAL_CONST_COND_PUSH_() if (sizeof(double) == sizeof(long double)) { GTEST_INTENTIONAL_CONST_COND_POP_() EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value)); } else { EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value)); } } TEST(TupleMatchesTest, WorksForSize0) { std::tuple<> matchers; std::tuple<> values; EXPECT_TRUE(TupleMatches(matchers, values)); } TEST(TupleMatchesTest, WorksForSize1) { std::tuple<Matcher<int>> matchers(Eq(1)); std::tuple<int> values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); } TEST(TupleMatchesTest, WorksForSize2) { std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a')); std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); EXPECT_FALSE(TupleMatches(matchers, values4)); } TEST(TupleMatchesTest, WorksForSize5) { std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, Matcher<std::string>> matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); std::tuple<int, char, bool, long, std::string> values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), values3(2, 'a', true, 2L, "hi"); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); } TEST(AssertTest, SucceedsOnTrue) { Assert(true, __FILE__, __LINE__, "This should succeed."); Assert(true, __FILE__, __LINE__); } TEST(AssertTest, FailsFatallyOnFalse) { EXPECT_DEATH_IF_SUPPORTED( { Assert(false, __FILE__, __LINE__, "This should fail."); }, ""); EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, ""); } TEST(ExpectTest, SucceedsOnTrue) { Expect(true, __FILE__, __LINE__, "This should succeed."); Expect(true, __FILE__, __LINE__); } TEST(ExpectTest, FailsNonfatallyOnFalse) { EXPECT_NONFATAL_FAILURE( { Expect(false, __FILE__, __LINE__, "This should fail."); }, "This should fail"); EXPECT_NONFATAL_FAILURE( { Expect(false, __FILE__, __LINE__); }, "Expectation failed"); } class LogIsVisibleTest : public ::testing::Test { protected: void SetUp() override { original_verbose_ = GMOCK_FLAG_GET(verbose); } void TearDown() override { GMOCK_FLAG_SET(verbose, original_verbose_); } std::string original_verbose_; }; TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) { GMOCK_FLAG_SET(verbose, kInfoVerbosity); EXPECT_TRUE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_FALSE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } #if GTEST_HAS_STREAM_REDIRECTION void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, bool should_print) { const std::string old_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); Log(severity, "Test log.\n", 0); if (should_print) { EXPECT_THAT( GetCapturedStdout().c_str(), ContainsRegex(severity == kWarning ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" : "^\nTest log\\.\nStack trace:\n")); } else { EXPECT_STREQ("", GetCapturedStdout().c_str()); } GMOCK_FLAG_SET(verbose, old_flag); } TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, kInfoVerbosity); CaptureStdout(); Log(kInfo, "Test log.\n", -1); EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str()); GMOCK_FLAG_SET(verbose, saved_flag); } struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface { std::string CurrentStackTrace(int max_depth, int skip_count) override { return (testing::Message() << max_depth << "::" << skip_count << "\n") .GetString(); } void UponLeavingGTest() override {} }; TEST(LogTest, NoSkippingStackFrameInOptMode) { MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter; GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter); CaptureStdout(); Log(kWarning, "Test log.\n", 100); const std::string log = GetCapturedStdout(); std::string expected_trace = (testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << "::") .GetString(); std::string expected_message = "\nGMOCK WARNING:\n" "Test log.\n" "Stack trace:\n" + expected_trace; EXPECT_THAT(log, HasSubstr(expected_message)); int skip_count = atoi(log.substr(expected_message.size()).c_str()); #if defined(NDEBUG) const int expected_skip_count = 0; #else const int expected_skip_count = 100; #endif EXPECT_THAT(skip_count, AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10))); GetUnitTestImpl()->set_os_stack_trace_getter(nullptr); } TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) { TestLogWithSeverity(kInfoVerbosity, kInfo, true); TestLogWithSeverity(kInfoVerbosity, kWarning, true); } TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) { TestLogWithSeverity(kWarningVerbosity, kInfo, false); TestLogWithSeverity(kWarningVerbosity, kWarning, true); } TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) { TestLogWithSeverity(kErrorVerbosity, kInfo, false); TestLogWithSeverity(kErrorVerbosity, kWarning, false); } TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) { TestLogWithSeverity("invalid", kInfo, false); TestLogWithSeverity("invalid", kWarning, true); } std::string GrabOutput(void (*logger)(), const char* verbosity) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, verbosity); CaptureStdout(); logger(); GMOCK_FLAG_SET(verbose, saved_flag); return GetCapturedStdout(); } class DummyMock { public: MOCK_METHOD0(TestMethod, void()); MOCK_METHOD1(TestMethodArg, void(int dummy)); }; void ExpectCallLogger() { DummyMock mock; EXPECT_CALL(mock, TestMethod()); mock.TestMethod(); } TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)), HasSubstr("EXPECT_CALL(mock, TestMethod())")); } TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str()); } TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str()); } void OnCallLogger() { DummyMock mock; ON_CALL(mock, TestMethod()); } TEST(OnCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethod())")); } TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str()); } TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str()); } void OnCallAnyArgumentLogger() { DummyMock mock; ON_CALL(mock, TestMethodArg(_)); } TEST(OnCallTest, LogsAnythingArgument) { EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethodArg(_)")); } #endif TEST(StlContainerViewTest, WorksForStlContainer) { StaticAssertTypeEq<std::vector<int>, StlContainerView<std::vector<int>>::type>(); StaticAssertTypeEq<const std::vector<double>&, StlContainerView<std::vector<double>>::const_reference>(); typedef std::vector<char> Chars; Chars v1; const Chars& v2(StlContainerView<Chars>::ConstReference(v1)); EXPECT_EQ(&v1, &v2); v1.push_back('a'); Chars v3 = StlContainerView<Chars>::Copy(v1); EXPECT_THAT(v3, Eq(v3)); } TEST(StlContainerViewTest, WorksForStaticNativeArray) { StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>(); StaticAssertTypeEq<NativeArray<double>, StlContainerView<const double[4]>::type>(); StaticAssertTypeEq<NativeArray<char[3]>, StlContainerView<const char[2][3]>::type>(); StaticAssertTypeEq<const NativeArray<int>, StlContainerView<int[2]>::const_reference>(); int a1[3] = {0, 1, 2}; NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); EXPECT_EQ(2, a3.begin()[2]); a1[0] = 3; EXPECT_EQ(0, a3.begin()[0]); } TEST(StlContainerViewTest, WorksForDynamicNativeArray) { StaticAssertTypeEq<NativeArray<int>, StlContainerView<std::tuple<const int*, size_t>>::type>(); StaticAssertTypeEq< NativeArray<double>, StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>(); StaticAssertTypeEq< const NativeArray<int>, StlContainerView<std::tuple<const int*, int>>::const_reference>(); int a1[3] = {0, 1, 2}; const int* const p1 = a1; NativeArray<int> a2 = StlContainerView<std::tuple<const int*, int>>::ConstReference( std::make_tuple(p1, 3)); EXPECT_EQ(3U, a2.size()); EXPECT_EQ(a1, a2.begin()); const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy( std::make_tuple(static_cast<int*>(a1), 3)); ASSERT_EQ(3U, a3.size()); EXPECT_EQ(0, a3.begin()[0]); EXPECT_EQ(1, a3.begin()[1]); EXPECT_EQ(2, a3.begin()[2]); a1[0] = 3; EXPECT_EQ(0, a3.begin()[0]); } TEST(FunctionTest, Nullary) { typedef Function<int()> F; EXPECT_EQ(0u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value)); EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Unary) { typedef Function<int(bool)> F; EXPECT_EQ(1u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value)); EXPECT_TRUE(( std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(bool), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, Binary) { typedef Function<int(bool, const long&)> F; EXPECT_EQ(2u, F::ArgumentCount); EXPECT_TRUE((std::is_same<int, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value)); EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>, F::ArgumentTuple>::value)); EXPECT_TRUE( (std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE((std::is_same<void(bool, const long&), F::MakeResultVoid>::value)); EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&), F::MakeResultIgnoredValue>::value)); } TEST(FunctionTest, LongArgumentList) { typedef Function<char(bool, int, char*, int&, const long&)> F; EXPECT_EQ(5u, F::ArgumentCount); EXPECT_TRUE((std::is_same<char, F::Result>::value)); EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value)); EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value)); EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value)); EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value)); EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value)); EXPECT_TRUE( (std::is_same<std::tuple<bool, int, char*, int&, const long&>, F::ArgumentTuple>::value)); EXPECT_TRUE( (std::is_same< std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>, Matcher<const long&>>, F::ArgumentMatcherTuple>::value)); EXPECT_TRUE( (std::is_same<void(bool, int, char*, int&, const long&), F::MakeResultVoid>::value)); EXPECT_TRUE(( std::is_same<IgnoredValue(bool, int, char*, int&, const long&), F::MakeResultIgnoredValue>::value)); } TEST(Base64Unescape, InvalidString) { std::string unescaped; EXPECT_FALSE(Base64Unescape("(invalid)", &unescaped)); } TEST(Base64Unescape, ShortString) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQh", &unescaped)); EXPECT_EQ("Hello world!", unescaped); } TEST(Base64Unescape, ShortStringWithPadding) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ=", &unescaped)); EXPECT_EQ("Hello world", unescaped); } TEST(Base64Unescape, ShortStringWithoutPadding) { std::string unescaped; EXPECT_TRUE(Base64Unescape("SGVsbG8gd29ybGQ", &unescaped)); EXPECT_EQ("Hello world", unescaped); } TEST(Base64Unescape, LongStringWithWhiteSpaces) { std::string escaped = R"(TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=)"; std::string expected = "Man is distinguished, not only by his reason, but by this singular " "passion from other animals, which is a lust of the mind, that by a " "perseverance of delight in the continued and indefatigable generation " "of knowledge, exceeds the short vehemence of any carnal pleasure."; std::string unescaped; EXPECT_TRUE(Base64Unescape(escaped, &unescaped)); EXPECT_EQ(expected, unescaped); } } } }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/src/gmock-internal-utils.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-internal-utils_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
3c05ab69-2780-41fa-a46f-a2a323fc8a0d
cpp
google/googletest
gmock-cardinalities
googlemock/src/gmock-cardinalities.cc
googlemock/test/gmock-cardinalities_test.cc
#include "gmock/gmock-cardinalities.h" #include <limits.h> #include <ostream> #include <sstream> #include <string> #include "gmock/internal/gmock-internal-utils.h" #include "gtest/gtest.h" namespace testing { namespace { class BetweenCardinalityImpl : public CardinalityInterface { public: BetweenCardinalityImpl(int min, int max) : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) { std::stringstream ss; if (min < 0) { ss << "The invocation lower bound must be >= 0, " << "but is actually " << min << "."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (max < 0) { ss << "The invocation upper bound must be >= 0, " << "but is actually " << max << "."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (min > max) { ss << "The invocation upper bound (" << max << ") must be >= the invocation lower bound (" << min << ")."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } } int ConservativeLowerBound() const override { return min_; } int ConservativeUpperBound() const override { return max_; } bool IsSatisfiedByCallCount(int call_count) const override { return min_ <= call_count && call_count <= max_; } bool IsSaturatedByCallCount(int call_count) const override { return call_count >= max_; } void DescribeTo(::std::ostream* os) const override; private: const int min_; const int max_; BetweenCardinalityImpl(const BetweenCardinalityImpl&) = delete; BetweenCardinalityImpl& operator=(const BetweenCardinalityImpl&) = delete; }; inline std::string FormatTimes(int n) { if (n == 1) { return "once"; } else if (n == 2) { return "twice"; } else { std::stringstream ss; ss << n << " times"; return ss.str(); } } void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const { if (min_ == 0) { if (max_ == 0) { *os << "never called"; } else if (max_ == INT_MAX) { *os << "called any number of times"; } else { *os << "called at most " << FormatTimes(max_); } } else if (min_ == max_) { *os << "called " << FormatTimes(min_); } else if (max_ == INT_MAX) { *os << "called at least " << FormatTimes(min_); } else { *os << "called between " << min_ << " and " << max_ << " times"; } } } void Cardinality::DescribeActualCallCountTo(int actual_call_count, ::std::ostream* os) { if (actual_call_count > 0) { *os << "called " << FormatTimes(actual_call_count); } else { *os << "never called"; } } GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); } GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); } GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); } GTEST_API_ Cardinality Between(int min, int max) { return Cardinality(new BetweenCardinalityImpl(min, max)); } GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); } }
#include <ostream> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" namespace { using std::stringstream; using testing::AnyNumber; using testing::AtLeast; using testing::AtMost; using testing::Between; using testing::Cardinality; using testing::CardinalityInterface; using testing::Exactly; using testing::IsSubstring; using testing::MakeCardinality; class MockFoo { public: MockFoo() = default; MOCK_METHOD0(Bar, int()); private: MockFoo(const MockFoo&) = delete; MockFoo& operator=(const MockFoo&) = delete; }; TEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; } TEST(CardinalityTest, IsCopyable) { Cardinality c = Exactly(1); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); c = Exactly(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); } TEST(CardinalityTest, IsOverSaturatedByCallCountWorks) { const Cardinality c = AtMost(5); EXPECT_FALSE(c.IsOverSaturatedByCallCount(4)); EXPECT_FALSE(c.IsOverSaturatedByCallCount(5)); EXPECT_TRUE(c.IsOverSaturatedByCallCount(6)); } TEST(CardinalityTest, CanDescribeActualCallCount) { stringstream ss0; Cardinality::DescribeActualCallCountTo(0, &ss0); EXPECT_EQ("never called", ss0.str()); stringstream ss1; Cardinality::DescribeActualCallCountTo(1, &ss1); EXPECT_EQ("called once", ss1.str()); stringstream ss2; Cardinality::DescribeActualCallCountTo(2, &ss2); EXPECT_EQ("called twice", ss2.str()); stringstream ss3; Cardinality::DescribeActualCallCountTo(3, &ss3); EXPECT_EQ("called 3 times", ss3.str()); } TEST(AnyNumber, Works) { const Cardinality c = AnyNumber(); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(9)); EXPECT_FALSE(c.IsSaturatedByCallCount(9)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called any number of times", ss.str()); } TEST(AnyNumberTest, HasCorrectBounds) { const Cardinality c = AnyNumber(); EXPECT_EQ(0, c.ConservativeLowerBound()); EXPECT_EQ(INT_MAX, c.ConservativeUpperBound()); } TEST(AtLeastTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { AtLeast(-1); }, "The invocation lower bound must be >= 0"); } TEST(AtLeastTest, OnZero) { const Cardinality c = AtLeast(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "any number of times", ss.str()); } TEST(AtLeastTest, OnPositiveNumber) { const Cardinality c = AtLeast(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); stringstream ss1; AtLeast(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "at least once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "at least twice", ss2.str()); stringstream ss3; AtLeast(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "at least 3 times", ss3.str()); } TEST(AtLeastTest, HasCorrectBounds) { const Cardinality c = AtLeast(2); EXPECT_EQ(2, c.ConservativeLowerBound()); EXPECT_EQ(INT_MAX, c.ConservativeUpperBound()); } TEST(AtMostTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { AtMost(-1); }, "The invocation upper bound must be >= 0"); } TEST(AtMostTest, OnZero) { const Cardinality c = AtMost(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(AtMostTest, OnPositiveNumber) { const Cardinality c = AtMost(2); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(1)); EXPECT_FALSE(c.IsSaturatedByCallCount(1)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); stringstream ss1; AtMost(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "called at most once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss2.str()); stringstream ss3; AtMost(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "called at most 3 times", ss3.str()); } TEST(AtMostTest, HasCorrectBounds) { const Cardinality c = AtMost(2); EXPECT_EQ(0, c.ConservativeLowerBound()); EXPECT_EQ(2, c.ConservativeUpperBound()); } TEST(BetweenTest, OnNegativeStart) { EXPECT_NONFATAL_FAILURE( { Between(-1, 2); }, "The invocation lower bound must be >= 0, but is actually -1"); } TEST(BetweenTest, OnNegativeEnd) { EXPECT_NONFATAL_FAILURE( { Between(1, -2); }, "The invocation upper bound must be >= 0, but is actually -2"); } TEST(BetweenTest, OnStartBiggerThanEnd) { EXPECT_NONFATAL_FAILURE( { Between(2, 1); }, "The invocation upper bound (1) must be >= " "the invocation lower bound (2)"); } TEST(BetweenTest, OnZeroStartAndZeroEnd) { const Cardinality c = Between(0, 0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(BetweenTest, OnZeroStartAndNonZeroEnd) { const Cardinality c = Between(0, 2); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); EXPECT_FALSE(c.IsSatisfiedByCallCount(4)); EXPECT_TRUE(c.IsSaturatedByCallCount(4)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called at most twice", ss.str()); } TEST(BetweenTest, OnSameStartAndEnd) { const Cardinality c = Between(3, 3); EXPECT_FALSE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); EXPECT_TRUE(c.IsSatisfiedByCallCount(3)); EXPECT_TRUE(c.IsSaturatedByCallCount(3)); EXPECT_FALSE(c.IsSatisfiedByCallCount(4)); EXPECT_TRUE(c.IsSaturatedByCallCount(4)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss.str()); } TEST(BetweenTest, OnDifferentStartAndEnd) { const Cardinality c = Between(3, 5); EXPECT_FALSE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSaturatedByCallCount(2)); EXPECT_TRUE(c.IsSatisfiedByCallCount(3)); EXPECT_FALSE(c.IsSaturatedByCallCount(3)); EXPECT_TRUE(c.IsSatisfiedByCallCount(5)); EXPECT_TRUE(c.IsSaturatedByCallCount(5)); EXPECT_FALSE(c.IsSatisfiedByCallCount(6)); EXPECT_TRUE(c.IsSaturatedByCallCount(6)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "called between 3 and 5 times", ss.str()); } TEST(BetweenTest, HasCorrectBounds) { const Cardinality c = Between(3, 5); EXPECT_EQ(3, c.ConservativeLowerBound()); EXPECT_EQ(5, c.ConservativeUpperBound()); } TEST(ExactlyTest, OnNegativeNumber) { EXPECT_NONFATAL_FAILURE( { Exactly(-1); }, "The invocation lower bound must be >= 0"); } TEST(ExactlyTest, OnZero) { const Cardinality c = Exactly(0); EXPECT_TRUE(c.IsSatisfiedByCallCount(0)); EXPECT_TRUE(c.IsSaturatedByCallCount(0)); EXPECT_FALSE(c.IsSatisfiedByCallCount(1)); EXPECT_TRUE(c.IsSaturatedByCallCount(1)); stringstream ss; c.DescribeTo(&ss); EXPECT_PRED_FORMAT2(IsSubstring, "never called", ss.str()); } TEST(ExactlyTest, OnPositiveNumber) { const Cardinality c = Exactly(2); EXPECT_FALSE(c.IsSatisfiedByCallCount(0)); EXPECT_FALSE(c.IsSaturatedByCallCount(0)); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_TRUE(c.IsSaturatedByCallCount(2)); stringstream ss1; Exactly(1).DescribeTo(&ss1); EXPECT_PRED_FORMAT2(IsSubstring, "called once", ss1.str()); stringstream ss2; c.DescribeTo(&ss2); EXPECT_PRED_FORMAT2(IsSubstring, "called twice", ss2.str()); stringstream ss3; Exactly(3).DescribeTo(&ss3); EXPECT_PRED_FORMAT2(IsSubstring, "called 3 times", ss3.str()); } TEST(ExactlyTest, HasCorrectBounds) { const Cardinality c = Exactly(3); EXPECT_EQ(3, c.ConservativeLowerBound()); EXPECT_EQ(3, c.ConservativeUpperBound()); } class EvenCardinality : public CardinalityInterface { public: bool IsSatisfiedByCallCount(int call_count) const override { return (call_count % 2 == 0); } bool IsSaturatedByCallCount(int ) const override { return false; } void DescribeTo(::std::ostream* ss) const override { *ss << "called even number of times"; } }; TEST(MakeCardinalityTest, ConstructsCardinalityFromInterface) { const Cardinality c = MakeCardinality(new EvenCardinality); EXPECT_TRUE(c.IsSatisfiedByCallCount(2)); EXPECT_FALSE(c.IsSatisfiedByCallCount(3)); EXPECT_FALSE(c.IsSaturatedByCallCount(10000)); stringstream ss; c.DescribeTo(&ss); EXPECT_EQ("called even number of times", ss.str()); } }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/src/gmock-cardinalities.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-cardinalities_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
be659964-e353-481a-b2dd-23f6f1b2652a
cpp
google/googletest
gmock-spec-builders
googlemock/src/gmock-spec-builders.cc
googlemock/test/gmock-spec-builders_test.cc
#include "gmock/gmock-spec-builders.h" #include <stdlib.h> #include <iostream> #include <map> #include <memory> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" #if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC) #include <unistd.h> #endif #ifdef GTEST_OS_QURT #include <qurt_event.h> #endif #if defined(_MSC_VER) && (_MSC_VER == 1900) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800) #endif namespace testing { namespace internal { GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const std::string& message) { ::std::ostringstream s; s << internal::FormatFileLocation(file, line) << " " << message << ::std::endl; Log(severity, s.str(), 0); } ExpectationBase::ExpectationBase(const char* a_file, int a_line, const std::string& a_source_text) : file_(a_file), line_(a_line), source_text_(a_source_text), cardinality_specified_(false), cardinality_(Exactly(1)), call_count_(0), retired_(false), extra_matcher_specified_(false), repeated_action_specified_(false), retires_on_saturation_(false), last_clause_(kNone), action_count_checked_(false) {} ExpectationBase::~ExpectationBase() = default; void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { cardinality_specified_ = true; cardinality_ = a_cardinality; } void ExpectationBase::RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { if (is_retired()) { return; } ::std::vector<ExpectationBase*> expectations(1, this); while (!expectations.empty()) { ExpectationBase* exp = expectations.back(); expectations.pop_back(); for (ExpectationSet::const_iterator it = exp->immediate_prerequisites_.begin(); it != exp->immediate_prerequisites_.end(); ++it) { ExpectationBase* next = it->expectation_base().get(); if (!next->is_retired()) { next->Retire(); expectations.push_back(next); } } } } bool ExpectationBase::AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); ::std::vector<const ExpectationBase*> expectations(1, this); while (!expectations.empty()) { const ExpectationBase* exp = expectations.back(); expectations.pop_back(); for (ExpectationSet::const_iterator it = exp->immediate_prerequisites_.begin(); it != exp->immediate_prerequisites_.end(); ++it) { const ExpectationBase* next = it->expectation_base().get(); if (!next->IsSatisfied()) return false; expectations.push_back(next); } } return true; } void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); ::std::vector<const ExpectationBase*> expectations(1, this); while (!expectations.empty()) { const ExpectationBase* exp = expectations.back(); expectations.pop_back(); for (ExpectationSet::const_iterator it = exp->immediate_prerequisites_.begin(); it != exp->immediate_prerequisites_.end(); ++it) { const ExpectationBase* next = it->expectation_base().get(); if (next->IsSatisfied()) { if (next->call_count_ == 0) { expectations.push_back(next); } } else { *result += *it; } } } } void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); *os << " Expected: to be "; cardinality().DescribeTo(os); *os << "\n Actual: "; Cardinality::DescribeActualCallCountTo(call_count(), os); *os << " - " << (IsOverSaturated() ? "over-saturated" : IsSaturated() ? "saturated" : IsSatisfied() ? "satisfied" : "unsatisfied") << " and " << (is_retired() ? "retired" : "active"); } void ExpectationBase::CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_) { bool should_check = false; { MutexLock l(&mutex_); if (!action_count_checked_) { action_count_checked_ = true; should_check = true; } } if (should_check) { if (!cardinality_specified_) { return; } const int action_count = static_cast<int>(untyped_actions_.size()); const int upper_bound = cardinality().ConservativeUpperBound(); const int lower_bound = cardinality().ConservativeLowerBound(); bool too_many; if (action_count > upper_bound || (action_count == upper_bound && repeated_action_specified_)) { too_many = true; } else if (0 < action_count && action_count < lower_bound && !repeated_action_specified_) { too_many = false; } else { return; } ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Too " << (too_many ? "many" : "few") << " actions specified in " << source_text() << "...\n" << "Expected to be "; cardinality().DescribeTo(&ss); ss << ", but has " << (too_many ? "" : "only ") << action_count << " WillOnce()" << (action_count == 1 ? "" : "s"); if (repeated_action_specified_) { ss << " and a WillRepeatedly()"; } ss << "."; Log(kWarning, ss.str(), -1); } } void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) { if (last_clause_ == kTimes) { ExpectSpecProperty(false, ".Times() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty( last_clause_ < kTimes, ".Times() may only appear *before* .InSequence(), .WillOnce(), " ".WillRepeatedly(), or .RetiresOnSaturation(), not after."); } last_clause_ = kTimes; SpecifyCardinality(a_cardinality); } GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { const int stack_frames_to_skip = GMOCK_FLAG_GET(verbose) == kInfoVerbosity ? 3 : -1; switch (reaction) { case kAllow: Log(kInfo, msg, stack_frames_to_skip); break; case kWarn: Log(kWarning, msg + "\nNOTE: You can safely ignore the above warning unless this " "call should not happen. Do not suppress it by blindly adding " "an EXPECT_CALL() if you don't mean to enforce the call. " "See " "https: "gmock_cook_book.md#" "knowing-when-to-expect-useoncall for details.\n", stack_frames_to_skip); break; default: Expect(false, nullptr, -1, msg); } } UntypedFunctionMockerBase::UntypedFunctionMockerBase() : mock_obj_(nullptr), name_("") {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default; void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { { MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; } Mock::Register(mock_obj, this); } void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; name_ = name; } const void* UntypedFunctionMockerBase::MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const void* mock_obj; { MutexLock l(&g_gmock_mutex); Assert(mock_obj_ != nullptr, __FILE__, __LINE__, "MockObject() must not be called before RegisterOwner() or " "SetOwnerAndName() has been called."); mock_obj = mock_obj_; } return mock_obj; } const char* UntypedFunctionMockerBase::Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const char* name; { MutexLock l(&g_gmock_mutex); Assert(name_ != nullptr, __FILE__, __LINE__, "Name() must not be called before SetOwnerAndName() has " "been called."); name = name_; } return name; } Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { if (it->get() == exp) { return Expectation(*it); } } Assert(false, __FILE__, __LINE__, "Cannot find expectation."); return Expectation(); } bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); bool expectations_met = true; for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { ExpectationBase* const untyped_expectation = it->get(); if (untyped_expectation->IsOverSaturated()) { expectations_met = false; } else if (!untyped_expectation->IsSatisfied()) { expectations_met = false; ::std::stringstream ss; const ::std::string& expectation_name = untyped_expectation->GetDescription(); ss << "Actual function "; if (!expectation_name.empty()) { ss << "\"" << expectation_name << "\" "; } ss << "call count doesn't match " << untyped_expectation->source_text() << "...\n"; untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->DescribeCallCountTo(&ss); Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } } UntypedExpectations expectations_to_delete; untyped_expectations_.swap(expectations_to_delete); g_gmock_mutex.Unlock(); expectations_to_delete.clear(); g_gmock_mutex.Lock(); return expectations_met; } static CallReaction intToCallReaction(int mock_behavior) { if (mock_behavior >= kAllow && mock_behavior <= kFail) { return static_cast<internal::CallReaction>(mock_behavior); } return kWarn; } } namespace { typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; struct MockObjectState { MockObjectState() : first_used_file(nullptr), first_used_line(-1), leakable(false) {} const char* first_used_file; int first_used_line; ::std::string first_used_test_suite; ::std::string first_used_test; bool leakable; FunctionMockers function_mockers; }; class MockObjectRegistry { public: typedef std::map<const void*, MockObjectState> StateMap; ~MockObjectRegistry() { if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return; internal::MutexLock l(&internal::g_gmock_mutex); int leaked_count = 0; for (StateMap::const_iterator it = states_.begin(); it != states_.end(); ++it) { if (it->second.leakable) continue; std::cout << "\n"; const MockObjectState& state = it->second; std::cout << internal::FormatFileLocation(state.first_used_file, state.first_used_line); std::cout << " ERROR: this mock object"; if (!state.first_used_test.empty()) { std::cout << " (used in test " << state.first_used_test_suite << "." << state.first_used_test << ")"; } std::cout << " should be deleted but never is. Its address is @" << it->first << "."; leaked_count++; } if (leaked_count > 0) { std::cout << "\nERROR: " << leaked_count << " leaked mock " << (leaked_count == 1 ? "object" : "objects") << " found at program exit. Expectations on a mock object are " "verified when the object is destructed. Leaking a mock " "means that its expectations aren't verified, which is " "usually a test bug. If you really intend to leak a mock, " "you can suppress this error using " "testing::Mock::AllowLeak(mock_object), or you may use a " "fake or stub instead of a mock.\n"; std::cout.flush(); ::std::cerr.flush(); #ifdef GTEST_OS_QURT qurt_exception_raise_fatal(); #else _Exit(1); #endif } } StateMap& states() { return states_; } private: StateMap states_; }; MockObjectRegistry g_mock_object_registry; std::unordered_map<uintptr_t, internal::CallReaction>& UninterestingCallReactionMap() { static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>; return *map; } void SetReactionOnUninterestingCalls(uintptr_t mock_obj, internal::CallReaction reaction) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); UninterestingCallReactionMap()[mock_obj] = reaction; } } void Mock::AllowUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); } void Mock::WarnUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); } void Mock::FailUninterestingCalls(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kFail); } void Mock::UnregisterCallReaction(uintptr_t mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj)); } internal::CallReaction Mock::GetReactionOnUninterestingCalls( const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return (UninterestingCallReactionMap().count( reinterpret_cast<uintptr_t>(mock_obj)) == 0) ? internal::intToCallReaction( GMOCK_FLAG_GET(default_mock_behavior)) : UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>( mock_obj)]; } void Mock::AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].leakable = true; } bool Mock::VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return VerifyAndClearExpectationsLocked(mock_obj); } bool Mock::VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); ClearDefaultActionsLocked(mock_obj); return VerifyAndClearExpectationsLocked(mock_obj); } bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { return true; } bool expectations_met = true; FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { if (!(*it)->VerifyAndClearExpectationsLocked()) { expectations_met = false; } } return expectations_met; } bool Mock::IsNaggy(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn; } bool Mock::IsNice(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow; } bool Mock::IsStrict(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail; } void Mock::Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); } void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); MockObjectState& state = g_mock_object_registry.states()[mock_obj]; if (state.first_used_file == nullptr) { state.first_used_file = file; state.first_used_line = line; const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != nullptr) { state.first_used_test_suite = test_info->test_suite_name(); state.first_used_test = test_info->name(); } } } void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); for (MockObjectRegistry::StateMap::iterator it = g_mock_object_registry.states().begin(); it != g_mock_object_registry.states().end(); ++it) { FunctionMockers& mockers = it->second.function_mockers; if (mockers.erase(mocker) > 0) { if (mockers.empty()) { g_mock_object_registry.states().erase(it); } return; } } } void Mock::ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { return; } FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { (*it)->ClearDefaultActionsLocked(); } } Expectation::Expectation() = default; Expectation::Expectation( const std::shared_ptr<internal::ExpectationBase>& an_expectation_base) : expectation_base_(an_expectation_base) {} Expectation::~Expectation() = default; void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { if (last_expectation_->expectation_base() != nullptr) { expectation.expectation_base()->immediate_prerequisites_ += *last_expectation_; } *last_expectation_ = expectation; } } InSequence::InSequence() { if (internal::g_gmock_implicit_sequence.get() == nullptr) { internal::g_gmock_implicit_sequence.set(new Sequence); sequence_created_ = true; } else { sequence_created_ = false; } } InSequence::~InSequence() { if (sequence_created_) { delete internal::g_gmock_implicit_sequence.get(); internal::g_gmock_implicit_sequence.set(nullptr); } } } #if defined(_MSC_VER) && (_MSC_VER == 1900) GTEST_DISABLE_MSC_WARNINGS_POP_() #endif
#include "gmock/gmock-spec-builders.h" #include <memory> #include <ostream> #include <sstream> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" namespace testing { namespace { using ::testing::internal::FormatFileLocation; using ::testing::internal::kAllow; using ::testing::internal::kErrorVerbosity; using ::testing::internal::kFail; using ::testing::internal::kInfoVerbosity; using ::testing::internal::kWarn; using ::testing::internal::kWarningVerbosity; #if GTEST_HAS_STREAM_REDIRECTION using ::testing::internal::CaptureStdout; using ::testing::internal::GetCapturedStdout; #endif class Incomplete; class MockIncomplete { public: MOCK_METHOD1(ByRefFunc, void(const Incomplete& x)); }; void PrintTo(const Incomplete& x, ::std::ostream* os); TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) { MockIncomplete incomplete; EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber()); } void PrintTo(const Incomplete& , ::std::ostream* os) { *os << "incomplete"; } class Result {}; class NonDefaultConstructible { public: explicit NonDefaultConstructible(int ) {} }; class MockA { public: MockA() = default; MOCK_METHOD1(DoA, void(int n)); MOCK_METHOD1(ReturnResult, Result(int n)); MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible()); MOCK_METHOD2(Binary, bool(int x, int y)); MOCK_METHOD2(ReturnInt, int(int x, int y)); private: MockA(const MockA&) = delete; MockA& operator=(const MockA&) = delete; }; class MockB { public: MockB() = default; MOCK_CONST_METHOD0(DoB, int()); MOCK_METHOD1(DoB, int(int n)); private: MockB(const MockB&) = delete; MockB& operator=(const MockB&) = delete; }; class ReferenceHoldingMock { public: ReferenceHoldingMock() = default; MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*)); private: ReferenceHoldingMock(const ReferenceHoldingMock&) = delete; ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete; }; #define Method MethodW class CC { public: virtual ~CC() = default; virtual int Method() = 0; }; class MockCC : public CC { public: MockCC() = default; MOCK_METHOD0(Method, int()); private: MockCC(const MockCC&) = delete; MockCC& operator=(const MockCC&) = delete; }; TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { MockCC cc; ON_CALL(cc, Method()); } TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { MockCC cc; ON_CALL(cc, Method()).WillByDefault(Return(42)); EXPECT_EQ(42, cc.Method()); } TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { MockCC cc; EXPECT_CALL(cc, Method()); cc.Method(); } TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) { MockCC cc; EXPECT_CALL(cc, Method()).WillOnce(Return(42)); EXPECT_EQ(42, cc.Method()); } #undef Method TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) { MockA a; MockA* pa = &a; ON_CALL(*pa++, DoA(_)); EXPECT_EQ(&a + 1, pa); } TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) { MockA a; int n = 0; ON_CALL(a, DoA(n++)); EXPECT_EQ(1, n); } TEST(OnCallSyntaxTest, WithIsOptional) { MockA a; ON_CALL(a, DoA(5)).WillByDefault(Return()); ON_CALL(a, DoA(_)).With(_).WillByDefault(Return()); } TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { ON_CALL(a, ReturnResult(_)) .With(_) .With(_) .WillByDefault(Return(Result())); }, ".With() cannot appear more than once in an ON_CALL()"); } TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) { MockA a; EXPECT_DEATH_IF_SUPPORTED( { ON_CALL(a, DoA(5)); a.DoA(5); }, ""); } TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return()); }, ".WillByDefault() must appear exactly once in an ON_CALL()"); } TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) { MockA a; MockA* pa = &a; EXPECT_CALL(*pa++, DoA(_)); a.DoA(0); EXPECT_EQ(&a + 1, pa); } TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) { MockA a; int n = 0; EXPECT_CALL(a, DoA(n++)); a.DoA(0); EXPECT_EQ(1, n); } TEST(ExpectCallSyntaxTest, WithIsOptional) { MockA a; EXPECT_CALL(a, DoA(5)).Times(0); EXPECT_CALL(a, DoA(6)).With(_).Times(0); } TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(6)).With(_).With(_); }, ".With() cannot appear more than once in an EXPECT_CALL()"); a.DoA(6); } TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).Times(1).With(_); }, ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(1); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_); }, ".With() must be the first clause in an EXPECT_CALL()"); a.DoA(2); } TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { MockA a; EXPECT_CALL(a, DoA(1)).WillOnce(Return()); EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); a.DoA(2); } TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).Times(1).Times(2); }, ".Times() cannot appear more than once in an EXPECT_CALL()"); a.DoA(1); a.DoA(1); } TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { MockA a; Sequence s; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1); }, ".Times() may only appear *before* "); a.DoA(1); } TEST(ExpectCallSyntaxTest, InSequenceIsOptional) { MockA a; Sequence s; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).InSequence(s); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) { MockA a; Sequence s1, s2; EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1); a.DoA(1); } TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) { MockA a; Sequence s; Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber()); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).After(e).InSequence(s); }, ".InSequence() cannot appear after "); a.DoA(2); } TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) { MockA a; Sequence s; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s); }, ".InSequence() cannot appear after "); a.DoA(1); } TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) { MockA a; Expectation e = EXPECT_CALL(a, DoA(1)); EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); }, ".After() cannot appear after "); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).WillOnce(Return()); a.DoA(1); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) { MockA a; EXPECT_CALL(a, DoA(1)) .Times(AnyNumber()) .WillOnce(Return()) .WillOnce(Return()) .WillOnce(Return()); } TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return()); }, ".WillOnce() cannot appear after "); a.DoA(1); } TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)).WillOnce(Return()); EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return()); a.DoA(1); a.DoA(2); a.DoA(2); } TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly( Return()); }, ".WillRepeatedly() cannot appear more than once in an " "EXPECT_CALL()"); } TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return()); }, ".WillRepeatedly() cannot appear after "); } TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { MockA a; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1)).RetiresOnSaturation(); a.DoA(1); a.DoA(1); } TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) { MockA a; EXPECT_NONFATAL_FAILURE( { EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation(); }, ".RetiresOnSaturation() cannot appear more than once"); a.DoA(1); } TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) { { MockA a; EXPECT_CALL(a, DoA(1)); a.DoA(1); } EXPECT_NONFATAL_FAILURE( { MockA a; EXPECT_CALL(a, DoA(1)); }, "to be called once"); EXPECT_NONFATAL_FAILURE( { MockA a; EXPECT_CALL(a, DoA(1)); a.DoA(1); a.DoA(1); }, "to be called once"); } #if GTEST_HAS_STREAM_REDIRECTION TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { CaptureStdout(); { MockB b; EXPECT_CALL(b, DoB()).Times(0); EXPECT_CALL(b, DoB(1)).Times(AtMost(1)); EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1)); EXPECT_CALL(b, DoB(3)) .Times(Between(1, 2)) .WillOnce(Return(1)) .WillOnce(Return(2)); EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly( Return(2)); b.DoB(2); b.DoB(3); } EXPECT_STREQ("", GetCapturedStdout().c_str()); } TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { CaptureStdout(); { MockB b; EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce( Return(2)); EXPECT_CALL(b, DoB(1)) .Times(1) .WillOnce(Return(1)) .WillOnce(Return(2)) .RetiresOnSaturation(); EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly( Return(2)); b.DoB(1); b.DoB(2); } const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 1 WillOnce().", output); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be called at most once, " "but has 2 WillOnce()s.", output); EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n" "Expected to be called once, but has 2 WillOnce()s.", output); EXPECT_PRED_FORMAT2(IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 0 WillOnce()s " "and a WillRepeatedly().", output); EXPECT_PRED_FORMAT2( IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n" "Expected to be called once, but has 1 WillOnce() " "and a WillRepeatedly().", output); } TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { MockB b; EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1)); CaptureStdout(); b.DoB(); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "Too few actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be called between 2 and 3 times, " "but has only 1 WillOnce().", output); b.DoB(); } TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { int original_behavior = GMOCK_FLAG_GET(default_mock_behavior); GMOCK_FLAG_SET(default_mock_behavior, kAllow); CaptureStdout(); { MockA a; a.DoA(0); } std::string output = GetCapturedStdout(); EXPECT_TRUE(output.empty()) << output; GMOCK_FLAG_SET(default_mock_behavior, kWarn); CaptureStdout(); { MockA a; a.DoA(0); } std::string warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, kFail); EXPECT_NONFATAL_FAILURE( { MockA a; a.DoA(0); }, "Uninteresting mock function call"); GMOCK_FLAG_SET(default_mock_behavior, -1); CaptureStdout(); { MockA a; a.DoA(0); } warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, 3); CaptureStdout(); { MockA a; a.DoA(0); } warning_output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", warning_output); GMOCK_FLAG_SET(default_mock_behavior, original_behavior); } #endif TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) { MockB b; EXPECT_CALL(b, DoB()); EXPECT_EQ(0, b.DoB()); } TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) { MockB b; ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(0, b.DoB(2)); } TEST(OnCallTest, PicksLastMatchingOnCall) { MockB b; ON_CALL(b, DoB(_)).WillByDefault(Return(3)); ON_CALL(b, DoB(2)).WillByDefault(Return(2)); ON_CALL(b, DoB(1)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)); EXPECT_EQ(2, b.DoB(2)); } TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) { MockB b; EXPECT_CALL(b, DoB()); b.DoB(); b.DoB(1); b.DoB(2); } TEST(ExpectCallTest, PicksLastMatchingExpectCall) { MockB b; EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2)); EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1)); EXPECT_EQ(1, b.DoB(1)); } TEST(ExpectCallTest, CatchesTooFewCalls) { EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2)); b.DoB(5); }, "Actual function \"DoB Method\" call count " "doesn't match EXPECT_CALL(b, DoB(5))...\n" " Expected: to be called at least twice\n" " Actual: called once - unsatisfied and active"); } TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); } EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); }, "to be called twice"); { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice"); } } TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) { { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); } { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } EXPECT_NONFATAL_FAILURE( { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); }, "to be called at least once"); } #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L TEST(ExpectCallTest, NonMoveableType) { struct NonMoveableStruct { explicit NonMoveableStruct(int x_in) : x(x_in) {} NonMoveableStruct(NonMoveableStruct&&) = delete; int x; }; static_assert(!std::is_move_constructible_v<NonMoveableStruct>); static_assert(!std::is_copy_constructible_v<NonMoveableStruct>); static_assert(!std::is_move_assignable_v<NonMoveableStruct>); static_assert(!std::is_copy_assignable_v<NonMoveableStruct>); const auto return_17 = [] { return NonMoveableStruct(17); }; static_cast<void>(OnceAction<NonMoveableStruct()>{return_17}); static_cast<void>(Action<NonMoveableStruct()>{return_17}); static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17}); static_cast<void>(Action<NonMoveableStruct(int)>{return_17}); MockFunction<NonMoveableStruct()> mock; EXPECT_CALL(mock, Call) .WillOnce(return_17) .WillRepeatedly(return_17); EXPECT_EQ(17, mock.AsStdFunction()().x); EXPECT_EQ(17, mock.AsStdFunction()().x); EXPECT_EQ(17, mock.AsStdFunction()().x); } #endif TEST(ExpectCallTest, NthMatchTakesNthAction) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce( Return(3)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(3, b.DoB()); } TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB()); } #if GTEST_HAS_STREAM_REDIRECTION TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { MockB b; EXPECT_CALL(b, DoB(_)).Times(1); EXPECT_CALL(b, DoB()) .Times(AnyNumber()) .WillOnce(Return(1)) .WillOnce(Return(2)); CaptureStdout(); EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(1, b.DoB()); EXPECT_EQ(2, b.DoB()); const std::string output1 = GetCapturedStdout(); EXPECT_STREQ("", output1.c_str()); CaptureStdout(); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB()); const std::string output2 = GetCapturedStdout(); EXPECT_THAT(output2.c_str(), HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" "Called 3 times, but only 2 WillOnce()s are specified" " - returning default value.")); EXPECT_THAT(output2.c_str(), HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n" "Called 4 times, but only 2 WillOnce()s are specified" " - returning default value.")); } TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) { MockB b; std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1)); EXPECT_EQ(1, b.DoB()); CaptureStdout(); EXPECT_EQ(0, b.DoB()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output); } TEST(FunctionMockerMessageTest, ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) { std::string on_call_location; CaptureStdout(); { NaggyMock<MockB> b; on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1); ON_CALL(b, DoB(_)).WillByDefault(Return(0)); b.DoB(0); } EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout()); } #endif TEST(UninterestingCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_TRUE(a.Binary(1, 2)); MockB b; EXPECT_EQ(0, b.DoB()); } TEST(UnexpectedCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2), "Unexpected mock function call"); EXPECT_TRUE(result); MockB b; EXPECT_CALL(b, DoB(0)).Times(0); int n = -1; EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call"); EXPECT_EQ(0, n); } TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) { MockA a1; EXPECT_CALL(a1, DoA(1)); a1.DoA(1); EXPECT_NONFATAL_FAILURE( a1.DoA(9), "Unexpected mock function call - returning directly.\n" " Function call: DoA(9)\n" "Google Mock tried the following 1 expectation, but it didn't match:"); EXPECT_NONFATAL_FAILURE( a1.DoA(9), " Expected arg #0: is equal to 1\n" " Actual: 9\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); MockA a2; EXPECT_CALL(a2, DoA(1)); EXPECT_CALL(a2, DoA(3)); a2.DoA(1); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "Unexpected mock function call - returning directly.\n" " Function call: DoA(2)\n" "Google Mock tried the following 2 expectations, but none matched:"); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n" " Expected arg #0: is equal to 1\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); EXPECT_NONFATAL_FAILURE( a2.DoA(2), "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n" " Expected arg #0: is equal to 3\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: never called - unsatisfied and active"); a2.DoA(3); } TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) { MockB b1; EXPECT_CALL(b1, DoB(1)); b1.DoB(1); EXPECT_NONFATAL_FAILURE( b1.DoB(2), "Unexpected mock function call - returning default value.\n" " Function call: DoB(2)\n" " Returns: 0\n" "Google Mock tried the following 1 expectation, but it didn't match:"); EXPECT_NONFATAL_FAILURE( b1.DoB(2), " Expected arg #0: is equal to 1\n" " Actual: 2\n" " Expected: to be called once\n" " Actual: called once - saturated and active"); } TEST(UnexpectedCallTest, RetiredExpectation) { MockB b; EXPECT_CALL(b, DoB(1)).RetiresOnSaturation(); b.DoB(1); EXPECT_NONFATAL_FAILURE(b.DoB(1), " Expected: the expectation is active\n" " Actual: it is retired"); } TEST(UnexpectedCallTest, UnmatchedArguments) { MockB b; EXPECT_CALL(b, DoB(1)); EXPECT_NONFATAL_FAILURE(b.DoB(2), " Expected arg #0: is equal to 1\n" " Actual: 2\n"); b.DoB(1); } TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) { Sequence s1, s2; MockB b; EXPECT_CALL(b, DoB(1)).InSequence(s1); EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1); EXPECT_CALL(b, DoB(3)).InSequence(s2); EXPECT_CALL(b, DoB(4)).InSequence(s1, s2); ::testing::TestPartResultArray failures; { ::testing::ScopedFakeTestPartResultReporter reporter(&failures); b.DoB(4); } ASSERT_EQ(1, failures.size()); const ::testing::TestPartResult& r = failures.GetTestPartResult(0); EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type()); #ifdef GTEST_USES_POSIX_RE EXPECT_THAT(r.message(), ContainsRegex( "the following immediate pre-requisites are not satisfied:\n" "(.|\n)*: pre-requisite #0\n" "(.|\n)*: pre-requisite #1")); #else EXPECT_THAT(r.message(), ContainsRegex( "the following immediate pre-requisites are not satisfied:")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); #endif b.DoB(1); b.DoB(3); b.DoB(4); } TEST(UndefinedReturnValueTest, ReturnValueIsMandatoryWhenNotDefaultConstructible) { MockA a; #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible()); #else EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), ""); #endif } TEST(ExcessiveCallTest, DoesDefaultAction) { MockA a; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(0, 0)); a.Binary(0, 0); bool result = false; EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0), "Mock function called more times than expected"); EXPECT_TRUE(result); MockB b; EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0); int n = -1; EXPECT_NONFATAL_FAILURE( n = b.DoB(0), "Mock function \"DoB Method\" called more times than expected"); EXPECT_EQ(0, n); } TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) { MockA a; EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0); EXPECT_NONFATAL_FAILURE( a.DoA(9), "Mock function \"DoA Method\" called more times than expected - " "returning directly.\n" " Function call: DoA(9)\n" " Expected: to be never called\n" " Actual: called once - over-saturated and active"); } TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) { MockB b; EXPECT_CALL(b, DoB(_)); b.DoB(1); EXPECT_NONFATAL_FAILURE( b.DoB(2), "Mock function called more times than expected - " "returning default value.\n" " Function call: DoB(2)\n" " Returns: 0\n" " Expected: to be called once\n" " Actual: called twice - over-saturated and active"); } TEST(InSequenceTest, AllExpectationInScopeAreInSequence) { MockA a; { InSequence dummy; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)); } EXPECT_NONFATAL_FAILURE( { a.DoA(2); }, "Unexpected mock function call"); a.DoA(1); a.DoA(2); } TEST(InSequenceTest, NestedInSequence) { MockA a; { InSequence dummy; EXPECT_CALL(a, DoA(1)); { InSequence dummy2; EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, DoA(3)); } } EXPECT_NONFATAL_FAILURE( { a.DoA(1); a.DoA(3); }, "Unexpected mock function call"); a.DoA(2); a.DoA(3); } TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) { MockA a; { InSequence dummy; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)); } EXPECT_CALL(a, DoA(3)); EXPECT_NONFATAL_FAILURE( { a.DoA(2); }, "Unexpected mock function call"); a.DoA(3); a.DoA(1); a.DoA(2); } TEST(SequenceTest, AnyOrderIsOkByDefault) { { MockA a; MockB b; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(b, DoB()).Times(AnyNumber()); a.DoA(1); b.DoB(); } { MockA a; MockB b; EXPECT_CALL(a, DoA(1)); EXPECT_CALL(b, DoB()).Times(AnyNumber()); b.DoB(); a.DoA(1); } } TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) { MockA a; ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Sequence s; EXPECT_CALL(a, ReturnResult(1)).InSequence(s); EXPECT_CALL(a, ReturnResult(2)).InSequence(s); EXPECT_CALL(a, ReturnResult(3)).InSequence(s); a.ReturnResult(1); EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); a.ReturnResult(2); a.ReturnResult(3); } TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) { MockA a; ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Sequence s; EXPECT_CALL(a, ReturnResult(1)).InSequence(s); EXPECT_CALL(a, ReturnResult(2)).InSequence(s); EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call"); a.ReturnResult(1); a.ReturnResult(2); } class PartialOrderTest : public testing::Test { protected: PartialOrderTest() { ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result())); Sequence x, y; EXPECT_CALL(a_, ReturnResult(1)).InSequence(x); EXPECT_CALL(b_, DoB()).Times(2).InSequence(y); EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y); EXPECT_CALL(a_, ReturnResult(3)).InSequence(x); } MockA a_; MockB b_; }; TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) { a_.ReturnResult(1); b_.DoB(); EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call"); b_.DoB(); a_.ReturnResult(3); } TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) { EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call"); a_.ReturnResult(1); b_.DoB(); b_.DoB(); a_.ReturnResult(3); } TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) { EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call"); a_.ReturnResult(1); b_.DoB(); b_.DoB(); a_.ReturnResult(3); } TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) { a_.ReturnResult(1); b_.DoB(); b_.DoB(); a_.ReturnResult(3); EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call"); } TEST(SequenceTest, Retirement) { MockA a; Sequence s; EXPECT_CALL(a, DoA(1)).InSequence(s); EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation(); EXPECT_CALL(a, DoA(1)).InSequence(s); a.DoA(1); a.DoA(2); a.DoA(1); } TEST(ExpectationTest, ConstrutorsWork) { MockA a; Expectation e1; Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_); { Sequence s; Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1); Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s); } Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2); Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return()); Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return()); Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation(); Expectation e10 = e2; EXPECT_THAT(e1, Ne(e2)); EXPECT_THAT(e2, Eq(e10)); a.DoA(2); a.DoA(3); a.DoA(4); a.DoA(5); a.DoA(6); a.DoA(7); a.DoA(8); a.DoA(9); } TEST(ExpectationTest, AssignmentWorks) { MockA a; Expectation e1; Expectation e2 = EXPECT_CALL(a, DoA(1)); EXPECT_THAT(e1, Ne(e2)); e1 = e2; EXPECT_THAT(e1, Eq(e2)); a.DoA(1); } TEST(ExpectationSetTest, MemberTypesAreCorrect) { ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>(); } TEST(ExpectationSetTest, ConstructorsWork) { MockA a; Expectation e1; const Expectation e2; ExpectationSet es1; ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); ExpectationSet es3 = e1; ExpectationSet es4(e1); ExpectationSet es5 = e2; ExpectationSet es6(e2); ExpectationSet es7 = es2; EXPECT_EQ(0, es1.size()); EXPECT_EQ(1, es2.size()); EXPECT_EQ(1, es3.size()); EXPECT_EQ(1, es4.size()); EXPECT_EQ(1, es5.size()); EXPECT_EQ(1, es6.size()); EXPECT_EQ(1, es7.size()); EXPECT_THAT(es3, Ne(es2)); EXPECT_THAT(es4, Eq(es3)); EXPECT_THAT(es5, Eq(es4)); EXPECT_THAT(es6, Eq(es5)); EXPECT_THAT(es7, Eq(es2)); a.DoA(1); } TEST(ExpectationSetTest, AssignmentWorks) { ExpectationSet es1; ExpectationSet es2 = Expectation(); es1 = es2; EXPECT_EQ(1, es1.size()); EXPECT_THAT(*(es1.begin()), Eq(Expectation())); EXPECT_THAT(es1, Eq(es2)); } TEST(ExpectationSetTest, InsertionWorks) { ExpectationSet es1; Expectation e1; es1 += e1; EXPECT_EQ(1, es1.size()); EXPECT_THAT(*(es1.begin()), Eq(e1)); MockA a; Expectation e2 = EXPECT_CALL(a, DoA(1)); es1 += e2; EXPECT_EQ(2, es1.size()); ExpectationSet::const_iterator it1 = es1.begin(); ExpectationSet::const_iterator it2 = it1; ++it2; EXPECT_TRUE(*it1 == e1 || *it2 == e1); EXPECT_TRUE(*it1 == e2 || *it2 == e2); a.DoA(1); } TEST(ExpectationSetTest, SizeWorks) { ExpectationSet es; EXPECT_EQ(0, es.size()); es += Expectation(); EXPECT_EQ(1, es.size()); MockA a; es += EXPECT_CALL(a, DoA(1)); EXPECT_EQ(2, es.size()); a.DoA(1); } TEST(ExpectationSetTest, IsEnumerable) { ExpectationSet es; EXPECT_TRUE(es.begin() == es.end()); es += Expectation(); ExpectationSet::const_iterator it = es.begin(); EXPECT_TRUE(it != es.end()); EXPECT_THAT(*it, Eq(Expectation())); ++it; EXPECT_TRUE(it == es.end()); } TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) { MockA a; ExpectationSet es; es += EXPECT_CALL(a, DoA(1)); es += EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, DoA(3)).After(es); a.DoA(1); a.DoA(2); a.DoA(3); } TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) { MockA a; MockB b; const Expectation e1 = EXPECT_CALL(a, DoA(1)); const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1); EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); b.DoB(); b.DoB(); a.DoA(2); } TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) { MockA a; MockB b; Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(b, DoB()).After(e1); EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call"); b.DoB(); a.DoA(2); } TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) { MockA a; MockB b; Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1); EXPECT_CALL(a, DoA(2)).After(e2); a.DoA(1); b.DoB(); EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call"); b.DoB(); a.DoA(2); } TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) { MockA a; ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Expectation e = EXPECT_CALL(a, DoA(1)); const ExpectationSet es = EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, ReturnResult(3)).After(e, es); EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); a.DoA(2); a.DoA(1); a.ReturnResult(3); } TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) { MockA a; Expectation e = EXPECT_CALL(a, DoA(1)); const ExpectationSet es = EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, DoA(3)).After(e, es); a.DoA(2); EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call"); a.DoA(1); a.DoA(3); } TEST(AfterTest, CanBeUsedWithInSequence) { MockA a; Sequence s; Expectation e = EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(2)).InSequence(s); EXPECT_CALL(a, DoA(3)).InSequence(s).After(e); a.DoA(1); EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call"); a.DoA(2); a.DoA(3); } TEST(AfterTest, CanBeCalledManyTimes) { MockA a; Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e3 = EXPECT_CALL(a, DoA(3)); EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3); a.DoA(3); a.DoA(1); a.DoA(2); a.DoA(4); } TEST(AfterTest, AcceptsUpToFiveArguments) { MockA a; Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e3 = EXPECT_CALL(a, DoA(3)); ExpectationSet es1 = EXPECT_CALL(a, DoA(4)); ExpectationSet es2 = EXPECT_CALL(a, DoA(5)); EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2); a.DoA(5); a.DoA(2); a.DoA(4); a.DoA(1); a.DoA(3); a.DoA(6); } TEST(AfterTest, AcceptsDuplicatedInput) { MockA a; ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result())); Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); ExpectationSet es; es += e1; es += e2; EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1); a.DoA(1); EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); a.DoA(2); a.ReturnResult(3); } TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) { MockA a; ExpectationSet es1 = EXPECT_CALL(a, DoA(1)); Expectation e2 = EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, DoA(3)).After(es1); es1 += e2; a.DoA(1); a.DoA(3); a.DoA(2); } TEST(DeletingMockEarlyTest, Success1) { MockB* const b1 = new MockB; MockA* const a = new MockA; MockB* const b2 = new MockB; { InSequence dummy; EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); EXPECT_CALL(*a, Binary(_, _)) .Times(AnyNumber()) .WillRepeatedly(Return(true)); EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } EXPECT_EQ(1, b1->DoB(1)); delete b1; EXPECT_TRUE(a->Binary(0, 1)); delete b2; EXPECT_TRUE(a->Binary(1, 2)); delete a; } TEST(DeletingMockEarlyTest, Success2) { MockB* const b1 = new MockB; MockA* const a = new MockA; MockB* const b2 = new MockB; { InSequence dummy; EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } delete a; EXPECT_EQ(1, b1->DoB(1)); EXPECT_EQ(2, b2->DoB(2)); delete b1; delete b2; } GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) ACTION_P(Delete, ptr) { delete ptr; } GTEST_DISABLE_MSC_WARNINGS_POP_() TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { MockA* const a = new MockA; EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a)); a->DoA(42); } TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) { MockA* const a = new MockA; EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result()))); a->ReturnResult(42); } TEST(DeletingMockEarlyTest, Failure1) { MockB* const b1 = new MockB; MockA* const a = new MockA; MockB* const b2 = new MockB; { InSequence dummy; EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1)); EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2)); } delete a; EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call"); EXPECT_EQ(1, b1->DoB(1)); delete b1; delete b2; } TEST(DeletingMockEarlyTest, Failure2) { MockB* const b1 = new MockB; MockA* const a = new MockA; MockB* const b2 = new MockB; { InSequence dummy; EXPECT_CALL(*b1, DoB(_)); EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber()); EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()); } EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called"); EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call"); delete a; delete b2; } class EvenNumberCardinality : public CardinalityInterface { public: bool IsSatisfiedByCallCount(int call_count) const override { return call_count % 2 == 0; } bool IsSaturatedByCallCount(int ) const override { return false; } void DescribeTo(::std::ostream* os) const override { *os << "called even number of times"; } }; Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); } TEST(ExpectationBaseTest, AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) { MockA* a = new MockA; Sequence s; EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s); EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s); EXPECT_CALL(*a, DoA(3)).Times(AnyNumber()); a->DoA(3); a->DoA(1); EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times"); } struct Printable {}; inline void operator<<(::std::ostream& os, const Printable&) { os << "Printable"; } struct Unprintable { Unprintable() : value(0) {} int value; }; class MockC { public: MockC() = default; MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p, const Printable& x, Unprintable y)); MOCK_METHOD0(NonVoidMethod, int()); private: MockC(const MockC&) = delete; MockC& operator=(const MockC&) = delete; }; class VerboseFlagPreservingFixture : public testing::Test { protected: VerboseFlagPreservingFixture() : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {} ~VerboseFlagPreservingFixture() override { GMOCK_FLAG_SET(verbose, saved_verbose_flag_); } private: const std::string saved_verbose_flag_; VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete; VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) = delete; }; #if GTEST_HAS_STREAM_REDIRECTION TEST(FunctionCallMessageTest, UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); NaggyMock<MockC> c; CaptureStdout(); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output); } TEST(FunctionCallMessageTest, UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) { GMOCK_FLAG_SET(verbose, kInfoVerbosity); NaggyMock<MockC> c; CaptureStdout(); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output); #ifndef NDEBUG EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output); CaptureStdout(); c.NonVoidMethod(); const std::string output2 = GetCapturedStdout(); EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2); #endif } TEST(FunctionCallMessageTest, UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) { NaggyMock<MockB> b; CaptureStdout(); b.DoB(); const std::string output1 = GetCapturedStdout(); EXPECT_PRED_FORMAT2( IsSubstring, "Uninteresting mock function call - returning default value.\n" " Function call: DoB()\n" " Returns: 0\n", output1.c_str()); NaggyMock<MockC> c; CaptureStdout(); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); const std::string output2 = GetCapturedStdout(); EXPECT_THAT( output2.c_str(), ContainsRegex("Uninteresting mock function call - returning directly\\.\n" " Function call: VoidMethod" "\\(false, 5, \"Hi\", NULL, @.+ " "Printable, 4-byte object <00-00 00-00>\\)")); } class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { public: void VerifyOutput(const std::string& output, bool should_print, const std::string& expected_substring, const std::string& function_name) { if (should_print) { EXPECT_THAT(output.c_str(), HasSubstr(expected_substring)); #ifndef NDEBUG EXPECT_THAT(output.c_str(), HasSubstr(function_name)); #else static_cast<void>(function_name); #endif } else { EXPECT_STREQ("", output.c_str()); } } void TestExpectedCall(bool should_print) { MockA a; EXPECT_CALL(a, DoA(5)); EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true)); CaptureStdout(); a.DoA(5); VerifyOutput(GetCapturedStdout(), should_print, "Mock function call matches EXPECT_CALL(a, DoA(5))...\n" " Function call: DoA(5)\n" "Stack trace:\n", "DoA"); CaptureStdout(); a.Binary(2, 1); VerifyOutput(GetCapturedStdout(), should_print, "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n" " Function call: Binary(2, 1)\n" " Returns: true\n" "Stack trace:\n", "Binary"); } void TestUninterestingCallOnNaggyMock(bool should_print) { NaggyMock<MockA> a; const std::string note = "NOTE: You can safely ignore the above warning unless this " "call should not happen. Do not suppress it by blindly adding " "an EXPECT_CALL() if you don't mean to enforce the call. " "See " "https: "gmock_cook_book.md#" "knowing-when-to-expect-useoncall for details."; CaptureStdout(); a.DoA(5); VerifyOutput(GetCapturedStdout(), should_print, "\nGMOCK WARNING:\n" "Uninteresting mock function call - returning directly.\n" " Function call: DoA(5)\n" + note, "DoA"); CaptureStdout(); a.Binary(2, 1); VerifyOutput(GetCapturedStdout(), should_print, "\nGMOCK WARNING:\n" "Uninteresting mock function call - returning default value.\n" " Function call: Binary(2, 1)\n" " Returns: false\n" + note, "Binary"); } }; TEST_F(GMockVerboseFlagTest, Info) { GMOCK_FLAG_SET(verbose, kInfoVerbosity); TestExpectedCall(true); TestUninterestingCallOnNaggyMock(true); } TEST_F(GMockVerboseFlagTest, Warning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); TestExpectedCall(false); TestUninterestingCallOnNaggyMock(true); } TEST_F(GMockVerboseFlagTest, Error) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); TestExpectedCall(false); TestUninterestingCallOnNaggyMock(false); } TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) { GMOCK_FLAG_SET(verbose, "invalid"); TestExpectedCall(false); TestUninterestingCallOnNaggyMock(true); } #endif class PrintMeNot {}; void PrintTo(PrintMeNot , ::std::ostream* ) { ADD_FAILURE() << "Google Mock is printing a value that shouldn't be " << "printed even to an internal buffer."; } class LogTestHelper { public: LogTestHelper() = default; MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot)); private: LogTestHelper(const LogTestHelper&) = delete; LogTestHelper& operator=(const LogTestHelper&) = delete; }; class GMockLogTest : public VerboseFlagPreservingFixture { protected: LogTestHelper helper_; }; TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { GMOCK_FLAG_SET(verbose, kWarningVerbosity); EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); } TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); } TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) { GMOCK_FLAG_SET(verbose, kErrorVerbosity); ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot())); helper_.Foo(PrintMeNot()); } TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) { MockA* a = new MockA; Mock::AllowLeak(a); } TEST(AllowLeakTest, CanBeCalledBeforeOnCall) { MockA* a = new MockA; Mock::AllowLeak(a); ON_CALL(*a, DoA(_)).WillByDefault(Return()); a->DoA(0); } TEST(AllowLeakTest, CanBeCalledAfterOnCall) { MockA* a = new MockA; ON_CALL(*a, DoA(_)).WillByDefault(Return()); Mock::AllowLeak(a); } TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) { MockA* a = new MockA; Mock::AllowLeak(a); EXPECT_CALL(*a, DoA(_)); a->DoA(0); } TEST(AllowLeakTest, CanBeCalledAfterExpectCall) { MockA* a = new MockA; EXPECT_CALL(*a, DoA(_)).Times(AnyNumber()); Mock::AllowLeak(a); } TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) { MockA* a = new MockA; ON_CALL(*a, DoA(_)).WillByDefault(Return()); EXPECT_CALL(*a, DoA(_)).Times(AnyNumber()); Mock::AllowLeak(a); } TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) { MockB b; ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)); b.DoB(); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)); bool result = true; EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), "Actual: never called"); ASSERT_FALSE(result); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { MockB b; EXPECT_CALL(b, DoB()).WillOnce(Return(1)); EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(); b.DoB(1); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) { MockB b; EXPECT_CALL(b, DoB(0)).WillOnce(Return(1)); EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(1); bool result = true; EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), "Actual: never called"); ASSERT_FALSE(result); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) { MockB b; EXPECT_CALL(b, DoB()); b.DoB(); Mock::VerifyAndClearExpectations(&b); EXPECT_CALL(b, DoB(_)).WillOnce(Return(1)); b.DoB(1); Mock::VerifyAndClearExpectations(&b); Mock::VerifyAndClearExpectations(&b); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearTest, NoMethodHasDefaultActions) { MockB b; Mock::VerifyAndClear(&b); EXPECT_EQ(0, b.DoB()); } TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { MockB b; ON_CALL(b, DoB()).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); EXPECT_EQ(0, b.DoB()); } TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { MockB b; ON_CALL(b, DoB()).WillByDefault(Return(1)); ON_CALL(b, DoB(_)).WillByDefault(Return(2)); Mock::VerifyAndClear(&b); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(0)); } TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { MockB b; ON_CALL(b, DoB(0)).WillByDefault(Return(1)); ON_CALL(b, DoB(_)).WillByDefault(Return(2)); Mock::VerifyAndClear(&b); EXPECT_EQ(0, b.DoB(0)); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearTest, CanCallManyTimes) { MockB b; ON_CALL(b, DoB()).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b); ON_CALL(b, DoB(_)).WillByDefault(Return(1)); Mock::VerifyAndClear(&b); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearTest, Success) { MockB b; ON_CALL(b, DoB()).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(1)).WillOnce(Return(2)); b.DoB(); b.DoB(1); ASSERT_TRUE(Mock::VerifyAndClear(&b)); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearTest, Failure) { MockB b; ON_CALL(b, DoB(_)).WillByDefault(Return(1)); EXPECT_CALL(b, DoB()).WillOnce(Return(2)); b.DoB(1); bool result = true; EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b), "Actual: never called"); ASSERT_FALSE(result); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearTest, Const) { MockB b; ON_CALL(Const(b), DoB()).WillByDefault(Return(1)); EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2)); b.DoB(); b.DoB(); ASSERT_TRUE(Mock::VerifyAndClear(&b)); EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB(1)); } TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) { MockB b; ON_CALL(b, DoB()).WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)).WillOnce(Return(2)); b.DoB(1); Mock::VerifyAndClear(&b); EXPECT_CALL(b, DoB()).WillOnce(Return(3)); ON_CALL(b, DoB(_)).WillByDefault(Return(4)); EXPECT_EQ(3, b.DoB()); EXPECT_EQ(4, b.DoB(1)); } TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { MockA a; MockB b1; MockB b2; ON_CALL(a, Binary(_, _)).WillByDefault(Return(true)); EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false)); ON_CALL(b1, DoB()).WillByDefault(Return(1)); EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2)); ON_CALL(b2, DoB()).WillByDefault(Return(3)); EXPECT_CALL(b2, DoB(_)); b2.DoB(0); Mock::VerifyAndClear(&b2); EXPECT_TRUE(a.Binary(0, 0)); EXPECT_FALSE(a.Binary(0, 0)); EXPECT_EQ(1, b1.DoB()); EXPECT_EQ(2, b1.DoB(0)); } TEST(VerifyAndClearTest, DestroyingChainedMocksDoesNotDeadlockThroughExpectations) { std::shared_ptr<MockA> a(new MockA); ReferenceHoldingMock test_mock; EXPECT_CALL(test_mock, AcceptReference(_)) .WillRepeatedly(SetArgPointee<0>(a)); a.reset(); } TEST(VerifyAndClearTest, DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) { std::shared_ptr<MockA> a(new MockA); ReferenceHoldingMock test_mock; ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a)); a.reset(); } TEST(SynchronizationTest, CanCallMockMethodInAction) { MockA a; MockC c; ON_CALL(a, DoA(_)).WillByDefault( IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod))); EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1)) .WillOnce(Invoke(&a, &MockA::DoA)) .RetiresOnSaturation(); EXPECT_CALL(c, NonVoidMethod()); a.DoA(1); } TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) { MockA a; int do_a_arg0 = 0; ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0)); int do_a_47_arg0 = 0; ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0)); a.DoA(17); EXPECT_THAT(do_a_arg0, 17); EXPECT_THAT(do_a_47_arg0, 0); a.DoA(47); EXPECT_THAT(do_a_arg0, 17); EXPECT_THAT(do_a_47_arg0, 47); ON_CALL(a, Binary).WillByDefault(Return(true)); ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false)); EXPECT_THAT(a.Binary(14, 17), true); EXPECT_THAT(a.Binary(17, 14), false); } TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) { MockB b; ON_CALL(b, DoB()).WillByDefault(Return(9)); ON_CALL(b, DoB(5)).WillByDefault(Return(11)); EXPECT_THAT(b.DoB(), 9); EXPECT_THAT(b.DoB(1), 0); EXPECT_THAT(b.DoB(5), 11); } struct MockWithConstMethods { public: MOCK_CONST_METHOD1(Foo, int(int)); MOCK_CONST_METHOD2(Bar, int(int, const char*)); }; TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) { MockWithConstMethods mock; ON_CALL(mock, Foo).WillByDefault(Return(7)); ON_CALL(mock, Bar).WillByDefault(Return(33)); EXPECT_THAT(mock.Foo(17), 7); EXPECT_THAT(mock.Bar(27, "purple"), 33); } class MockConstOverload { public: MOCK_METHOD1(Overloaded, int(int)); MOCK_CONST_METHOD1(Overloaded, int(int)); }; TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstOverloadedMethods) { MockConstOverload mock; ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7)); ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9)); ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11)); ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13)); EXPECT_THAT(mock.Overloaded(1), 7); EXPECT_THAT(mock.Overloaded(5), 9); EXPECT_THAT(mock.Overloaded(7), 7); const MockConstOverload& const_mock = mock; EXPECT_THAT(const_mock.Overloaded(1), 0); EXPECT_THAT(const_mock.Overloaded(5), 11); EXPECT_THAT(const_mock.Overloaded(7), 13); } } } int main(int argc, char** argv) { testing::InitGoogleMock(&argc, argv); GMOCK_FLAG_SET(catch_leaked_mocks, true); GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity); return RUN_ALL_TESTS(); }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/src/gmock-spec-builders.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-spec-builders_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
cfb250fc-4603-4bcf-a95d-0b15964ff56f
cpp
google/googletest
gmock
googlemock/src/gmock.cc
googlemock/test/gmock_test.cc
#include "gmock/gmock.h" #include <string> #include "gmock/internal/gmock-port.h" GMOCK_DEFINE_bool_(catch_leaked_mocks, true, "true if and only if Google Mock should report leaked " "mock objects as failures."); GMOCK_DEFINE_string_(verbose, testing::internal::kWarningVerbosity, "Controls how verbose Google Mock's output is." " Valid values:\n" " info - prints all messages.\n" " warning - prints warnings and errors.\n" " error - prints errors only."); GMOCK_DEFINE_int32_(default_mock_behavior, 1, "Controls the default behavior of mocks." " Valid values:\n" " 0 - by default, mocks act as NiceMocks.\n" " 1 - by default, mocks act as NaggyMocks.\n" " 2 - by default, mocks act as StrictMocks."); namespace testing { namespace internal { static const char* ParseGoogleMockFlagValue(const char* str, const char* flag_name, bool def_optional) { if (str == nullptr || flag_name == nullptr) return nullptr; const std::string flag_name_str = std::string("--gmock_") + flag_name; const size_t flag_name_len = flag_name_str.length(); if (strncmp(str, flag_name_str.c_str(), flag_name_len) != 0) return nullptr; const char* flag_end = str + flag_name_len; if (def_optional && (flag_end[0] == '\0')) { return flag_end; } if (flag_end[0] != '=') return nullptr; return flag_end + 1; } static bool ParseGoogleMockFlag(const char* str, const char* flag_name, bool* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true); if (value_str == nullptr) return false; *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } template <typename String> static bool ParseGoogleMockFlag(const char* str, const char* flag_name, String* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, false); if (value_str == nullptr) return false; *value = value_str; return true; } static bool ParseGoogleMockFlag(const char* str, const char* flag_name, int32_t* value) { const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true); if (value_str == nullptr) return false; return ParseInt32(Message() << "The value of flag --" << flag_name, value_str, value); } template <typename CharType> void InitGoogleMockImpl(int* argc, CharType** argv) { InitGoogleTest(argc, argv); if (*argc <= 0) return; for (int i = 1; i != *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); bool found_gmock_flag = false; #define GMOCK_INTERNAL_PARSE_FLAG(flag_name) \ if (!found_gmock_flag) { \ auto value = GMOCK_FLAG_GET(flag_name); \ if (ParseGoogleMockFlag(arg, #flag_name, &value)) { \ GMOCK_FLAG_SET(flag_name, value); \ found_gmock_flag = true; \ } \ } GMOCK_INTERNAL_PARSE_FLAG(catch_leaked_mocks) GMOCK_INTERNAL_PARSE_FLAG(verbose) GMOCK_INTERNAL_PARSE_FLAG(default_mock_behavior) if (found_gmock_flag) { for (int j = i; j != *argc; j++) { argv[j] = argv[j + 1]; } (*argc)--; i--; } } } } GTEST_API_ void InitGoogleMock(int* argc, char** argv) { internal::InitGoogleMockImpl(argc, argv); } GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { internal::InitGoogleMockImpl(argc, argv); } GTEST_API_ void InitGoogleMock() { int argc = 1; const auto arg0 = "dummy"; char* argv0 = const_cast<char*>(arg0); char** argv = &argv0; internal::InitGoogleMockImpl(&argc, argv); } }
#include "gmock/gmock.h" #include <string> #include "gtest/gtest.h" #include "gtest/internal/custom/gtest.h" #if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) using testing::InitGoogleMock; template <typename Char, int M, int N> void TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N], const ::std::string& expected_gmock_verbose) { const ::std::string old_verbose = GMOCK_FLAG_GET(verbose); int argc = M - 1; InitGoogleMock(&argc, const_cast<Char**>(argv)); ASSERT_EQ(N - 1, argc) << "The new argv has wrong number of elements."; for (int i = 0; i < N; i++) { EXPECT_STREQ(new_argv[i], argv[i]); } EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG_GET(verbose)); GMOCK_FLAG_SET(verbose, old_verbose); } TEST(InitGoogleMockTest, ParsesInvalidCommandLine) { const char* argv[] = {nullptr}; const char* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesEmptyCommandLine) { const char* argv[] = {"foo.exe", nullptr}; const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesSingleFlag) { const char* argv[] = {"foo.exe", "--gmock_verbose=info", nullptr}; const char* new_argv[] = {"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); } TEST(InitGoogleMockTest, ParsesMultipleFlags) { int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior); const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", L"--gmock_default_mock_behavior=2", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior)); EXPECT_NE(2, old_default_behavior); GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior); } TEST(InitGoogleMockTest, ParsesUnrecognizedFlag) { const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { const char* argv[] = {"foo.exe", "--non_gmock_flag=blah", "--gmock_verbose=error", nullptr}; const char* new_argv[] = {"foo.exe", "--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } TEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) { const wchar_t* argv[] = {nullptr}; const wchar_t* new_argv[] = {nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) { const wchar_t* argv[] = {L"foo.exe", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesSingleFlag) { const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); } TEST(WideInitGoogleMockTest, ParsesMultipleFlags) { int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior); const wchar_t* argv[] = {L"foo.exe", L"--gmock_verbose=info", L"--gmock_default_mock_behavior=2", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", nullptr}; TestInitGoogleMock(argv, new_argv, "info"); EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior)); EXPECT_NE(2, old_default_behavior); GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior); } TEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) { const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose)); } TEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) { const wchar_t* argv[] = {L"foo.exe", L"--non_gmock_flag=blah", L"--gmock_verbose=error", nullptr}; const wchar_t* new_argv[] = {L"foo.exe", L"--non_gmock_flag=blah", nullptr}; TestInitGoogleMock(argv, new_argv, "error"); } #endif TEST(FlagTest, IsAccessibleInCode) { bool dummy = GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose).empty(); (void)dummy; }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/src/gmock.cc
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
8972e675-3107-459c-ae27-431e066074a2
cpp
google/googletest
gtest_pred_impl
googletest/include/gtest/gtest_pred_impl.h
googletest/test/gtest_pred_impl_unittest.cc
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #include "gtest/gtest-assertion-result.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" namespace testing { #define GTEST_ASSERT_(expression, on_failure) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar = (expression)) \ ; \ else \ on_failure(gtest_ar.failure_message()) template <typename Pred, typename T1> AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1); } #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \ GTEST_ASSERT_(pred_format(#v1, v1), on_failure) #define GTEST_PRED1_(pred, v1, on_failure) \ GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure) #define EXPECT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) #define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2> AssertionResult AssertPred2Helper(const char* pred_text, const char* e1, const char* e2, Pred pred, const T1& v1, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2); } #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure) #define GTEST_PRED2_(pred, v1, v2, on_failure) \ GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \ on_failure) #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) #define ASSERT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2, typename T3> AssertionResult AssertPred3Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, Pred pred, const T1& v1, const T2& v2, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3); } #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure) #define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \ GTEST_ASSERT_( \ ::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \ on_failure) #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) #define ASSERT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2, typename T3, typename T4> AssertionResult AssertPred4Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" << e4 << " evaluates to " << ::testing::PrintToString(v4); } #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure) #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \ GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \ v1, v2, v3, v4), \ on_failure) #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) #define ASSERT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) template <typename Pred, typename T1, typename T2, typename T3, typename T4, typename T5> AssertionResult AssertPred5Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ", " << e5 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n" << e5 << " evaluates to " << ::testing::PrintToString(v5); } #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure) \ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ on_failure) #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \ GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \ pred, v1, v2, v3, v4, v5), \ on_failure) #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) } #endif
#include <iostream> #include <ostream> #include "gtest/gtest-spi.h" #include "gtest/gtest.h" struct Bool { explicit Bool(int val) : value(val != 0) {} bool operator>(int n) const { return value > Bool(n).value; } Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); } bool operator==(const Bool& rhs) const { return value == rhs.value; } bool value; }; std::ostream& operator<<(std::ostream& os, const Bool& x) { return os << (x.value ? "true" : "false"); } template <typename T1> bool PredFunction1(T1 v1) { return v1 > 0; } bool PredFunction1Int(int v1) { return v1 > 0; } bool PredFunction1Bool(Bool v1) { return v1 > 0; } struct PredFunctor1 { template <typename T1> bool operator()(const T1& v1) { return v1 > 0; } }; template <typename T1> testing::AssertionResult PredFormatFunction1(const char* e1, const T1& v1) { if (PredFunction1(v1)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " is expected to be positive, but evaluates to " << v1 << "."; } struct PredFormatFunctor1 { template <typename T1> testing::AssertionResult operator()(const char* e1, const T1& v1) const { return PredFormatFunction1(e1, v1); } }; class Predicate1Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; }; bool Predicate1Test::expected_to_finish_; bool Predicate1Test::finished_; int Predicate1Test::n1_; typedef Predicate1Test EXPECT_PRED_FORMAT1Test; typedef Predicate1Test ASSERT_PRED_FORMAT1Test; typedef Predicate1Test EXPECT_PRED1Test; typedef Predicate1Test ASSERT_PRED1Test; TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeSuccess) { EXPECT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeSuccess) { EXPECT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunction1Int, n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED1Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunction1Bool, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED1Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED1(PredFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED1(PredFunction1Int, ++n1_); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeSuccess) { ASSERT_PRED1(PredFunction1Bool, Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED1(PredFunctor1(), ++n1_); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) { ASSERT_PRED1(PredFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunction1Int, n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunction1Bool, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED1(PredFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunction1, n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunction1, ++n1_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunction1, n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), n1_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++)); finished_ = true; }, ""); } template <typename T1, typename T2> bool PredFunction2(T1 v1, T2 v2) { return v1 + v2 > 0; } bool PredFunction2Int(int v1, int v2) { return v1 + v2 > 0; } bool PredFunction2Bool(Bool v1, Bool v2) { return v1 + v2 > 0; } struct PredFunctor2 { template <typename T1, typename T2> bool operator()(const T1& v1, const T2& v2) { return v1 + v2 > 0; } }; template <typename T1, typename T2> testing::AssertionResult PredFormatFunction2(const char* e1, const char* e2, const T1& v1, const T2& v2) { if (PredFunction2(v1, v2)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " + " << e2 << " is expected to be positive, but evaluates to " << v1 + v2 << "."; } struct PredFormatFunctor2 { template <typename T1, typename T2> testing::AssertionResult operator()(const char* e1, const char* e2, const T1& v1, const T2& v2) const { return PredFormatFunction2(e1, e2, v1, v2); } }; class Predicate2Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; static int n2_; }; bool Predicate2Test::expected_to_finish_; bool Predicate2Test::finished_; int Predicate2Test::n1_; int Predicate2Test::n2_; typedef Predicate2Test EXPECT_PRED_FORMAT2Test; typedef Predicate2Test ASSERT_PRED_FORMAT2Test; typedef Predicate2Test EXPECT_PRED2Test; typedef Predicate2Test ASSERT_PRED2Test; TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeSuccess) { EXPECT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeSuccess) { EXPECT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunction2Int, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED2Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED2Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED2(PredFunction2Int, ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeSuccess) { ASSERT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED2(PredFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) { ASSERT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunction2Int, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++)); finished_ = true; }, ""); } template <typename T1, typename T2, typename T3> bool PredFunction3(T1 v1, T2 v2, T3 v3) { return v1 + v2 + v3 > 0; } bool PredFunction3Int(int v1, int v2, int v3) { return v1 + v2 + v3 > 0; } bool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { return v1 + v2 + v3 > 0; } struct PredFunctor3 { template <typename T1, typename T2, typename T3> bool operator()(const T1& v1, const T2& v2, const T3& v3) { return v1 + v2 + v3 > 0; } }; template <typename T1, typename T2, typename T3> testing::AssertionResult PredFormatFunction3(const char* e1, const char* e2, const char* e3, const T1& v1, const T2& v2, const T3& v3) { if (PredFunction3(v1, v2, v3)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " + " << e2 << " + " << e3 << " is expected to be positive, but evaluates to " << v1 + v2 + v3 << "."; } struct PredFormatFunctor3 { template <typename T1, typename T2, typename T3> testing::AssertionResult operator()(const char* e1, const char* e2, const char* e3, const T1& v1, const T2& v2, const T3& v3) const { return PredFormatFunction3(e1, e2, e3, v1, v2, v3); } }; class Predicate3Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = n3_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " "exactly once."; EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; static int n2_; static int n3_; }; bool Predicate3Test::expected_to_finish_; bool Predicate3Test::finished_; int Predicate3Test::n1_; int Predicate3Test::n2_; int Predicate3Test::n3_; typedef Predicate3Test EXPECT_PRED_FORMAT3Test; typedef Predicate3Test ASSERT_PRED_FORMAT3Test; typedef Predicate3Test EXPECT_PRED3Test; typedef Predicate3Test ASSERT_PRED3Test; TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeSuccess) { EXPECT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeSuccess) { EXPECT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED3Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED3Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeSuccess) { ASSERT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) { ASSERT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED3Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED3Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) { ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) { ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++)); finished_ = true; }, ""); } template <typename T1, typename T2, typename T3, typename T4> bool PredFunction4(T1 v1, T2 v2, T3 v3, T4 v4) { return v1 + v2 + v3 + v4 > 0; } bool PredFunction4Int(int v1, int v2, int v3, int v4) { return v1 + v2 + v3 + v4 > 0; } bool PredFunction4Bool(Bool v1, Bool v2, Bool v3, Bool v4) { return v1 + v2 + v3 + v4 > 0; } struct PredFunctor4 { template <typename T1, typename T2, typename T3, typename T4> bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4) { return v1 + v2 + v3 + v4 > 0; } }; template <typename T1, typename T2, typename T3, typename T4> testing::AssertionResult PredFormatFunction4(const char* e1, const char* e2, const char* e3, const char* e4, const T1& v1, const T2& v2, const T3& v3, const T4& v4) { if (PredFunction4(v1, v2, v3, v4)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " is expected to be positive, but evaluates to " << v1 + v2 + v3 + v4 << "."; } struct PredFormatFunctor4 { template <typename T1, typename T2, typename T3, typename T4> testing::AssertionResult operator()(const char* e1, const char* e2, const char* e3, const char* e4, const T1& v1, const T2& v2, const T3& v3, const T4& v4) const { return PredFormatFunction4(e1, e2, e3, e4, v1, v2, v3, v4); } }; class Predicate4Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = n3_ = n4_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " "exactly once."; EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 " "exactly once."; EXPECT_EQ(1, n4_) << "The predicate assertion didn't evaluate argument 5 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; static int n2_; static int n3_; static int n4_; }; bool Predicate4Test::expected_to_finish_; bool Predicate4Test::finished_; int Predicate4Test::n1_; int Predicate4Test::n2_; int Predicate4Test::n3_; int Predicate4Test::n4_; typedef Predicate4Test EXPECT_PRED_FORMAT4Test; typedef Predicate4Test ASSERT_PRED_FORMAT4Test; typedef Predicate4Test EXPECT_PRED4Test; typedef Predicate4Test ASSERT_PRED4Test; TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) { EXPECT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) { EXPECT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED4Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED4Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) { ASSERT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) { ASSERT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED4Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED4Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) { EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) { ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) { ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++)); finished_ = true; }, ""); } template <typename T1, typename T2, typename T3, typename T4, typename T5> bool PredFunction5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return v1 + v2 + v3 + v4 + v5 > 0; } bool PredFunction5Int(int v1, int v2, int v3, int v4, int v5) { return v1 + v2 + v3 + v4 + v5 > 0; } bool PredFunction5Bool(Bool v1, Bool v2, Bool v3, Bool v4, Bool v5) { return v1 + v2 + v3 + v4 + v5 > 0; } struct PredFunctor5 { template <typename T1, typename T2, typename T3, typename T4, typename T5> bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { return v1 + v2 + v3 + v4 + v5 > 0; } }; template <typename T1, typename T2, typename T3, typename T4, typename T5> testing::AssertionResult PredFormatFunction5(const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { if (PredFunction5(v1, v2, v3, v4, v5)) return testing::AssertionSuccess(); return testing::AssertionFailure() << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 << " is expected to be positive, but evaluates to " << v1 + v2 + v3 + v4 + v5 << "."; } struct PredFormatFunctor5 { template <typename T1, typename T2, typename T3, typename T4, typename T5> testing::AssertionResult operator()(const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) const { return PredFormatFunction5(e1, e2, e3, e4, e5, v1, v2, v3, v4, v5); } }; class Predicate5Test : public testing::Test { protected: void SetUp() override { expected_to_finish_ = true; finished_ = false; n1_ = n2_ = n3_ = n4_ = n5_ = 0; } void TearDown() override { EXPECT_EQ(1, n1_) << "The predicate assertion didn't evaluate argument 2 " "exactly once."; EXPECT_EQ(1, n2_) << "The predicate assertion didn't evaluate argument 3 " "exactly once."; EXPECT_EQ(1, n3_) << "The predicate assertion didn't evaluate argument 4 " "exactly once."; EXPECT_EQ(1, n4_) << "The predicate assertion didn't evaluate argument 5 " "exactly once."; EXPECT_EQ(1, n5_) << "The predicate assertion didn't evaluate argument 6 " "exactly once."; if (expected_to_finish_ && !finished_) { FAIL() << "The predicate assertion unexpectedly aborted the test."; } else if (!expected_to_finish_ && finished_) { FAIL() << "The failed predicate assertion didn't abort the test " "as expected."; } } static bool expected_to_finish_; static bool finished_; static int n1_; static int n2_; static int n3_; static int n4_; static int n5_; }; bool Predicate5Test::expected_to_finish_; bool Predicate5Test::finished_; int Predicate5Test::n1_; int Predicate5Test::n2_; int Predicate5Test::n3_; int Predicate5Test::n4_; int Predicate5Test::n5_; typedef Predicate5Test EXPECT_PRED_FORMAT5Test; typedef Predicate5Test ASSERT_PRED_FORMAT5Test; typedef Predicate5Test EXPECT_PRED5Test; typedef Predicate5Test ASSERT_PRED5Test; TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeSuccess) { EXPECT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeSuccess) { EXPECT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED5Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED5Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeSuccess) { ASSERT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) { ASSERT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED5Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED5Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) { EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) { EXPECT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) { EXPECT_NONFATAL_FAILURE( { EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) { ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) { ASSERT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) { ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_), Bool(++n4_), Bool(++n5_)); finished_ = true; } TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++); finished_ = true; }, ""); } TEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) { expected_to_finish_ = false; EXPECT_FATAL_FAILURE( { ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++), Bool(n4_++), Bool(n5_++)); finished_ = true; }, ""); }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/include/gtest/gtest_pred_impl.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/test/gtest_pred_impl_unittest.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
a9992761-60ae-4860-b1ae-26de4e70e862
cpp
google/googletest
gtest_prod
googletest/include/gtest/gtest_prod.h
googletest/test/gtest_prod_test.cc
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_ #define FRIEND_TEST(test_case_name, test_name) \ friend class test_case_name##_##test_name##_Test #endif
#include "production.h" #include "gtest/gtest.h" TEST(PrivateCodeTest, CanAccessPrivateMembers) { PrivateCode a; EXPECT_EQ(0, a.x_); a.set_x(1); EXPECT_EQ(1, a.x_); } typedef testing::Test PrivateCodeFixtureTest; TEST_F(PrivateCodeFixtureTest, CanAccessPrivateMembers) { PrivateCode a; EXPECT_EQ(0, a.x_); a.set_x(2); EXPECT_EQ(2, a.x_); }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/include/gtest/gtest_prod.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googletest/test/gtest_prod_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
d346eaeb-6eef-4e54-a536-922f731fe6d3
cpp
google/googletest
gmock-more-actions
googlemock/include/gmock/gmock-more-actions.h
googlemock/test/gmock-more-actions_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #include <memory> #include <utility> #include "gmock/gmock-actions.h" #include "gmock/internal/gmock-port.h" #include "gmock/internal/custom/gmock-generated-actions.h" #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ kind0 name0, kind1 name1 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2) \ kind0 name0, kind1 name1, kind2 name2 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3 #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, \ kind4, name4, kind5, name5) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6 #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6, kind7 name7 #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6, kind7 name7, kind8 name8 #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9 #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \ name0, name1 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2) \ name0, name1, name2 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3) \ name0, name1, name2, name3 #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \ name0, name1, name2, name3, name4 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, \ kind4, name4, kind5, name5) \ name0, name1, name2, name3, name4, name5 #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6) \ name0, name1, name2, name3, name4, name5, name6 #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7) \ name0, name1, name2, name3, name4, name5, name6, name7 #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ name0, name1, name2, name3, name4, name5, name6, name7, name8 #define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS( \ kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \ kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \ name0, name1, name2, name3, name4, name5, name6, name7, name8, name9 #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ , typename p0##_type, typename p1##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ , typename p0##_type, typename p1##_type, typename p2##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8, p9) \ , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() () #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \ (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \ (p0##_type gmock_p0, p1##_type gmock_p1) \ : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)) #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)) #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)) #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)) #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)) #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)) #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)), \ p8(::std::move(gmock_p8)) #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p9##_type gmock_p9) \ : p0(::std::move(gmock_p0)), \ p1(::std::move(gmock_p1)), \ p2(::std::move(gmock_p2)), \ p3(::std::move(gmock_p3)), \ p4(::std::move(gmock_p4)), \ p5(::std::move(gmock_p5)), \ p6(::std::move(gmock_p6)), \ p7(::std::move(gmock_p7)), \ p8(::std::move(gmock_p8)), \ p9(::std::move(gmock_p9)) #define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \ {} #define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default; #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \ p0##_type p0; \ p1##_type p1; #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; #define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; #define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; \ p7##_type p7; #define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; \ p7##_type p7; \ p8##_type p8; #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ p0##_type p0; \ p1##_type p1; \ p2##_type p2; \ p3##_type p3; \ p4##_type p4; \ p5##_type p5; \ p6##_type p6; \ p7##_type p7; \ p8##_type p8; \ p9##_type p9; #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0 #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ p0, p1, p2, p3, p4 #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ p0, p1, p2, p3, p4, p5 #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ p0, p1, p2, p3, p4, p5, p6 #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ p0, p1, p2, p3, p4, p5, p6, p7 #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ p0, p1, p2, p3, p4, p5, p6, p7, p8 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \ , p0##_type, p1##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ , p0##_type, p1##_type, p2##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ , p0##_type, p1##_type, p2##_type, p3##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ p6##_type, p7##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ p6##_type, p7##_type, p8##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8, p9) \ , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ p6##_type, p7##_type, p8##_type, p9##_type #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \ p0##_type p0, p1##_type p1 #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \ p0##_type p0, p1##_type p1, p2##_type p2 #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3 #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5 #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6 #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6, p7##_type p7 #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \ p8) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9 #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P #define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2 #define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3 #define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4 #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7) \ P8 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8) \ P9 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) \ P10 #define GMOCK_ACTION_CLASS_(name, value_params) \ GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) #define ACTION_TEMPLATE(name, template_params, value_params) \ template <GMOCK_INTERNAL_DECL_##template_params \ GMOCK_INTERNAL_DECL_TYPE_##value_params> \ class GMOCK_ACTION_CLASS_(name, value_params) { \ public: \ explicit GMOCK_ACTION_CLASS_(name, value_params)( \ GMOCK_INTERNAL_DECL_##value_params) \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ = default; \ , \ : impl_(std::make_shared<gmock_Impl>( \ GMOCK_INTERNAL_LIST_##value_params)){}) \ GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \ name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_ \ ##value_params \ GMOCK_ACTION_CLASS_(name, value_params)(GMOCK_ACTION_CLASS_( \ name, value_params) &&) noexcept GMOCK_INTERNAL_DEFN_COPY_ \ ##value_params template <typename F> \ operator ::testing::Action<F>() const { \ return GMOCK_PP_IF( \ GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), \ (::testing::internal::MakeAction<F, gmock_Impl>()), \ (::testing::internal::MakeAction<F>(impl_))); \ } \ \ private: \ class gmock_Impl { \ public: \ explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \ template <typename function_type, typename return_type, \ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ GMOCK_INTERNAL_DEFN_##value_params \ }; \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), , \ std::shared_ptr<const gmock_Impl> impl_;) \ }; \ template <GMOCK_INTERNAL_DECL_##template_params \ GMOCK_INTERNAL_DECL_TYPE_##value_params> \ GMOCK_ACTION_CLASS_( \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ GMOCK_INTERNAL_LIST_TYPE_##value_params> \ name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_; \ template <GMOCK_INTERNAL_DECL_##template_params \ GMOCK_INTERNAL_DECL_TYPE_##value_params> \ inline GMOCK_ACTION_CLASS_( \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ GMOCK_INTERNAL_LIST_TYPE_##value_params> \ name(GMOCK_INTERNAL_DECL_##value_params) { \ return GMOCK_ACTION_CLASS_( \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ GMOCK_INTERNAL_LIST_TYPE_##value_params>( \ GMOCK_INTERNAL_LIST_##value_params); \ } \ template <GMOCK_INTERNAL_DECL_##template_params \ GMOCK_INTERNAL_DECL_TYPE_##value_params> \ template <typename function_type, typename return_type, typename args_type, \ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ return_type GMOCK_ACTION_CLASS_( \ name, value_params)<GMOCK_INTERNAL_LIST_##template_params \ GMOCK_INTERNAL_LIST_TYPE_##value_params>:: \ gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \ const namespace testing { GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) namespace internal { template <typename F, typename... Args> auto InvokeArgument(F &&f, Args... args) -> decltype(std::forward<F>(f)(args...)) { return std::forward<F>(f)(args...); } template <std::size_t index, typename... Params> struct InvokeArgumentAction { template <typename... Args, typename = typename std::enable_if<(index < sizeof...(Args))>::type> auto operator()(Args &&...args) const -> decltype(internal::InvokeArgument( std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)), std::declval<const Params &>()...)) { internal::FlatTuple<Args &&...> args_tuple(FlatTupleConstructTag{}, std::forward<Args>(args)...); return params.Apply([&](const Params &...unpacked_params) { auto &&callable = std::move(args_tuple.template Get<index>()); return internal::InvokeArgument( std::forward<decltype(callable)>(callable), unpacked_params...); }); } internal::FlatTuple<Params...> params; }; } template <std::size_t index, typename... Params> internal::InvokeArgumentAction<index, typename std::decay<Params>::type...> InvokeArgument(Params &&...params) { return {internal::FlatTuple<typename std::decay<Params>::type...>( internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)}; } GTEST_DISABLE_MSC_WARNINGS_POP_() } #endif
#include "gmock/gmock-more-actions.h" #include <algorithm> #include <functional> #include <iterator> #include <memory> #include <sstream> #include <string> #include <tuple> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4577) namespace testing { namespace gmock_more_actions_test { using ::std::plus; using ::std::string; using testing::Action; using testing::DeleteArg; using testing::Invoke; using testing::ReturnArg; using testing::ReturnPointee; using testing::SaveArg; using testing::SaveArgPointee; using testing::SetArgReferee; using testing::Unused; using testing::WithArg; using testing::WithoutArgs; inline short Short(short n) { return n; } inline char Char(char ch) { return ch; } int Nullary() { return 1; } bool g_done = false; bool Unary(int x) { return x < 0; } bool ByConstRef(const std::string& s) { return s == "Hi"; } const double g_double = 0; bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } }; struct UnaryMoveOnlyFunctor : UnaryFunctor { UnaryMoveOnlyFunctor() = default; UnaryMoveOnlyFunctor(const UnaryMoveOnlyFunctor&) = delete; UnaryMoveOnlyFunctor(UnaryMoveOnlyFunctor&&) = default; }; struct OneShotUnaryFunctor { int operator()(bool x) && { return x ? 1 : -1; } }; const char* Binary(const char* input, short n) { return input + n; } int Ternary(int x, char y, short z) { return x + y + z; } int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } struct SumOf5Functor { int operator()(int a, int b, int c, int d, int e) { return a + b + c + d + e; } }; int SumOf6(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } struct SumOf6Functor { int operator()(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } }; std::string Concat7(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } std::string Concat8(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } std::string Concat9(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } std::string Concat10(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9, const char* s10) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } class Foo { public: Foo() : value_(123) {} int Nullary() const { return value_; } short Unary(long x) { return static_cast<short>(value_ + x); } std::string Binary(const std::string& str, char c) const { return str + c; } int Ternary(int x, bool y, char z) { return value_ + x + y * z; } int SumOf4(int a, int b, int c, int d) const { return a + b + c + d + value_; } int SumOfLast2(Unused, Unused, int a, int b) const { return a + b; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } int SumOf6(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } std::string Concat7(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } std::string Concat8(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } std::string Concat9(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } std::string Concat10(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9, const char* s10) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } private: int value_; }; TEST(InvokeTest, Nullary) { Action<int()> a = Invoke(Nullary); EXPECT_EQ(1, a.Perform(std::make_tuple())); } TEST(InvokeTest, Unary) { Action<bool(int)> a = Invoke(Unary); EXPECT_FALSE(a.Perform(std::make_tuple(1))); EXPECT_TRUE(a.Perform(std::make_tuple(-1))); } TEST(InvokeTest, Binary) { Action<const char*(const char*, short)> a = Invoke(Binary); const char* p = "Hello"; EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2)))); } TEST(InvokeTest, Ternary) { Action<int(int, char, short)> a = Invoke(Ternary); EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3)))); } TEST(InvokeTest, FunctionThatTakes4Arguments) { Action<int(int, int, int, int)> a = Invoke(SumOf4); EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4))); } TEST(InvokeTest, FunctionThatTakes5Arguments) { Action<int(int, int, int, int, int)> a = Invoke(SumOf5); EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } TEST(InvokeTest, FunctionThatTakes6Arguments) { Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6); EXPECT_EQ(123456, a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } inline const char* CharPtr(const char* s) { return s; } TEST(InvokeTest, FunctionThatTakes7Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat7); EXPECT_EQ("1234567", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7")))); } TEST(InvokeTest, FunctionThatTakes8Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat8); EXPECT_EQ("12345678", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8")))); } TEST(InvokeTest, FunctionThatTakes9Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat9); EXPECT_EQ("123456789", a.Perform(std::make_tuple( CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9")))); } TEST(InvokeTest, FunctionThatTakes10Arguments) { Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(Concat10); EXPECT_EQ("1234567890", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9"), CharPtr("0")))); } TEST(InvokeTest, FunctionWithUnusedParameters) { Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2); std::tuple<int, int, double, std::string> dummy = std::make_tuple(10, 2, 5.6, std::string("hi")); EXPECT_EQ(12, a1.Perform(dummy)); Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2); EXPECT_EQ( 23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr)))); } TEST(InvokeTest, MethodWithUnusedParameters) { Foo foo; Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2); EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); } TEST(InvokeTest, Functor) { Action<long(long, int)> a = Invoke(plus<long>()); EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2))); } TEST(InvokeTest, FunctionWithCompatibleType) { Action<long(int, short, char, bool)> a = Invoke(SumOf4); EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } TEST(InvokeMethodTest, Nullary) { Foo foo; Action<int()> a = Invoke(&foo, &Foo::Nullary); EXPECT_EQ(123, a.Perform(std::make_tuple())); } TEST(InvokeMethodTest, Unary) { Foo foo; Action<short(long)> a = Invoke(&foo, &Foo::Unary); EXPECT_EQ(4123, a.Perform(std::make_tuple(4000))); } TEST(InvokeMethodTest, Binary) { Foo foo; Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary); std::string s("Hell"); std::tuple<std::string, char> dummy = std::make_tuple(s, 'o'); EXPECT_EQ("Hello", a.Perform(dummy)); } TEST(InvokeMethodTest, Ternary) { Foo foo; Action<int(int, bool, char)> a = Invoke(&foo, &Foo::Ternary); EXPECT_EQ(1124, a.Perform(std::make_tuple(1000, true, Char(1)))); } TEST(InvokeMethodTest, MethodThatTakes4Arguments) { Foo foo; Action<int(int, int, int, int)> a = Invoke(&foo, &Foo::SumOf4); EXPECT_EQ(1357, a.Perform(std::make_tuple(1000, 200, 30, 4))); } TEST(InvokeMethodTest, MethodThatTakes5Arguments) { Foo foo; Action<int(int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf5); EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); } TEST(InvokeMethodTest, MethodThatTakes6Arguments) { Foo foo; Action<int(int, int, int, int, int, int)> a = Invoke(&foo, &Foo::SumOf6); EXPECT_EQ(123456, a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); } TEST(InvokeMethodTest, MethodThatTakes7Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat7); EXPECT_EQ("1234567", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7")))); } TEST(InvokeMethodTest, MethodThatTakes8Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat8); EXPECT_EQ("12345678", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8")))); } TEST(InvokeMethodTest, MethodThatTakes9Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat9); EXPECT_EQ("123456789", a.Perform(std::make_tuple( CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9")))); } TEST(InvokeMethodTest, MethodThatTakes10Arguments) { Foo foo; Action<std::string(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*)> a = Invoke(&foo, &Foo::Concat10); EXPECT_EQ("1234567890", a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4"), CharPtr("5"), CharPtr("6"), CharPtr("7"), CharPtr("8"), CharPtr("9"), CharPtr("0")))); } TEST(InvokeMethodTest, MethodWithCompatibleType) { Foo foo; Action<long(int, short, char, bool)> a = Invoke(&foo, &Foo::SumOf4); EXPECT_EQ(4444, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); } TEST(WithoutArgsTest, NoArg) { Action<int(int n)> a = WithoutArgs(Invoke(Nullary)); EXPECT_EQ(1, a.Perform(std::make_tuple(2))); } TEST(WithArgTest, OneArg) { Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary)); EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1))); EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1))); } TEST(ReturnArgActionTest, WorksForOneArgIntArg0) { const Action<int(int)> a = ReturnArg<0>(); EXPECT_EQ(5, a.Perform(std::make_tuple(5))); } TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) { const Action<bool(bool, bool, bool)> a = ReturnArg<0>(); EXPECT_TRUE(a.Perform(std::make_tuple(true, false, false))); } TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) { const Action<std::string(int, int, std::string, int)> a = ReturnArg<2>(); EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8))); } TEST(ReturnArgActionTest, WorksForNonConstRefArg0) { const Action<std::string&(std::string&)> a = ReturnArg<0>(); std::string s = "12345"; EXPECT_EQ(&s, &a.Perform(std::forward_as_tuple(s))); } TEST(SaveArgActionTest, WorksForSameType) { int result = 0; const Action<void(int n)> a1 = SaveArg<0>(&result); a1.Perform(std::make_tuple(5)); EXPECT_EQ(5, result); } TEST(SaveArgActionTest, WorksForCompatibleType) { int result = 0; const Action<void(bool, char)> a1 = SaveArg<1>(&result); a1.Perform(std::make_tuple(true, 'a')); EXPECT_EQ('a', result); } TEST(SaveArgPointeeActionTest, WorksForSameType) { int result = 0; const int value = 5; const Action<void(const int*)> a1 = SaveArgPointee<0>(&result); a1.Perform(std::make_tuple(&value)); EXPECT_EQ(5, result); } TEST(SaveArgPointeeActionTest, WorksForCompatibleType) { int result = 0; char value = 'a'; const Action<void(bool, char*)> a1 = SaveArgPointee<1>(&result); a1.Perform(std::make_tuple(true, &value)); EXPECT_EQ('a', result); } TEST(SetArgRefereeActionTest, WorksForSameType) { int value = 0; const Action<void(int&)> a1 = SetArgReferee<0>(1); a1.Perform(std::tuple<int&>(value)); EXPECT_EQ(1, value); } TEST(SetArgRefereeActionTest, WorksForCompatibleType) { int value = 0; const Action<void(int, int&)> a1 = SetArgReferee<1>('a'); a1.Perform(std::tuple<int, int&>(0, value)); EXPECT_EQ('a', value); } TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { int value = 0; const Action<void(bool, int, int&, const char*)> a1 = SetArgReferee<2>('a'); a1.Perform(std::tuple<bool, int, int&, const char*>(true, 0, value, "hi")); EXPECT_EQ('a', value); } class DeletionTester { public: explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) { *is_deleted_ = false; } ~DeletionTester() { *is_deleted_ = true; } private: bool* is_deleted_; }; TEST(DeleteArgActionTest, OneArg) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); const Action<void(DeletionTester*)> a1 = DeleteArg<0>(); EXPECT_FALSE(is_deleted); a1.Perform(std::make_tuple(t)); EXPECT_TRUE(is_deleted); } TEST(DeleteArgActionTest, TenArgs) { bool is_deleted = false; DeletionTester* t = new DeletionTester(&is_deleted); const Action<void(bool, int, int, const char*, bool, int, int, int, int, DeletionTester*)> a1 = DeleteArg<9>(); EXPECT_FALSE(is_deleted); a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); EXPECT_TRUE(is_deleted); } #if GTEST_HAS_EXCEPTIONS TEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) { const Action<void(int n)> a = Throw('a'); EXPECT_THROW(a.Perform(std::make_tuple(0)), char); } class MyException {}; TEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) { const Action<double(char ch)> a = Throw(MyException()); EXPECT_THROW(a.Perform(std::make_tuple('0')), MyException); } TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) { const Action<double()> a = Throw(MyException()); EXPECT_THROW(a.Perform(std::make_tuple()), MyException); } class Object { public: virtual ~Object() {} virtual void Func() {} }; class MockObject : public Object { public: ~MockObject() override {} MOCK_METHOD(void, Func, (), (override)); }; TEST(ThrowActionTest, Times0) { EXPECT_NONFATAL_FAILURE( [] { try { MockObject m; ON_CALL(m, Func()).WillByDefault([] { throw "something"; }); EXPECT_CALL(m, Func()).Times(0); m.Func(); } catch (...) { } }(), ""); } #endif TEST(SetArrayArgumentTest, SetsTheNthArray) { using MyFunction = void(bool, int*, char*); int numbers[] = {1, 2, 3}; Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3); int n[4] = {}; int* pn = n; char ch[4] = {}; char* pch = ch; a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(1, n[0]); EXPECT_EQ(2, n[1]); EXPECT_EQ(3, n[2]); EXPECT_EQ(0, n[3]); EXPECT_EQ('\0', ch[0]); EXPECT_EQ('\0', ch[1]); EXPECT_EQ('\0', ch[2]); EXPECT_EQ('\0', ch[3]); std::string letters = "abc"; a = SetArrayArgument<2>(letters.begin(), letters.end()); std::fill_n(n, 4, 0); std::fill_n(ch, 4, '\0'); a.Perform(std::make_tuple(true, pn, pch)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); EXPECT_EQ(0, n[3]); EXPECT_EQ('a', ch[0]); EXPECT_EQ('b', ch[1]); EXPECT_EQ('c', ch[2]); EXPECT_EQ('\0', ch[3]); } TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { using MyFunction = void(bool, int*); int numbers[] = {1, 2, 3}; Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers); int n[4] = {}; int* pn = n; a.Perform(std::make_tuple(true, pn)); EXPECT_EQ(0, n[0]); EXPECT_EQ(0, n[1]); EXPECT_EQ(0, n[2]); EXPECT_EQ(0, n[3]); } TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { using MyFunction = void(bool, int*); char chars[] = {97, 98, 99}; Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3); int codes[4] = {111, 222, 333, 444}; int* pcodes = codes; a.Perform(std::make_tuple(true, pcodes)); EXPECT_EQ(97, codes[0]); EXPECT_EQ(98, codes[1]); EXPECT_EQ(99, codes[2]); EXPECT_EQ(444, codes[3]); } TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) { using MyFunction = void(bool, std::back_insert_iterator<std::string>); std::string letters = "abc"; Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end()); std::string s; a.Perform(std::make_tuple(true, std::back_inserter(s))); EXPECT_EQ(letters, s); } TEST(ReturnPointeeTest, Works) { int n = 42; const Action<int()> a = ReturnPointee(&n); EXPECT_EQ(42, a.Perform(std::make_tuple())); n = 43; EXPECT_EQ(43, a.Perform(std::make_tuple())); } TEST(InvokeArgumentTest, Function0) { Action<int(int, int (*)())> a = InvokeArgument<1>(); EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary))); } TEST(InvokeArgumentTest, Functor1) { Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor()))); } TEST(InvokeArgumentTest, Functor1MoveOnly) { Action<int(UnaryMoveOnlyFunctor)> a = InvokeArgument<0>(true); EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryMoveOnlyFunctor()))); } TEST(InvokeArgumentTest, OneShotFunctor1) { Action<int(OneShotUnaryFunctor)> a = InvokeArgument<0>(true); EXPECT_EQ(1, a.Perform(std::make_tuple(OneShotUnaryFunctor()))); } TEST(InvokeArgumentTest, Function5) { Action<int(int (*)(int, int, int, int, int))> a = InvokeArgument<0>(10000, 2000, 300, 40, 5); EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5))); } TEST(InvokeArgumentTest, Functor5) { Action<int(SumOf5Functor)> a = InvokeArgument<0>(10000, 2000, 300, 40, 5); EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor()))); } TEST(InvokeArgumentTest, Function6) { Action<int(int (*)(int, int, int, int, int, int))> a = InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6))); } TEST(InvokeArgumentTest, Functor6) { Action<int(SumOf6Functor)> a = InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor()))); } TEST(InvokeArgumentTest, Function7) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7"); EXPECT_EQ("1234567", a.Perform(std::make_tuple(&Concat7))); } TEST(InvokeArgumentTest, Function8) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8"); EXPECT_EQ("12345678", a.Perform(std::make_tuple(&Concat8))); } TEST(InvokeArgumentTest, Function9) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9"); EXPECT_EQ("123456789", a.Perform(std::make_tuple(&Concat9))); } TEST(InvokeArgumentTest, Function10) { Action<std::string(std::string(*)( const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); EXPECT_EQ("1234567890", a.Perform(std::make_tuple(&Concat10))); } TEST(InvokeArgumentTest, ByPointerFunction) { Action<const char*(const char* (*)(const char* input, short n))> a = InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1)); EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } TEST(InvokeArgumentTest, FunctionWithCStringLiteral) { Action<const char*(const char* (*)(const char* input, short n))> a = InvokeArgument<0>("Hi", Short(1)); EXPECT_STREQ("i", a.Perform(std::make_tuple(&Binary))); } TEST(InvokeArgumentTest, ByConstReferenceFunction) { Action<bool(bool (*function)(const std::string& s))> a = InvokeArgument<0>(std::string("Hi")); EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef))); } TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) { Action<bool(bool (*)(const double& x))> a = InvokeArgument<0>(ByRef(g_double)); EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); double x = 0; a = InvokeArgument<0>(ByRef(x)); EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble))); } TEST(InvokeArgumentTest, MoveOnlyType) { struct Marker {}; struct { MOCK_METHOD(bool, MockMethod, (std::unique_ptr<Marker>, std::function<int()>), ()); } mock; ON_CALL(mock, MockMethod(_, _)).WillByDefault(InvokeArgument<1>()); ON_CALL(mock, MockMethod(_, _)) .WillByDefault(WithArg<1>(InvokeArgument<0>())); } TEST(DoAllTest, TwoActions) { int n = 0; Action<int(int*)> a = DoAll(SetArgPointee<0>(1), Return(2)); EXPECT_EQ(2, a.Perform(std::make_tuple(&n))); EXPECT_EQ(1, n); } TEST(DoAllTest, ThreeActions) { int m = 0, n = 0; Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), Return(3)); EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); } TEST(DoAllTest, FourActions) { int m = 0, n = 0; char ch = '\0'; Action<int(int*, int*, char*)> a = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), Return(3)); EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', ch); } TEST(DoAllTest, FiveActions) { int m = 0, n = 0; char a = '\0', b = '\0'; Action<int(int*, int*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); } TEST(DoAllTest, SixActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0'; Action<int(int*, int*, char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); } TEST(DoAllTest, SevenActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0'; Action<int(int*, int*, char*, char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); } TEST(DoAllTest, EightActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0'; Action<int(int*, int*, char*, char*, char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); } TEST(DoAllTest, NineActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0'; Action<int(int*, int*, char*, char*, char*, char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3)); EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); EXPECT_EQ('f', f); } TEST(DoAllTest, TenActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0'; char e = '\0', f = '\0', g = '\0'; Action<int(int*, int*, char*, char*, char*, char*, char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3)); EXPECT_EQ( 3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); EXPECT_EQ('f', f); EXPECT_EQ('g', g); } TEST(DoAllTest, NoArgs) { bool ran_first = false; Action<bool()> a = DoAll([&] { ran_first = true; }, [&] { return ran_first; }); EXPECT_TRUE(a.Perform({})); } TEST(DoAllTest, MoveOnlyArgs) { bool ran_first = false; Action<int(std::unique_ptr<int>)> a = DoAll(InvokeWithoutArgs([&] { ran_first = true; }), [](std::unique_ptr<int> p) { return *p; }); EXPECT_EQ(7, a.Perform(std::make_tuple(std::unique_ptr<int>(new int(7))))); EXPECT_TRUE(ran_first); } TEST(DoAllTest, ImplicitlyConvertsActionArguments) { bool ran_first = false; Action<void(std::vector<int>)> first = [&] { ran_first = true; }; Action<int(std::vector<int>)> a = DoAll(first, [](std::vector<int> arg) { return arg.front(); }); EXPECT_EQ(7, a.Perform(std::make_tuple(std::vector<int>{7}))); EXPECT_TRUE(ran_first); } GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503) ACTION(Return5) { return 5; } TEST(ActionMacroTest, WorksWhenNotReferencingArguments) { Action<double()> a1 = Return5(); EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple())); Action<int(double, bool)> a2 = Return5(); EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true))); } ACTION(IncrementArg1) { (*arg1)++; } TEST(ActionMacroTest, WorksWhenReturningVoid) { Action<void(int, int*)> a1 = IncrementArg1(); int n = 0; a1.Perform(std::make_tuple(5, &n)); EXPECT_EQ(1, n); } ACTION(IncrementArg2) { StaticAssertTypeEq<int*, arg2_type>(); arg2_type temp = arg2; (*temp)++; } TEST(ActionMacroTest, CanReferenceArgumentType) { Action<void(int, bool, int*)> a1 = IncrementArg2(); int n = 0; a1.Perform(std::make_tuple(5, false, &n)); EXPECT_EQ(1, n); } ACTION(Sum2) { StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>(); args_type args_copy = args; return std::get<0>(args_copy) + std::get<1>(args_copy); } TEST(ActionMacroTest, CanReferenceArgumentTuple) { Action<int(int, char, int*)> a1 = Sum2(); int dummy = 0; EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy))); } namespace { int Dummy(bool flag) { return flag ? 1 : 0; } } ACTION(InvokeDummy) { StaticAssertTypeEq<int(bool), function_type>(); function_type* fp = &Dummy; return (*fp)(true); } TEST(ActionMacroTest, CanReferenceMockFunctionType) { Action<int(bool)> a1 = InvokeDummy(); EXPECT_EQ(1, a1.Perform(std::make_tuple(true))); EXPECT_EQ(1, a1.Perform(std::make_tuple(false))); } ACTION(InvokeDummy2) { StaticAssertTypeEq<int, return_type>(); return_type result = Dummy(true); return result; } TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) { Action<int(bool)> a1 = InvokeDummy2(); EXPECT_EQ(1, a1.Perform(std::make_tuple(true))); EXPECT_EQ(1, a1.Perform(std::make_tuple(false))); } ACTION(ReturnAddrOfConstBoolReferenceArg) { StaticAssertTypeEq<const bool&, arg1_type>(); return &arg1; } TEST(ActionMacroTest, WorksForConstReferenceArg) { Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg(); const bool b = false; EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b))); } ACTION(ReturnAddrOfIntReferenceArg) { StaticAssertTypeEq<int&, arg0_type>(); return &arg0; } TEST(ActionMacroTest, WorksForNonConstReferenceArg) { Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg(); int n = 0; EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1))); } namespace action_test { ACTION(Sum) { return arg0 + arg1; } } TEST(ActionMacroTest, WorksInNamespace) { Action<int(int, int)> a1 = action_test::Sum(); EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2))); } ACTION(PlusTwo) { return arg0 + 2; } TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) { Action<int(int)> a1 = PlusTwo(); EXPECT_EQ(4, a1.Perform(std::make_tuple(2))); Action<double(float, void*)> a2 = PlusTwo(); int dummy; EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy))); } ACTION_P(Plus, n) { return arg0 + n; } TEST(ActionPMacroTest, DefinesParameterizedAction) { Action<int(int m, bool t)> a1 = Plus(9); EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true))); } ACTION_P(TypedPlus, n) { arg0_type t1 = arg0; n_type t2 = n; return t1 + t2; } TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) { Action<int(char m, bool t)> a1 = TypedPlus(9); EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true))); } TEST(ActionPMacroTest, WorksInCompatibleMockFunction) { Action<std::string(const std::string& s)> a1 = Plus("tail"); const std::string re = "re"; std::tuple<const std::string> dummy = std::make_tuple(re); EXPECT_EQ("retail", a1.Perform(dummy)); } ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; } ACTION_P(OverloadedAction, default_value) { return arg0 ? arg1 : default_value; } ACTION_P2(OverloadedAction, true_value, false_value) { return arg0 ? true_value : false_value; } TEST(ActionMacroTest, CanDefineOverloadedActions) { using MyAction = Action<const char*(bool, const char*)>; const MyAction a1 = OverloadedAction(); EXPECT_STREQ("hello", a1.Perform(std::make_tuple(false, CharPtr("world")))); EXPECT_STREQ("world", a1.Perform(std::make_tuple(true, CharPtr("world")))); const MyAction a2 = OverloadedAction("hi"); EXPECT_STREQ("hi", a2.Perform(std::make_tuple(false, CharPtr("world")))); EXPECT_STREQ("world", a2.Perform(std::make_tuple(true, CharPtr("world")))); const MyAction a3 = OverloadedAction("hi", "you"); EXPECT_STREQ("hi", a3.Perform(std::make_tuple(true, CharPtr("world")))); EXPECT_STREQ("you", a3.Perform(std::make_tuple(false, CharPtr("world")))); } ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; } TEST(ActionPnMacroTest, WorksFor3Parameters) { Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4); EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true))); Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">"); const std::string re = "re"; std::tuple<const std::string> dummy = std::make_tuple(re); EXPECT_EQ("retail->", a2.Perform(dummy)); } ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; } TEST(ActionPnMacroTest, WorksFor4Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4); EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10))); } ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; } TEST(ActionPnMacroTest, WorksFor5Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10))); } ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5; } TEST(ActionPnMacroTest, WorksFor6Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10))); } ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6; } TEST(ActionPnMacroTest, WorksFor7Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10))); } ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7; } TEST(ActionPnMacroTest, WorksFor8Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, a1.Perform(std::make_tuple(10))); } ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8; } TEST(ActionPnMacroTest, WorksFor9Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, a1.Perform(std::make_tuple(10))); } ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) { arg0_type t0 = arg0; last_param_type t9 = last_param; return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9; } TEST(ActionPnMacroTest, WorksFor10Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, a1.Perform(std::make_tuple(10))); } ACTION_P2(PadArgument, prefix, suffix) { std::string prefix_str(prefix); char suffix_char = static_cast<char>(suffix); return prefix_str + arg0 + suffix_char; } TEST(ActionPnMacroTest, SimpleTypePromotion) { Action<std::string(const char*)> no_promo = PadArgument(std::string("foo"), 'r'); Action<std::string(const char*)> promo = PadArgument("foo", static_cast<int>('r')); EXPECT_EQ("foobar", no_promo.Perform(std::make_tuple(CharPtr("ba")))); EXPECT_EQ("foobar", promo.Perform(std::make_tuple(CharPtr("ba")))); } ACTION_P3(ConcatImpl, a, b, c) { std::stringstream ss; ss << a << b << c; return ss.str(); } template <typename T1, typename T2> ConcatImplActionP3<std::string, T1, T2> Concat(const std::string& a, T1 b, T2 c) { GTEST_INTENTIONAL_CONST_COND_PUSH_() if (true) { GTEST_INTENTIONAL_CONST_COND_POP_() return ConcatImpl(a, b, c); } else { return ConcatImpl<std::string, T1, T2>(a, b, c); } } template <typename T1, typename T2> ConcatImplActionP3<T1, int, T2> Concat(T1 a, int b, T2 c) { return ConcatImpl(a, b, c); } TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) { Action<const std::string()> a1 = Concat("Hello", "1", 2); EXPECT_EQ("Hello12", a1.Perform(std::make_tuple())); a1 = Concat(1, 2, 3); EXPECT_EQ("123", a1.Perform(std::make_tuple())); } ACTION(DoFoo) {} ACTION_P(DoFoo, p) {} ACTION_P2(DoFoo, p0, p1) {} TEST(ActionPnMacroTest, TypesAreCorrect) { DoFooAction a0 = DoFoo(); DoFooActionP<int> a1 = DoFoo(1); DoFooActionP2<int, char> a2 = DoFoo(1, '2'); PlusActionP3<int, int, char> a3 = Plus(1, 2, '3'); PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4'); PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5'); PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6'); PlusActionP7<int, int, int, int, int, int, char> a7 = Plus(1, 2, 3, 4, 5, 6, '7'); PlusActionP8<int, int, int, int, int, int, int, char> a8 = Plus(1, 2, 3, 4, 5, 6, 7, '8'); PlusActionP9<int, int, int, int, int, int, int, int, char> a9 = Plus(1, 2, 3, 4, 5, 6, 7, 8, '9'); PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0'); (void)a0; (void)a1; (void)a2; (void)a3; (void)a4; (void)a5; (void)a6; (void)a7; (void)a8; (void)a9; (void)a10; } ACTION_P(Plus1, x) { return x; } ACTION_P2(Plus2, x, y) { return x + y; } ACTION_P3(Plus3, x, y, z) { return x + y + z; } ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9; } TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) { int x = 1, y = 2, z = 3; const std::tuple<> empty = std::make_tuple(); Action<int()> a = Plus1<int&>(x); EXPECT_EQ(1, a.Perform(empty)); a = Plus2<const int&, int&>(x, y); EXPECT_EQ(3, a.Perform(empty)); a = Plus3<int&, const int&, int&>(x, y, z); EXPECT_EQ(6, a.Perform(empty)); int n[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&, int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9]); EXPECT_EQ(55, a.Perform(empty)); } class TenArgConstructorClass { public: TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10) : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {} int value_; }; ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_0_VALUE_PARAMS()) { return new T; } TEST(ActionTemplateTest, WorksWithoutValueParam) { const Action<int*()> a = CreateNew<int>(); int* p = a.Perform(std::make_tuple()); delete p; } ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_1_VALUE_PARAMS(a0)) { return new T(a0); } TEST(ActionTemplateTest, WorksWithValueParams) { const Action<int*()> a = CreateNew<int>(42); int* p = a.Perform(std::make_tuple()); EXPECT_EQ(42, *p); delete p; } ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { delete std::get<k>(args); } class BoolResetter { public: explicit BoolResetter(bool* value) : value_(value) {} ~BoolResetter() { *value_ = false; } private: bool* value_; }; TEST(ActionTemplateTest, WorksForIntegralTemplateParams) { const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>(); int n = 0; bool b = true; auto* resetter = new BoolResetter(&b); a.Perform(std::make_tuple(&n, resetter)); EXPECT_FALSE(b); } ACTION_TEMPLATE(ReturnSmartPointer, HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class, Pointer), AND_1_VALUE_PARAMS(pointee)) { return Pointer<pointee_type>(new pointee_type(pointee)); } TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) { const Action<std::shared_ptr<int>()> a = ReturnSmartPointer<std::shared_ptr>(42); std::shared_ptr<int> p = a.Perform(std::make_tuple()); EXPECT_EQ(42, *p); } template <typename T1, typename T2, typename T3, int k4, bool k5, unsigned int k6, typename T7, typename T8, typename T9> struct GiantTemplate { public: explicit GiantTemplate(int a_value) : value(a_value) {} int value; }; ACTION_TEMPLATE(ReturnGiant, HAS_10_TEMPLATE_PARAMS(typename, T1, typename, T2, typename, T3, int, k4, bool, k5, unsigned int, k6, class, T7, class, T8, class, T9, template <typename T> class, T10), AND_1_VALUE_PARAMS(value)) { return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value); } TEST(ActionTemplateTest, WorksFor10TemplateParameters) { using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6, char, unsigned, int>; const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char, unsigned, int, std::shared_ptr>(42); Giant giant = a.Perform(std::make_tuple()); EXPECT_EQ(42, giant.value); } ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) { return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10; } TEST(ActionTemplateTest, WorksFor10ValueParameters) { const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(55, a.Perform(std::make_tuple())); } ACTION(ReturnSum) { return 0; } ACTION_P(ReturnSum, x) { return x; } ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_2_VALUE_PARAMS(v1, v2)) { return static_cast<Number>(v1) + v2; } ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_3_VALUE_PARAMS(v1, v2, v3)) { return static_cast<Number>(v1) + v2 + v3; } ACTION_TEMPLATE(ReturnSum, HAS_2_TEMPLATE_PARAMS(typename, Number, int, k), AND_4_VALUE_PARAMS(v1, v2, v3, v4)) { return static_cast<Number>(v1) + v2 + v3 + v4 + k; } TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) { const Action<int()> a0 = ReturnSum(); const Action<int()> a1 = ReturnSum(1); const Action<int()> a2 = ReturnSum<int>(1, 2); const Action<int()> a3 = ReturnSum<int>(1, 2, 3); const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5); EXPECT_EQ(0, a0.Perform(std::make_tuple())); EXPECT_EQ(1, a1.Perform(std::make_tuple())); EXPECT_EQ(3, a2.Perform(std::make_tuple())); EXPECT_EQ(6, a3.Perform(std::make_tuple())); EXPECT_EQ(12345, a4.Perform(std::make_tuple())); } } } GTEST_DISABLE_MSC_WARNINGS_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/include/gmock/gmock-more-actions.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-more-actions_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
df840d78-1120-4a2f-b520-503efce89ecf
cpp
google/googletest
gmock-function-mocker
googlemock/include/gmock/gmock-function-mocker.h
googlemock/test/gmock-function-mocker_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ #include <cstddef> #include <type_traits> #include <utility> #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-pp.h" namespace testing { namespace internal { template <typename T> using identity_t = T; template <typename Pattern> struct ThisRefAdjuster { template <typename T> using AdjustT = typename std::conditional< std::is_const<typename std::remove_reference<Pattern>::type>::value, typename std::conditional<std::is_lvalue_reference<Pattern>::value, const T&, const T&&>::type, typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&, T&&>::type>::type; template <typename MockType> static AdjustT<MockType> Adjust(const MockType& mock) { return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock)); } }; constexpr bool PrefixOf(const char* a, const char* b) { return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); } template <size_t N, size_t M> constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(prefix, str); } template <size_t N, size_t M> constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { return N <= M && internal::PrefixOf(suffix, str + M - N); } template <size_t N, size_t M> constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { return N == M && internal::PrefixOf(a, b); } template <size_t N> constexpr bool ValidateSpec(const char (&spec)[N]) { return internal::Equals("const", spec) || internal::Equals("override", spec) || internal::Equals("final", spec) || internal::Equals("noexcept", spec) || (internal::StartsWith("noexcept(", spec) && internal::EndsWith(")", spec)) || internal::Equals("ref(&)", spec) || internal::Equals("ref(&&)", spec) || (internal::StartsWith("Calltype(", spec) && internal::EndsWith(")", spec)); } } using internal::FunctionMocker; } #define MOCK_METHOD(...) \ GMOCK_INTERNAL_WARNING_PUSH() \ GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \ GMOCK_INTERNAL_WARNING_POP() #define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \ GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) #define GMOCK_INTERNAL_WRONG_ARITY(...) \ static_assert( \ false, \ "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ "it must also be enclosed in parentheses.") #define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ static_assert( \ GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") #define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ static_assert( \ std::is_function<__VA_ARGS__>::value, \ "Signature must be a function type, maybe return type contains " \ "unprotected comma."); \ static_assert( \ ::testing::tuple_size<typename ::testing::internal::Function< \ __VA_ARGS__>::ArgumentTuple>::value == _N, \ "This method does not take " GMOCK_PP_STRINGIZE( \ _N) " arguments. Parenthesize all types with unprotected commas.") #define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) #define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ _Override, _Final, _NoexceptSpec, \ _CallType, _RefSpec, _Signature) \ typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \ _Signature)>::Result \ GMOCK_INTERNAL_EXPAND(_CallType) \ _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ GMOCK_PP_IF(_Constness, const, ) \ _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \ GMOCK_PP_IF(_Final, final, ) { \ GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .SetOwnerAndName(this, #_MethodName); \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ } \ ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \ GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ GMOCK_PP_IF(_Constness, const, ) _RefSpec { \ GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ } \ ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \ const ::testing::internal::WithoutMatchers&, \ GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \ return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \ _Constness, const, ) int _RefSpec>::Adjust(*this) \ .gmock_##_MethodName(GMOCK_PP_REPEAT( \ GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ } \ mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \ GMOCK_MOCKER_(_N, _Constness, _MethodName) #define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ #define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) #define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ GMOCK_PP_HAS_COMMA( \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) #define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) #define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) #define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ GMOCK_PP_IF( \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ _elem, ) #define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple) #define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \ GMOCK_PP_IF( \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \ GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) #define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) #define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \ GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) #ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ static_assert( \ ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \ "Token \'" GMOCK_PP_STRINGIZE( \ _elem) "\' cannot be recognized as a valid specification " \ "modifier. Is a ',' missing?"); #else #define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ static_assert( \ (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \ GMOCK_PP_STRINGIZE( \ _elem) " cannot be recognized as a valid specification modifier."); #endif #define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) #define GMOCK_INTERNAL_DETECT_CONST_I_const , #define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) #define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , #define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) #define GMOCK_INTERNAL_DETECT_FINAL_I_final , #define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) #define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , #define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem) #define GMOCK_INTERNAL_DETECT_REF_I_ref , #define GMOCK_INTERNAL_UNPACK_ref(x) x #define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \ GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem) #define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype , #define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__ #define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \ GMOCK_PP_REMOVE_PARENS, \ GMOCK_PP_IDENTITY)(_Ret)>( \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) #define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ GMOCK_PP_COMMA_IF(_i) \ GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ GMOCK_PP_IDENTITY) \ (_elem) #define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ gmock_a##_i #define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ ::std::forward<GMOCK_INTERNAL_ARG_O( \ _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i) #define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ gmock_a##_i #define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ GMOCK_PP_COMMA_IF(_i) \ gmock_a##_i #define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ GMOCK_PP_COMMA_IF(_i) \ ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>() #define GMOCK_INTERNAL_ARG_O(_i, ...) \ typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type #define GMOCK_INTERNAL_MATCHER_O(_i, ...) \ const ::testing::Matcher<typename ::testing::internal::Function< \ __VA_ARGS__>::template Arg<_i>::type>& #define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__) #define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__) #define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__) #define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__) #define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__) #define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__) #define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__) #define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__) #define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__) #define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__) #define MOCK_METHOD10(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__) #define MOCK_CONST_METHOD0(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__) #define MOCK_CONST_METHOD1(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__) #define MOCK_CONST_METHOD2(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__) #define MOCK_CONST_METHOD3(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__) #define MOCK_CONST_METHOD4(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__) #define MOCK_CONST_METHOD5(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__) #define MOCK_CONST_METHOD6(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__) #define MOCK_CONST_METHOD7(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__) #define MOCK_CONST_METHOD8(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__) #define MOCK_CONST_METHOD9(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__) #define MOCK_CONST_METHOD10(m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__) #define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__) #define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__) #define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__) #define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__) #define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__) #define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__) #define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__) #define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__) #define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__) #define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__) #define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__) #define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__) #define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__) #define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__) #define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__) #define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__) #define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__) #define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__) #define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__) #define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__) #define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__) #define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__) #define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__) #define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__) #define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__) #define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__) #define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__) #define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__) #define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__) #define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__) #define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__) #define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__) #define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__) #define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__) #define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__) #define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__) #define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__) #define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__) #define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__) #define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__) #define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__) #define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__) #define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__) #define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__) #define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) #define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \ GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ args_num, ::testing::internal::identity_t<__VA_ARGS__>); \ GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \ (::testing::internal::identity_t<__VA_ARGS__>)) #define GMOCK_MOCKER_(arity, constness, Method) \ GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) #endif
#include "gmock/gmock-function-mocker.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4503) #ifdef GTEST_OS_WINDOWS #include <objbase.h> #endif #include <functional> #include <map> #include <string> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace testing { namespace gmock_function_mocker_test { using testing::_; using testing::A; using testing::An; using testing::AnyNumber; using testing::Const; using testing::DoDefault; using testing::Eq; using testing::Lt; using testing::MockFunction; using testing::Ref; using testing::Return; using testing::ReturnRef; using testing::TypedEq; template <typename T> class TemplatedCopyable { public: TemplatedCopyable() = default; template <typename U> TemplatedCopyable(const U& other) {} }; class FooInterface { public: virtual ~FooInterface() = default; virtual void VoidReturning(int x) = 0; virtual int Nullary() = 0; virtual bool Unary(int x) = 0; virtual long Binary(short x, int y) = 0; virtual int Decimal(bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k) = 0; virtual bool TakesNonConstReference(int& n) = 0; virtual std::string TakesConstReference(const int& n) = 0; virtual bool TakesConst(const int x) = 0; virtual int OverloadedOnArgumentNumber() = 0; virtual int OverloadedOnArgumentNumber(int n) = 0; virtual int OverloadedOnArgumentType(int n) = 0; virtual char OverloadedOnArgumentType(char c) = 0; virtual int OverloadedOnConstness() = 0; virtual char OverloadedOnConstness() const = 0; virtual int TypeWithHole(int (*func)()) = 0; virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0; virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 0; virtual int (*ReturnsFunctionPointer1(int))(bool) = 0; using fn_ptr = int (*)(bool); virtual fn_ptr ReturnsFunctionPointer2(int) = 0; virtual int RefQualifiedConstRef() const& = 0; virtual int RefQualifiedConstRefRef() const&& = 0; virtual int RefQualifiedRef() & = 0; virtual int RefQualifiedRefRef() && = 0; virtual int RefQualifiedOverloaded() const& = 0; virtual int RefQualifiedOverloaded() const&& = 0; virtual int RefQualifiedOverloaded() & = 0; virtual int RefQualifiedOverloaded() && = 0; #ifdef GTEST_OS_WINDOWS STDMETHOD_(int, CTNullary)() = 0; STDMETHOD_(bool, CTUnary)(int x) = 0; STDMETHOD_(int, CTDecimal) (bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k) = 0; STDMETHOD_(char, CTConst)(int x) const = 0; #endif }; GTEST_DISABLE_MSC_WARNINGS_PUSH_(4373) class MockFoo : public FooInterface { public: MockFoo() = default; MOCK_METHOD(void, VoidReturning, (int n)); MOCK_METHOD(int, Nullary, ()); MOCK_METHOD(bool, Unary, (int)); MOCK_METHOD(long, Binary, (short, int)); MOCK_METHOD(int, Decimal, (bool, char, short, int, long, float, double, unsigned, char*, const std::string& str), (override)); MOCK_METHOD(bool, TakesNonConstReference, (int&)); MOCK_METHOD(std::string, TakesConstReference, (const int&)); MOCK_METHOD(bool, TakesConst, (const int)); MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (), ()); MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (int), (const)); MOCK_METHOD(int, OverloadedOnArgumentNumber, ()); MOCK_METHOD(int, OverloadedOnArgumentNumber, (int)); MOCK_METHOD(int, OverloadedOnArgumentType, (int)); MOCK_METHOD(char, OverloadedOnArgumentType, (char)); MOCK_METHOD(int, OverloadedOnConstness, (), (override)); MOCK_METHOD(char, OverloadedOnConstness, (), (override, const)); MOCK_METHOD(int, TypeWithHole, (int (*)()), ()); MOCK_METHOD(int, TypeWithComma, ((const std::map<int, std::string>&))); MOCK_METHOD(int, TypeWithTemplatedCopyCtor, (const TemplatedCopyable<int>&)); MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ()); MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ()); #ifdef GTEST_OS_WINDOWS MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(int, CTDecimal, (bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k), (Calltype(STDMETHODCALLTYPE))); MOCK_METHOD(char, CTConst, (int), (const, Calltype(STDMETHODCALLTYPE))); MOCK_METHOD((std::map<int, std::string>), CTReturnTypeWithComma, (), (Calltype(STDMETHODCALLTYPE))); #endif MOCK_METHOD(int, RefQualifiedConstRef, (), (const, ref(&), override)); MOCK_METHOD(int, RefQualifiedConstRefRef, (), (const, ref(&&), override)); MOCK_METHOD(int, RefQualifiedRef, (), (ref(&), override)); MOCK_METHOD(int, RefQualifiedRefRef, (), (ref(&&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&), override)); MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override)); private: MockFoo(const MockFoo&) = delete; MockFoo& operator=(const MockFoo&) = delete; }; class LegacyMockFoo : public FooInterface { public: LegacyMockFoo() = default; MOCK_METHOD1(VoidReturning, void(int n)); MOCK_METHOD0(Nullary, int()); MOCK_METHOD1(Unary, bool(int)); MOCK_METHOD2(Binary, long(short, int)); MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, double, unsigned, char*, const std::string& str)); MOCK_METHOD1(TakesNonConstReference, bool(int&)); MOCK_METHOD1(TakesConstReference, std::string(const int&)); MOCK_METHOD1(TakesConst, bool(const int)); MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>()); MOCK_CONST_METHOD1(ReturnTypeWithComma, std::map<int, std::string>(int)); MOCK_METHOD0(OverloadedOnArgumentNumber, int()); MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); MOCK_METHOD1(OverloadedOnArgumentType, int(int)); MOCK_METHOD1(OverloadedOnArgumentType, char(char)); MOCK_METHOD0(OverloadedOnConstness, int()); MOCK_CONST_METHOD0(OverloadedOnConstness, char()); MOCK_METHOD1(TypeWithHole, int(int (*)())); MOCK_METHOD1(TypeWithComma, int(const std::map<int, std::string>&)); MOCK_METHOD1(TypeWithTemplatedCopyCtor, int(const TemplatedCopyable<int>&)); MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool)); MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int)); #ifdef GTEST_OS_WINDOWS MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int()); MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, int(bool b, char c, short d, int e, long f, float g, double h, unsigned i, char* j, const std::string& k)); MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int)); MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma, std::map<int, std::string>()); #endif int RefQualifiedConstRef() const& override { return 0; } int RefQualifiedConstRefRef() const&& override { return 0; } int RefQualifiedRef() & override { return 0; } int RefQualifiedRefRef() && override { return 0; } int RefQualifiedOverloaded() const& override { return 0; } int RefQualifiedOverloaded() const&& override { return 0; } int RefQualifiedOverloaded() & override { return 0; } int RefQualifiedOverloaded() && override { return 0; } private: LegacyMockFoo(const LegacyMockFoo&) = delete; LegacyMockFoo& operator=(const LegacyMockFoo&) = delete; }; GTEST_DISABLE_MSC_WARNINGS_POP_() template <class T> class FunctionMockerTest : public testing::Test { protected: FunctionMockerTest() : foo_(&mock_foo_) {} FooInterface* const foo_; T mock_foo_; }; using FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>; TYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes); TYPED_TEST(FunctionMockerTest, MocksVoidFunction) { EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100))); this->foo_->VoidReturning(0); } TYPED_TEST(FunctionMockerTest, MocksNullaryFunction) { EXPECT_CALL(this->mock_foo_, Nullary()) .WillOnce(DoDefault()) .WillOnce(Return(1)); EXPECT_EQ(0, this->foo_->Nullary()); EXPECT_EQ(1, this->foo_->Nullary()); } TYPED_TEST(FunctionMockerTest, MocksUnaryFunction) { EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true)); EXPECT_TRUE(this->foo_->Unary(2)); EXPECT_FALSE(this->foo_->Unary(2)); } TYPED_TEST(FunctionMockerTest, MocksBinaryFunction) { EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3)); EXPECT_EQ(3, this->foo_->Binary(2, 1)); } TYPED_TEST(FunctionMockerTest, MocksDecimalFunction) { EXPECT_CALL(this->mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi")) .WillOnce(Return(5)); EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); } TYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) { int a = 0; EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a))) .WillOnce(Return(true)); EXPECT_TRUE(this->foo_->TakesNonConstReference(a)); } TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) { int a = 0; EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a))) .WillOnce(Return("Hello")); EXPECT_EQ("Hello", this->foo_->TakesConstReference(a)); } TYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) { EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault()); EXPECT_FALSE(this->foo_->TakesConst(5)); } TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) { EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber()) .WillOnce(Return(1)); EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_)) .WillOnce(Return(2)); EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1)); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber()); } TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) { EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>())) .WillOnce(Return(1)); EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a'))) .WillOnce(Return('b')); EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0)); EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a')); } TYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) { EXPECT_CALL(this->mock_foo_, OverloadedOnConstness()); EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness()) .WillOnce(Return('a')); EXPECT_EQ(0, this->foo_->OverloadedOnConstness()); EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness()); } TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) { const std::map<int, std::string> a_map; EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map)); EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map)); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma()); EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42)); } TYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) { EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_)) .WillOnce(Return(true)); EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>())); } #ifdef GTEST_OS_WINDOWS TYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) { EXPECT_CALL(this->mock_foo_, CTNullary()) .WillOnce(Return(-1)) .WillOnce(Return(0)); EXPECT_EQ(-1, this->foo_->CTNullary()); EXPECT_EQ(0, this->foo_->CTNullary()); } TYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) { EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2))) .Times(2) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(this->foo_->CTUnary(2)); EXPECT_FALSE(this->foo_->CTUnary(2)); } TYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) { EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, "hi")) .WillOnce(Return(10)); EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); } TYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a')); EXPECT_EQ('a', Const(*this->foo_).CTConst(0)); } TYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { const std::map<int, std::string> a_map; EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map)); EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma()); } #endif TEST(FunctionMockerTest, RefQualified) { MockFoo mock_foo; EXPECT_CALL(mock_foo, RefQualifiedConstRef).WillOnce(Return(1)); EXPECT_CALL(std::move(mock_foo), RefQualifiedConstRefRef) .WillOnce(Return(2)); EXPECT_CALL(mock_foo, RefQualifiedRef).WillOnce(Return(3)); EXPECT_CALL(std::move(mock_foo), RefQualifiedRefRef) .WillOnce(Return(4)); EXPECT_CALL(static_cast<const MockFoo&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(5)); EXPECT_CALL(static_cast<const MockFoo&&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(6)); EXPECT_CALL(static_cast<MockFoo&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(7)); EXPECT_CALL(static_cast<MockFoo&&>(mock_foo), RefQualifiedOverloaded()) .WillOnce(Return(8)); EXPECT_EQ(mock_foo.RefQualifiedConstRef(), 1); EXPECT_EQ(std::move(mock_foo).RefQualifiedConstRefRef(), 2); EXPECT_EQ(mock_foo.RefQualifiedRef(), 3); EXPECT_EQ(std::move(mock_foo).RefQualifiedRefRef(), 4); EXPECT_EQ(std::cref(mock_foo).get().RefQualifiedOverloaded(), 5); EXPECT_EQ(std::move(std::cref(mock_foo).get()) .RefQualifiedOverloaded(), 6); EXPECT_EQ(mock_foo.RefQualifiedOverloaded(), 7); EXPECT_EQ(std::move(mock_foo).RefQualifiedOverloaded(), 8); } class MockB { public: MockB() = default; MOCK_METHOD(void, DoB, ()); private: MockB(const MockB&) = delete; MockB& operator=(const MockB&) = delete; }; class LegacyMockB { public: LegacyMockB() = default; MOCK_METHOD0(DoB, void()); private: LegacyMockB(const LegacyMockB&) = delete; LegacyMockB& operator=(const LegacyMockB&) = delete; }; template <typename T> class ExpectCallTest : public ::testing::Test {}; using ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>; TYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes); TYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) { { TypeParam b; } { TypeParam b; b.DoB(); } { TypeParam b; b.DoB(); b.DoB(); } } template <typename T> class StackInterface { public: virtual ~StackInterface() = default; virtual void Push(const T& value) = 0; virtual void Pop() = 0; virtual int GetSize() const = 0; virtual const T& GetTop() const = 0; }; template <typename T> class MockStack : public StackInterface<T> { public: MockStack() = default; MOCK_METHOD(void, Push, (const T& elem), ()); MOCK_METHOD(void, Pop, (), (final)); MOCK_METHOD(int, GetSize, (), (const, override)); MOCK_METHOD(const T&, GetTop, (), (const)); MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (), ()); MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (int), (const)); private: MockStack(const MockStack&) = delete; MockStack& operator=(const MockStack&) = delete; }; template <typename T> class LegacyMockStack : public StackInterface<T> { public: LegacyMockStack() = default; MOCK_METHOD1_T(Push, void(const T& elem)); MOCK_METHOD0_T(Pop, void()); MOCK_CONST_METHOD0_T(GetSize, int()); MOCK_CONST_METHOD0_T(GetTop, const T&()); MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>()); MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); private: LegacyMockStack(const LegacyMockStack&) = delete; LegacyMockStack& operator=(const LegacyMockStack&) = delete; }; template <typename T> class TemplateMockTest : public ::testing::Test {}; using TemplateMockTestTypes = ::testing::Types<MockStack<int>, LegacyMockStack<int>>; TYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes); TYPED_TEST(TemplateMockTest, Works) { TypeParam mock; EXPECT_CALL(mock, GetSize()) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); EXPECT_EQ(1, mock.GetSize()); EXPECT_EQ(5, mock.GetTop()); mock.Pop(); EXPECT_EQ(0, mock.GetSize()); } TYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) { TypeParam mock; const std::map<int, int> a_map; EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map)); EXPECT_CALL(mock, ReturnTypeWithComma(1)).WillOnce(Return(a_map)); EXPECT_EQ(a_map, mock.ReturnTypeWithComma()); EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); } #ifdef GTEST_OS_WINDOWS template <typename T> class StackInterfaceWithCallType { public: virtual ~StackInterfaceWithCallType() {} STDMETHOD_(void, Push)(const T& value) = 0; STDMETHOD_(void, Pop)() = 0; STDMETHOD_(int, GetSize)() const = 0; STDMETHOD_(const T&, GetTop)() const = 0; }; template <typename T> class MockStackWithCallType : public StackInterfaceWithCallType<T> { public: MockStackWithCallType() {} MOCK_METHOD(void, Push, (const T& elem), (Calltype(STDMETHODCALLTYPE), override)); MOCK_METHOD(void, Pop, (), (Calltype(STDMETHODCALLTYPE), override)); MOCK_METHOD(int, GetSize, (), (Calltype(STDMETHODCALLTYPE), override, const)); MOCK_METHOD(const T&, GetTop, (), (Calltype(STDMETHODCALLTYPE), override, const)); private: MockStackWithCallType(const MockStackWithCallType&) = delete; MockStackWithCallType& operator=(const MockStackWithCallType&) = delete; }; template <typename T> class LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> { public: LegacyMockStackWithCallType() {} MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem)); MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void()); MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int()); MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&()); private: LegacyMockStackWithCallType(const LegacyMockStackWithCallType&) = delete; LegacyMockStackWithCallType& operator=(const LegacyMockStackWithCallType&) = delete; }; template <typename T> class TemplateMockTestWithCallType : public ::testing::Test {}; using TemplateMockTestWithCallTypeTypes = ::testing::Types<MockStackWithCallType<int>, LegacyMockStackWithCallType<int>>; TYPED_TEST_SUITE(TemplateMockTestWithCallType, TemplateMockTestWithCallTypeTypes); TYPED_TEST(TemplateMockTestWithCallType, Works) { TypeParam mock; EXPECT_CALL(mock, GetSize()) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(0)); EXPECT_CALL(mock, Push(_)); int n = 5; EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n)); EXPECT_CALL(mock, Pop()).Times(AnyNumber()); EXPECT_EQ(0, mock.GetSize()); mock.Push(5); EXPECT_EQ(1, mock.GetSize()); EXPECT_EQ(5, mock.GetTop()); mock.Pop(); EXPECT_EQ(0, mock.GetSize()); } #endif #define MY_MOCK_METHODS1_ \ MOCK_METHOD(void, Overloaded, ()); \ MOCK_METHOD(int, Overloaded, (int), (const)); \ MOCK_METHOD(bool, Overloaded, (bool f, int n)) #define LEGACY_MY_MOCK_METHODS1_ \ MOCK_METHOD0(Overloaded, void()); \ MOCK_CONST_METHOD1(Overloaded, int(int n)); \ MOCK_METHOD2(Overloaded, bool(bool f, int n)) class MockOverloadedOnArgNumber { public: MockOverloadedOnArgNumber() = default; MY_MOCK_METHODS1_; private: MockOverloadedOnArgNumber(const MockOverloadedOnArgNumber&) = delete; MockOverloadedOnArgNumber& operator=(const MockOverloadedOnArgNumber&) = delete; }; class LegacyMockOverloadedOnArgNumber { public: LegacyMockOverloadedOnArgNumber() = default; LEGACY_MY_MOCK_METHODS1_; private: LegacyMockOverloadedOnArgNumber(const LegacyMockOverloadedOnArgNumber&) = delete; LegacyMockOverloadedOnArgNumber& operator=( const LegacyMockOverloadedOnArgNumber&) = delete; }; template <typename T> class OverloadedMockMethodTest : public ::testing::Test {}; using OverloadedMockMethodTestTypes = ::testing::Types<MockOverloadedOnArgNumber, LegacyMockOverloadedOnArgNumber>; TYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes); TYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { TypeParam mock; EXPECT_CALL(mock, Overloaded()); EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true)); mock.Overloaded(); EXPECT_EQ(2, mock.Overloaded(1)); EXPECT_TRUE(mock.Overloaded(true, 1)); } #define MY_MOCK_METHODS2_ \ MOCK_CONST_METHOD1(Overloaded, int(int n)); \ MOCK_METHOD1(Overloaded, int(int n)) class MockOverloadedOnConstness { public: MockOverloadedOnConstness() = default; MY_MOCK_METHODS2_; private: MockOverloadedOnConstness(const MockOverloadedOnConstness&) = delete; MockOverloadedOnConstness& operator=(const MockOverloadedOnConstness&) = delete; }; TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) { MockOverloadedOnConstness mock; const MockOverloadedOnConstness* const_mock = &mock; EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3)); EXPECT_EQ(2, mock.Overloaded(1)); EXPECT_EQ(3, const_mock->Overloaded(1)); } TEST(MockMethodMockFunctionTest, WorksForVoidNullary) { MockFunction<void()> foo; EXPECT_CALL(foo, Call()); foo.Call(); } TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) { MockFunction<int()> foo; EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_EQ(1, foo.Call()); EXPECT_EQ(2, foo.Call()); } TEST(MockMethodMockFunctionTest, WorksForVoidUnary) { MockFunction<void(int)> foo; EXPECT_CALL(foo, Call(1)); foo.Call(1); } TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) { MockFunction<int(bool, int)> foo; EXPECT_CALL(foo, Call(false, 42)).WillOnce(Return(1)).WillOnce(Return(2)); EXPECT_CALL(foo, Call(true, Ge(100))).WillOnce(Return(3)); EXPECT_EQ(1, foo.Call(false, 42)); EXPECT_EQ(2, foo.Call(false, 42)); EXPECT_EQ(3, foo.Call(true, 120)); } TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { MockFunction<int(bool a0, char a1, int a2, int a3, int a4, int a5, int a6, char a7, int a8, bool a9)> foo; EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _)) .WillOnce(Return(1)) .WillOnce(Return(2)); EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true)); EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false)); } TEST(MockMethodMockFunctionTest, AsStdFunction) { MockFunction<int(int)> foo; auto call = [](const std::function<int(int)>& f, int i) { return f(i); }; EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1)); EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2)); EXPECT_EQ(-1, call(foo.AsStdFunction(), 1)); EXPECT_EQ(-2, call(foo.AsStdFunction(), 2)); } TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) { MockFunction<int&()> foo; int value = 1; EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value)); int& ref = foo.AsStdFunction()(); EXPECT_EQ(1, ref); value = 2; EXPECT_EQ(2, ref); } TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) { MockFunction<int(int&)> foo; auto call = [](const std::function<int(int&)>& f, int& i) { return f(i); }; int i = 42; EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); } namespace { template <typename Expected, typename F> static constexpr bool IsMockFunctionTemplateArgumentDeducedTo( const internal::MockFunction<F>&) { return std::is_same<F, Expected>::value; } } template <typename F> class MockMethodMockFunctionSignatureTest : public Test {}; using MockMethodMockFunctionSignatureTypes = Types<void(), int(), void(int), int(int), int(bool, int), int(bool, char, int, int, int, int, int, char, int, bool)>; TYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest, MockMethodMockFunctionSignatureTypes); TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForRawSignature) { using Argument = TypeParam; MockFunction<Argument> foo; EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); } TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForStdFunction) { using Argument = std::function<TypeParam>; MockFunction<Argument> foo; EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); } TYPED_TEST( MockMethodMockFunctionSignatureTest, IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) { using ForRawSignature = decltype(&MockFunction<TypeParam>::Call); using ForStdFunction = decltype(&MockFunction<std::function<TypeParam>>::Call); EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value)); } template <typename F> struct AlternateCallable {}; TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionTemplateArgumentDeducedForAlternateCallable) { using Argument = AlternateCallable<TypeParam>; MockFunction<Argument> foo; EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo)); } TYPED_TEST(MockMethodMockFunctionSignatureTest, IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) { using ForRawSignature = decltype(&MockFunction<TypeParam>::Call); using ForStdFunction = decltype(&MockFunction<std::function<TypeParam>>::Call); EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value)); } struct MockMethodSizes0 { MOCK_METHOD(void, func, ()); }; struct MockMethodSizes1 { MOCK_METHOD(void, func, (int)); }; struct MockMethodSizes2 { MOCK_METHOD(void, func, (int, int)); }; struct MockMethodSizes3 { MOCK_METHOD(void, func, (int, int, int)); }; struct MockMethodSizes4 { MOCK_METHOD(void, func, (int, int, int, int)); }; struct LegacyMockMethodSizes0 { MOCK_METHOD0(func, void()); }; struct LegacyMockMethodSizes1 { MOCK_METHOD1(func, void(int)); }; struct LegacyMockMethodSizes2 { MOCK_METHOD2(func, void(int, int)); }; struct LegacyMockMethodSizes3 { MOCK_METHOD3(func, void(int, int, int)); }; struct LegacyMockMethodSizes4 { MOCK_METHOD4(func, void(int, int, int, int)); }; TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes1)); EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes2)); EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes3)); EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes4)); EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0)); } TEST(MockMethodMockFunctionTest, EnsureNoUnusedMemberFunction) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic error "-Wunused-member-function" #endif struct Foo { MOCK_METHOD(void, foo, ()); }; EXPECT_CALL(Foo(), foo()).Times(0); #ifdef __clang__ #pragma clang diagnostic pop #endif } void hasTwoParams(int, int); void MaybeThrows(); void DoesntThrow() noexcept; struct MockMethodNoexceptSpecifier { MOCK_METHOD(void, func1, (), (noexcept)); MOCK_METHOD(void, func2, (), (noexcept(true))); MOCK_METHOD(void, func3, (), (noexcept(false))); MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows())))); MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow())))); MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const)); MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow())))); MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1, 2))), const)); }; TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func1())); EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func2())); EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func3())); EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func4())); EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func5())); EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func6())); EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func7())); EXPECT_EQ(noexcept(std::declval<MockMethodNoexceptSpecifier>().func8()), noexcept(hasTwoParams(1, 2))); } } } GTEST_DISABLE_MSC_WARNINGS_POP_()
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/include/gmock/gmock-function-mocker.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-function-mocker_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
079bd92d-f5c1-4c05-b597-b2414a6c6e8c
cpp
google/googletest
gmock-nice-strict
googlemock/include/gmock/gmock-nice-strict.h
googlemock/test/gmock-nice-strict_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ #include <cstdint> #include <type_traits> #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-port.h" namespace testing { template <class MockClass> class NiceMock; template <class MockClass> class NaggyMock; template <class MockClass> class StrictMock; namespace internal { template <typename T> std::true_type StrictnessModifierProbe(const NiceMock<T>&); template <typename T> std::true_type StrictnessModifierProbe(const NaggyMock<T>&); template <typename T> std::true_type StrictnessModifierProbe(const StrictMock<T>&); std::false_type StrictnessModifierProbe(...); template <typename T> constexpr bool HasStrictnessModifier() { return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value; } #if defined(GTEST_OS_WINDOWS) && !defined(GTEST_OS_WINDOWS_MINGW) && \ (defined(_MSC_VER) || defined(__clang__)) #define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases) #else #define GTEST_INTERNAL_EMPTY_BASE_CLASS #endif template <typename Base> class NiceMockImpl { public: NiceMockImpl() { ::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~NiceMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; template <typename Base> class NaggyMockImpl { public: NaggyMockImpl() { ::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~NaggyMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; template <typename Base> class StrictMockImpl { public: StrictMockImpl() { ::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this)); } ~StrictMockImpl() { ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this)); } }; } template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock : private internal::NiceMockImpl<MockClass>, public MockClass { public: static_assert(!internal::HasStrictnessModifier<MockClass>(), "Can't apply NiceMock to a class hierarchy that already has a " "strictness modifier. See " "https: "gmock_cook_book.html#NiceStrictNaggy"); NiceMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename A> explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: NiceMock(const NiceMock&) = delete; NiceMock& operator=(const NiceMock&) = delete; }; template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock : private internal::NaggyMockImpl<MockClass>, public MockClass { static_assert(!internal::HasStrictnessModifier<MockClass>(), "Can't apply NaggyMock to a class hierarchy that already has a " "strictness modifier. See " "https: "gmock_cook_book.html#NiceStrictNaggy"); public: NaggyMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename A> explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: NaggyMock(const NaggyMock&) = delete; NaggyMock& operator=(const NaggyMock&) = delete; }; template <class MockClass> class GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock : private internal::StrictMockImpl<MockClass>, public MockClass { public: static_assert( !internal::HasStrictnessModifier<MockClass>(), "Can't apply StrictMock to a class hierarchy that already has a " "strictness modifier. See " "https: "gmock_cook_book.html#NiceStrictNaggy"); StrictMock() : MockClass() { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename A> explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } template <typename TArg1, typename TArg2, typename... An> StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args) : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2), std::forward<An>(args)...) { static_assert(sizeof(*this) == sizeof(MockClass), "The impl subclass shouldn't introduce any padding"); } private: StrictMock(const StrictMock&) = delete; StrictMock& operator=(const StrictMock&) = delete; }; #undef GTEST_INTERNAL_EMPTY_BASE_CLASS } #endif
#include "gmock/gmock-nice-strict.h" #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" class Mock { public: Mock() = default; MOCK_METHOD0(DoThis, void()); private: Mock(const Mock&) = delete; Mock& operator=(const Mock&) = delete; }; namespace testing { namespace gmock_nice_strict_test { using testing::HasSubstr; using testing::NaggyMock; using testing::NiceMock; using testing::StrictMock; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif class NotDefaultConstructible { public: explicit NotDefaultConstructible(int) {} }; class CallsMockMethodInDestructor { public: ~CallsMockMethodInDestructor() { OnDestroy(); } MOCK_METHOD(void, OnDestroy, ()); }; class Foo { public: virtual ~Foo() = default; virtual void DoThis() = 0; virtual int DoThat(bool flag) = 0; }; class MockFoo : public Foo { public: MockFoo() = default; void Delete() { delete this; } MOCK_METHOD0(DoThis, void()); MOCK_METHOD1(DoThat, int(bool flag)); MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible()); private: MockFoo(const MockFoo&) = delete; MockFoo& operator=(const MockFoo&) = delete; }; class MockBar { public: explicit MockBar(const std::string& s) : str_(s) {} MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, const std::string& a7, const std::string& a8, bool a9, bool a10) { str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); } virtual ~MockBar() = default; const std::string& str() const { return str_; } MOCK_METHOD0(This, int()); MOCK_METHOD2(That, std::string(int, bool)); private: std::string str_; MockBar(const MockBar&) = delete; MockBar& operator=(const MockBar&) = delete; }; class MockBaz { public: class MoveOnly { public: MoveOnly() = default; MoveOnly(const MoveOnly&) = delete; MoveOnly& operator=(const MoveOnly&) = delete; MoveOnly(MoveOnly&&) = default; MoveOnly& operator=(MoveOnly&&) = default; }; MockBaz(MoveOnly) {} }; #if GTEST_HAS_STREAM_REDIRECTION TEST(RawMockTest, WarningForUninterestingCall) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); MockFoo raw_foo; CaptureStdout(); raw_foo.DoThis(); raw_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); MockFoo* const raw_foo = new MockFoo; ON_CALL(*raw_foo, DoThis()).WillByDefault(Invoke(raw_foo, &MockFoo::Delete)); CaptureStdout(); raw_foo->DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(RawMockTest, InfoForUninterestingCall) { MockFoo raw_foo; const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "info"); CaptureStdout(); raw_foo.DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(RawMockTest, IsNaggy_IsNice_IsStrict) { MockFoo raw_foo; EXPECT_TRUE(Mock::IsNaggy(&raw_foo)); EXPECT_FALSE(Mock::IsNice(&raw_foo)); EXPECT_FALSE(Mock::IsStrict(&raw_foo)); } TEST(NiceMockTest, NoWarningForUninterestingCall) { NiceMock<MockFoo> nice_foo; CaptureStdout(); nice_foo.DoThis(); nice_foo.DoThat(true); EXPECT_EQ("", GetCapturedStdout()); } TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { NiceMock<MockFoo>* const nice_foo = new NiceMock<MockFoo>; ON_CALL(*nice_foo, DoThis()) .WillByDefault(Invoke(nice_foo, &MockFoo::Delete)); CaptureStdout(); nice_foo->DoThis(); EXPECT_EQ("", GetCapturedStdout()); } TEST(NiceMockTest, InfoForUninterestingCall) { NiceMock<MockFoo> nice_foo; const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "info"); CaptureStdout(); nice_foo.DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } #endif TEST(NiceMockTest, AllowsExpectedCall) { NiceMock<MockFoo> nice_foo; EXPECT_CALL(nice_foo, DoThis()); nice_foo.DoThis(); } TEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) { NiceMock<MockFoo> nice_foo; #if GTEST_HAS_EXCEPTIONS try { nice_foo.ReturnNonDefaultConstructible(); FAIL(); } catch (const std::runtime_error& ex) { EXPECT_THAT(ex.what(), HasSubstr("ReturnNonDefaultConstructible")); } #else EXPECT_DEATH_IF_SUPPORTED({ nice_foo.ReturnNonDefaultConstructible(); }, ""); #endif } TEST(NiceMockTest, UnexpectedCallFails) { NiceMock<MockFoo> nice_foo; EXPECT_CALL(nice_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(nice_foo.DoThis(), "called more times than expected"); } TEST(NiceMockTest, NonDefaultConstructor) { NiceMock<MockBar> nice_bar("hi"); EXPECT_EQ("hi", nice_bar.str()); nice_bar.This(); nice_bar.That(5, true); } TEST(NiceMockTest, NonDefaultConstructor10) { NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, false); EXPECT_EQ("abcdefghTF", nice_bar.str()); nice_bar.This(); nice_bar.That(5, true); } TEST(NiceMockTest, AllowLeak) { NiceMock<MockFoo>* leaked = new NiceMock<MockFoo>; Mock::AllowLeak(leaked); EXPECT_CALL(*leaked, DoThis()); leaked->DoThis(); } TEST(NiceMockTest, MoveOnlyConstructor) { NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly{}); } TEST(NiceMockTest, AcceptsClassNamedMock) { NiceMock< ::Mock> nice; EXPECT_CALL(nice, DoThis()); nice.DoThis(); } TEST(NiceMockTest, IsNiceInDestructor) { { NiceMock<CallsMockMethodInDestructor> nice_on_destroy; } } TEST(NiceMockTest, IsNaggy_IsNice_IsStrict) { NiceMock<MockFoo> nice_foo; EXPECT_FALSE(Mock::IsNaggy(&nice_foo)); EXPECT_TRUE(Mock::IsNice(&nice_foo)); EXPECT_FALSE(Mock::IsStrict(&nice_foo)); } #if GTEST_HAS_STREAM_REDIRECTION TEST(NaggyMockTest, WarningForUninterestingCall) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); NaggyMock<MockFoo> naggy_foo; CaptureStdout(); naggy_foo.DoThis(); naggy_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>; ON_CALL(*naggy_foo, DoThis()) .WillByDefault(Invoke(naggy_foo, &MockFoo::Delete)); CaptureStdout(); naggy_foo->DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } #endif TEST(NaggyMockTest, AllowsExpectedCall) { NaggyMock<MockFoo> naggy_foo; EXPECT_CALL(naggy_foo, DoThis()); naggy_foo.DoThis(); } TEST(NaggyMockTest, UnexpectedCallFails) { NaggyMock<MockFoo> naggy_foo; EXPECT_CALL(naggy_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(naggy_foo.DoThis(), "called more times than expected"); } TEST(NaggyMockTest, NonDefaultConstructor) { NaggyMock<MockBar> naggy_bar("hi"); EXPECT_EQ("hi", naggy_bar.str()); naggy_bar.This(); naggy_bar.That(5, true); } TEST(NaggyMockTest, NonDefaultConstructor10) { NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true, false); EXPECT_EQ("01234567TF", naggy_bar.str()); naggy_bar.This(); naggy_bar.That(5, true); } TEST(NaggyMockTest, AllowLeak) { NaggyMock<MockFoo>* leaked = new NaggyMock<MockFoo>; Mock::AllowLeak(leaked); EXPECT_CALL(*leaked, DoThis()); leaked->DoThis(); } TEST(NaggyMockTest, MoveOnlyConstructor) { NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly{}); } TEST(NaggyMockTest, AcceptsClassNamedMock) { NaggyMock< ::Mock> naggy; EXPECT_CALL(naggy, DoThis()); naggy.DoThis(); } TEST(NaggyMockTest, IsNaggyInDestructor) { const std::string saved_flag = GMOCK_FLAG_GET(verbose); GMOCK_FLAG_SET(verbose, "warning"); CaptureStdout(); { NaggyMock<CallsMockMethodInDestructor> naggy_on_destroy; } EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG_SET(verbose, saved_flag); } TEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) { NaggyMock<MockFoo> naggy_foo; EXPECT_TRUE(Mock::IsNaggy(&naggy_foo)); EXPECT_FALSE(Mock::IsNice(&naggy_foo)); EXPECT_FALSE(Mock::IsStrict(&naggy_foo)); } TEST(StrictMockTest, AllowsExpectedCall) { StrictMock<MockFoo> strict_foo; EXPECT_CALL(strict_foo, DoThis()); strict_foo.DoThis(); } TEST(StrictMockTest, UnexpectedCallFails) { StrictMock<MockFoo> strict_foo; EXPECT_CALL(strict_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(), "called more times than expected"); } TEST(StrictMockTest, UninterestingCallFails) { StrictMock<MockFoo> strict_foo; EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(), "Uninteresting mock function call"); } TEST(StrictMockTest, UninterestingCallFailsAfterDeath) { StrictMock<MockFoo>* const strict_foo = new StrictMock<MockFoo>; ON_CALL(*strict_foo, DoThis()) .WillByDefault(Invoke(strict_foo, &MockFoo::Delete)); EXPECT_NONFATAL_FAILURE(strict_foo->DoThis(), "Uninteresting mock function call"); } TEST(StrictMockTest, NonDefaultConstructor) { StrictMock<MockBar> strict_bar("hi"); EXPECT_EQ("hi", strict_bar.str()); EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), "Uninteresting mock function call"); } TEST(StrictMockTest, NonDefaultConstructor10) { StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, false); EXPECT_EQ("abcdefghTF", strict_bar.str()); EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), "Uninteresting mock function call"); } TEST(StrictMockTest, AllowLeak) { StrictMock<MockFoo>* leaked = new StrictMock<MockFoo>; Mock::AllowLeak(leaked); EXPECT_CALL(*leaked, DoThis()); leaked->DoThis(); } TEST(StrictMockTest, MoveOnlyConstructor) { StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly{}); } TEST(StrictMockTest, AcceptsClassNamedMock) { StrictMock< ::Mock> strict; EXPECT_CALL(strict, DoThis()); strict.DoThis(); } TEST(StrictMockTest, IsStrictInDestructor) { EXPECT_NONFATAL_FAILURE( { StrictMock<CallsMockMethodInDestructor> strict_on_destroy; }, "Uninteresting mock function call"); } TEST(StrictMockTest, IsNaggy_IsNice_IsStrict) { StrictMock<MockFoo> strict_foo; EXPECT_FALSE(Mock::IsNaggy(&strict_foo)); EXPECT_FALSE(Mock::IsNice(&strict_foo)); EXPECT_TRUE(Mock::IsStrict(&strict_foo)); } } }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/include/gmock/gmock-nice-strict.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-nice-strict_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
9cf5631b-5f5c-40c4-9b7c-57d2040f9a38
cpp
google/googletest
gmock-actions
googlemock/include/gmock/gmock-actions.h
googlemock/test/gmock-actions_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE #include <errno.h> #endif #include <algorithm> #include <exception> #include <functional> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-pp.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) namespace testing { namespace internal { template <typename T, bool kDefaultConstructible> struct BuiltInDefaultValueGetter { static T Get() { return T(); } }; template <typename T> struct BuiltInDefaultValueGetter<T, false> { static T Get() { Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); #if defined(__GNUC__) || defined(__clang__) __builtin_unreachable(); #elif defined(_MSC_VER) __assume(0); #else return Invalid<T>(); #endif } }; template <typename T> class BuiltInDefaultValue { public: static bool Exists() { return ::std::is_default_constructible<T>::value; } static T Get() { return BuiltInDefaultValueGetter< T, ::std::is_default_constructible<T>::value>::Get(); } }; template <typename T> class BuiltInDefaultValue<const T> { public: static bool Exists() { return BuiltInDefaultValue<T>::Exists(); } static T Get() { return BuiltInDefaultValue<T>::Get(); } }; template <typename T> class BuiltInDefaultValue<T*> { public: static bool Exists() { return true; } static T* Get() { return nullptr; } }; #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ template <> \ class BuiltInDefaultValue<type> { \ public: \ static bool Exists() { return true; } \ static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); #endif GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ template <typename P> struct negation : std::integral_constant<bool, bool(!P::value)> {}; template <typename...> struct conjunction : std::true_type {}; template <typename P1> struct conjunction<P1> : P1 {}; template <typename P1, typename... Ps> struct conjunction<P1, Ps...> : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {}; template <typename...> struct disjunction : std::false_type {}; template <typename P1> struct disjunction<P1> : P1 {}; template <typename P1, typename... Ps> struct disjunction<P1, Ps...> : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {}; template <typename...> using void_t = void; template <typename From, typename To> struct is_implicitly_convertible { private: template <typename T> static void Accept(T); template <typename T> static T Make(); template <typename T, typename = decltype(Accept<To>(Make<T>()))> static std::true_type TestImplicitConversion(int); template <typename T> static std::false_type TestImplicitConversion(...); public: using type = decltype(TestImplicitConversion<From>(0)); static constexpr bool value = type::value; }; template <typename F, typename... Args> using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...)); template <typename Void, typename R, typename F, typename... Args> struct is_callable_r_impl : std::false_type {}; template <typename R, typename F, typename... Args> struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...> : std::conditional< std::is_void<R>::value, std::true_type, is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {}; template <typename R, typename F, typename... Args> using is_callable_r = is_callable_r_impl<void, R, F, Args...>; template <typename T> typename std::add_const<T>::type& as_const(T& t) { return t; } } template <typename F> class OnceAction; template <typename Result, typename... Args> class OnceAction<Result(Args...)> final { private: template <typename Callable> using IsDirectlyCompatible = internal::conjunction< std::is_constructible<typename std::decay<Callable>::type, Callable>, internal::is_callable_r<Result, typename std::decay<Callable>::type, Args...>>; template <typename Callable> using IsCompatibleAfterIgnoringArguments = internal::conjunction< std::is_constructible<typename std::decay<Callable>::type, Callable>, internal::is_callable_r<Result, typename std::decay<Callable>::type>>; public: template <typename Callable, typename std::enable_if< internal::conjunction< internal::negation<std::is_same< OnceAction, typename std::decay<Callable>::type>>, IsDirectlyCompatible<Callable>> ::value, int>::type = 0> OnceAction(Callable&& callable) : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>( {}, std::forward<Callable>(callable))) {} template <typename Callable, typename std::enable_if< internal::conjunction< internal::negation<std::is_same< OnceAction, typename std::decay<Callable>::type>>, internal::negation<IsDirectlyCompatible<Callable>>, IsCompatibleAfterIgnoringArguments<Callable>>::value, int>::type = 0> OnceAction(Callable&& callable) : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{ std::forward<Callable>(callable)}) {} OnceAction(const OnceAction&) = delete; OnceAction& operator=(const OnceAction&) = delete; OnceAction(OnceAction&&) = default; Result Call(Args... args) && { return function_(std::forward<Args>(args)...); } private: template <typename Callable> class StdFunctionAdaptor final { public: struct CallableTag final {}; template <typename F> explicit StdFunctionAdaptor(CallableTag, F&& callable) : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {} template <typename... ArgRefs> internal::call_result_t<Callable, ArgRefs...> operator()( ArgRefs&&... args) const { return std::move(*callable_)(std::forward<ArgRefs>(args)...); } private: std::shared_ptr<Callable> callable_; }; template <typename Callable> struct IgnoreIncomingArguments { internal::call_result_t<Callable> operator()(Args&&...) { return std::move(callable)(); } Callable callable; }; std::function<Result(Args...)> function_; }; template <typename T> class DefaultValue { public: static void Set(T x) { delete producer_; producer_ = new FixedValueProducer(x); } typedef T (*FactoryFunction)(); static void SetFactory(FactoryFunction factory) { delete producer_; producer_ = new FactoryValueProducer(factory); } static void Clear() { delete producer_; producer_ = nullptr; } static bool IsSet() { return producer_ != nullptr; } static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); } static T Get() { return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get() : producer_->Produce(); } private: class ValueProducer { public: virtual ~ValueProducer() = default; virtual T Produce() = 0; }; class FixedValueProducer : public ValueProducer { public: explicit FixedValueProducer(T value) : value_(value) {} T Produce() override { return value_; } private: const T value_; FixedValueProducer(const FixedValueProducer&) = delete; FixedValueProducer& operator=(const FixedValueProducer&) = delete; }; class FactoryValueProducer : public ValueProducer { public: explicit FactoryValueProducer(FactoryFunction factory) : factory_(factory) {} T Produce() override { return factory_(); } private: const FactoryFunction factory_; FactoryValueProducer(const FactoryValueProducer&) = delete; FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; }; static ValueProducer* producer_; }; template <typename T> class DefaultValue<T&> { public: static void Set(T& x) { address_ = &x; } static void Clear() { address_ = nullptr; } static bool IsSet() { return address_ != nullptr; } static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); } static T& Get() { return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get() : *address_; } private: static T* address_; }; template <> class DefaultValue<void> { public: static bool Exists() { return true; } static void Get() {} }; template <typename T> typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr; template <typename T> T* DefaultValue<T&>::address_ = nullptr; template <typename F> class ActionInterface { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; ActionInterface() = default; virtual ~ActionInterface() = default; virtual Result Perform(const ArgumentTuple& args) = 0; private: ActionInterface(const ActionInterface&) = delete; ActionInterface& operator=(const ActionInterface&) = delete; }; template <typename F> class Action; template <typename R, typename... Args> class Action<R(Args...)> { private: using F = R(Args...); struct ActionAdapter { ::std::shared_ptr<ActionInterface<F>> impl_; template <typename... InArgs> typename internal::Function<F>::Result operator()(InArgs&&... args) { return impl_->Perform( ::std::forward_as_tuple(::std::forward<InArgs>(args)...)); } }; template <typename G> using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>; public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; Action() = default; template < typename G, typename = typename std::enable_if<internal::disjunction< IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>, G>>::value>::type> Action(G&& fun) { Init(::std::forward<G>(fun), IsCompatibleFunctor<G>()); } explicit Action(ActionInterface<F>* impl) : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {} template <typename Func> Action(const Action<Func>& action) : fun_(action.fun_) {} bool IsDoDefault() const { return fun_ == nullptr; } Result Perform(ArgumentTuple args) const { if (IsDoDefault()) { internal::IllegalDoDefault(__FILE__, __LINE__); } return internal::Apply(fun_, ::std::move(args)); } operator OnceAction<F>() const { struct OA { Action<F> action; R operator()(Args... args) && { return action.Perform( std::forward_as_tuple(std::forward<Args>(args)...)); } }; return OA{*this}; } private: template <typename G> friend class Action; template <typename G> void Init(G&& g, ::std::true_type) { fun_ = ::std::forward<G>(g); } template <typename G> void Init(G&& g, ::std::false_type) { fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)}; } template <typename FunctionImpl> struct IgnoreArgs { template <typename... InArgs> Result operator()(const InArgs&...) const { return function_impl(); } FunctionImpl function_impl; }; ::std::function<F> fun_; }; template <typename Impl> class PolymorphicAction { public: explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} template <typename F> operator Action<F>() const { return Action<F>(new MonomorphicImpl<F>(impl_)); } private: template <typename F> class MonomorphicImpl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} Result Perform(const ArgumentTuple& args) override { return impl_.template Perform<Result>(args); } private: Impl impl_; }; Impl impl_; }; template <typename F> Action<F> MakeAction(ActionInterface<F>* impl) { return Action<F>(impl); } template <typename Impl> inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) { return PolymorphicAction<Impl>(impl); } namespace internal { template <typename T> struct ByMoveWrapper { explicit ByMoveWrapper(T value) : payload(std::move(value)) {} T payload; }; template <typename R> class ReturnAction final { public: explicit ReturnAction(R value) : value_(std::move(value)) {} template <typename U, typename... Args, typename = typename std::enable_if<conjunction< negation<std::is_same<void, U>>, negation<std::is_reference<U>>, std::is_convertible<R, U>, std::is_move_constructible<U>>::value>::type> operator OnceAction<U(Args...)>() && { return Impl<U>(std::move(value_)); } template <typename U, typename... Args, typename = typename std::enable_if<conjunction< negation<std::is_same<void, U>>, negation<std::is_reference<U>>, std::is_convertible<const R&, U>, std::is_copy_constructible<U>>::value>::type> operator Action<U(Args...)>() const { return Impl<U>(value_); } private: template <typename U> class Impl final { public: explicit Impl(R&& input_value) : state_(new State(std::move(input_value))) {} explicit Impl(const R& input_value) : state_(new State(input_value)) {} U operator()() && { return std::move(state_->value); } U operator()() const& { return state_->value; } private: struct State { explicit State(const R& input_value_in) : input_value(input_value_in), value(ImplicitCast_<U>(internal::as_const(input_value))) {} explicit State(R&& input_value_in) : input_value(std::move(input_value_in)), value(ImplicitCast_<U>(std::move(input_value))) {} R input_value; U value; }; const std::shared_ptr<State> state_; }; R value_; }; template <typename T> class ReturnAction<ByMoveWrapper<T>> final { public: explicit ReturnAction(ByMoveWrapper<T> wrapper) : state_(new State(std::move(wrapper.payload))) {} T operator()() const { GTEST_CHECK_(!state_->called) << "A ByMove() action must be performed at most once."; state_->called = true; return std::move(state_->value); } private: struct State { explicit State(T&& value_in) : value(std::move(value_in)) {} T value; bool called = false; }; const std::shared_ptr<State> state_; }; class ReturnNullAction { public: template <typename Result, typename ArgumentTuple> static Result Perform(const ArgumentTuple&) { return nullptr; } }; class ReturnVoidAction { public: template <typename Result, typename ArgumentTuple> static void Perform(const ArgumentTuple&) { static_assert(std::is_void<Result>::value, "Result should be void."); } }; template <typename T> class ReturnRefAction { public: explicit ReturnRefAction(T& ref) : ref_(ref) {} template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; static_assert(std::is_reference<Result>::value, "use Return instead of ReturnRef to return a value"); return Action<F>(new Impl<F>(ref_)); } private: template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(T& ref) : ref_(ref) {} Result Perform(const ArgumentTuple&) override { return ref_; } private: T& ref_; }; T& ref_; }; template <typename T> class ReturnRefOfCopyAction { public: explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; static_assert(std::is_reference<Result>::value, "use Return instead of ReturnRefOfCopy to return a value"); return Action<F>(new Impl<F>(value_)); } private: template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const T& value) : value_(value) {} Result Perform(const ArgumentTuple&) override { return value_; } private: T value_; }; const T value_; }; template <typename T> class ReturnRoundRobinAction { public: explicit ReturnRoundRobinAction(std::vector<T> values) { GTEST_CHECK_(!values.empty()) << "ReturnRoundRobin requires at least one element."; state_->values = std::move(values); } template <typename... Args> T operator()(Args&&...) const { return state_->Next(); } private: struct State { T Next() { T ret_val = values[i++]; if (i == values.size()) i = 0; return ret_val; } std::vector<T> values; size_t i = 0; }; std::shared_ptr<State> state_ = std::make_shared<State>(); }; class DoDefaultAction { public: template <typename F> operator Action<F>() const { return Action<F>(); } }; template <typename T1, typename T2> class AssignAction { public: AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& ) const { *ptr_ = value_; } private: T1* const ptr_; const T2 value_; }; #ifndef GTEST_OS_WINDOWS_MOBILE template <typename T> class SetErrnoAndReturnAction { public: SetErrnoAndReturnAction(int errno_value, T result) : errno_(errno_value), result_(result) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& ) const { errno = errno_; return result_; } private: const int errno_; const T result_; }; #endif template <size_t N, typename A, typename = void> struct SetArgumentPointeeAction { A value; template <typename... Args> void operator()(const Args&... args) const { *::std::get<N>(std::tie(args...)) = value; } }; template <class Class, typename MethodPtr> struct InvokeMethodAction { Class* const obj_ptr; const MethodPtr method_ptr; template <typename... Args> auto operator()(Args&&... args) const -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) { return (obj_ptr->*method_ptr)(std::forward<Args>(args)...); } }; template <typename FunctionImpl> struct InvokeWithoutArgsAction { FunctionImpl function_impl; template <typename... Args> auto operator()(const Args&...) -> decltype(function_impl()) { return function_impl(); } }; template <class Class, typename MethodPtr> struct InvokeMethodWithoutArgsAction { Class* const obj_ptr; const MethodPtr method_ptr; using ReturnType = decltype((std::declval<Class*>()->*std::declval<MethodPtr>())()); template <typename... Args> ReturnType operator()(const Args&...) const { return (obj_ptr->*method_ptr)(); } }; template <typename A> class IgnoreResultAction { public: explicit IgnoreResultAction(const A& action) : action_(action) {} template <typename F> operator Action<F>() const { typedef typename internal::Function<F>::Result Result; static_assert(std::is_void<Result>::value, "Result type should be void."); return Action<F>(new Impl<F>(action_)); } private: template <typename F> class Impl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const A& action) : action_(action) {} void Perform(const ArgumentTuple& args) override { action_.Perform(args); } private: typedef typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction; const Action<OriginalFunction> action_; }; const A action_; }; template <typename InnerAction, size_t... I> struct WithArgsAction { InnerAction inner_action; template <typename R, typename... Args> using InnerSignature = R(typename std::tuple_element<I, std::tuple<Args...>>::type...); template < typename R, typename... Args, typename std::enable_if< std::is_convertible<InnerAction, OnceAction<R(internal::TupleElement< I, std::tuple<Args...>>...)>>::value, int>::type = 0> operator OnceAction<R(Args...)>() && { struct OA { OnceAction<InnerSignature<R, Args...>> inner_action; R operator()(Args&&... args) && { return std::move(inner_action) .Call(std::get<I>( std::forward_as_tuple(std::forward<Args>(args)...))...); } }; return OA{std::move(inner_action)}; } template < typename R, typename... Args, typename std::enable_if< std::is_convertible<const InnerAction&, Action<R(internal::TupleElement< I, std::tuple<Args...>>...)>>::value, int>::type = 0> operator Action<R(Args...)>() const { Action<InnerSignature<R, Args...>> converted(inner_action); return [converted](Args&&... args) -> R { return converted.Perform(std::forward_as_tuple( std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...)); }; } }; template <typename... Actions> class DoAllAction; template <typename FinalAction> class DoAllAction<FinalAction> { public: struct UserConstructorTag {}; template <typename T> explicit DoAllAction(UserConstructorTag, T&& action) : final_action_(std::forward<T>(action)) {} template <typename R, typename... Args, typename std::enable_if< std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value, int>::type = 0> operator OnceAction<R(Args...)>() && { return std::move(final_action_); } template < typename R, typename... Args, typename std::enable_if< conjunction< negation< std::is_convertible<FinalAction, OnceAction<R(Args...)>>>, std::is_convertible<FinalAction, Action<R(Args...)>>>::value, int>::type = 0> operator OnceAction<R(Args...)>() && { return Action<R(Args...)>(std::move(final_action_)); } template < typename R, typename... Args, typename std::enable_if< std::is_convertible<const FinalAction&, Action<R(Args...)>>::value, int>::type = 0> operator Action<R(Args...)>() const { return final_action_; } private: FinalAction final_action_; }; template <typename InitialAction, typename... OtherActions> class DoAllAction<InitialAction, OtherActions...> : private DoAllAction<OtherActions...> { private: using Base = DoAllAction<OtherActions...>; template <typename T> using InitialActionArgType = typename std::conditional<std::is_scalar<T>::value, T, const T&>::type; public: struct UserConstructorTag {}; template <typename T, typename... U> explicit DoAllAction(UserConstructorTag, T&& initial_action, U&&... other_actions) : Base({}, std::forward<U>(other_actions)...), initial_action_(std::forward<T>(initial_action)) {} template < typename R, typename... Args, typename std::enable_if< conjunction<std::is_convertible< InitialAction, OnceAction<void(InitialActionArgType<Args>...)>>, std::is_convertible<Base, OnceAction<R(Args...)>>>::value, int>::type = 0> operator OnceAction<R(Args...)>() && { struct OA { OnceAction<void(InitialActionArgType<Args>...)> initial_action; OnceAction<R(Args...)> remaining_actions; R operator()(Args... args) && { std::move(initial_action) .Call(static_cast<InitialActionArgType<Args>>(args)...); return std::move(remaining_actions).Call(std::forward<Args>(args)...); } }; return OA{ std::move(initial_action_), std::move(static_cast<Base&>(*this)), }; } template < typename R, typename... Args, typename std::enable_if< conjunction< negation<std::is_convertible< InitialAction, OnceAction<void(InitialActionArgType<Args>...)>>>, std::is_convertible<InitialAction, Action<void(InitialActionArgType<Args>...)>>, std::is_convertible<Base, OnceAction<R(Args...)>>>::value, int>::type = 0> operator OnceAction<R(Args...)>() && { return DoAll( Action<void(InitialActionArgType<Args>...)>(std::move(initial_action_)), std::move(static_cast<Base&>(*this))); } template < typename R, typename... Args, typename std::enable_if< conjunction< std::is_convertible<const InitialAction&, Action<void(InitialActionArgType<Args>...)>>, std::is_convertible<const Base&, Action<R(Args...)>>>::value, int>::type = 0> operator Action<R(Args...)>() const { struct OA { Action<void(InitialActionArgType<Args>...)> initial_action; Action<R(Args...)> remaining_actions; R operator()(Args... args) const { initial_action.Perform(std::forward_as_tuple( static_cast<InitialActionArgType<Args>>(args)...)); return remaining_actions.Perform( std::forward_as_tuple(std::forward<Args>(args)...)); } }; return OA{ initial_action_, static_cast<const Base&>(*this), }; } private: InitialAction initial_action_; }; template <typename T, typename... Params> struct ReturnNewAction { T* operator()() const { return internal::Apply( [](const Params&... unpacked_params) { return new T(unpacked_params...); }, params); } std::tuple<Params...> params; }; template <size_t k> struct ReturnArgAction { template <typename... Args, typename = typename std::enable_if<(k < sizeof...(Args))>::type> auto operator()(Args&&... args) const -> decltype(std::get<k>( std::forward_as_tuple(std::forward<Args>(args)...))) { return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...)); } }; template <size_t k, typename Ptr> struct SaveArgAction { Ptr pointer; template <typename... Args> void operator()(const Args&... args) const { *pointer = std::get<k>(std::tie(args...)); } }; template <size_t k, typename Ptr> struct SaveArgPointeeAction { Ptr pointer; template <typename... Args> void operator()(const Args&... args) const { *pointer = *std::get<k>(std::tie(args...)); } }; template <size_t k, typename T> struct SetArgRefereeAction { T value; template <typename... Args> void operator()(Args&&... args) const { using argk_type = typename ::std::tuple_element<k, std::tuple<Args...>>::type; static_assert(std::is_lvalue_reference<argk_type>::value, "Argument must be a reference type."); std::get<k>(std::tie(args...)) = value; } }; template <size_t k, typename I1, typename I2> struct SetArrayArgumentAction { I1 first; I2 last; template <typename... Args> void operator()(const Args&... args) const { auto value = std::get<k>(std::tie(args...)); for (auto it = first; it != last; ++it, (void)++value) { *value = *it; } } }; template <size_t k> struct DeleteArgAction { template <typename... Args> void operator()(const Args&... args) const { delete std::get<k>(std::tie(args...)); } }; template <typename Ptr> struct ReturnPointeeAction { Ptr pointer; template <typename... Args> auto operator()(const Args&...) const -> decltype(*pointer) { return *pointer; } }; #if GTEST_HAS_EXCEPTIONS template <typename T> struct ThrowAction { T exception; template <typename R, typename... Args> operator Action<R(Args...)>() const { T copy = exception; return [copy](Args...) -> R { throw copy; }; } }; struct RethrowAction { std::exception_ptr exception; template <typename R, typename... Args> operator Action<R(Args...)>() const { return [ex = exception](Args...) -> R { std::rethrow_exception(ex); }; } }; #endif } typedef internal::IgnoredValue Unused; template <typename... Action> internal::DoAllAction<typename std::decay<Action>::type...> DoAll( Action&&... action) { return internal::DoAllAction<typename std::decay<Action>::type...>( {}, std::forward<Action>(action)...); } template <size_t k, typename InnerAction> internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg( InnerAction&& action) { return {std::forward<InnerAction>(action)}; } template <size_t k, size_t... ks, typename InnerAction> internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...> WithArgs(InnerAction&& action) { return {std::forward<InnerAction>(action)}; } template <typename InnerAction> internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs( InnerAction&& action) { return {std::forward<InnerAction>(action)}; } template <typename R> internal::ReturnAction<R> Return(R value) { return internal::ReturnAction<R>(std::move(value)); } inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() { return MakePolymorphicAction(internal::ReturnNullAction()); } inline PolymorphicAction<internal::ReturnVoidAction> Return() { return MakePolymorphicAction(internal::ReturnVoidAction()); } template <typename R> inline internal::ReturnRefAction<R> ReturnRef(R& x) { return internal::ReturnRefAction<R>(x); } template <typename R, R* = nullptr> internal::ReturnRefAction<R> ReturnRef(R&&) = delete; template <typename R> inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) { return internal::ReturnRefOfCopyAction<R>(x); } template <typename R> internal::ByMoveWrapper<R> ByMove(R x) { return internal::ByMoveWrapper<R>(std::move(x)); } template <typename T> internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) { return internal::ReturnRoundRobinAction<T>(std::move(vals)); } template <typename T> internal::ReturnRoundRobinAction<T> ReturnRoundRobin( std::initializer_list<T> vals) { return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals)); } inline internal::DoDefaultAction DoDefault() { return internal::DoDefaultAction(); } template <size_t N, typename T> internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) { return {std::move(value)}; } template <size_t N, typename T> internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) { return {std::move(value)}; } template <typename T1, typename T2> PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) { return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); } #ifndef GTEST_OS_WINDOWS_MOBILE template <typename T> PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn( int errval, T result) { return MakePolymorphicAction( internal::SetErrnoAndReturnAction<T>(errval, result)); } #endif template <typename FunctionImpl> typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) { return std::forward<FunctionImpl>(function_impl); } template <class Class, typename MethodPtr> internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr, MethodPtr method_ptr) { return {obj_ptr, method_ptr}; } template <typename FunctionImpl> internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type> InvokeWithoutArgs(FunctionImpl function_impl) { return {std::move(function_impl)}; } template <class Class, typename MethodPtr> internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs( Class* obj_ptr, MethodPtr method_ptr) { return {obj_ptr, method_ptr}; } template <typename A> inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) { return internal::IgnoreResultAction<A>(an_action); } template <typename T> inline ::std::reference_wrapper<T> ByRef(T& l_value) { return ::std::reference_wrapper<T>(l_value); } template <typename T, typename... Params> internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew( Params&&... params) { return {std::forward_as_tuple(std::forward<Params>(params)...)}; } template <size_t k> internal::ReturnArgAction<k> ReturnArg() { return {}; } template <size_t k, typename Ptr> internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) { return {pointer}; } template <size_t k, typename Ptr> internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) { return {pointer}; } template <size_t k, typename T> internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee( T&& value) { return {std::forward<T>(value)}; } template <size_t k, typename I1, typename I2> internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first, I2 last) { return {first, last}; } template <size_t k> internal::DeleteArgAction<k> DeleteArg() { return {}; } template <typename Ptr> internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) { return {pointer}; } #if GTEST_HAS_EXCEPTIONS template <typename T> typename std::enable_if< !std::is_base_of<std::exception_ptr, typename std::decay<T>::type>::value, internal::ThrowAction<typename std::decay<T>::type>>::type Throw(T&& exception) { return {std::forward<T>(exception)}; } inline internal::RethrowAction Rethrow(std::exception_ptr exception) { return {std::move(exception)}; } #endif namespace internal { struct ExcessiveArg {}; template <typename F, typename Impl> struct ActionImpl; template <typename Impl> struct ImplBase { struct Holder { explicit operator const Impl&() const { return *ptr; } std::shared_ptr<Impl> ptr; }; using type = typename std::conditional<std::is_constructible<Impl>::value, Impl, Holder>::type; }; template <typename R, typename... Args, typename Impl> struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type { using Base = typename ImplBase<Impl>::type; using function_type = R(Args...); using args_type = std::tuple<Args...>; ActionImpl() = default; explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {} R operator()(Args&&... arg) const { static constexpr size_t kMaxArgs = sizeof...(Args) <= 10 ? sizeof...(Args) : 10; return Apply(std::make_index_sequence<kMaxArgs>{}, std::make_index_sequence<10 - kMaxArgs>{}, args_type{std::forward<Args>(arg)...}); } template <std::size_t... arg_id, std::size_t... excess_id> R Apply(std::index_sequence<arg_id...>, std::index_sequence<excess_id...>, const args_type& args) const { static constexpr ExcessiveArg kExcessArg{}; return static_cast<const Impl&>(*this) .template gmock_PerformImpl< function_type, R, args_type, typename std::tuple_element<arg_id, args_type>::type...>( args, std::get<arg_id>(args)..., ((void)excess_id, kExcessArg)...); } }; template <typename F, typename Impl> ::testing::Action<F> MakeAction() { return ::testing::Action<F>(ActionImpl<F, Impl>()); } template <typename F, typename Impl> ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) { return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl))); } #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ , GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const arg##i##_type& arg##i #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED const args_type& args GMOCK_PP_REPEAT( \ GMOCK_INTERNAL_ARG_UNUSED, , 10) #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type #define GMOCK_ACTION_TYPE_PARAMS_(params) \ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ , param##_type gmock_p##i #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ , std::forward<param##_type>(gmock_p##i) #define GMOCK_ACTION_GVALUE_PARAMS_(params) \ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ , param(::std::forward<param##_type>(gmock_p##i)) #define GMOCK_ACTION_INIT_PARAMS_(params) \ GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; #define GMOCK_ACTION_FIELD_PARAMS_(params) \ GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) #define GMOCK_INTERNAL_ACTION(name, full_name, params) \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ class full_name { \ public: \ explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ : impl_(std::make_shared<gmock_Impl>( \ GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ full_name(const full_name&) = default; \ full_name(full_name&&) noexcept = default; \ template <typename F> \ operator ::testing::Action<F>() const { \ return ::testing::internal::MakeAction<F>(impl_); \ } \ \ private: \ class gmock_Impl { \ public: \ explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ : GMOCK_ACTION_INIT_PARAMS_(params) {} \ template <typename function_type, typename return_type, \ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ GMOCK_ACTION_FIELD_PARAMS_(params) \ }; \ std::shared_ptr<const gmock_Impl> impl_; \ }; \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \ GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \ GMOCK_ACTION_GVALUE_PARAMS_(params)); \ } \ template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \ template <typename function_type, typename return_type, typename args_type, \ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ return_type \ full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const } #define ACTION(name) \ class name##Action { \ public: \ explicit name##Action() noexcept {} \ name##Action(const name##Action&) noexcept {} \ template <typename F> \ operator ::testing::Action<F>() const { \ return ::testing::internal::MakeAction<F, gmock_Impl>(); \ } \ \ private: \ class gmock_Impl { \ public: \ template <typename function_type, typename return_type, \ typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ }; \ }; \ inline name##Action name() GTEST_MUST_USE_RESULT_; \ inline name##Action name() { return name##Action(); } \ template <typename function_type, typename return_type, typename args_type, \ GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \ return_type name##Action::gmock_Impl::gmock_PerformImpl( \ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) #define ACTION_P2(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) #define ACTION_P3(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) #define ACTION_P4(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) #define ACTION_P5(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) #define ACTION_P6(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) #define ACTION_P7(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) #define ACTION_P8(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) #define ACTION_P9(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) #define ACTION_P10(name, ...) \ GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) } GTEST_DISABLE_MSC_WARNINGS_POP_() #endif
#include "gmock/gmock-actions.h" #include <algorithm> #include <functional> #include <iterator> #include <memory> #include <sstream> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "gtest/internal/gtest-port.h" GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100 4503) #if defined(_MSC_VER) && (_MSC_VER == 1900) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800) #endif namespace testing { namespace { using ::testing::internal::BuiltInDefaultValue; TEST(TypeTraits, Negation) { static_assert(std::is_base_of<std::false_type, internal::negation<std::true_type>>::value, ""); static_assert(std::is_base_of<std::true_type, internal::negation<std::false_type>>::value, ""); static_assert(std::is_base_of< std::true_type, internal::negation<std::integral_constant<int, 0>>>::value, ""); static_assert(std::is_base_of< std::false_type, internal::negation<std::integral_constant<int, 1>>>::value, ""); static_assert(std::is_base_of< std::false_type, internal::negation<std::integral_constant<int, -1>>>::value, ""); } template <int> struct MyFalse : std::integral_constant<int, 0> {}; template <int> struct MyTrue : std::integral_constant<int, -1> {}; TEST(TypeTraits, Conjunction) { static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value, ""); static_assert( std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value, ""); static_assert( std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, ""); static_assert( std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, MyTrue<2>>>::value, ""); static_assert( std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, MyFalse<2>>>::value, ""); struct Empty {}; static_assert( std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>, Empty>>::value, ""); static_assert( std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>, MyTrue<2>>>::value, ""); } TEST(TypeTraits, Disjunction) { static_assert( std::is_base_of<std::false_type, internal::disjunction<>>::value, ""); static_assert( std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value, ""); static_assert( std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, ""); static_assert( std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, MyFalse<2>>>::value, ""); static_assert( std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, MyTrue<2>>>::value, ""); struct Empty {}; static_assert( std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>, Empty>>::value, ""); static_assert( std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>, MyFalse<2>>>::value, ""); } TEST(TypeTraits, IsInvocableRV) { struct C { int operator()() const { return 0; } void operator()(int) & {} std::string operator()(int) && { return ""; }; }; static_assert(internal::is_callable_r<int, C>::value, ""); static_assert(internal::is_callable_r<int, C&>::value, ""); static_assert(internal::is_callable_r<int, const C>::value, ""); static_assert(internal::is_callable_r<int, const C&>::value, ""); static_assert(internal::is_callable_r<void, C>::value, ""); static_assert(internal::is_callable_r<const volatile void, C>::value, ""); static_assert(internal::is_callable_r<char, C>::value, ""); static_assert(internal::is_callable_r<void, C&, int>::value, ""); static_assert(!internal::is_callable_r<int, C&, int>::value, ""); static_assert(!internal::is_callable_r<std::string, C&, int>::value, ""); static_assert(!internal::is_callable_r<void, const C&, int>::value, ""); static_assert(internal::is_callable_r<std::string, C, int>::value, ""); static_assert(internal::is_callable_r<void, C, int>::value, ""); static_assert(!internal::is_callable_r<int, C, int>::value, ""); static_assert(!internal::is_callable_r<void, C, std::string>::value, ""); static_assert(!internal::is_callable_r<void, C, int, int>::value, ""); #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \ GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L { struct NonMoveable { NonMoveable() = default; NonMoveable(NonMoveable&&) = delete; }; static_assert(!std::is_move_constructible_v<NonMoveable>); struct Callable { NonMoveable operator()() { return NonMoveable(); } }; static_assert(internal::is_callable_r<NonMoveable, Callable>::value); static_assert(internal::is_callable_r<void, Callable>::value); static_assert( internal::is_callable_r<const volatile void, Callable>::value); static_assert(!internal::is_callable_r<int, Callable>::value); static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value); } #endif static_assert(!internal::is_callable_r<void, int>::value, ""); static_assert(!internal::is_callable_r<void, void (C::*)()>::value, ""); static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, ""); } TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr); EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr); } TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists()); } TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) { EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<char>::Get()); #if GMOCK_WCHAR_T_IS_NATIVE_ #if !defined(__WCHAR_UNSIGNED__) EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get()); #else EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get()); #endif #endif EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<int>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<float>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<double>::Get()); } TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) { EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<char>::Exists()); #if GMOCK_WCHAR_T_IS_NATIVE_ EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists()); #endif EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<int>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<float>::Exists()); EXPECT_TRUE(BuiltInDefaultValue<double>::Exists()); } TEST(BuiltInDefaultValueTest, IsFalseForBool) { EXPECT_FALSE(BuiltInDefaultValue<bool>::Get()); } TEST(BuiltInDefaultValueTest, BoolExists) { EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists()); } TEST(BuiltInDefaultValueTest, IsEmptyStringForString) { EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get()); } TEST(BuiltInDefaultValueTest, ExistsForString) { EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists()); } TEST(BuiltInDefaultValueTest, WorksForConstTypes) { EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get()); EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get()); EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr); EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get()); } class MyDefaultConstructible { public: MyDefaultConstructible() : value_(42) {} int value() const { return value_; } private: int value_; }; class MyNonDefaultConstructible { public: explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {} int value() const { return value_; } private: int value_; }; TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) { EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists()); } TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) { EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value()); } TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) { EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists()); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) { EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, ""); } TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) { EXPECT_DEATH_IF_SUPPORTED( { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } TEST(DefaultValueTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); } TEST(DefaultValueTest, CanBeSetAndUnset) { EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); DefaultValue<int>::Set(1); DefaultValue<const MyNonDefaultConstructible>::Set( MyNonDefaultConstructible(42)); EXPECT_EQ(1, DefaultValue<int>::Get()); EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists()); DefaultValue<int>::Clear(); DefaultValue<const MyNonDefaultConstructible>::Clear(); EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists()); } TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int>::IsSet()); EXPECT_TRUE(DefaultValue<int>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists()); EXPECT_EQ(0, DefaultValue<int>::Get()); EXPECT_DEATH_IF_SUPPORTED( { DefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) { EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr); DefaultValue<std::unique_ptr<int>>::SetFactory( [] { return std::make_unique<int>(42); }); EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists()); std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get(); EXPECT_EQ(42, *i); } TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); } TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); } TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) { EXPECT_FALSE(DefaultValue<int&>::Exists()); EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); } TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) { int n = 1; DefaultValue<const int&>::Set(n); MyNonDefaultConstructible x(42); DefaultValue<MyNonDefaultConstructible&>::Set(x); EXPECT_TRUE(DefaultValue<const int&>::Exists()); EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists()); EXPECT_EQ(&n, &(DefaultValue<const int&>::Get())); EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get())); DefaultValue<const int&>::Clear(); DefaultValue<MyNonDefaultConstructible&>::Clear(); EXPECT_FALSE(DefaultValue<const int&>::Exists()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists()); EXPECT_FALSE(DefaultValue<const int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); } TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) { EXPECT_FALSE(DefaultValue<int&>::IsSet()); EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet()); EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, ""); EXPECT_DEATH_IF_SUPPORTED( { DefaultValue<MyNonDefaultConstructible>::Get(); }, ""); } typedef int MyGlobalFunction(bool, int); class MyActionImpl : public ActionInterface<MyGlobalFunction> { public: int Perform(const std::tuple<bool, int>& args) override { return std::get<0>(args) ? std::get<1>(args) : 0; } }; TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) { MyActionImpl my_action_impl; (void)my_action_impl; } TEST(ActionInterfaceTest, MakeAction) { Action<MyGlobalFunction> action = MakeAction(new MyActionImpl); EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); } TEST(ActionTest, CanBeConstructedFromActionInterface) { Action<MyGlobalFunction> action(new MyActionImpl); } TEST(ActionTest, DelegatesWorkToActionInterface) { const Action<MyGlobalFunction> action(new MyActionImpl); EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1))); } TEST(ActionTest, IsCopyable) { Action<MyGlobalFunction> a1(new MyActionImpl); Action<MyGlobalFunction> a2(a1); EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); a2 = a1; EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1))); EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1))); } class IsNotZero : public ActionInterface<bool(int)> { public: bool Perform(const std::tuple<int>& arg) override { return std::get<0>(arg) != 0; } }; TEST(ActionTest, CanBeConvertedToOtherActionType) { const Action<bool(int)> a1(new IsNotZero); const Action<int(char)> a2 = Action<int(char)>(a1); EXPECT_EQ(1, a2.Perform(std::make_tuple('a'))); EXPECT_EQ(0, a2.Perform(std::make_tuple('\0'))); } class ReturnSecondArgumentAction { public: template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& args) { return std::get<1>(args); } }; class ReturnZeroFromNullaryFunctionAction { public: template <typename Result> Result Perform(const std::tuple<>&) const { return 0; } }; PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { return MakePolymorphicAction(ReturnSecondArgumentAction()); } PolymorphicAction<ReturnZeroFromNullaryFunctionAction> ReturnZeroFromNullaryFunction() { return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction()); } TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) { Action<int(bool, int, double)> a1 = ReturnSecondArgument(); EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0))); } TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) { Action<int()> a1 = ReturnZeroFromNullaryFunction(); EXPECT_EQ(0, a1.Perform(std::make_tuple())); Action<void*()> a2 = ReturnZeroFromNullaryFunction(); EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr); } TEST(ReturnTest, WorksForVoid) { const Action<void(int)> ret = Return(); return ret.Perform(std::make_tuple(1)); } TEST(ReturnTest, ReturnsGivenValue) { Action<int()> ret = Return(1); EXPECT_EQ(1, ret.Perform(std::make_tuple())); ret = Return(-5); EXPECT_EQ(-5, ret.Perform(std::make_tuple())); } TEST(ReturnTest, AcceptsStringLiteral) { Action<const char*()> a1 = Return("Hello"); EXPECT_STREQ("Hello", a1.Perform(std::make_tuple())); Action<std::string()> a2 = Return("world"); EXPECT_EQ("world", a2.Perform(std::make_tuple())); } TEST(ReturnTest, SupportsReferenceLikeReturnType) { struct Result { const std::vector<int>* v; Result(const std::vector<int>& vec) : v(&vec) {} }; MockFunction<Result()> mock; EXPECT_CALL(mock, Call) .WillOnce(Return(std::vector<int>{17, 19, 23})) .WillRepeatedly(Return(std::vector<int>{29, 31, 37})); EXPECT_THAT(mock.AsStdFunction()(), Field(&Result::v, Pointee(ElementsAre(17, 19, 23)))); EXPECT_THAT(mock.AsStdFunction()(), Field(&Result::v, Pointee(ElementsAre(29, 31, 37)))); } TEST(ReturnTest, PrefersConversionOperator) { struct In; struct Out { int x; explicit Out(const int val) : x(val) {} explicit Out(const In&) : x(0) {} }; struct In { operator Out() const { return Out{19}; } }; EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19)); MockFunction<Out()> mock; EXPECT_CALL(mock, Call).WillOnce(Return(In())); EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19)); } TEST(ReturnTest, ConversionRequiresConstLvalueReference) { using R = int; using U = std::reference_wrapper<const int>; static_assert(std::is_convertible<const R&, U>::value, ""); static_assert(!std::is_convertible<R, U>::value, ""); MockFunction<U()> mock; EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19)); EXPECT_EQ(17, mock.AsStdFunction()()); EXPECT_EQ(19, mock.AsStdFunction()()); } TEST(ReturnTest, ConversionRequiresMutableLvalueReference) { struct S { S(std::string&) {} }; static_assert(std::is_convertible<std::string&, S>::value, ""); #ifndef _MSC_VER static_assert(!std::is_convertible<std::string&&, S>::value, ""); #endif static_assert(!std::is_convertible<const std::string&, S>::value, ""); using RA = decltype(Return(std::string())); static_assert(!std::is_convertible<RA, Action<S()>>::value, ""); #ifndef _MSC_VER static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, ""); #endif } TEST(ReturnTest, MoveOnlyResultType) { { MockFunction<std::unique_ptr<int>()> mock; EXPECT_CALL(mock, Call) .WillOnce(Return(std::unique_ptr<int>(new int(17)))); EXPECT_THAT(mock.AsStdFunction()(), Pointee(17)); } static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())), Action<std::unique_ptr<int>()>>::value, ""); } struct Base { bool operator==(const Base&) { return true; } }; struct Derived : public Base { bool operator==(const Derived&) { return true; } }; TEST(ReturnTest, IsCovariant) { Base base; Derived derived; Action<Base*()> ret = Return(&base); EXPECT_EQ(&base, ret.Perform(std::make_tuple())); ret = Return(&derived); EXPECT_EQ(&derived, ret.Perform(std::make_tuple())); } class FromType { public: explicit FromType(bool* is_converted) : converted_(is_converted) {} bool* converted() const { return converted_; } private: bool* const converted_; }; class ToType { public: ToType(const FromType& x) { *x.converted() = true; } }; TEST(ReturnTest, ConvertsArgumentWhenConverted) { bool converted = false; FromType x(&converted); Action<ToType()> action(Return(x)); EXPECT_TRUE(converted) << "Return must convert its argument in its own " << "conversion operator."; converted = false; action.Perform(std::tuple<>()); EXPECT_FALSE(converted) << "Action must NOT convert its argument " << "when performed."; } TEST(ReturnNullTest, WorksInPointerReturningFunction) { const Action<int*()> a1 = ReturnNull(); EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); const Action<const char*(bool)> a2 = ReturnNull(); EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr); } TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) { const Action<std::unique_ptr<const int>()> a1 = ReturnNull(); EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr); const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull(); EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr); } TEST(ReturnRefTest, WorksForReference) { const int n = 0; const Action<const int&(bool)> ret = ReturnRef(n); EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true))); } TEST(ReturnRefTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRef(base); EXPECT_EQ(&base, &a.Perform(std::make_tuple())); a = ReturnRef(derived); EXPECT_EQ(&derived, &a.Perform(std::make_tuple())); } template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))> bool CanCallReturnRef(T&&) { return true; } bool CanCallReturnRef(Unused) { return false; } TEST(ReturnRefTest, WorksForNonTemporary) { int scalar_value = 123; EXPECT_TRUE(CanCallReturnRef(scalar_value)); std::string non_scalar_value("ABC"); EXPECT_TRUE(CanCallReturnRef(non_scalar_value)); const int const_scalar_value{321}; EXPECT_TRUE(CanCallReturnRef(const_scalar_value)); const std::string const_non_scalar_value("CBA"); EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value)); } TEST(ReturnRefTest, DoesNotWorkForTemporary) { auto scalar_value = []() -> int { return 123; }; EXPECT_FALSE(CanCallReturnRef(scalar_value())); auto non_scalar_value = []() -> std::string { return "ABC"; }; EXPECT_FALSE(CanCallReturnRef(non_scalar_value())); EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321))); auto const_non_scalar_value = []() -> const std::string { return "CBA"; }; EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value())); } TEST(ReturnRefOfCopyTest, WorksForReference) { int n = 42; const Action<const int&()> ret = ReturnRefOfCopy(n); EXPECT_NE(&n, &ret.Perform(std::make_tuple())); EXPECT_EQ(42, ret.Perform(std::make_tuple())); n = 43; EXPECT_NE(&n, &ret.Perform(std::make_tuple())); EXPECT_EQ(42, ret.Perform(std::make_tuple())); } TEST(ReturnRefOfCopyTest, IsCovariant) { Base base; Derived derived; Action<Base&()> a = ReturnRefOfCopy(base); EXPECT_NE(&base, &a.Perform(std::make_tuple())); a = ReturnRefOfCopy(derived); EXPECT_NE(&derived, &a.Perform(std::make_tuple())); } TEST(ReturnRoundRobinTest, WorksForInitList) { Action<int()> ret = ReturnRoundRobin({1, 2, 3}); EXPECT_EQ(1, ret.Perform(std::make_tuple())); EXPECT_EQ(2, ret.Perform(std::make_tuple())); EXPECT_EQ(3, ret.Perform(std::make_tuple())); EXPECT_EQ(1, ret.Perform(std::make_tuple())); EXPECT_EQ(2, ret.Perform(std::make_tuple())); EXPECT_EQ(3, ret.Perform(std::make_tuple())); } TEST(ReturnRoundRobinTest, WorksForVector) { std::vector<double> v = {4.4, 5.5, 6.6}; Action<double()> ret = ReturnRoundRobin(v); EXPECT_EQ(4.4, ret.Perform(std::make_tuple())); EXPECT_EQ(5.5, ret.Perform(std::make_tuple())); EXPECT_EQ(6.6, ret.Perform(std::make_tuple())); EXPECT_EQ(4.4, ret.Perform(std::make_tuple())); EXPECT_EQ(5.5, ret.Perform(std::make_tuple())); EXPECT_EQ(6.6, ret.Perform(std::make_tuple())); } class MockClass { public: MockClass() = default; MOCK_METHOD1(IntFunc, int(bool flag)); MOCK_METHOD0(Foo, MyNonDefaultConstructible()); MOCK_METHOD0(MakeUnique, std::unique_ptr<int>()); MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>()); MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>()); MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>)); MOCK_METHOD2(TakeUnique, int(const std::unique_ptr<int>&, std::unique_ptr<int>)); private: MockClass(const MockClass&) = delete; MockClass& operator=(const MockClass&) = delete; }; TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(0, mock.IntFunc(true)); } TEST(DoDefaultDeathTest, DiesForUnknowType) { MockClass mock; EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault()); #if GTEST_HAS_EXCEPTIONS EXPECT_ANY_THROW(mock.Foo()); #else EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, ""); #endif } void VoidFunc(bool ) {} TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) { MockClass mock; EXPECT_CALL(mock, IntFunc(_)) .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault())); EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, ""); } TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) { DefaultValue<int>::Set(1); MockClass mock; EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(1, mock.IntFunc(false)); DefaultValue<int>::Clear(); } TEST(DoDefaultTest, DoesWhatOnCallSpecifies) { MockClass mock; ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2)); EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault()); EXPECT_EQ(2, mock.IntFunc(false)); } TEST(DoDefaultTest, CannotBeUsedInOnCall) { MockClass mock; EXPECT_NONFATAL_FAILURE( { ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault()); }, "DoDefault() cannot be used in ON_CALL()"); } TEST(SetArgPointeeTest, SetsTheNthPointee) { typedef void MyFunction(bool, int*, char*); Action<MyFunction> a = SetArgPointee<1>(2); int n = 0; char ch = '\0'; a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgPointee<2>('a'); n = 0; ch = '\0'; a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } TEST(SetArgPointeeTest, AcceptsStringLiteral) { typedef void MyFunction(std::string*, const char**); Action<MyFunction> a = SetArgPointee<0>("hi"); std::string str; const char* ptr = nullptr; a.Perform(std::make_tuple(&str, &ptr)); EXPECT_EQ("hi", str); EXPECT_TRUE(ptr == nullptr); a = SetArgPointee<1>("world"); str = ""; a.Perform(std::make_tuple(&str, &ptr)); EXPECT_EQ("", str); EXPECT_STREQ("world", ptr); } TEST(SetArgPointeeTest, AcceptsWideStringLiteral) { typedef void MyFunction(const wchar_t**); Action<MyFunction> a = SetArgPointee<0>(L"world"); const wchar_t* ptr = nullptr; a.Perform(std::make_tuple(&ptr)); EXPECT_STREQ(L"world", ptr); #if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(std::wstring*); Action<MyStringFunction> a2 = SetArgPointee<0>(L"world"); std::wstring str = L""; a2.Perform(std::make_tuple(&str)); EXPECT_EQ(L"world", str); #endif } TEST(SetArgPointeeTest, AcceptsCharPointer) { typedef void MyFunction(bool, std::string*, const char**); const char* const hi = "hi"; Action<MyFunction> a = SetArgPointee<1>(hi); std::string str; const char* ptr = nullptr; a.Perform(std::make_tuple(true, &str, &ptr)); EXPECT_EQ("hi", str); EXPECT_TRUE(ptr == nullptr); char world_array[] = "world"; char* const world = world_array; a = SetArgPointee<2>(world); str = ""; a.Perform(std::make_tuple(true, &str, &ptr)); EXPECT_EQ("", str); EXPECT_EQ(world, ptr); } TEST(SetArgPointeeTest, AcceptsWideCharPointer) { typedef void MyFunction(bool, const wchar_t**); const wchar_t* const hi = L"hi"; Action<MyFunction> a = SetArgPointee<1>(hi); const wchar_t* ptr = nullptr; a.Perform(std::make_tuple(true, &ptr)); EXPECT_EQ(hi, ptr); #if GTEST_HAS_STD_WSTRING typedef void MyStringFunction(bool, std::wstring*); wchar_t world_array[] = L"world"; wchar_t* const world = world_array; Action<MyStringFunction> a2 = SetArgPointee<1>(world); std::wstring str; a2.Perform(std::make_tuple(true, &str)); EXPECT_EQ(world_array, str); #endif } TEST(SetArgumentPointeeTest, SetsTheNthPointee) { typedef void MyFunction(bool, int*, char*); Action<MyFunction> a = SetArgumentPointee<1>(2); int n = 0; char ch = '\0'; a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(2, n); EXPECT_EQ('\0', ch); a = SetArgumentPointee<2>('a'); n = 0; ch = '\0'; a.Perform(std::make_tuple(true, &n, &ch)); EXPECT_EQ(0, n); EXPECT_EQ('a', ch); } int Nullary() { return 1; } class NullaryFunctor { public: int operator()() { return 2; } }; bool g_done = false; void VoidNullary() { g_done = true; } class VoidNullaryFunctor { public: void operator()() { g_done = true; } }; short Short(short n) { return n; } char Char(char ch) { return ch; } const char* CharPtr(const char* s) { return s; } bool Unary(int x) { return x < 0; } const char* Binary(const char* input, short n) { return input + n; } void VoidBinary(int, char) { g_done = true; } int Ternary(int x, char y, short z) { return x + y + z; } int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } class Foo { public: Foo() : value_(123) {} int Nullary() const { return value_; } private: int value_; }; TEST(InvokeWithoutArgsTest, Function) { Action<int(int)> a = InvokeWithoutArgs(Nullary); EXPECT_EQ(1, a.Perform(std::make_tuple(2))); Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5))); Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); g_done = false; a3.Perform(std::make_tuple(1)); EXPECT_TRUE(g_done); } TEST(InvokeWithoutArgsTest, Functor) { Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); EXPECT_EQ(2, a.Perform(std::make_tuple())); Action<int(int, double, char)> a2 = InvokeWithoutArgs(NullaryFunctor()); EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a'))); Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor()); g_done = false; a3.Perform(std::make_tuple()); EXPECT_TRUE(g_done); } TEST(InvokeWithoutArgsTest, Method) { Foo foo; Action<int(bool, char)> a = InvokeWithoutArgs(&foo, &Foo::Nullary); EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a'))); } TEST(IgnoreResultTest, PolymorphicAction) { Action<void(int)> a = IgnoreResult(Return(5)); a.Perform(std::make_tuple(1)); } int ReturnOne() { g_done = true; return 1; } TEST(IgnoreResultTest, MonomorphicAction) { g_done = false; Action<void()> a = IgnoreResult(Invoke(ReturnOne)); a.Perform(std::make_tuple()); EXPECT_TRUE(g_done); } MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double ) { g_done = true; return MyNonDefaultConstructible(42); } TEST(IgnoreResultTest, ActionReturningClass) { g_done = false; Action<void(int)> a = IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); a.Perform(std::make_tuple(2)); EXPECT_TRUE(g_done); } TEST(AssignTest, Int) { int x = 0; Action<void(int)> a = Assign(&x, 5); a.Perform(std::make_tuple(0)); EXPECT_EQ(5, x); } TEST(AssignTest, String) { ::std::string x; Action<void(void)> a = Assign(&x, "Hello, world"); a.Perform(std::make_tuple()); EXPECT_EQ("Hello, world", x); } TEST(AssignTest, CompatibleTypes) { double x = 0; Action<void(int)> a = Assign(&x, 5); a.Perform(std::make_tuple(0)); EXPECT_DOUBLE_EQ(5, x); } TEST(DoAll, SupportsRefQualifiedActions) { struct InitialAction { void operator()(const int arg) && { EXPECT_EQ(17, arg); } }; struct FinalAction { int operator()() && { return 19; } }; MockFunction<int(int)> mock; EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{})); EXPECT_EQ(19, mock.AsStdFunction()(17)); } TEST(DoAll, ProvidesLvalueReferencesToInitialActions) { struct Obj {}; { struct InitialAction { void operator()(Obj&) const { FAIL() << "Unexpected call"; } void operator()(const Obj&) const {} void operator()(Obj&&) const { FAIL() << "Unexpected call"; } void operator()(const Obj&&) const { FAIL() << "Unexpected call"; } }; MockFunction<void(Obj)> mock; EXPECT_CALL(mock, Call) .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})) .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})); mock.AsStdFunction()(Obj{}); mock.AsStdFunction()(Obj{}); } { struct InitialAction { void operator()(Obj&) const { FAIL() << "Unexpected call"; } void operator()(const Obj&) const {} void operator()(Obj&&) const { FAIL() << "Unexpected call"; } void operator()(const Obj&&) const { FAIL() << "Unexpected call"; } }; MockFunction<void(const Obj&)> mock; EXPECT_CALL(mock, Call) .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {})) .WillRepeatedly( DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {})); mock.AsStdFunction()(Obj{}); mock.AsStdFunction()(Obj{}); } { struct InitialAction { void operator()(Obj&) const {} void operator()(Obj&&) const { FAIL() << "Unexpected call"; } }; MockFunction<void(Obj&)> mock; EXPECT_CALL(mock, Call) .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {})) .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {})); Obj obj; mock.AsStdFunction()(obj); mock.AsStdFunction()(obj); } { struct InitialAction { void operator()(Obj&) const {} void operator()(Obj&&) const { FAIL() << "Unexpected call"; } }; MockFunction<void(Obj&&)> mock; EXPECT_CALL(mock, Call) .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})) .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})); mock.AsStdFunction()(Obj{}); mock.AsStdFunction()(Obj{}); } { struct InitialAction { void operator()(Obj&) && {} }; MockFunction<void(Obj&)> mock; EXPECT_CALL(mock, Call) .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {})); Obj obj; mock.AsStdFunction()(obj); } { struct InitialAction { void operator()(Obj&) && {} }; MockFunction<void(Obj&&)> mock; EXPECT_CALL(mock, Call) .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {})); mock.AsStdFunction()(Obj{}); } } TEST(DoAll, SupportsTypeErasedActions) { const Action<void()> initial_action = [] {}; const Action<int()> final_action = [] { return 17; }; MockFunction<int()> mock; EXPECT_CALL(mock, Call) .WillOnce(DoAll(initial_action, initial_action, final_action)) .WillRepeatedly(DoAll(initial_action, initial_action, final_action)); EXPECT_EQ(17, mock.AsStdFunction()()); { struct FinalAction { FinalAction() = default; FinalAction(FinalAction&&) = default; int operator()() && { return 17; } }; EXPECT_CALL(mock, Call) .WillOnce(DoAll(initial_action, initial_action, FinalAction{})); EXPECT_EQ(17, mock.AsStdFunction()()); } } TEST(DoAll, ConvertibleToOnceActionWithUserProvidedActionConversion) { struct CustomFinal final { operator Action<int()>() { return Return(17); } operator Action<int(int, char)>() { return Return(19); } }; { OnceAction<int()> action = DoAll(CustomFinal{}); EXPECT_EQ(17, std::move(action).Call()); } { OnceAction<int(int, char)> action = DoAll(CustomFinal{}); EXPECT_EQ(19, std::move(action).Call(0, 0)); } struct CustomInitial final { operator Action<void()>() { return [] {}; } operator Action<void(int, char)>() { return [] {}; } }; { OnceAction<int()> action = DoAll(CustomInitial{}, CustomFinal{}); EXPECT_EQ(17, std::move(action).Call()); } { OnceAction<int(int, char)> action = DoAll(CustomInitial{}, CustomFinal{}); EXPECT_EQ(19, std::move(action).Call(0, 0)); } } TEST(WithArgsTest, OneArg) { Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1))); EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1))); } TEST(WithArgsTest, TwoArgs) { Action<const char*(const char* s, double x, short n)> a = WithArgs<0, 2>(Invoke(Binary)); const char s[] = "Hello"; EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2)))); } struct ConcatAll { std::string operator()() const { return {}; } template <typename... I> std::string operator()(const char* a, I... i) const { return a + ConcatAll()(i...); } }; TEST(WithArgsTest, TenArgs) { Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{})); EXPECT_EQ("0123210123", a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), CharPtr("3")))); } class SubtractAction : public ActionInterface<int(int, int)> { public: int Perform(const std::tuple<int, int>& args) override { return std::get<0>(args) - std::get<1>(args); } }; TEST(WithArgsTest, NonInvokeAction) { Action<int(const std::string&, int, int)> a = WithArgs<2, 1>(MakeAction(new SubtractAction)); std::tuple<std::string, int, int> dummy = std::make_tuple(std::string("hi"), 2, 10); EXPECT_EQ(8, a.Perform(dummy)); } TEST(WithArgsTest, Identity) { Action<int(int x, char y, short z)> a = WithArgs<0, 1, 2>(Invoke(Ternary)); EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3)))); } TEST(WithArgsTest, RepeatedArguments) { Action<int(bool, int m, int n)> a = WithArgs<1, 1, 1, 1>(Invoke(SumOf4)); EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10))); } TEST(WithArgsTest, ReversedArgumentOrder) { Action<const char*(short n, const char* input)> a = WithArgs<1, 0>(Invoke(Binary)); const char s[] = "Hello"; EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s)))); } TEST(WithArgsTest, ArgsOfCompatibleTypes) { Action<long(short x, char y, double z, char c)> a = WithArgs<0, 1, 3>(Invoke(Ternary)); EXPECT_EQ(123, a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3)))); } TEST(WithArgsTest, VoidAction) { Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary)); g_done = false; a.Perform(std::make_tuple(1.5, 'a', 3)); EXPECT_TRUE(g_done); } TEST(WithArgsTest, ReturnReference) { Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; }); int i = 0; const int& res = aa.Perform(std::forward_as_tuple(i, nullptr)); EXPECT_EQ(&i, &res); } TEST(WithArgsTest, InnerActionWithConversion) { Action<Derived*()> inner = [] { return nullptr; }; MockFunction<Base*(double)> mock; EXPECT_CALL(mock, Call) .WillOnce(WithoutArgs(inner)) .WillRepeatedly(WithoutArgs(inner)); EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1)); EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1)); } TEST(WithArgsTest, RefQualifiedInnerAction) { struct SomeAction { int operator()(const int arg) && { EXPECT_EQ(17, arg); return 19; } }; MockFunction<int(int, int)> mock; EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{})); EXPECT_EQ(19, mock.AsStdFunction()(0, 17)); } #ifndef GTEST_OS_WINDOWS_MOBILE class SetErrnoAndReturnTest : public testing::Test { protected: void SetUp() override { errno = 0; } void TearDown() override { errno = 0; } }; TEST_F(SetErrnoAndReturnTest, Int) { Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5); EXPECT_EQ(-5, a.Perform(std::make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, Ptr) { int x; Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x); EXPECT_EQ(&x, a.Perform(std::make_tuple())); EXPECT_EQ(ENOTTY, errno); } TEST_F(SetErrnoAndReturnTest, CompatibleTypes) { Action<double()> a = SetErrnoAndReturn(EINVAL, 5); EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple())); EXPECT_EQ(EINVAL, errno); } #endif TEST(ByRefTest, IsCopyable) { const std::string s1 = "Hi"; const std::string s2 = "Hello"; auto ref_wrapper = ByRef(s1); const std::string& r1 = ref_wrapper; EXPECT_EQ(&s1, &r1); ref_wrapper = ByRef(s2); const std::string& r2 = ref_wrapper; EXPECT_EQ(&s2, &r2); auto ref_wrapper1 = ByRef(s1); ref_wrapper = ref_wrapper1; const std::string& r3 = ref_wrapper; EXPECT_EQ(&s1, &r3); } TEST(ByRefTest, ConstValue) { const int n = 0; const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } TEST(ByRefTest, NonConstValue) { int n = 0; int& ref = ByRef(n); EXPECT_EQ(&n, &ref); const int& const_ref = ByRef(n); EXPECT_EQ(&n, &const_ref); } TEST(ByRefTest, ExplicitType) { int n = 0; const int& r1 = ByRef<const int>(n); EXPECT_EQ(&n, &r1); Derived d; Derived& r2 = ByRef<Derived>(d); EXPECT_EQ(&d, &r2); const Derived& r3 = ByRef<const Derived>(d); EXPECT_EQ(&d, &r3); Base& r4 = ByRef<Base>(d); EXPECT_EQ(&d, &r4); const Base& r5 = ByRef<const Base>(d); EXPECT_EQ(&d, &r5); } TEST(ByRefTest, PrintsCorrectly) { int n = 42; ::std::stringstream expected, actual; testing::internal::UniversalPrinter<const int&>::Print(n, &expected); testing::internal::UniversalPrint(ByRef(n), &actual); EXPECT_EQ(expected.str(), actual.str()); } struct UnaryConstructorClass { explicit UnaryConstructorClass(int v) : value(v) {} int value; }; TEST(ReturnNewTest, Unary) { Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); UnaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(4000, c->value); delete c; } TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { Action<UnaryConstructorClass*(bool, int)> a = ReturnNew<UnaryConstructorClass>(4000); UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5)); EXPECT_EQ(4000, c->value); delete c; } TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) { Action<const UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); const UnaryConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(4000, c->value); delete c; } class TenArgConstructorClass { public: TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10) : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {} int value_; }; TEST(ReturnNewTest, ConstructorThatTakes10Arguments) { Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>( 1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90, 0); TenArgConstructorClass* c = a.Perform(std::make_tuple()); EXPECT_EQ(1234567890, c->value_); delete c; } std::unique_ptr<int> UniquePtrSource() { return std::make_unique<int>(19); } std::vector<std::unique_ptr<int>> VectorUniquePtrSource() { std::vector<std::unique_ptr<int>> out; out.emplace_back(new int(7)); return out; } TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) { MockClass mock; std::unique_ptr<int> i(new int(19)); EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i)))); EXPECT_CALL(mock, MakeVectorUnique()) .WillOnce(Return(ByMove(VectorUniquePtrSource()))); Derived* d = new Derived; EXPECT_CALL(mock, MakeUniqueBase()) .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d)))); std::unique_ptr<int> result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique(); EXPECT_EQ(1u, vresult.size()); EXPECT_NE(nullptr, vresult[0]); EXPECT_EQ(7, *vresult[0]); std::unique_ptr<Base> result2 = mock.MakeUniqueBase(); EXPECT_EQ(d, result2.get()); } TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) { testing::MockFunction<void()> mock_function; MockClass mock; std::unique_ptr<int> i(new int(19)); EXPECT_CALL(mock_function, Call()); EXPECT_CALL(mock, MakeUnique()) .WillOnce(DoAll(InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call), Return(ByMove(std::move(i))))); std::unique_ptr<int> result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); } TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) { MockClass mock; DefaultValue<std::unique_ptr<int>>::SetFactory( [] { return std::make_unique<int>(42); }); EXPECT_EQ(42, *mock.MakeUnique()); EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource)); EXPECT_CALL(mock, MakeVectorUnique()) .WillRepeatedly(Invoke(VectorUniquePtrSource)); std::unique_ptr<int> result1 = mock.MakeUnique(); EXPECT_EQ(19, *result1); std::unique_ptr<int> result2 = mock.MakeUnique(); EXPECT_EQ(19, *result2); EXPECT_NE(result1, result2); std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique(); EXPECT_EQ(1u, vresult.size()); EXPECT_NE(nullptr, vresult[0]); EXPECT_EQ(7, *vresult[0]); } TEST(MockMethodTest, CanTakeMoveOnlyValue) { MockClass mock; auto make = [](int i) { return std::make_unique<int>(i); }; EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) { return *i; }); EXPECT_CALL(mock, TakeUnique(testing::Pointee(7))) .WillOnce(Return(-7)) .RetiresOnSaturation(); EXPECT_CALL(mock, TakeUnique(testing::IsNull())) .WillOnce(Return(-1)) .RetiresOnSaturation(); EXPECT_EQ(5, mock.TakeUnique(make(5))); EXPECT_EQ(-7, mock.TakeUnique(make(7))); EXPECT_EQ(7, mock.TakeUnique(make(7))); EXPECT_EQ(7, mock.TakeUnique(make(7))); EXPECT_EQ(-1, mock.TakeUnique({})); auto lvalue = make(6); EXPECT_CALL(mock, TakeUnique(_, _)) .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) { return *i * *j; }); EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7))); std::unique_ptr<int> saved; EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) { saved = std::move(i); return 0; }); EXPECT_EQ(0, mock.TakeUnique(make(42))); EXPECT_EQ(42, *saved); } TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) { struct Return17 { int operator()() && { return 17; } }; { MockFunction<int()> mock; EXPECT_CALL(mock, Call).WillOnce(Return17()); EXPECT_EQ(17, mock.AsStdFunction()()); } { MockFunction<int(int)> mock; EXPECT_CALL(mock, Call).WillOnce(Return17()); EXPECT_EQ(17, mock.AsStdFunction()(0)); } } TEST(MockMethodTest, ActionHasMultipleCallOperators) { struct ReturnInt { int operator()() && { return 17; } int operator()() const& { return 19; } }; { MockFunction<int()> mock; EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt()); EXPECT_EQ(17, mock.AsStdFunction()()); EXPECT_EQ(19, mock.AsStdFunction()()); EXPECT_EQ(19, mock.AsStdFunction()()); } { MockFunction<int(int)> mock; EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt()); EXPECT_EQ(17, mock.AsStdFunction()(0)); EXPECT_EQ(19, mock.AsStdFunction()(0)); EXPECT_EQ(19, mock.AsStdFunction()(0)); } } TEST(MockMethodTest, MoveOnlyAction) { { struct Return17 { Return17() = default; Return17(Return17&&) = default; Return17(const Return17&) = delete; Return17 operator=(const Return17&) = delete; int operator()() && { return 17; } }; MockFunction<int()> mock; EXPECT_CALL(mock, Call).WillOnce(Return17()); EXPECT_EQ(17, mock.AsStdFunction()()); } { struct Return17 { Return17() = default; Return17(Return17&&) = default; Return17(const Return17&) = delete; Return17 operator=(const Return17&) = delete; int operator()() const { return 17; } }; MockFunction<int()> mock; EXPECT_CALL(mock, Call).WillOnce(Return17()); EXPECT_EQ(17, mock.AsStdFunction()()); } } TEST(MockMethodTest, ActionReturnsIgnoredValue) { struct ReturnInt { int operator()() const { return 0; } }; MockFunction<void()> mock; EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt()); mock.AsStdFunction()(); mock.AsStdFunction()(); } TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) { MockFunction<int()> mock; const auto action = [] { return 17; }; EXPECT_CALL(mock, Call).WillOnce(action); EXPECT_EQ(17, mock.AsStdFunction()()); } struct StaticAssertSingleArgument { template <typename... Args> static constexpr bool CheckArgs() { static_assert(sizeof...(Args) == 1, ""); return true; } template <typename... Args, bool = CheckArgs<Args...>()> int operator()(Args...) const { return 17; } }; TEST(MockMethodTest, ActionSwallowsAllArguments) { MockFunction<int(int)> mock; EXPECT_CALL(mock, Call) .WillOnce(StaticAssertSingleArgument{}) .WillRepeatedly(StaticAssertSingleArgument{}); EXPECT_EQ(17, mock.AsStdFunction()(0)); EXPECT_EQ(17, mock.AsStdFunction()(0)); } struct ActionWithTemplatedConversionOperators { template <typename... Args> operator OnceAction<int(Args...)>() && { return [] { return 17; }; } template <typename... Args> operator Action<int(Args...)>() const { return [] { return 19; }; } }; TEST(MockMethodTest, ActionHasTemplatedConversionOperators) { MockFunction<int()> mock; EXPECT_CALL(mock, Call) .WillOnce(ActionWithTemplatedConversionOperators{}) .WillRepeatedly(ActionWithTemplatedConversionOperators{}); EXPECT_EQ(17, mock.AsStdFunction()()); EXPECT_EQ(19, mock.AsStdFunction()()); } int Add(int val, int& ref, int* ptr) { int result = val + ref + *ptr; ref = 42; *ptr = 43; return result; } int Deref(std::unique_ptr<int> ptr) { return *ptr; } struct Double { template <typename T> T operator()(T t) { return 2 * t; } }; std::unique_ptr<int> UniqueInt(int i) { return std::make_unique<int>(i); } TEST(FunctorActionTest, ActionFromFunction) { Action<int(int, int&, int*)> a = &Add; int x = 1, y = 2, z = 3; EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z))); EXPECT_EQ(42, y); EXPECT_EQ(43, z); Action<int(std::unique_ptr<int>)> a1 = &Deref; EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7)))); } TEST(FunctorActionTest, ActionFromLambda) { Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; }; EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5))); EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5))); std::unique_ptr<int> saved; Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) { saved = std::move(p); }; a2.Perform(std::make_tuple(UniqueInt(5))); EXPECT_EQ(5, *saved); } TEST(FunctorActionTest, PolymorphicFunctor) { Action<int(int)> ai = Double(); EXPECT_EQ(2, ai.Perform(std::make_tuple(1))); Action<double(double)> ad = Double(); EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5))); } TEST(FunctorActionTest, TypeConversion) { const Action<bool(int)> a1 = [](int i) { return i > 1; }; const Action<int(bool)> a2 = Action<int(bool)>(a1); EXPECT_EQ(1, a1.Perform(std::make_tuple(42))); EXPECT_EQ(0, a2.Perform(std::make_tuple(42))); const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); }; const Action<int(const char*)> s2 = Action<int(const char*)>(s1); EXPECT_EQ(0, s2.Perform(std::make_tuple(""))); EXPECT_EQ(1, s2.Perform(std::make_tuple("hello"))); const Action<bool(std::string)> x1 = [](Unused) { return 42; }; const Action<bool(std::string)> x2 = [] { return 42; }; EXPECT_TRUE(x1.Perform(std::make_tuple("hello"))); EXPECT_TRUE(x2.Perform(std::make_tuple("hello"))); std::function<int()> f = [] { return 7; }; Action<int(int)> d = f; f = nullptr; EXPECT_EQ(7, d.Perform(std::make_tuple(1))); Action<void(int)>(nullptr); } TEST(FunctorActionTest, UnusedArguments) { Action<int(int, double y, double z)> a = [](int i, Unused, Unused) { return 2 * i; }; std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44); EXPECT_EQ(6, a.Perform(dummy)); } TEST(MoveOnlyArgumentsTest, ReturningActions) { Action<int(std::unique_ptr<int>)> a = Return(1); EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr))); a = testing::WithoutArgs([]() { return 7; }); EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr))); Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3); int x = 0; a2.Perform(std::make_tuple(nullptr, &x)); EXPECT_EQ(x, 3); } ACTION(ReturnArity) { return std::tuple_size<args_type>::value; } TEST(ActionMacro, LargeArity) { EXPECT_EQ( 1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0))); EXPECT_EQ( 10, testing::Action<int(int, int, int, int, int, int, int, int, int, int)>( ReturnArity()) .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))); EXPECT_EQ( 20, testing::Action<int(int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int)>( ReturnArity()) .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19))); } } } #if defined(_MSC_VER) && (_MSC_VER == 1900) GTEST_DISABLE_MSC_WARNINGS_POP_() #endif GTEST_DISABLE_MSC_WARNINGS_POP_()
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/include/gmock/gmock-actions.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-actions_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
39659618-dcb7-4a1b-937c-9aca3dc040f3
cpp
google/googletest
gmock-port
googlemock/include/gmock/internal/custom/gmock-port.h
googlemock/test/gmock-port_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #endif
#include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" TEST(DummyTest, Dummy) {}
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/include/gmock/internal/custom/gmock-port.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-port_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
7fc42d15-469c-4a02-a9ec-48ef227ad356
cpp
google/googletest
gmock-pp
googlemock/include/gmock/internal/gmock-pp.h
googlemock/test/gmock-pp_test.cc
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_ #define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_ #define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2) #define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__) #define GMOCK_PP_EMPTY(...) #define GMOCK_PP_COMMA(...) , #define GMOCK_PP_IDENTITY(_1) _1 #define GMOCK_PP_NARG(...) \ GMOCK_PP_INTERNAL_16TH( \ (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) #define GMOCK_PP_HAS_COMMA(...) \ GMOCK_PP_INTERNAL_16TH( \ (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)) #define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg)) #define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__)) #define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \ GMOCK_PP_IDENTITY( \ GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__)) #define GMOCK_PP_IS_EMPTY(...) \ GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__), \ GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \ GMOCK_PP_HAS_COMMA(__VA_ARGS__()), \ GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__())) #define GMOCK_PP_IF(_Cond, _Then, _Else) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else) #define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \ GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else)) #define GMOCK_PP_NARG0(...) \ GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__)) #define GMOCK_PP_IS_BEGIN_PARENS(...) \ GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \ GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__)) #define GMOCK_PP_IS_ENCLOSED_PARENS(...) \ GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \ GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0) #define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__ #define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \ (0, _Macro, _Data, _Tuple) #define GMOCK_PP_REPEAT(_Macro, _Data, _N) \ GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \ (0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE) #define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i) #define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i) #define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , ) #define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2 #define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__ #define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5 #define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4) \ GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \ _1, _2, _3, _4)) #define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 , #define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then #define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else #define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \ _10, _11, _12, _13, _14, _15, _16, \ ...) \ _16 #define GMOCK_PP_INTERNAL_16TH(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args) #define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1 #define GMOCK_PP_INTERNAL_HEAD(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args) #define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__ #define GMOCK_PP_INTERNAL_TAIL(_Args) \ GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args) #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _ #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1, #define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \ 0, #define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__ #define GMOCK_PP_INTERNAL_INC_0 1 #define GMOCK_PP_INTERNAL_INC_1 2 #define GMOCK_PP_INTERNAL_INC_2 3 #define GMOCK_PP_INTERNAL_INC_3 4 #define GMOCK_PP_INTERNAL_INC_4 5 #define GMOCK_PP_INTERNAL_INC_5 6 #define GMOCK_PP_INTERNAL_INC_6 7 #define GMOCK_PP_INTERNAL_INC_7 8 #define GMOCK_PP_INTERNAL_INC_8 9 #define GMOCK_PP_INTERNAL_INC_9 10 #define GMOCK_PP_INTERNAL_INC_10 11 #define GMOCK_PP_INTERNAL_INC_11 12 #define GMOCK_PP_INTERNAL_INC_12 13 #define GMOCK_PP_INTERNAL_INC_13 14 #define GMOCK_PP_INTERNAL_INC_14 15 #define GMOCK_PP_INTERNAL_INC_15 16 #define GMOCK_PP_INTERNAL_COMMA_IF_0 #define GMOCK_PP_INTERNAL_COMMA_IF_1 , #define GMOCK_PP_INTERNAL_COMMA_IF_2 , #define GMOCK_PP_INTERNAL_COMMA_IF_3 , #define GMOCK_PP_INTERNAL_COMMA_IF_4 , #define GMOCK_PP_INTERNAL_COMMA_IF_5 , #define GMOCK_PP_INTERNAL_COMMA_IF_6 , #define GMOCK_PP_INTERNAL_COMMA_IF_7 , #define GMOCK_PP_INTERNAL_COMMA_IF_8 , #define GMOCK_PP_INTERNAL_COMMA_IF_9 , #define GMOCK_PP_INTERNAL_COMMA_IF_10 , #define GMOCK_PP_INTERNAL_COMMA_IF_11 , #define GMOCK_PP_INTERNAL_COMMA_IF_12 , #define GMOCK_PP_INTERNAL_COMMA_IF_13 , #define GMOCK_PP_INTERNAL_COMMA_IF_14 , #define GMOCK_PP_INTERNAL_COMMA_IF_15 , #define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \ _Macro(_i, _Data, _element) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple) \ GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \ GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data, \ (GMOCK_PP_TAIL _Tuple)) #endif
#include "gmock/internal/gmock-pp.h" #define GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_comma , #define GMOCK_TEST_REPLACE_comma_WITH_COMMA(x) \ GMOCK_PP_CAT(GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_, x) namespace testing { namespace internal { namespace gmockpp { static_assert(GMOCK_PP_CAT(1, 4) == 14, ""); static_assert(GMOCK_PP_INTERNAL_INTERNAL_16TH(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18) == 16, ""); static_assert(GMOCK_PP_NARG() == 1, ""); static_assert(GMOCK_PP_NARG(x) == 1, ""); static_assert(GMOCK_PP_NARG(x, y) == 2, ""); static_assert(GMOCK_PP_NARG(x, y, z) == 3, ""); static_assert(GMOCK_PP_NARG(x, y, z, w) == 4, ""); static_assert(!GMOCK_PP_HAS_COMMA(), ""); static_assert(GMOCK_PP_HAS_COMMA(b, ), ""); static_assert(!GMOCK_PP_HAS_COMMA((, )), ""); static_assert(GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma)), ""); static_assert( GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))), ""); static_assert(!GMOCK_PP_IS_EMPTY(, ), ""); static_assert(!GMOCK_PP_IS_EMPTY(a), ""); static_assert(!GMOCK_PP_IS_EMPTY(()), ""); static_assert(GMOCK_PP_IF(1, 1, 2) == 1, ""); static_assert(GMOCK_PP_IF(0, 1, 2) == 2, ""); static_assert(GMOCK_PP_NARG0(x) == 1, ""); static_assert(GMOCK_PP_NARG0(x, y) == 2, ""); static_assert(GMOCK_PP_HEAD(1) == 1, ""); static_assert(GMOCK_PP_HEAD(1, 2) == 1, ""); static_assert(GMOCK_PP_HEAD(1, 2, 3) == 1, ""); static_assert(GMOCK_PP_TAIL(1, 2) == 2, ""); static_assert(GMOCK_PP_HEAD(GMOCK_PP_TAIL(1, 2, 3)) == 2, ""); static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss), ""); static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss()), ""); static_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss() sss), ""); static_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)), ""); static_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)ss), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss()), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss() sss), ""); static_assert(!GMOCK_PP_IS_ENCLOSED_PARENS((sss)ss), ""); static_assert(GMOCK_PP_REMOVE_PARENS((1 + 1)) * 2 == 3, ""); static_assert(GMOCK_PP_INC(4) == 5, ""); template <class... Args> struct Test { static constexpr int kArgs = sizeof...(Args); }; #define GMOCK_PP_INTERNAL_TYPE_TEST(_i, _Data, _element) \ GMOCK_PP_COMMA_IF(_i) _element static_assert(Test<GMOCK_PP_FOR_EACH(GMOCK_PP_INTERNAL_TYPE_TEST, ~, (int, float, double, char))>::kArgs == 4, ""); #define GMOCK_PP_INTERNAL_VAR_TEST_1(_x) 1 #define GMOCK_PP_INTERNAL_VAR_TEST_2(_x, _y) 2 #define GMOCK_PP_INTERNAL_VAR_TEST_3(_x, _y, _z) 3 #define GMOCK_PP_INTERNAL_VAR_TEST(...) \ GMOCK_PP_VARIADIC_CALL(GMOCK_PP_INTERNAL_VAR_TEST_, __VA_ARGS__) static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y) == 2, ""); static_assert(GMOCK_PP_INTERNAL_VAR_TEST(silly) == 1, ""); static_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y, z) == 3, ""); #define GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1 static_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1), ""); static_assert(GMOCK_PP_IS_EMPTY(), ""); static_assert(GMOCK_PP_IS_ENCLOSED_PARENS((sss)), ""); static_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_TAIL(1)), ""); static_assert(GMOCK_PP_NARG0() == 0, ""); } } }
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/include/gmock/internal/gmock-pp.h
https://github.com/google/googletest/blob/a1e255a582377e1006bb88a408ac3f933ba7c916/googlemock/test/gmock-pp_test.cc
a1e255a582377e1006bb88a408ac3f933ba7c916
5e09cbdf-fe29-4ffe-a2f9-f891eb797915
cpp
google/libaddressinput
fake_storage
cpp/test/fake_storage.cc
cpp/test/fake_storage_test.cc
#include "fake_storage.h" #include <cassert> #include <cstddef> #include <string> namespace i18n { namespace addressinput { FakeStorage::FakeStorage() = default; FakeStorage::~FakeStorage() { for (const auto& pair : data_) { delete pair.second; } } void FakeStorage::Put(const std::string& key, std::string* data) { assert(data != nullptr); auto result = data_.emplace(key, data); if (!result.second) { delete result.first->second; result.first->second = data; } } void FakeStorage::Get(const std::string& key, const Callback& data_ready) const { auto data_it = data_.find(key); bool success = data_it != data_.end(); data_ready(success, key, success ? new std::string(*data_it->second) : nullptr); } } }
#include "fake_storage.h" #include <libaddressinput/callback.h> #include <libaddressinput/storage.h> #include <cstddef> #include <memory> #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::FakeStorage; using i18n::addressinput::Storage; class FakeStorageTest : public testing::Test { public: FakeStorageTest(const FakeStorageTest&) = delete; FakeStorageTest& operator=(const FakeStorageTest&) = delete; protected: FakeStorageTest() : storage_(), success_(false), key_(), data_(), data_ready_(BuildCallback(this, &FakeStorageTest::OnDataReady)) {} FakeStorage storage_; bool success_; std::string key_; std::string data_; const std::unique_ptr<const Storage::Callback> data_ready_; private: void OnDataReady(bool success, const std::string& key, std::string* data) { ASSERT_FALSE(success && data == nullptr); success_ = success; key_ = key; if (data != nullptr) { data_ = *data; delete data; } } }; TEST_F(FakeStorageTest, GetWithoutPutReturnsEmptyData) { storage_.Get("key", *data_ready_); EXPECT_FALSE(success_); EXPECT_EQ("key", key_); EXPECT_TRUE(data_.empty()); } TEST_F(FakeStorageTest, GetReturnsWhatWasPut) { storage_.Put("key", new std::string("value")); storage_.Get("key", *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ("key", key_); EXPECT_EQ("value", data_); } TEST_F(FakeStorageTest, SecondPutOverwritesData) { storage_.Put("key", new std::string("bad-value")); storage_.Put("key", new std::string("good-value")); storage_.Get("key", *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ("key", key_); EXPECT_EQ("good-value", data_); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/fake_storage.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/fake_storage_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
07bd49a1-db7e-41b9-92e8-f63855c89c1b
cpp
google/libaddressinput
testdata_source
cpp/test/testdata_source.cc
cpp/test/testdata_source_test.cc
#include "testdata_source.h" #include <cassert> #include <cstddef> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <string> namespace i18n { namespace addressinput { const char kDataFileName[] = TEST_DATA_DIR "/countryinfo.txt"; namespace { const char kNormalPrefix = '-'; const char kAggregatePrefix = '+'; const char kDataKeyPrefix[] = "data/"; const size_t kDataKeyPrefixLength = sizeof kDataKeyPrefix - 1; const size_t kCldrRegionCodeLength = 2; const size_t kAggregateDataKeyLength = kDataKeyPrefixLength + kCldrRegionCodeLength; std::map<std::string, std::string> InitData(const std::string& src_path) { std::map<std::string, std::string> data; std::ifstream file(src_path); if (!file.is_open()) { std::cerr << "Error opening \"" << src_path << "\"." << '\n'; std::exit(EXIT_FAILURE); } const std::string normal_prefix(1, kNormalPrefix); const std::string aggregate_prefix(1, kAggregatePrefix); std::string key; std::string value; auto last_data_it = data.end(); auto aggregate_data_it = data.end(); while (file.good()) { std::getline(file, key, '='); if (!key.empty()) { std::getline(file, value, '\n'); last_data_it = data.emplace_hint(last_data_it, normal_prefix + key, value); if (key.compare(0, kDataKeyPrefixLength, kDataKeyPrefix, kDataKeyPrefixLength) == 0) { if (aggregate_data_it != data.end() && key.compare(0, kAggregateDataKeyLength, aggregate_data_it->first, sizeof kAggregatePrefix, kAggregateDataKeyLength) == 0) { aggregate_data_it->second.append(", \"" + key + "\": " + value); } else { assert(key.size() == kAggregateDataKeyLength); if (aggregate_data_it != data.end()) { aggregate_data_it->second.push_back('}'); } const std::string& aggregate_key = aggregate_prefix + key.substr(0, kAggregateDataKeyLength); aggregate_data_it = data.emplace_hint( aggregate_data_it, aggregate_key, "{\"" + key + "\": " + value); } } } } file.close(); return data; } const std::map<std::string, std::string>& GetData(const std::string& src_path) { static const std::map<std::string, std::string> kData(InitData(src_path)); return kData; } } TestdataSource::TestdataSource(bool aggregate, const std::string& src_path) : aggregate_(aggregate), src_path_(src_path) {} TestdataSource::TestdataSource(bool aggregate) : aggregate_(aggregate), src_path_(kDataFileName) {} TestdataSource::~TestdataSource() = default; void TestdataSource::Get(const std::string& key, const Callback& data_ready) const { std::string prefixed_key(1, aggregate_ ? kAggregatePrefix : kNormalPrefix); prefixed_key += key; auto data_it = GetData(src_path_).find(prefixed_key); bool success = data_it != GetData(src_path_).end(); std::string* data = nullptr; if (success) { data = new std::string(data_it->second); } else { success = true; data = new std::string("{}"); } data_ready(success, key, data); } } }
#include "testdata_source.h" #include <libaddressinput/callback.h> #include <libaddressinput/source.h> #include <cstddef> #include <memory> #include <string> #include <gtest/gtest.h> #include "region_data_constants.h" namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::kDataFileName; using i18n::addressinput::RegionDataConstants; using i18n::addressinput::Source; using i18n::addressinput::TestdataSource; class TestdataSourceTest : public testing::TestWithParam<std::string> { public: TestdataSourceTest(const TestdataSourceTest&) = delete; TestdataSourceTest& operator=(const TestdataSourceTest&) = delete; protected: TestdataSourceTest() : source_(false), source_with_path_(false, kDataFileName), aggregate_source_(true), aggregate_source_with_path_(true, kDataFileName), success_(false), key_(), data_(), data_ready_(BuildCallback(this, &TestdataSourceTest::OnDataReady)) {} TestdataSource source_; TestdataSource source_with_path_; TestdataSource aggregate_source_; TestdataSource aggregate_source_with_path_; bool success_; std::string key_; std::string data_; const std::unique_ptr<const Source::Callback> data_ready_; private: void OnDataReady(bool success, const std::string& key, std::string* data) { ASSERT_FALSE(success && data == nullptr); success_ = success; key_ = key; if (data != nullptr) { data_ = *data; delete data; } } }; testing::AssertionResult DataIsValid(const std::string& data, const std::string& key) { if (data.empty()) { return testing::AssertionFailure() << "empty data"; } std::string expected_data_begin = R"({"id":")" + key + R"(")"; if (data.compare(0, expected_data_begin.length(), expected_data_begin) != 0) { return testing::AssertionFailure() << data << " does not begin with " << expected_data_begin; } static const char kDataEnd[] = "\"}"; static const size_t kDataEndLength = sizeof kDataEnd - 1; if (data.compare(data.length() - kDataEndLength, kDataEndLength, kDataEnd, kDataEndLength) != 0) { return testing::AssertionFailure() << data << " does not end with " << kDataEnd; } return testing::AssertionSuccess(); } TEST_P(TestdataSourceTest, TestdataSourceHasValidDataForRegion) { std::string key = "data/" + GetParam(); source_.Get(key, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(key, key_); EXPECT_TRUE(DataIsValid(data_, key)); }; TEST_P(TestdataSourceTest, TestdataSourceWithPathHasValidDataForRegion) { std::string key = "data/" + GetParam(); source_with_path_.Get(key, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(key, key_); EXPECT_TRUE(DataIsValid(data_, key)); }; testing::AssertionResult AggregateDataIsValid(const std::string& data, const std::string& key) { if (data.empty()) { return testing::AssertionFailure() << "empty data"; } std::string expected_data_begin = "{\"" + key; if (data.compare(0, expected_data_begin.length(), expected_data_begin) != 0) { return testing::AssertionFailure() << data << " does not begin with " << expected_data_begin; } static const char kDataEnd[] = "\"}}"; static const size_t kDataEndLength = sizeof kDataEnd - 1; if (data.compare(data.length() - kDataEndLength, kDataEndLength, kDataEnd, kDataEndLength) != 0) { return testing::AssertionFailure() << data << " does not end with " << kDataEnd; } return testing::AssertionSuccess(); } TEST_P(TestdataSourceTest, TestdataSourceHasValidAggregatedDataForRegion) { std::string key = "data/" + GetParam(); aggregate_source_.Get(key, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(key, key_); EXPECT_TRUE(AggregateDataIsValid(data_, key)); }; TEST_P(TestdataSourceTest, TestdataSourceWithPathHasValidAggregatedDataForRegion) { std::string key = "data/" + GetParam(); aggregate_source_with_path_.Get(key, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(key, key_); EXPECT_TRUE(AggregateDataIsValid(data_, key)); }; INSTANTIATE_TEST_SUITE_P( AllRegions, TestdataSourceTest, testing::ValuesIn(RegionDataConstants::GetRegionCodes())); TEST_F(TestdataSourceTest, GetExistingData) { static const std::string kKey = "data"; source_.Get(kKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kKey, key_); EXPECT_TRUE(DataIsValid(data_, kKey)); } TEST_F(TestdataSourceTest, GetMissingKeyReturnsEmptyDictionary) { static const std::string kJunkKey = "junk"; source_.Get(kJunkKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kJunkKey, key_); EXPECT_EQ("{}", data_); } TEST_F(TestdataSourceTest, AggregateGetMissingKeyReturnsEmptyDictionary) { static const std::string kJunkKey = "junk"; aggregate_source_.Get(kJunkKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kJunkKey, key_); EXPECT_EQ("{}", data_); } TEST_F(TestdataSourceTest, GetEmptyKeyReturnsEmptyDictionary) { static const std::string kEmptyKey; source_.Get(kEmptyKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kEmptyKey, key_); EXPECT_EQ("{}", data_); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/testdata_source.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/testdata_source_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
fe4ae289-cef5-456c-802a-cfe0bf6dd346
cpp
google/libaddressinput
preload_supplier
cpp/src/preload_supplier.cc
cpp/test/preload_supplier_test.cc
#include <libaddressinput/preload_supplier.h> #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/callback.h> #include <libaddressinput/supplier.h> #include <algorithm> #include <cassert> #include <cstddef> #include <map> #include <memory> #include <set> #include <stack> #include <string> #include <vector> #include "lookup_key.h" #include "region_data_constants.h" #include "retriever.h" #include "rule.h" #include "util/json.h" #include "util/size.h" #include "util/string_compare.h" namespace i18n { namespace addressinput { namespace { class IndexLess { public: bool operator()(const std::string& a, const std::string& b) const { static const StringCompare kStringCompare; return kStringCompare.NaturalLess(a, b); } }; } class IndexMap : public std::map<std::string, const Rule*, IndexLess> {}; namespace { class Helper { public: Helper(const Helper&) = delete; Helper& operator=(const Helper&) = delete; Helper(const std::string& region_code, const std::string& key, const PreloadSupplier::Callback& loaded, const Retriever& retriever, std::set<std::string>* pending, IndexMap* rule_index, IndexMap* language_rule_index, std::vector<const Rule*>* rule_storage, std::map<std::string, const Rule*>* region_rules) : region_code_(region_code), loaded_(loaded), pending_(pending), rule_index_(rule_index), language_rule_index_(language_rule_index), rule_storage_(rule_storage), region_rules_(region_rules), retrieved_(BuildCallback(this, &Helper::OnRetrieved)) { assert(pending_ != nullptr); assert(rule_index_ != nullptr); assert(rule_storage_ != nullptr); assert(region_rules_ != nullptr); assert(retrieved_ != nullptr); pending_->insert(key); retriever.Retrieve(key, *retrieved_); } private: ~Helper() = default; void OnRetrieved(bool success, const std::string& key, const std::string& data) { int rule_count = 0; size_t status = pending_->erase(key); assert(status == 1); (void)status; Json json; std::string id; std::vector<const Rule*> sub_rules; auto last_index_it = rule_index_->end(); auto last_latin_it = rule_index_->end(); auto language_index_it = language_rule_index_->end(); auto last_region_it = region_rules_->end(); IndexMap::const_iterator hints[size(LookupKey::kHierarchy) - 1]; std::fill(hints, hints + size(hints), rule_index_->end()); if (!success) { goto callback; } if (!json.ParseObject(data)) { success = false; goto callback; } for (auto ptr : json.GetSubDictionaries()) { assert(ptr != nullptr); if (!ptr->GetStringValueForKey("id", &id)) { success = false; goto callback; } assert(!id.empty()); size_t depth = std::count(id.begin(), id.end(), '/') - 1; assert(depth < size(LookupKey::kHierarchy)); AddressField field = LookupKey::kHierarchy[depth]; auto* rule = new Rule; if (field == COUNTRY) { rule->CopyFrom(Rule::GetDefault()); } rule->ParseJsonRule(*ptr); assert(id == rule->GetId()); rule_storage_->push_back(rule); if (depth > 0) { sub_rules.push_back(rule); } last_index_it = rule_index_->emplace_hint(last_index_it, id, rule); last_region_it = region_rules_->emplace_hint(last_region_it, id, rule); ++rule_count; } for (auto ptr : sub_rules) { assert(ptr != nullptr); std::stack<const Rule*> hierarchy; hierarchy.push(ptr); for (std::string parent_id(ptr->GetId());;) { std::string::size_type pos = parent_id.rfind('/'); if (pos == sizeof "data/ZZ" - 1) { break; } parent_id.resize(pos); IndexMap::const_iterator* const hint = &hints[hierarchy.size() - 1]; if (*hint == rule_index_->end() || (*hint)->first != parent_id) { *hint = rule_index_->find(parent_id); } assert(*hint != rule_index_->end()); hierarchy.push((*hint)->second); } std::string human_id(ptr->GetId().substr(0, sizeof "data/ZZ" - 1)); std::string latin_id(human_id); for (; !hierarchy.empty(); hierarchy.pop()) { const Rule* rule = hierarchy.top(); human_id.push_back('/'); if (!rule->GetName().empty()) { human_id.append(rule->GetName()); } else { const std::string& id = rule->GetId(); std::string::size_type pos = id.rfind('/'); assert(pos != std::string::npos); human_id.append(id.substr(pos + 1)); } if (!rule->GetLatinName().empty()) { latin_id.push_back('/'); latin_id.append(rule->GetLatinName()); } } { const std::string& id = ptr->GetId(); std::string::size_type pos = id.rfind("--"); if (pos != std::string::npos) { language_index_it = language_rule_index_->emplace_hint( language_index_it, human_id, ptr); human_id.append(id, pos, id.size() - pos); } } last_index_it = rule_index_->emplace_hint(last_index_it, human_id, ptr); if (std::count(human_id.begin(), human_id.end(), '/') == std::count(latin_id.begin(), latin_id.end(), '/')) { last_latin_it = rule_index_->emplace_hint(last_latin_it, latin_id, ptr); } } callback: loaded_(success, region_code_, rule_count); delete this; } const std::string region_code_; const PreloadSupplier::Callback& loaded_; std::set<std::string>* const pending_; IndexMap* const rule_index_; IndexMap* const language_rule_index_; std::vector<const Rule*>* const rule_storage_; std::map<std::string, const Rule*>* const region_rules_; const std::unique_ptr<const Retriever::Callback> retrieved_; }; std::string KeyFromRegionCode(const std::string& region_code) { AddressData address; address.region_code = region_code; LookupKey lookup_key; lookup_key.FromAddress(address); return lookup_key.ToKeyString(0); } } PreloadSupplier::PreloadSupplier(const Source* source, Storage* storage) : retriever_(new Retriever(source, storage)), pending_(), rule_index_(new IndexMap), language_rule_index_(new IndexMap), rule_storage_(), region_rules_() {} PreloadSupplier::~PreloadSupplier() { for (auto ptr : rule_storage_) { delete ptr; } } void PreloadSupplier::Supply(const LookupKey& lookup_key, const Supplier::Callback& supplied) { Supplier::RuleHierarchy hierarchy; bool success = GetRuleHierarchy(lookup_key, &hierarchy, false); supplied(success, lookup_key, hierarchy); } void PreloadSupplier::SupplyGlobally(const LookupKey& lookup_key, const Supplier::Callback& supplied) { Supplier::RuleHierarchy hierarchy; bool success = GetRuleHierarchy(lookup_key, &hierarchy, true); supplied(success, lookup_key, hierarchy); } const Rule* PreloadSupplier::GetRule(const LookupKey& lookup_key) const { assert(IsLoaded(lookup_key.GetRegionCode())); Supplier::RuleHierarchy hierarchy; if (!GetRuleHierarchy(lookup_key, &hierarchy, false)) { return nullptr; } return hierarchy.rule[lookup_key.GetDepth()]; } void PreloadSupplier::LoadRules(const std::string& region_code, const Callback& loaded) { const std::string key = KeyFromRegionCode(region_code); if (IsLoadedKey(key)) { loaded(true, region_code, 0); return; } if (IsPendingKey(key)) { return; } new Helper(region_code, key, loaded, *retriever_, &pending_, rule_index_.get(), language_rule_index_.get(), &rule_storage_, &region_rules_[region_code]); } const std::map<std::string, const Rule*>& PreloadSupplier::GetRulesForRegion( const std::string& region_code) const { assert(IsLoaded(region_code)); return region_rules_.find(region_code)->second; } bool PreloadSupplier::IsLoaded(const std::string& region_code) const { return IsLoadedKey(KeyFromRegionCode(region_code)); } bool PreloadSupplier::IsPending(const std::string& region_code) const { return IsPendingKey(KeyFromRegionCode(region_code)); } bool PreloadSupplier::GetRuleHierarchy(const LookupKey& lookup_key, RuleHierarchy* hierarchy, const bool search_globally) const { assert(hierarchy != nullptr); if (RegionDataConstants::IsSupported(lookup_key.GetRegionCode())) { size_t max_depth = std::min( lookup_key.GetDepth(), RegionDataConstants::GetMaxLookupKeyDepth(lookup_key.GetRegionCode())); for (size_t depth = 0; depth <= max_depth; ++depth) { const std::string key = lookup_key.ToKeyString(depth); const Rule* rule = nullptr; auto it = rule_index_->find(key); if (it != rule_index_->end()) { rule = it->second; } else if (search_globally && depth > 0 && !hierarchy->rule[0]->GetLanguages().empty()) { it = language_rule_index_->find(key); if (it != language_rule_index_->end()) { rule = it->second; } } if (rule == nullptr) { return depth > 0; } hierarchy->rule[depth] = rule; } } return true; } size_t PreloadSupplier::GetLoadedRuleDepth( const std::string& region_code) const { const size_t code_size = 7; std::string full_code = region_code.substr(0, code_size); size_t depth = 0; auto it = rule_index_->find(full_code); while (it != rule_index_->end()) { const Rule* rule = it->second; depth++; if (rule->GetSubKeys().empty()) return depth; full_code += "/" + rule->GetSubKeys()[0]; it = rule_index_->find(full_code); } return depth; } bool PreloadSupplier::IsLoadedKey(const std::string& key) const { return rule_index_->find(key) != rule_index_->end(); } bool PreloadSupplier::IsPendingKey(const std::string& key) const { return pending_.find(key) != pending_.end(); } } }
#include <libaddressinput/preload_supplier.h> #include <libaddressinput/address_data.h> #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/supplier.h> #include <cstddef> #include <memory> #include <string> #include <gtest/gtest.h> #include "lookup_key.h" #include "rule.h" #include "testdata_source.h" namespace { using i18n::addressinput::AddressData; using i18n::addressinput::BuildCallback; using i18n::addressinput::LookupKey; using i18n::addressinput::NullStorage; using i18n::addressinput::PreloadSupplier; using i18n::addressinput::Rule; using i18n::addressinput::Supplier; using i18n::addressinput::TestdataSource; class PreloadSupplierTest : public testing::Test { public: PreloadSupplierTest(const PreloadSupplierTest&) = delete; PreloadSupplierTest& operator=(const PreloadSupplierTest&) = delete; protected: PreloadSupplierTest() : supplier_(new TestdataSource(true), new NullStorage), loaded_callback_(BuildCallback(this, &PreloadSupplierTest::OnLoaded)), supplied_callback_( BuildCallback(this, &PreloadSupplierTest::OnSupplied)) {} PreloadSupplier supplier_; const std::unique_ptr<const PreloadSupplier::Callback> loaded_callback_; const std::unique_ptr<const Supplier::Callback> supplied_callback_; Supplier::RuleHierarchy hierarchy_; private: void OnLoaded(bool success, const std::string& region_code, int num_rules) { ASSERT_TRUE(success); ASSERT_FALSE(region_code.empty()); ASSERT_LT(0, num_rules); ASSERT_TRUE(supplier_.IsLoaded(region_code)); } void OnSupplied(bool success, const LookupKey& lookup_key, const Supplier::RuleHierarchy& hierarchy) { ASSERT_TRUE(success); hierarchy_ = hierarchy; } }; TEST_F(PreloadSupplierTest, GetUsRule) { supplier_.LoadRules("US", *loaded_callback_); LookupKey us_key; const AddressData us_address{.region_code = "US"}; us_key.FromAddress(us_address); const Rule* rule = supplier_.GetRule(us_key); ASSERT_TRUE(rule != nullptr); EXPECT_EQ("data/US", rule->GetId()); } TEST_F(PreloadSupplierTest, GetUsCaRule) { supplier_.LoadRules("US", *loaded_callback_); LookupKey ca_key; const AddressData ca_address{ .region_code = "US", .administrative_area = "CA", }; ca_key.FromAddress(ca_address); const Rule* rule = supplier_.GetRule(ca_key); ASSERT_TRUE(rule != nullptr); EXPECT_EQ("data/US/CA", rule->GetId()); } TEST_F(PreloadSupplierTest, GetUsCaliforniaRule) { supplier_.LoadRules("US", *loaded_callback_); LookupKey ca_key; const AddressData ca_address{ .region_code = "US", .administrative_area = "California", }; ca_key.FromAddress(ca_address); const Rule* rule = supplier_.GetRule(ca_key); ASSERT_TRUE(rule != nullptr); EXPECT_EQ("data/US/CA", rule->GetId()); } TEST_F(PreloadSupplierTest, GetZwRule) { supplier_.LoadRules("ZW", *loaded_callback_); LookupKey zw_key; const AddressData zw_address{.region_code = "ZW"}; zw_key.FromAddress(zw_address); const Rule* rule = supplier_.GetRule(zw_key); ASSERT_TRUE(rule != nullptr); EXPECT_EQ("data/ZW", rule->GetId()); } TEST_F(PreloadSupplierTest, GetUnknownRule) { supplier_.LoadRules("US", *loaded_callback_); LookupKey unknown_key; const AddressData unknown_address{ .region_code = "US", .administrative_area = "ZZ", }; unknown_key.FromAddress(unknown_address); const Rule* rule = supplier_.GetRule(unknown_key); EXPECT_TRUE(rule == nullptr); } TEST_F(PreloadSupplierTest, GetTooPreciseRule) { supplier_.LoadRules("US", *loaded_callback_); LookupKey precise_key; const AddressData precise_address{ .region_code = "US", .administrative_area = "CA", .locality = "Mountain View", }; precise_key.FromAddress(precise_address); const Rule* rule = supplier_.GetRule(precise_key); EXPECT_TRUE(rule == nullptr); } TEST_F(PreloadSupplierTest, GetRulesForRegion) { supplier_.LoadRules("CN", *loaded_callback_); const auto& rules = supplier_.GetRulesForRegion("CN"); EXPECT_TRUE(rules.find("data/CN") != rules.end()); EXPECT_LT(1U, rules.size()); } TEST_F(PreloadSupplierTest, SupplyRegionCode) { supplier_.LoadRules("CA", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CA", .administrative_area = "NB", }; key.FromAddress(address); supplier_.Supply(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/CA/NB", hierarchy_.rule[1]->GetId()); EXPECT_TRUE(hierarchy_.rule[2] == nullptr); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyGloballyRegionCode) { supplier_.LoadRules("CA", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CA", .administrative_area = "NB", }; key.FromAddress(address); supplier_.SupplyGlobally(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/CA/NB", hierarchy_.rule[1]->GetId()); EXPECT_TRUE(hierarchy_.rule[2] == nullptr); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyRegionName) { supplier_.LoadRules("CA", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CA", .administrative_area = "New Brunswick", }; key.FromAddress(address); supplier_.Supply(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/CA/NB", hierarchy_.rule[1]->GetId()); EXPECT_TRUE(hierarchy_.rule[2] == nullptr); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyGloballyRegionName) { supplier_.LoadRules("CA", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CA", .administrative_area = "New Brunswick", }; key.FromAddress(address); supplier_.SupplyGlobally(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/CA/NB", hierarchy_.rule[1]->GetId()); EXPECT_TRUE(hierarchy_.rule[2] == nullptr); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyRegionNameLanguage) { supplier_.LoadRules("CA", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CA", .administrative_area = "Nouveau-Brunswick", }; key.FromAddress(address); supplier_.Supply(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); EXPECT_TRUE(hierarchy_.rule[1] == nullptr); EXPECT_TRUE(hierarchy_.rule[2] == nullptr); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyRegionNameLanguageSet) { supplier_.LoadRules("CA", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CA", .administrative_area = "Nouveau-Brunswick", .language_code = "fr", }; key.FromAddress(address); supplier_.Supply(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/CA/NB--fr", hierarchy_.rule[1]->GetId()); EXPECT_TRUE(hierarchy_.rule[2] == nullptr); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyGloballyRegionNameLanguage) { supplier_.LoadRules("CA", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CA", .administrative_area = "Nouveau-Brunswick", }; key.FromAddress(address); supplier_.SupplyGlobally(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/CA/NB--fr", hierarchy_.rule[1]->GetId()); EXPECT_TRUE(hierarchy_.rule[2] == nullptr); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyRegionNameHK) { supplier_.LoadRules("HK", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "HK", .administrative_area = "新界", .locality = "大嶼山石壁", }; key.FromAddress(address); supplier_.Supply(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/HK/新界", hierarchy_.rule[1]->GetId()); ASSERT_TRUE(hierarchy_.rule[2] != nullptr); EXPECT_EQ("data/HK/新界/大嶼山石壁", hierarchy_.rule[2]->GetId()); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyGloballyRegionNameHKEnglish) { supplier_.LoadRules("HK", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "HK", .administrative_area = "New Territories", .locality = "Tsing Yi", }; key.FromAddress(address); supplier_.SupplyGlobally(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/HK/New Territories--en", hierarchy_.rule[1]->GetId()); ASSERT_TRUE(hierarchy_.rule[2] != nullptr); EXPECT_EQ("data/HK/New Territories/Tsing Yi--en", hierarchy_.rule[2]->GetId()); EXPECT_TRUE(hierarchy_.rule[3] == nullptr); } TEST_F(PreloadSupplierTest, SupplyRegionNameAllLevels) { supplier_.LoadRules("CN", *loaded_callback_); LookupKey key; const AddressData address{ .region_code = "CN", .administrative_area = "云南省", .locality = "临沧市", .dependent_locality = "临翔区", }; key.FromAddress(address); supplier_.Supply(key, *supplied_callback_); ASSERT_TRUE(hierarchy_.rule[0] != nullptr); EXPECT_EQ(key.ToKeyString(0), hierarchy_.rule[0]->GetId()); ASSERT_TRUE(hierarchy_.rule[1] != nullptr); EXPECT_EQ("data/CN/云南省", hierarchy_.rule[1]->GetId()); ASSERT_TRUE(hierarchy_.rule[2] != nullptr); EXPECT_EQ("data/CN/云南省/临沧市", hierarchy_.rule[2]->GetId()); ASSERT_TRUE(hierarchy_.rule[3] != nullptr); EXPECT_EQ("data/CN/云南省/临沧市/临翔区", hierarchy_.rule[3]->GetId()); } TEST_F(PreloadSupplierTest, GetLoadedRuleDepth) { supplier_.LoadRules("CA", *loaded_callback_); EXPECT_EQ(2, supplier_.GetLoadedRuleDepth("data/CA")); EXPECT_EQ(0, supplier_.GetLoadedRuleDepth( "data/CN")); supplier_.LoadRules("CN", *loaded_callback_); EXPECT_EQ(4, supplier_.GetLoadedRuleDepth( "data/CN")); EXPECT_EQ( 0, supplier_.GetLoadedRuleDepth("data/PP")); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/preload_supplier.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/preload_supplier_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
cccc576d-36ac-4c6e-b326-5772629b3882
cpp
google/libaddressinput
rule_retriever
cpp/src/rule_retriever.cc
cpp/test/rule_retriever_test.cc
#include "rule_retriever.h" #include <libaddressinput/callback.h> #include <cassert> #include <cstddef> #include <memory> #include <string> #include "retriever.h" #include "rule.h" namespace i18n { namespace addressinput { namespace { class Helper { public: Helper(const Helper&) = delete; Helper& operator=(const Helper&) = delete; Helper(const std::string& key, const RuleRetriever::Callback& rule_ready, const Retriever& data_retriever) : rule_ready_(rule_ready), data_retrieved_(BuildCallback(this, &Helper::OnDataRetrieved)) { data_retriever.Retrieve(key, *data_retrieved_); } private: ~Helper() = default; void OnDataRetrieved(bool success, const std::string& key, const std::string& data) { Rule rule; if (!success) { rule_ready_(false, key, rule); } else { success = rule.ParseSerializedRule(data); rule_ready_(success, key, rule); } delete this; } const RuleRetriever::Callback& rule_ready_; const std::unique_ptr<const Retriever::Callback> data_retrieved_; }; } RuleRetriever::RuleRetriever(const Retriever* retriever) : data_retriever_(retriever) { assert(data_retriever_ != nullptr); } RuleRetriever::~RuleRetriever() = default; void RuleRetriever::RetrieveRule(const std::string& key, const Callback& rule_ready) const { new Helper(key, rule_ready, *data_retriever_); } } }
#include "rule_retriever.h" #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <memory> #include <string> #include <gtest/gtest.h> #include "retriever.h" #include "rule.h" #include "testdata_source.h" namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::NullStorage; using i18n::addressinput::Retriever; using i18n::addressinput::Rule; using i18n::addressinput::RuleRetriever; using i18n::addressinput::TestdataSource; class RuleRetrieverTest : public testing::Test { public: RuleRetrieverTest(const RuleRetrieverTest&) = delete; RuleRetrieverTest& operator=(const RuleRetrieverTest&) = delete; protected: RuleRetrieverTest() : rule_retriever_( new Retriever(new TestdataSource(false), new NullStorage)), success_(false), key_(), rule_(), rule_ready_(BuildCallback(this, &RuleRetrieverTest::OnRuleReady)) {} RuleRetriever rule_retriever_; bool success_; std::string key_; Rule rule_; const std::unique_ptr<const RuleRetriever::Callback> rule_ready_; private: void OnRuleReady(bool success, const std::string& key, const Rule& rule) { success_ = success; key_ = key; rule_.CopyFrom(rule); } }; TEST_F(RuleRetrieverTest, ExistingRule) { static const char kExistingKey[] = "data/CA"; rule_retriever_.RetrieveRule(kExistingKey, *rule_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kExistingKey, key_); EXPECT_FALSE(rule_.GetFormat().empty()); } TEST_F(RuleRetrieverTest, MissingRule) { static const char kMissingKey[] = "junk"; rule_retriever_.RetrieveRule(kMissingKey, *rule_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kMissingKey, key_); EXPECT_TRUE(rule_.GetFormat().empty()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/rule_retriever.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/rule_retriever_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
9a1e9b2d-2600-48e3-99d7-97d71167687b
cpp
google/libaddressinput
region_data
cpp/src/region_data.cc
cpp/test/region_data_test.cc
#include <libaddressinput/region_data.h> #include <cstddef> #include <string> #include <vector> namespace i18n { namespace addressinput { RegionData::RegionData(const std::string& region_code) : key_(region_code), name_(region_code), parent_(nullptr), sub_regions_() {} RegionData::~RegionData() { for (auto ptr : sub_regions_) { delete ptr; } } RegionData* RegionData::AddSubRegion(const std::string& key, const std::string& name) { auto* sub_region = new RegionData(key, name, this); sub_regions_.push_back(sub_region); return sub_region; } RegionData::RegionData(const std::string& key, const std::string& name, RegionData* parent) : key_(key), name_(name), parent_(parent), sub_regions_() {} } }
#include <libaddressinput/region_data.h> #include <cstddef> #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::RegionData; TEST(RegionDataTest, NoParentByDefault) { static const std::string kEmpty; RegionData region(kEmpty); EXPECT_FALSE(region.has_parent()); } TEST(RegionDataTest, NoSubRegionsByDefault) { static const std::string kEmpty; RegionData region(kEmpty); EXPECT_TRUE(region.sub_regions().empty()); } TEST(RegionDataTest, SubRegionGetsParent) { static const std::string kEmpty; RegionData region(kEmpty); region.AddSubRegion(kEmpty, kEmpty); ASSERT_EQ(1U, region.sub_regions().size()); ASSERT_TRUE(region.sub_regions()[0] != nullptr); EXPECT_EQ(&region, &region.sub_regions()[0]->parent()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/region_data.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/region_data_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
f1b1e34e-ee3d-41fc-b951-2ce70275d5d5
cpp
google/libaddressinput
format_element
cpp/src/format_element.cc
cpp/test/format_element_test.cc
#include "format_element.h" #include <libaddressinput/address_field.h> #include <cassert> #include <ostream> #include <string> namespace i18n { namespace addressinput { FormatElement::FormatElement(AddressField field) : field_(field), literal_() {} FormatElement::FormatElement(const std::string& literal) : field_(COUNTRY), literal_(literal) { assert(!literal.empty()); } FormatElement::FormatElement() : field_(COUNTRY), literal_("\n") {} bool FormatElement::operator==(const FormatElement& other) const { return field_ == other.field_ && literal_ == other.literal_; } } } std::ostream& operator<<(std::ostream& o, const i18n::addressinput::FormatElement& element) { if (element.IsField()) { o << "Field: " << element.GetField(); } else if (element.IsNewline()) { o << "Newline"; } else { o << "Literal: " << element.GetLiteral(); } return o; }
#include "format_element.h" #include <libaddressinput/address_field.h> #include <sstream> #include <gtest/gtest.h> namespace { using i18n::addressinput::FormatElement; using i18n::addressinput::SORTING_CODE; TEST(FormatElementTest, StreamFunctionNewline) { std::ostringstream oss; oss << FormatElement(); EXPECT_EQ("Newline", oss.str()); } TEST(FormatElementTest, StreamFunctionLiteral) { std::ostringstream oss; oss << FormatElement("Text"); EXPECT_EQ("Literal: Text", oss.str()); } TEST(FormatElementTest, StreamFunctionField) { std::ostringstream oss; oss << FormatElement(SORTING_CODE); EXPECT_EQ("Field: SORTING_CODE", oss.str()); } TEST(FormatElementTest, IsNewline) { EXPECT_TRUE(FormatElement().IsNewline()); EXPECT_FALSE(FormatElement(" ").IsNewline()); EXPECT_FALSE(FormatElement(SORTING_CODE).IsNewline()); } TEST(FormatElementTest, IsField) { EXPECT_FALSE(FormatElement().IsField()); EXPECT_FALSE(FormatElement(" ").IsField()); EXPECT_TRUE(FormatElement(SORTING_CODE).IsField()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/format_element.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/format_element_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
333a7cfe-6295-4698-b869-8f92995f060a
cpp
google/libaddressinput
validating_util
cpp/src/validating_util.cc
cpp/test/validating_util_test.cc
#include "validating_util.h" #include <cassert> #include <cstddef> #include <cstdio> #include <cstdlib> #include <ctime> #include <string> #include "util/md5.h" namespace i18n { namespace addressinput { namespace { const char kTimestampPrefix[] = "timestamp="; const size_t kTimestampPrefixLength = sizeof kTimestampPrefix - 1; const char kChecksumPrefix[] = "checksum="; const size_t kChecksumPrefixLength = sizeof kChecksumPrefix - 1; const char kSeparator = '\n'; bool UnwrapHeader(const char* header_prefix, size_t header_prefix_length, std::string* data, std::string* header_value) { assert(header_prefix != nullptr); assert(data != nullptr); assert(header_value != nullptr); if (data->compare( 0, header_prefix_length, header_prefix, header_prefix_length) != 0) { return false; } std::string::size_type separator_position = data->find(kSeparator, header_prefix_length); if (separator_position == std::string::npos) { return false; } header_value->assign( *data, header_prefix_length, separator_position - header_prefix_length); data->erase(0, separator_position + 1); return true; } } void ValidatingUtil::Wrap(time_t timestamp, std::string* data) { assert(data != nullptr); char timestamp_string[2 + 3 * sizeof timestamp]; int size = std::snprintf(timestamp_string, sizeof(timestamp_string), "%ld", static_cast<long>(timestamp)); assert(size > 0); assert(size < sizeof timestamp_string); (void)size; std::string header; header.append(kTimestampPrefix, kTimestampPrefixLength); header.append(timestamp_string); header.push_back(kSeparator); header.append(kChecksumPrefix, kChecksumPrefixLength); header.append(MD5String(*data)); header.push_back(kSeparator); data->reserve(header.size() + data->size()); data->insert(0, header); } bool ValidatingUtil::UnwrapTimestamp(std::string* data, time_t now) { assert(data != nullptr); if (now < 0) { return false; } std::string timestamp_string; if (!UnwrapHeader( kTimestampPrefix, kTimestampPrefixLength, data, &timestamp_string)) { return false; } time_t timestamp = atol(timestamp_string.c_str()); if (timestamp < 0) { return false; } static const double kOneMonthInSeconds = 30.0 * 24.0 * 60.0 * 60.0; double age_in_seconds = difftime(now, timestamp); return !(age_in_seconds < 0.0) && age_in_seconds < kOneMonthInSeconds; } bool ValidatingUtil::UnwrapChecksum(std::string* data) { assert(data != nullptr); std::string checksum; if (!UnwrapHeader(kChecksumPrefix, kChecksumPrefixLength, data, &checksum)) { return false; } return checksum == MD5String(*data); } } }
#include "validating_util.h" #include <string> #include <gtest/gtest.h> #define ITOA_HELPER(i) #i #define ITOA(i) ITOA_HELPER(i) #define DATA "{'foo': 'bar'}" #define TIMESTAMP 1388001600 #define TIMESTAMP_HALF_MONTH_AGO 1386705600 #define TIMESTAMP_TWO_MONTHS_AGO 1382817600 #define CHECKSUM "dd63dafcbd4d5b28badfcaf86fb6fcdb" namespace { using i18n::addressinput::ValidatingUtil; const char kUnwrappedData[] = DATA; const time_t kTimestamp = TIMESTAMP; const char kChecksummedData[] = "checksum=" CHECKSUM "\n" DATA; const char kCorruptedChecksummedData[] = "checksuM=" CHECKSUM "\n" DATA; const char kChecksumInMiddle[] = DATA "\n" "checksum=" CHECKSUM "\n" DATA; const char kWrappedData[] = "timestamp=" ITOA(TIMESTAMP) "\n" "checksum=" CHECKSUM "\n" DATA; const char kCorruptedWrappedData[] = "timestamP=" ITOA(TIMESTAMP) "\n" "checksum=" CHECKSUM "\n" DATA; const char kTimestampInMiddle[] = DATA "\n" "timestamp=" ITOA(TIMESTAMP) "\n" DATA; const char kTimestampHalfMonthAgo[] = "timestamp=" ITOA(TIMESTAMP_HALF_MONTH_AGO) "\n" DATA; const char kTimestampTwoMonthsAgo[] = "timestamp=" ITOA(TIMESTAMP_TWO_MONTHS_AGO) "\n" DATA; TEST(ValidatingUtilTest, UnwrapChecksum_CorruptedData) { std::string data(kCorruptedChecksummedData); EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data)); } TEST(ValidatingUtilTest, UnwrapChecksum_EmptyString) { std::string data; EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data)); } TEST(ValidatingUtilTest, UnwrapChecksum_GarbageData) { std::string data("garbage"); EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data)); } TEST(ValidatingUtilTest, UnwrapChecksum_InMiddle) { std::string data(kChecksumInMiddle); EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data)); } TEST(ValidatingUtilTest, UnwrapChecksum) { std::string data(kChecksummedData); EXPECT_TRUE(ValidatingUtil::UnwrapChecksum(&data)); EXPECT_EQ(kUnwrappedData, data); } TEST(ValidatingUtilTest, UnwrapTimestamp_CorruptedData) { std::string data(kCorruptedWrappedData); EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); } TEST(ValidatingUtilTest, UnwrapTimestamp_EmptyString) { std::string data; EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); } TEST(ValidatingUtilTest, UnwrapTimestamp_GarbageData) { std::string data("garbage"); EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); } TEST(ValidatingUtilTest, UnwrapTimestamp_InMiddle) { std::string data(kTimestampInMiddle); EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); } TEST(ValidatingUtilTest, UnwrapTimestamp_Recent) { std::string data(kTimestampHalfMonthAgo); EXPECT_TRUE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); EXPECT_EQ(kUnwrappedData, data); } TEST(ValidatingUtilTest, UnwrapTimestamp_Stale) { std::string data(kTimestampTwoMonthsAgo); EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); } TEST(ValidatingUtilTest, UnwrapTimestamp) { std::string data(kWrappedData); EXPECT_TRUE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); EXPECT_EQ(kChecksummedData, data); } TEST(ValidatingUtilTest, Wrap) { std::string data = kUnwrappedData; ValidatingUtil::Wrap(kTimestamp, &data); EXPECT_EQ(kWrappedData, data); } TEST(ValidatingUtilTest, WrapUnwrapIt) { std::string data = kUnwrappedData; ValidatingUtil::Wrap(kTimestamp, &data); EXPECT_TRUE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp)); EXPECT_EQ(kChecksummedData, data); EXPECT_TRUE(ValidatingUtil::UnwrapChecksum(&data)); EXPECT_EQ(kUnwrappedData, data); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/validating_util.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/validating_util_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
c62d5172-4d32-4cae-98d8-797551044cf6
cpp
google/libaddressinput
lookup_key
cpp/src/lookup_key.cc
cpp/test/lookup_key_test.cc
#include "lookup_key.h" #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <algorithm> #include <cassert> #include <cstddef> #include <functional> #include <string> #include "language.h" #include "region_data_constants.h" #include "rule.h" #include "util/cctype_tolower_equal.h" #include "util/size.h" namespace i18n { namespace addressinput { namespace { const char kSlashDelim[] = "/"; const char kDashDelim[] = "--"; const char kData[] = "data"; const char kUnknown[] = "ZZ"; bool ShouldSetLanguageForKey(const std::string& language_tag, const std::string& region_code) { if (RegionDataConstants::GetMaxLookupKeyDepth(region_code) == 0) { return false; } Rule rule; rule.CopyFrom(Rule::GetDefault()); if (!rule.ParseSerializedRule( RegionDataConstants::GetRegionData(region_code))) { return false; } const auto& languages = rule.GetLanguages(); if (languages.empty() || languages[0] == language_tag) { return false; } using std::placeholders::_1; return std::find_if(languages.begin() + 1, languages.end(), std::bind(&EqualToTolowerString, _1, language_tag)) != languages.end(); } } const AddressField LookupKey::kHierarchy[] = { COUNTRY, ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY, }; LookupKey::LookupKey() = default; LookupKey::~LookupKey() = default; void LookupKey::FromAddress(const AddressData& address) { nodes_.clear(); if (address.region_code.empty()) { nodes_.emplace(COUNTRY, kUnknown); } else { for (AddressField field : kHierarchy) { if (address.IsFieldEmpty(field)) { break; } const std::string& value = address.GetFieldValue(field); if (value.find('/') != std::string::npos) { break; } nodes_.emplace(field, value); } } Language address_language(address.language_code); std::string language_tag_no_latn = address_language.has_latin_script ? address_language.base : address_language.tag; if (ShouldSetLanguageForKey(language_tag_no_latn, address.region_code)) { language_ = language_tag_no_latn; } } void LookupKey::FromLookupKey(const LookupKey& parent, const std::string& child_node) { assert(parent.nodes_.size() < size(kHierarchy)); assert(!child_node.empty()); if (this != &parent) nodes_ = parent.nodes_; AddressField child_field = kHierarchy[nodes_.size()]; nodes_.emplace(child_field, child_node); } std::string LookupKey::ToKeyString(size_t max_depth) const { assert(max_depth < size(kHierarchy)); std::string key_string(kData); for (size_t i = 0; i <= max_depth; ++i) { AddressField field = kHierarchy[i]; auto it = nodes_.find(field); if (it == nodes_.end()) { break; } key_string.append(kSlashDelim); key_string.append(it->second); } if (!language_.empty()) { key_string.append(kDashDelim); key_string.append(language_); } return key_string; } const std::string& LookupKey::GetRegionCode() const { auto it = nodes_.find(COUNTRY); assert(it != nodes_.end()); return it->second; } size_t LookupKey::GetDepth() const { size_t depth = nodes_.size() - 1; assert(depth < size(kHierarchy)); return depth; } } }
#include "lookup_key.h" #include <libaddressinput/address_data.h> #include <cstddef> #include <gtest/gtest.h> #include "util/size.h" namespace { using i18n::addressinput::AddressData; using i18n::addressinput::LookupKey; const size_t kMaxDepth = size(LookupKey::kHierarchy) - 1; TEST(LookupKeyTest, Empty) { const AddressData address; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ("data/ZZ", lookup_key.ToKeyString(kMaxDepth)); } TEST(LookupKeyTest, AddressDepth1) { const AddressData address{.region_code = "111"}; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ(0, lookup_key.GetDepth()); EXPECT_EQ("data/111", lookup_key.ToKeyString(kMaxDepth)); } TEST(LookupKeyTest, AddressDepth2) { const AddressData address{ .region_code = "111", .administrative_area = "222", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ(1, lookup_key.GetDepth()); EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth)); } TEST(LookupKeyTest, AddressDepth3) { const AddressData address{ .region_code = "111", .administrative_area = "222", .locality = "333", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ(2, lookup_key.GetDepth()); EXPECT_EQ("data/111/222/333", lookup_key.ToKeyString(kMaxDepth)); } TEST(LookupKeyTest, AddressDepth4) { const AddressData address{ .region_code = "111", .administrative_area = "222", .locality = "333", .dependent_locality = "444", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ(3, lookup_key.GetDepth()); EXPECT_EQ("data/111/222/333/444", lookup_key.ToKeyString(kMaxDepth)); } TEST(LookupKeyTest, AddressDepthNonContiguous) { const AddressData address{ .region_code = "111", .administrative_area = "222", .dependent_locality = "444", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ(1, lookup_key.GetDepth()); EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth)); } TEST(LookupKeyTest, AddressDepthTerminateOnSlash) { const AddressData address{ .region_code = "111", .administrative_area = "222", .locality = "3/3", .dependent_locality = "444", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ(1, lookup_key.GetDepth()); EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth)); } TEST(LookupKeyTest, RequestDepth) { const AddressData address{ .region_code = "111", .administrative_area = "222", .locality = "333", .dependent_locality = "444", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ("data/111", lookup_key.ToKeyString(0)); EXPECT_EQ("data/111/222", lookup_key.ToKeyString(1)); EXPECT_EQ("data/111/222/333", lookup_key.ToKeyString(2)); EXPECT_EQ("data/111/222/333/444", lookup_key.ToKeyString(3)); } TEST(LookupKeyTest, WithLanguageCodeDefaultLanguage) { const AddressData address{ .region_code = "CA", .administrative_area = "ON", .language_code = "en", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ("data/CA", lookup_key.ToKeyString(0)); EXPECT_EQ("data/CA/ON", lookup_key.ToKeyString(1)); } TEST(LookupKeyTest, WithLanguageCodeAlternateLanguage) { const AddressData address{ .region_code = "CA", .administrative_area = "ON", .language_code = "fr", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ("data/CA--fr", lookup_key.ToKeyString(0)); EXPECT_EQ("data/CA/ON--fr", lookup_key.ToKeyString(1)); } TEST(LookupKeyTest, WithLanguageCodeInvalidLanguage) { const AddressData address{ .region_code = "CA", .administrative_area = "ON", .language_code = "de", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ("data/CA", lookup_key.ToKeyString(0)); EXPECT_EQ("data/CA/ON", lookup_key.ToKeyString(1)); } TEST(LookupKeyTest, WithLanguageCodeAlternateLanguageNoState) { const AddressData address{ .region_code = "AF", .language_code = "ps", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ("data/AF", lookup_key.ToKeyString(0)); } TEST(LookupKeyTest, GetRegionCode) { const AddressData address{.region_code = "rrr"}; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ(address.region_code, lookup_key.GetRegionCode()); } TEST(LookupKeyTest, FromAddressClearsExistingNodes) { AddressData address{ .region_code = "111", .administrative_area = "222", }; LookupKey lookup_key; lookup_key.FromAddress(address); EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth)); address.administrative_area.clear(); lookup_key.FromAddress(address); EXPECT_EQ("data/111", lookup_key.ToKeyString(kMaxDepth)); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/lookup_key.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/lookup_key_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
3975291b-1507-48db-9dd2-f43682542a45
cpp
google/libaddressinput
rule
cpp/src/rule.cc
cpp/test/rule_test.cc
#include "rule.h" #include <algorithm> #include <cassert> #include <cstddef> #include <string> #include <utility> #include <re2/re2.h> #include "address_field_util.h" #include "format_element.h" #include "grit.h" #include "messages.h" #include "region_data_constants.h" #include "util/json.h" #include "util/re2ptr.h" #include "util/size.h" #include "util/string_split.h" namespace i18n { namespace addressinput { namespace { const char kSeparator = '~'; struct NameIdInfo { const char* name; int id; static bool less(const NameIdInfo& a, const NameIdInfo& b) { return strcmp(a.name, b.name) < 0; } }; struct NameIdMap { const NameIdInfo* infos; size_t size; int GetIdFromName(const std::string& name) const { NameIdInfo key{name.c_str()}; const NameIdInfo* begin = infos; const NameIdInfo* end = begin + size; const NameIdInfo* probe = std::lower_bound(begin, end, key, NameIdInfo::less); return probe != end && name == probe->name ? probe->id : INVALID_MESSAGE_ID; } bool IsSorted() const { for (size_t n = 1; n < size; ++n) { if (!NameIdInfo::less(infos[n - 1], infos[n])) { return false; } } return true; } }; const NameIdInfo kAdminAreaInfoArray[] = { {"area", IDS_LIBADDRESSINPUT_AREA}, {"county", IDS_LIBADDRESSINPUT_COUNTY}, {"department", IDS_LIBADDRESSINPUT_DEPARTMENT}, {"district", IDS_LIBADDRESSINPUT_DISTRICT}, {"do_si", IDS_LIBADDRESSINPUT_DO_SI}, {"emirate", IDS_LIBADDRESSINPUT_EMIRATE}, {"island", IDS_LIBADDRESSINPUT_ISLAND}, {"oblast", IDS_LIBADDRESSINPUT_OBLAST}, {"parish", IDS_LIBADDRESSINPUT_PARISH}, {"prefecture", IDS_LIBADDRESSINPUT_PREFECTURE}, {"province", IDS_LIBADDRESSINPUT_PROVINCE}, {"state", IDS_LIBADDRESSINPUT_STATE}, }; const NameIdMap kAdminAreaMessageIds{ kAdminAreaInfoArray, size(kAdminAreaInfoArray) }; const NameIdInfo kPostalCodeInfoArray[] = { {"eircode", IDS_LIBADDRESSINPUT_EIR_CODE_LABEL}, {"pin", IDS_LIBADDRESSINPUT_PIN_CODE_LABEL}, {"postal", IDS_LIBADDRESSINPUT_POSTAL_CODE_LABEL}, {"zip", IDS_LIBADDRESSINPUT_ZIP_CODE_LABEL}, }; const NameIdMap kPostalCodeMessageIds{ kPostalCodeInfoArray, size(kPostalCodeInfoArray) }; const NameIdInfo kLocalityInfoArray[] = { {"city", IDS_LIBADDRESSINPUT_LOCALITY_LABEL}, {"district", IDS_LIBADDRESSINPUT_DISTRICT}, {"post_town", IDS_LIBADDRESSINPUT_POST_TOWN}, {"suburb", IDS_LIBADDRESSINPUT_SUBURB}, }; const NameIdMap kLocalityMessageIds{ kLocalityInfoArray, size(kLocalityInfoArray) }; const NameIdInfo kSublocalityInfoArray[] = { {"district", IDS_LIBADDRESSINPUT_DISTRICT}, {"neighborhood", IDS_LIBADDRESSINPUT_NEIGHBORHOOD}, {"suburb", IDS_LIBADDRESSINPUT_SUBURB}, {"townland", IDS_LIBADDRESSINPUT_TOWNLAND}, {"village_township", IDS_LIBADDRESSINPUT_VILLAGE_TOWNSHIP}, }; const NameIdMap kSublocalityMessageIds{ kSublocalityInfoArray, size(kSublocalityInfoArray) }; #ifndef _NDEBUG struct StaticMapChecker { StaticMapChecker() { assert(kAdminAreaMessageIds.IsSorted()); assert(kPostalCodeMessageIds.IsSorted()); assert(kLocalityMessageIds.IsSorted()); assert(kSublocalityMessageIds.IsSorted()); } }; #endif bool ContainsRegExSpecialCharacters(const std::string& input) { return input.find_first_of(R"(([\{?)") != std::string::npos; } } Rule::Rule() : id_(), format_(), latin_format_(), required_(), sub_keys_(), languages_(), postal_code_matcher_(nullptr), sole_postal_code_(), admin_area_name_message_id_(INVALID_MESSAGE_ID), postal_code_name_message_id_(INVALID_MESSAGE_ID), locality_name_message_id_(INVALID_MESSAGE_ID), sublocality_name_message_id_(INVALID_MESSAGE_ID), name_(), latin_name_(), postal_code_example_(), post_service_url_() {} Rule::~Rule() = default; const Rule& Rule::GetDefault() { static Rule* default_rule = nullptr; if (default_rule == nullptr) { default_rule = new Rule; default_rule->ParseSerializedRule( RegionDataConstants::GetDefaultRegionData()); } return *default_rule; } void Rule::CopyFrom(const Rule& rule) { assert(this != &rule); id_ = rule.id_; format_ = rule.format_; latin_format_ = rule.latin_format_; required_ = rule.required_; sub_keys_ = rule.sub_keys_; languages_ = rule.languages_; postal_code_matcher_.reset( rule.postal_code_matcher_ == nullptr ? nullptr : new RE2ptr(new RE2(rule.postal_code_matcher_->ptr->pattern(), rule.postal_code_matcher_->ptr->options()))); sole_postal_code_ = rule.sole_postal_code_; admin_area_name_message_id_ = rule.admin_area_name_message_id_; postal_code_name_message_id_ = rule.postal_code_name_message_id_; locality_name_message_id_ = rule.locality_name_message_id_; sublocality_name_message_id_ = rule.sublocality_name_message_id_; name_ = rule.name_; latin_name_ = rule.latin_name_; postal_code_example_ = rule.postal_code_example_; post_service_url_ = rule.post_service_url_; } bool Rule::ParseSerializedRule(const std::string& serialized_rule) { Json json; if (!json.ParseObject(serialized_rule)) { return false; } ParseJsonRule(json); return true; } void Rule::ParseJsonRule(const Json& json) { #ifndef _NDEBUG static StaticMapChecker map_checker; #endif std::string value; if (json.GetStringValueForKey("id", &value)) { id_.swap(value); } if (json.GetStringValueForKey("fmt", &value)) { ParseFormatRule(value, &format_); } if (json.GetStringValueForKey("lfmt", &value)) { ParseFormatRule(value, &latin_format_); } if (json.GetStringValueForKey("require", &value)) { ParseAddressFieldsRequired(value, &required_); } if (json.GetStringValueForKey("sub_keys", &value)) { SplitString(value, kSeparator, &sub_keys_); } if (json.GetStringValueForKey("languages", &value)) { SplitString(value, kSeparator, &languages_); } sole_postal_code_.clear(); if (json.GetStringValueForKey("zip", &value)) { RE2::Options options; options.set_never_capture(true); RE2* matcher = new RE2("^(" + value + ")", options); if (matcher->ok()) { postal_code_matcher_.reset(new RE2ptr(matcher)); } else { postal_code_matcher_.reset(nullptr); delete matcher; } if (!ContainsRegExSpecialCharacters(value)) { sole_postal_code_.swap(value); } } if (json.GetStringValueForKey("state_name_type", &value)) { admin_area_name_message_id_ = kAdminAreaMessageIds.GetIdFromName(value); } if (json.GetStringValueForKey("zip_name_type", &value)) { postal_code_name_message_id_ = kPostalCodeMessageIds.GetIdFromName(value); } if (json.GetStringValueForKey("locality_name_type", &value)) { locality_name_message_id_ = kLocalityMessageIds.GetIdFromName(value); } if (json.GetStringValueForKey("sublocality_name_type", &value)) { sublocality_name_message_id_ = kSublocalityMessageIds.GetIdFromName(value); } if (json.GetStringValueForKey("name", &value)) { name_.swap(value); } if (json.GetStringValueForKey("lname", &value)) { latin_name_.swap(value); } if (json.GetStringValueForKey("zipex", &value)) { postal_code_example_.swap(value); } if (json.GetStringValueForKey("posturl", &value)) { post_service_url_.swap(value); } } } }
#include "rule.h" #include <libaddressinput/address_field.h> #include <libaddressinput/localization.h> #include <cstddef> #include <string> #include <utility> #include <vector> #include <gtest/gtest.h> #include "format_element.h" #include "grit.h" #include "messages.h" #include "region_data_constants.h" #include "util/json.h" namespace { using i18n::addressinput::AddressField; using i18n::addressinput::ADMIN_AREA; using i18n::addressinput::FormatElement; using i18n::addressinput::INVALID_MESSAGE_ID; using i18n::addressinput::Json; using i18n::addressinput::LOCALITY; using i18n::addressinput::Localization; using i18n::addressinput::RegionDataConstants; using i18n::addressinput::Rule; using i18n::addressinput::STREET_ADDRESS; TEST(RuleTest, CopyOverwritesRule) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule( R"({)" R"("fmt":"%S%Z",)" R"("lfmt":"%Z%S",)" R"("id":"data/XA",)" R"("name":"Le Test",)" R"("lname":"Testistan",)" R"("require":"AC",)" R"("sub_keys":"aa~bb~cc",)" R"("languages":"en~fr",)" R"("zip":"\\d{3}",)" R"("state_name_type":"area",)" R"("locality_name_type":"post_town",)" R"("sublocality_name_type":"neighborhood",)" R"("zip_name_type":"postal",)" R"("zipex":"1234",)" R"("posturl":"http: R"(})")); Rule copy; EXPECT_NE(rule.GetFormat(), copy.GetFormat()); EXPECT_NE(rule.GetLatinFormat(), copy.GetLatinFormat()); EXPECT_NE(rule.GetId(), copy.GetId()); EXPECT_NE(rule.GetRequired(), copy.GetRequired()); EXPECT_NE(rule.GetSubKeys(), copy.GetSubKeys()); EXPECT_NE(rule.GetLanguages(), copy.GetLanguages()); EXPECT_NE(rule.GetAdminAreaNameMessageId(), copy.GetAdminAreaNameMessageId()); EXPECT_NE(rule.GetPostalCodeNameMessageId(), copy.GetPostalCodeNameMessageId()); EXPECT_NE(rule.GetLocalityNameMessageId(), copy.GetLocalityNameMessageId()); EXPECT_NE(rule.GetSublocalityNameMessageId(), copy.GetSublocalityNameMessageId()); EXPECT_NE(rule.GetName(), copy.GetName()); EXPECT_NE(rule.GetLatinName(), copy.GetLatinName()); EXPECT_NE(rule.GetPostalCodeExample(), copy.GetPostalCodeExample()); EXPECT_NE(rule.GetPostServiceUrl(), copy.GetPostServiceUrl()); EXPECT_TRUE(rule.GetPostalCodeMatcher() != nullptr); EXPECT_TRUE(copy.GetPostalCodeMatcher() == nullptr); copy.CopyFrom(rule); EXPECT_EQ(rule.GetFormat(), copy.GetFormat()); EXPECT_EQ(rule.GetLatinFormat(), copy.GetLatinFormat()); EXPECT_EQ(rule.GetId(), copy.GetId()); EXPECT_EQ(rule.GetRequired(), copy.GetRequired()); EXPECT_EQ(rule.GetSubKeys(), copy.GetSubKeys()); EXPECT_EQ(rule.GetLanguages(), copy.GetLanguages()); EXPECT_EQ(rule.GetAdminAreaNameMessageId(), copy.GetAdminAreaNameMessageId()); EXPECT_EQ(rule.GetPostalCodeNameMessageId(), copy.GetPostalCodeNameMessageId()); EXPECT_EQ(rule.GetSublocalityNameMessageId(), copy.GetSublocalityNameMessageId()); EXPECT_EQ(rule.GetLocalityNameMessageId(), copy.GetLocalityNameMessageId()); EXPECT_EQ(rule.GetName(), copy.GetName()); EXPECT_EQ(rule.GetLatinName(), copy.GetLatinName()); EXPECT_EQ(rule.GetPostalCodeExample(), copy.GetPostalCodeExample()); EXPECT_EQ(rule.GetPostServiceUrl(), copy.GetPostServiceUrl()); EXPECT_TRUE(copy.GetPostalCodeMatcher() != nullptr); } TEST(RuleTest, ParseOverwritesRule) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{" "\"fmt\":\"%S%Z\"," "\"state_name_type\":\"area\"," "\"zip\":\"1234\"," "\"zip_name_type\":\"postal\"," "\"zipex\":\"1234\"," "\"posturl\":\"http: "}")); EXPECT_FALSE(rule.GetFormat().empty()); EXPECT_EQ(IDS_LIBADDRESSINPUT_AREA, rule.GetAdminAreaNameMessageId()); EXPECT_EQ(IDS_LIBADDRESSINPUT_POSTAL_CODE_LABEL, rule.GetPostalCodeNameMessageId()); EXPECT_EQ("1234", rule.GetSolePostalCode()); EXPECT_EQ("1234", rule.GetPostalCodeExample()); EXPECT_EQ("http: ASSERT_TRUE(rule.ParseSerializedRule("{" "\"fmt\":\"\"," "\"state_name_type\":\"do_si\"," "\"zip_name_type\":\"zip\"," "\"zipex\":\"5678\"," "\"posturl\":\"http: "}")); EXPECT_TRUE(rule.GetFormat().empty()); EXPECT_EQ(IDS_LIBADDRESSINPUT_DO_SI, rule.GetAdminAreaNameMessageId()); EXPECT_EQ(IDS_LIBADDRESSINPUT_ZIP_CODE_LABEL, rule.GetPostalCodeNameMessageId()); EXPECT_TRUE(rule.GetSolePostalCode().empty()); EXPECT_EQ("5678", rule.GetPostalCodeExample()); EXPECT_EQ("http: } TEST(RuleTest, ParsesFormatCorrectly) { const std::vector<FormatElement> expected{ FormatElement{ADMIN_AREA}, FormatElement{LOCALITY}, }; Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"fmt\":\"%S%C\"}")); EXPECT_EQ(expected, rule.GetFormat()); } TEST(RuleTest, ParsesNameCorrectly) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"name\":\"Le Test\"}")); EXPECT_EQ("Le Test", rule.GetName()); } TEST(RuleTest, ParsesLatinNameCorrectly) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"lname\":\"Testistan\"}")); EXPECT_EQ("Testistan", rule.GetLatinName()); } TEST(RuleTest, ParsesLatinFormatCorrectly) { const std::vector<FormatElement> expected{ FormatElement{LOCALITY}, FormatElement{ADMIN_AREA}, }; Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"lfmt\":\"%C%S\"}")); EXPECT_EQ(expected, rule.GetLatinFormat()); } TEST(RuleTest, ParsesRequiredCorrectly) { const std::vector<AddressField> expected{ STREET_ADDRESS, LOCALITY, }; Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"require\":\"AC\"}")); EXPECT_EQ(expected, rule.GetRequired()); } TEST(RuleTest, ParsesSubKeysCorrectly) { const std::vector<std::string> expected{ "aa", "bb", "cc", }; Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"sub_keys\":\"aa~bb~cc\"}")); EXPECT_EQ(expected, rule.GetSubKeys()); } TEST(RuleTest, ParsesLanguagesCorrectly) { const std::vector<std::string> expected{ "de", "fr", "it", }; Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"de~fr~it\"}")); EXPECT_EQ(expected, rule.GetLanguages()); } TEST(RuleTest, ParsesPostalCodeExampleCorrectly) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"zipex\":\"1234,12345-6789\"}")); EXPECT_EQ("1234,12345-6789", rule.GetPostalCodeExample()); } TEST(RuleTest, ParsesPostServiceUrlCorrectly) { Rule rule; ASSERT_TRUE( rule.ParseSerializedRule("{\"posturl\":\"http: EXPECT_EQ("http: } TEST(RuleTest, PostalCodeMatcher) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule(R"({"zip":"\\d{3}"})")); EXPECT_TRUE(rule.GetPostalCodeMatcher() != nullptr); } TEST(RuleTest, PostalCodeMatcherInvalidRegExp) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule(R"({"zip":"("})")); EXPECT_TRUE(rule.GetPostalCodeMatcher() == nullptr); } TEST(RuleTest, ParsesJsonRuleCorrectly) { Json json; ASSERT_TRUE(json.ParseObject(R"({"zip":"\\d{3}"})")); Rule rule; rule.ParseJsonRule(json); EXPECT_TRUE(rule.GetPostalCodeMatcher() != nullptr); } TEST(RuleTest, EmptyStringIsNotValid) { Rule rule; EXPECT_FALSE(rule.ParseSerializedRule(std::string())); } TEST(RuleTest, EmptyDictionaryIsValid) { Rule rule; EXPECT_TRUE(rule.ParseSerializedRule("{}")); } class PostalCodeNameParseTest : public testing::TestWithParam<std::pair<std::string, int> > { public: PostalCodeNameParseTest(const PostalCodeNameParseTest&) = delete; PostalCodeNameParseTest& operator=(const PostalCodeNameParseTest&) = delete; protected: PostalCodeNameParseTest() = default; Rule rule_; }; TEST_P(PostalCodeNameParseTest, ParsedCorrectly) { ASSERT_TRUE(rule_.ParseSerializedRule(GetParam().first)); EXPECT_EQ(GetParam().second, rule_.GetPostalCodeNameMessageId()); } INSTANTIATE_TEST_SUITE_P( AllPostalCodeNames, PostalCodeNameParseTest, testing::Values(std::make_pair("{\"zip_name_type\":\"pin\"}", IDS_LIBADDRESSINPUT_PIN_CODE_LABEL), std::make_pair("{\"zip_name_type\":\"postal\"}", IDS_LIBADDRESSINPUT_POSTAL_CODE_LABEL), std::make_pair("{\"zip_name_type\":\"zip\"}", IDS_LIBADDRESSINPUT_ZIP_CODE_LABEL))); class LocalityNameParseTest : public testing::TestWithParam<std::pair<std::string, int> > { public: LocalityNameParseTest(const LocalityNameParseTest&) = delete; LocalityNameParseTest& operator=(const LocalityNameParseTest&) = delete; protected: LocalityNameParseTest() = default; Rule rule_; }; TEST_P(LocalityNameParseTest, ParsedCorrectly) { ASSERT_TRUE(rule_.ParseSerializedRule(GetParam().first)); EXPECT_EQ(GetParam().second, rule_.GetLocalityNameMessageId()); } INSTANTIATE_TEST_SUITE_P( AllLocalityNames, LocalityNameParseTest, testing::Values(std::make_pair("{\"locality_name_type\":\"post_town\"}", IDS_LIBADDRESSINPUT_POST_TOWN), std::make_pair("{\"locality_name_type\":\"city\"}", IDS_LIBADDRESSINPUT_LOCALITY_LABEL), std::make_pair("{\"locality_name_type\":\"district\"}", IDS_LIBADDRESSINPUT_DISTRICT))); class SublocalityNameParseTest : public testing::TestWithParam<std::pair<std::string, int> > { public: SublocalityNameParseTest(const SublocalityNameParseTest&) = delete; SublocalityNameParseTest& operator=(const SublocalityNameParseTest&) = delete; protected: SublocalityNameParseTest() = default; Rule rule_; }; TEST_P(SublocalityNameParseTest, ParsedCorrectly) { ASSERT_TRUE(rule_.ParseSerializedRule(GetParam().first)); EXPECT_EQ(GetParam().second, rule_.GetSublocalityNameMessageId()); } INSTANTIATE_TEST_SUITE_P( AllSublocalityNames, SublocalityNameParseTest, testing::Values( std::make_pair("{\"sublocality_name_type\":\"village_township\"}", IDS_LIBADDRESSINPUT_VILLAGE_TOWNSHIP), std::make_pair("{\"sublocality_name_type\":\"neighborhood\"}", IDS_LIBADDRESSINPUT_NEIGHBORHOOD), std::make_pair("{\"sublocality_name_type\":\"suburb\"}", IDS_LIBADDRESSINPUT_SUBURB), std::make_pair("{\"sublocality_name_type\":\"district\"}", IDS_LIBADDRESSINPUT_DISTRICT))); class AdminAreaNameParseTest : public testing::TestWithParam<std::pair<std::string, int> > { public: AdminAreaNameParseTest(const AdminAreaNameParseTest&) = delete; AdminAreaNameParseTest& operator=(const AdminAreaNameParseTest&) = delete; protected: AdminAreaNameParseTest() = default; Rule rule_; }; TEST_P(AdminAreaNameParseTest, ParsedCorrectly) { ASSERT_TRUE(rule_.ParseSerializedRule(GetParam().first)); EXPECT_EQ(GetParam().second, rule_.GetAdminAreaNameMessageId()); } INSTANTIATE_TEST_SUITE_P( AllAdminAreaNames, AdminAreaNameParseTest, testing::Values(std::make_pair("{\"state_name_type\":\"area\"}", IDS_LIBADDRESSINPUT_AREA), std::make_pair("{\"state_name_type\":\"county\"}", IDS_LIBADDRESSINPUT_COUNTY), std::make_pair("{\"state_name_type\":\"department\"}", IDS_LIBADDRESSINPUT_DEPARTMENT), std::make_pair("{\"state_name_type\":\"district\"}", IDS_LIBADDRESSINPUT_DISTRICT), std::make_pair("{\"state_name_type\":\"do_si\"}", IDS_LIBADDRESSINPUT_DO_SI), std::make_pair("{\"state_name_type\":\"emirate\"}", IDS_LIBADDRESSINPUT_EMIRATE), std::make_pair("{\"state_name_type\":\"island\"}", IDS_LIBADDRESSINPUT_ISLAND), std::make_pair("{\"state_name_type\":\"parish\"}", IDS_LIBADDRESSINPUT_PARISH), std::make_pair("{\"state_name_type\":\"prefecture\"}", IDS_LIBADDRESSINPUT_PREFECTURE), std::make_pair("{\"state_name_type\":\"province\"}", IDS_LIBADDRESSINPUT_PROVINCE), std::make_pair("{\"state_name_type\":\"state\"}", IDS_LIBADDRESSINPUT_STATE))); class RuleParseTest : public testing::TestWithParam<std::string> { public: RuleParseTest(const RuleParseTest&) = delete; RuleParseTest& operator=(const RuleParseTest&) = delete; protected: RuleParseTest() = default; std::string GetRegionData() const { std::string data = RegionDataConstants::GetRegionData(GetParam()); return !data.empty() ? data : GetParam(); } Rule rule_; Localization localization_; }; TEST_P(RuleParseTest, RegionDataParsedSuccessfully) { EXPECT_TRUE(rule_.ParseSerializedRule(GetRegionData())); } TEST_P(RuleParseTest, AdminAreaNameTypeHasUiString) { const std::string& region_data = GetRegionData(); rule_.ParseSerializedRule(region_data); if (region_data.find("state_name_type") != std::string::npos) { EXPECT_NE(INVALID_MESSAGE_ID, rule_.GetAdminAreaNameMessageId()); EXPECT_FALSE( localization_.GetString(rule_.GetAdminAreaNameMessageId()).empty()); } } TEST_P(RuleParseTest, PostalCodeNameTypeHasUiString) { const std::string& region_data = GetRegionData(); rule_.ParseSerializedRule(region_data); if (region_data.find("zip_name_type") != std::string::npos) { EXPECT_NE(INVALID_MESSAGE_ID, rule_.GetPostalCodeNameMessageId()); EXPECT_FALSE( localization_.GetString(rule_.GetPostalCodeNameMessageId()).empty()); } } TEST_P(RuleParseTest, LocalityNameTypeHasUiString) { const std::string& region_data = GetRegionData(); rule_.ParseSerializedRule(region_data); if (region_data.find("\"locality_name_type") != std::string::npos) { EXPECT_NE(INVALID_MESSAGE_ID, rule_.GetLocalityNameMessageId()); EXPECT_FALSE( localization_.GetString(rule_.GetLocalityNameMessageId()).empty()); } } TEST_P(RuleParseTest, SublocalityNameTypeHasUiString) { const std::string& region_data = GetRegionData(); rule_.ParseSerializedRule(region_data); if (region_data.find("sublocality_name_type") != std::string::npos) { EXPECT_NE(INVALID_MESSAGE_ID, rule_.GetSublocalityNameMessageId()); EXPECT_FALSE( localization_.GetString(rule_.GetSublocalityNameMessageId()).empty()); } } TEST_P(RuleParseTest, SolePostalCode) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"zip\":\"1234\"}")); EXPECT_TRUE(rule.GetPostalCodeMatcher() != nullptr); EXPECT_EQ(rule.GetSolePostalCode(), "1234"); Rule copy; EXPECT_TRUE(copy.GetPostalCodeMatcher() == nullptr); EXPECT_TRUE(copy.GetSolePostalCode().empty()); copy.CopyFrom(rule); EXPECT_TRUE(copy.GetPostalCodeMatcher() != nullptr); EXPECT_EQ(rule.GetSolePostalCode(), copy.GetSolePostalCode()); } INSTANTIATE_TEST_SUITE_P( AllRulesTest, RuleParseTest, testing::ValuesIn(RegionDataConstants::GetRegionCodes())); INSTANTIATE_TEST_SUITE_P( DefaultRuleTest, RuleParseTest, testing::Values(RegionDataConstants::GetDefaultRegionData())); }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/rule.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/rule_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
f28ff54a-3cd8-49b4-8105-283d85478981
cpp
google/libaddressinput
localization
cpp/src/localization.cc
cpp/test/localization_test.cc
#include <libaddressinput/localization.h> #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_problem.h> #include <cassert> #include <cstddef> #include <string> #include <vector> #include "messages.h" #include "region_data_constants.h" #include "rule.h" #include "util/string_split.h" #include "util/string_util.h" namespace { void PushBackUrl(const std::string& url, std::vector<std::string>* parameters) { assert(parameters != nullptr); parameters->push_back("<a href=\"" + url + "\">"); parameters->emplace_back("</a>"); } } namespace i18n { namespace addressinput { namespace { #include "en_messages.cc" std::string GetEnglishString(int message_id) { const char* str = GetString(message_id); return str != nullptr ? std::string(str) : std::string(); } } Localization::Localization() : get_string_(&GetEnglishString) {} std::string Localization::GetString(int message_id) const { return get_string_(message_id); } std::string Localization::GetErrorMessage(const AddressData& address, AddressField field, AddressProblem problem, bool enable_examples, bool enable_links) const { if (field == POSTAL_CODE) { Rule rule; rule.CopyFrom(Rule::GetDefault()); std::string postal_code_example, post_service_url; if (rule.ParseSerializedRule( RegionDataConstants::GetRegionData(address.region_code))) { if (enable_examples) { std::vector<std::string> examples_list; SplitString(rule.GetPostalCodeExample(), ',', &examples_list); if (!examples_list.empty()) { postal_code_example = examples_list.front(); } } if (enable_links) { post_service_url = rule.GetPostServiceUrl(); } } else { assert(false); } bool uses_postal_code_as_label = rule.GetPostalCodeNameMessageId() == IDS_LIBADDRESSINPUT_POSTAL_CODE_LABEL; return GetErrorMessageForPostalCode(problem, uses_postal_code_as_label, postal_code_example, post_service_url); } else { if (problem == MISSING_REQUIRED_FIELD) { return get_string_(IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD); } else if (problem == UNKNOWN_VALUE) { std::vector<std::string> parameters; if (AddressData::IsRepeatedFieldValue(field)) { const auto& values = address.GetRepeatedFieldValue(field); assert(!values.empty()); parameters.push_back(values.front()); } else { parameters.push_back(address.GetFieldValue(field)); } return DoReplaceStringPlaceholders( get_string_(IDS_LIBADDRESSINPUT_UNKNOWN_VALUE), parameters); } else if (problem == USES_P_O_BOX) { return get_string_(IDS_LIBADDRESSINPUT_PO_BOX_FORBIDDEN_VALUE); } else { assert(false); return ""; } } } void Localization::SetGetter(std::string (*getter)(int)) { assert(getter != nullptr); get_string_ = getter; } std::string Localization::GetErrorMessageForPostalCode( AddressProblem problem, bool uses_postal_code_as_label, const std::string& postal_code_example, const std::string& post_service_url) const { int message_id; std::vector<std::string> parameters; if (problem == MISSING_REQUIRED_FIELD) { if (!postal_code_example.empty() && !post_service_url.empty()) { message_id = uses_postal_code_as_label ? IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE_AND_URL : IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE_AND_URL; parameters.push_back(postal_code_example); PushBackUrl(post_service_url, &parameters); } else if (!postal_code_example.empty()) { message_id = uses_postal_code_as_label ? IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE : IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE; parameters.push_back(postal_code_example); } else { message_id = IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD; } return DoReplaceStringPlaceholders(get_string_(message_id), parameters); } else if (problem == INVALID_FORMAT) { if (!postal_code_example.empty() && !post_service_url.empty()) { message_id = uses_postal_code_as_label ? IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE_AND_URL : IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE_AND_URL; parameters.push_back(postal_code_example); PushBackUrl(post_service_url, &parameters); } else if (!postal_code_example.empty()) { message_id = uses_postal_code_as_label ? IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE : IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE; parameters.push_back(postal_code_example); } else { message_id = uses_postal_code_as_label ? IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE : IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP; } return DoReplaceStringPlaceholders(get_string_(message_id), parameters); } else if (problem == MISMATCHING_VALUE) { if (!post_service_url.empty()) { message_id = uses_postal_code_as_label ? IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE_URL : IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP_URL; PushBackUrl(post_service_url, &parameters); } else { message_id = uses_postal_code_as_label ? IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE : IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP; } return DoReplaceStringPlaceholders(get_string_(message_id), parameters); } else { assert(false); return ""; } } } }
#include <libaddressinput/localization.h> #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_problem.h> #include <string> #include <vector> #include <gtest/gtest.h> #include "grit.h" #include "messages.h" namespace { using i18n::addressinput::AddressData; using i18n::addressinput::AddressField; using i18n::addressinput::INVALID_MESSAGE_ID; using i18n::addressinput::Localization; using i18n::addressinput::COUNTRY; using i18n::addressinput::ADMIN_AREA; using i18n::addressinput::LOCALITY; using i18n::addressinput::DEPENDENT_LOCALITY; using i18n::addressinput::SORTING_CODE; using i18n::addressinput::POSTAL_CODE; using i18n::addressinput::STREET_ADDRESS; using i18n::addressinput::ORGANIZATION; using i18n::addressinput::RECIPIENT; using i18n::addressinput::MISSING_REQUIRED_FIELD; using i18n::addressinput::UNKNOWN_VALUE; using i18n::addressinput::INVALID_FORMAT; using i18n::addressinput::MISMATCHING_VALUE; using i18n::addressinput::USES_P_O_BOX; class LocalizationTest : public testing::TestWithParam<int> { public: LocalizationTest(const LocalizationTest&) = delete; LocalizationTest& operator=(const LocalizationTest&) = delete; protected: LocalizationTest() = default; Localization localization_; }; const char kValidMessage[] = "Data"; std::string GetValidMessage(int message_id) { return kValidMessage; } TEST_P(LocalizationTest, ValidStringGetterCanBeUsed) { localization_.SetGetter(&GetValidMessage); EXPECT_EQ(kValidMessage, localization_.GetString(GetParam())); } TEST_P(LocalizationTest, DefaultStringIsNotEmpty) { EXPECT_FALSE(localization_.GetString(GetParam()).empty()); } TEST_P(LocalizationTest, NoNewline) { EXPECT_EQ(std::string::npos, localization_.GetString(GetParam()).find('\n')); } TEST_P(LocalizationTest, NoDoubleSpace) { EXPECT_EQ(std::string::npos, localization_.GetString(GetParam()).find(std::string(2U, ' '))); } INSTANTIATE_TEST_SUITE_P( AllMessages, LocalizationTest, testing::Values( IDS_LIBADDRESSINPUT_COUNTRY_OR_REGION_LABEL, IDS_LIBADDRESSINPUT_LOCALITY_LABEL, IDS_LIBADDRESSINPUT_ADDRESS_LINE_1_LABEL, IDS_LIBADDRESSINPUT_PIN_CODE_LABEL, IDS_LIBADDRESSINPUT_POSTAL_CODE_LABEL, IDS_LIBADDRESSINPUT_ZIP_CODE_LABEL, IDS_LIBADDRESSINPUT_AREA, IDS_LIBADDRESSINPUT_COUNTY, IDS_LIBADDRESSINPUT_DEPARTMENT, IDS_LIBADDRESSINPUT_DISTRICT, IDS_LIBADDRESSINPUT_DO_SI, IDS_LIBADDRESSINPUT_EMIRATE, IDS_LIBADDRESSINPUT_ISLAND, IDS_LIBADDRESSINPUT_PARISH, IDS_LIBADDRESSINPUT_PREFECTURE, IDS_LIBADDRESSINPUT_PROVINCE, IDS_LIBADDRESSINPUT_STATE, IDS_LIBADDRESSINPUT_ORGANIZATION_LABEL, IDS_LIBADDRESSINPUT_RECIPIENT_LABEL, IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD, IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE_AND_URL, IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE, IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE_AND_URL, IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE, IDS_LIBADDRESSINPUT_UNKNOWN_VALUE, IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE_AND_URL, IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE, IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE, IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE_AND_URL, IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE, IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP, IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE_URL, IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE, IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP_URL, IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP, IDS_LIBADDRESSINPUT_PO_BOX_FORBIDDEN_VALUE)); TEST_F(LocalizationTest, InvalidMessageIsEmptyString) { EXPECT_TRUE(localization_.GetString(INVALID_MESSAGE_ID).empty()); } TEST(LocalizationGetErrorMessageTest, MissingRequiredPostalCode) { Localization localization; const AddressData address{.region_code = "CH"}; EXPECT_EQ("You must provide a postal code, for example 2544." " Don't know your postal code? Find it out" " <a href=\"http: "here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, true, true)); EXPECT_EQ("You must provide a postal code, for example 2544.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, true, false)); EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, false, false)); EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, false, true)); } TEST(LocalizationGetErrorMessageTest, MissingRequiredZipCode) { Localization localization; const AddressData address{.region_code = "US"}; EXPECT_EQ("You must provide a ZIP code, for example 95014." " Don't know your ZIP code? Find it out" " <a href=\"https: "input.action\">here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, true, true)); EXPECT_EQ("You must provide a ZIP code, for example 95014.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, true, false)); EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, false, false)); EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage(address, POSTAL_CODE, MISSING_REQUIRED_FIELD, false, true)); } TEST(LocalizationGetErrorMessageTest, MissingRequiredOtherFields) { Localization localization; const AddressData address{.region_code = "US"}; const std::vector<AddressField> other_fields{ COUNTRY, ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY, SORTING_CODE, STREET_ADDRESS, ORGANIZATION, RECIPIENT, }; for (AddressField field : other_fields) { EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage( address, field, MISSING_REQUIRED_FIELD, true, true)); EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage( address, field, MISSING_REQUIRED_FIELD, true, false)); EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage( address, field, MISSING_REQUIRED_FIELD, false, false)); EXPECT_EQ("You can't leave this empty.", localization.GetErrorMessage( address, field, MISSING_REQUIRED_FIELD, false, true)); } } TEST(LocalizationGetErrorMessageTest, UnknownValueOtherFields) { Localization localization; const AddressData address{ .region_code = "US", .address_line{ "bad address line 1", "bad address line 2", }, .administrative_area = "bad admin area", .locality = "bad locality", .dependent_locality = "bad dependent locality", .sorting_code = "bad sorting code", .organization = "bad organization", .recipient = "bad recipient", }; EXPECT_EQ("US " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, COUNTRY, UNKNOWN_VALUE, true, true)); EXPECT_EQ("US " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, COUNTRY, UNKNOWN_VALUE, true, false)); EXPECT_EQ("US " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, COUNTRY, UNKNOWN_VALUE, false, false)); EXPECT_EQ("US " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, COUNTRY, UNKNOWN_VALUE, false, true)); EXPECT_EQ("bad admin area " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ADMIN_AREA, UNKNOWN_VALUE, true, true)); EXPECT_EQ("bad admin area " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ADMIN_AREA, UNKNOWN_VALUE, true, false)); EXPECT_EQ("bad admin area " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ADMIN_AREA, UNKNOWN_VALUE, false, false)); EXPECT_EQ("bad admin area " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ADMIN_AREA, UNKNOWN_VALUE, false, true)); EXPECT_EQ("bad locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, LOCALITY, UNKNOWN_VALUE, true, true)); EXPECT_EQ("bad locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, LOCALITY, UNKNOWN_VALUE, true, false)); EXPECT_EQ("bad locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, LOCALITY, UNKNOWN_VALUE, false, false)); EXPECT_EQ("bad locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, LOCALITY, UNKNOWN_VALUE, false, true)); EXPECT_EQ("bad dependent locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, true, true)); EXPECT_EQ("bad dependent locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, true, false)); EXPECT_EQ("bad dependent locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, false, false)); EXPECT_EQ("bad dependent locality " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, false, true)); EXPECT_EQ("bad sorting code " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, SORTING_CODE, UNKNOWN_VALUE, true, true)); EXPECT_EQ("bad sorting code " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, SORTING_CODE, UNKNOWN_VALUE, true, false)); EXPECT_EQ("bad sorting code " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, SORTING_CODE, UNKNOWN_VALUE, false, false)); EXPECT_EQ("bad sorting code " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, SORTING_CODE, UNKNOWN_VALUE, false, true)); EXPECT_EQ("bad address line 1 " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, STREET_ADDRESS, UNKNOWN_VALUE, true, true)); EXPECT_EQ("bad address line 1 " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, STREET_ADDRESS, UNKNOWN_VALUE, true, false)); EXPECT_EQ("bad address line 1 " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, STREET_ADDRESS, UNKNOWN_VALUE, false, false)); EXPECT_EQ("bad address line 1 " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, STREET_ADDRESS, UNKNOWN_VALUE, false, true)); EXPECT_EQ("bad organization " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ORGANIZATION, UNKNOWN_VALUE, true, true)); EXPECT_EQ("bad organization " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ORGANIZATION, UNKNOWN_VALUE, true, false)); EXPECT_EQ("bad organization " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ORGANIZATION, UNKNOWN_VALUE, false, false)); EXPECT_EQ("bad organization " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, ORGANIZATION, UNKNOWN_VALUE, false, true)); EXPECT_EQ("bad recipient " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, RECIPIENT, UNKNOWN_VALUE, true, true)); EXPECT_EQ("bad recipient " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, RECIPIENT, UNKNOWN_VALUE, true, false)); EXPECT_EQ("bad recipient " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, RECIPIENT, UNKNOWN_VALUE, false, false)); EXPECT_EQ("bad recipient " "is not recognized as a known value for this field.", localization.GetErrorMessage( address, RECIPIENT, UNKNOWN_VALUE, false, true)); } TEST(LocalizationGetErrorMessageTest, InvalidFormatPostalCode) { Localization localization; const AddressData address{.region_code = "CH"}; EXPECT_EQ("This postal code format is not recognized. Example " "of a valid postal code: 2544." " Don't know your postal code? Find it out" " <a href=\"http: "here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, true, true)); EXPECT_EQ("This postal code format is not recognized. Example " "of a valid postal code: 2544.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, true, false)); EXPECT_EQ("This postal code format is not recognized.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, false, false)); EXPECT_EQ("This postal code format is not recognized.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, false, true)); } TEST(LocalizationGetErrorMessageTest, InvalidFormatZipCode) { Localization localization; const AddressData address{.region_code = "US"}; EXPECT_EQ("This ZIP code format is not recognized. Example of " "a valid ZIP code: 95014." " Don't know your ZIP code? Find it out" " <a href=\"https: "input.action\">here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, true, true)); EXPECT_EQ("This ZIP code format is not recognized. Example of " "a valid ZIP code: 95014.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, true, false)); EXPECT_EQ("This ZIP code format is not recognized.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, false, false)); EXPECT_EQ("This ZIP code format is not recognized.", localization.GetErrorMessage(address, POSTAL_CODE, INVALID_FORMAT, false, true)); } TEST(LocalizationGetErrorMessageTest, MismatchingValuePostalCode) { Localization localization; const AddressData address{.region_code = "CH"}; EXPECT_EQ("This postal code does not appear to match the rest " "of this address." " Don't know your postal code? Find it out" " <a href=\"http: "here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, true, true)); EXPECT_EQ("This postal code does not appear to match the rest " "of this address.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, true, false)); EXPECT_EQ("This postal code does not appear to match the rest " "of this address.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, false, false)); EXPECT_EQ("This postal code does not appear to match the rest " "of this address." " Don't know your postal code? Find it out" " <a href=\"http: "here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, false, true)); } TEST(LocalizationGetErrorMessageTest, MismatchingValueZipCode) { Localization localization; const AddressData address{.region_code = "US"}; EXPECT_EQ("This ZIP code does not appear to match the rest of " "this address." " Don't know your ZIP code? Find it out" " <a href=\"https: "input.action\">here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, true, true)); EXPECT_EQ("This ZIP code does not appear to match the rest of " "this address.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, true, false)); EXPECT_EQ("This ZIP code does not appear to match the rest of " "this address.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, false, false)); EXPECT_EQ("This ZIP code does not appear to match the rest of " "this address." " Don't know your ZIP code? Find it out" " <a href=\"https: "input.action\">here</a>.", localization.GetErrorMessage(address, POSTAL_CODE, MISMATCHING_VALUE, false, true)); } TEST(LocalizationGetErrorMessageTest, UsesPOBoxOtherFields) { Localization localization; const AddressData address{.region_code = "US"}; const std::vector<AddressField> other_fields{ COUNTRY, ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY, SORTING_CODE, STREET_ADDRESS, ORGANIZATION, RECIPIENT, }; for (AddressField field : other_fields) { EXPECT_EQ("This address line appears to contain a post " "office box. Please use a street" " or building address.", localization.GetErrorMessage( address, field, USES_P_O_BOX, true, true)); EXPECT_EQ("This address line appears to contain a post " "office box. Please use a street" " or building address.", localization.GetErrorMessage( address, field, USES_P_O_BOX, true, false)); EXPECT_EQ("This address line appears to contain a post " "office box. Please use a street" " or building address.", localization.GetErrorMessage( address, field, USES_P_O_BOX, false, false)); EXPECT_EQ("This address line appears to contain a post " "office box. Please use a street" " or building address.", localization.GetErrorMessage( address, field, USES_P_O_BOX, false, true)); } } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/localization.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/localization_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
7c414036-30e3-4213-8071-6e2396c36412
cpp
google/libaddressinput
address_field_util
cpp/src/address_field_util.cc
cpp/test/address_field_util_test.cc
#include "address_field_util.h" #include <libaddressinput/address_field.h> #include <algorithm> #include <cassert> #include <string> #include <vector> #include "format_element.h" namespace i18n { namespace addressinput { namespace { bool ParseFieldToken(char c, AddressField* field) { assert(field != nullptr); static const struct { char c; AddressField field; } kTokenMap[] = { { 'R', COUNTRY }, { 'S', ADMIN_AREA }, { 'C', LOCALITY }, { 'D', DEPENDENT_LOCALITY }, { 'X', SORTING_CODE }, { 'Z', POSTAL_CODE }, { 'A', STREET_ADDRESS }, { 'O', ORGANIZATION }, { 'N', RECIPIENT }, }; for (const auto& entry : kTokenMap) { if (c == entry.c) { *field = entry.field; return true; } } return false; } } void ParseFormatRule(const std::string& format, std::vector<FormatElement>* elements) { assert(elements != nullptr); elements->clear(); std::string::const_iterator prev = format.begin(); for (std::string::const_iterator next = format.begin(); next != format.end(); prev = ++next) { if ((next = std::find(next, format.end(), '%')) == format.end()) { break; } if (prev < next) { elements->emplace_back(std::string(prev, next)); } if ((prev = ++next) == format.end()) { break; } AddressField field; if (*next == 'n') { elements->emplace_back(); } else if (ParseFieldToken(*next, &field)) { elements->emplace_back(field); } } if (prev != format.end()) { elements->emplace_back(std::string(prev, format.end())); } } void ParseAddressFieldsRequired(const std::string& required, std::vector<AddressField>* fields) { assert(fields != nullptr); fields->clear(); for (char c : required) { AddressField field; if (ParseFieldToken(c, &field)) { fields->push_back(field); } } } } }
#include "address_field_util.h" #include <libaddressinput/address_field.h> #include <string> #include <vector> #include <gtest/gtest.h> #include "format_element.h" namespace { using i18n::addressinput::AddressField; using i18n::addressinput::FormatElement; using i18n::addressinput::ParseFormatRule; using i18n::addressinput::COUNTRY; using i18n::addressinput::LOCALITY; using i18n::addressinput::POSTAL_CODE; using i18n::addressinput::STREET_ADDRESS; using i18n::addressinput::ORGANIZATION; using i18n::addressinput::RECIPIENT; TEST(AddressFieldUtilTest, FormatParseNewline) { std::vector<FormatElement> actual; ParseFormatRule("%O%n%N%n%A%nAX-%Z %C%nÅLAND", &actual); const std::vector<FormatElement> expected{ FormatElement{ORGANIZATION}, FormatElement{}, FormatElement{RECIPIENT}, FormatElement{}, FormatElement{STREET_ADDRESS}, FormatElement{}, FormatElement{"AX-"}, FormatElement{POSTAL_CODE}, FormatElement{" "}, FormatElement{LOCALITY}, FormatElement{}, FormatElement{"ÅLAND"}, }; EXPECT_EQ(expected, actual); } TEST(AddressFieldUtilTest, FormatUnknownTokenIsIgnored) { std::vector<FormatElement> actual; ParseFormatRule("%1%R", &actual); const std::vector<FormatElement> expected{FormatElement{COUNTRY}}; EXPECT_EQ(expected, actual); } TEST(AddressFieldUtilTest, FormatPrefixWithoutTokenIsIgnored) { std::vector<FormatElement> actual; ParseFormatRule("%", &actual); EXPECT_TRUE(actual.empty()); } TEST(AddressFieldUtilTest, FormatEmptyString) { std::vector<FormatElement> fields; ParseFormatRule(std::string(), &fields); EXPECT_TRUE(fields.empty()); } TEST(AddressFieldUtilTest, RequiredParseDefault) { std::vector<AddressField> actual; ParseAddressFieldsRequired("AC", &actual); const std::vector<AddressField> expected{ STREET_ADDRESS, LOCALITY, }; EXPECT_EQ(expected, actual); } TEST(AddressFieldUtilTest, RequiredEmptyString) { std::vector<AddressField> fields; ParseAddressFieldsRequired(std::string(), &fields); EXPECT_TRUE(fields.empty()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_field_util.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_field_util_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
79b73ddc-d78b-4fc8-891a-abd1b5e2ac20
cpp
google/libaddressinput
region_data_builder
cpp/src/region_data_builder.cc
cpp/test/region_data_builder_test.cc
#include <libaddressinput/region_data_builder.h> #include <libaddressinput/address_data.h> #include <libaddressinput/preload_supplier.h> #include <libaddressinput/region_data.h> #include <cassert> #include <cstddef> #include <string> #include <vector> #include "language.h" #include "lookup_key.h" #include "region_data_constants.h" #include "rule.h" #include "util/size.h" namespace i18n { namespace addressinput { namespace { const size_t kLookupKeysMaxDepth = size(LookupKey::kHierarchy) - 1; void BuildRegionTreeRecursively( const std::map<std::string, const Rule*>& rules, std::map<std::string, const Rule*>::const_iterator hint, const LookupKey& parent_key, RegionData* parent_region, const std::vector<std::string>& keys, bool prefer_latin_name, size_t region_max_depth) { assert(parent_region != nullptr); LookupKey lookup_key; for (const auto& key : keys) { lookup_key.FromLookupKey(parent_key, key); const std::string lookup_key_string = lookup_key.ToKeyString(kLookupKeysMaxDepth); ++hint; if (hint == rules.end() || hint->first != lookup_key_string) { hint = rules.find(lookup_key_string); if (hint == rules.end()) { return; } } const Rule* rule = hint->second; assert(rule != nullptr); const std::string& local_name = rule->GetName().empty() ? key : rule->GetName(); const std::string& name = prefer_latin_name && !rule->GetLatinName().empty() ? rule->GetLatinName() : local_name; RegionData* region = parent_region->AddSubRegion(key, name); if (!rule->GetSubKeys().empty() && region_max_depth > parent_key.GetDepth()) { BuildRegionTreeRecursively(rules, hint, lookup_key, region, rule->GetSubKeys(), prefer_latin_name, region_max_depth); } } } RegionData* BuildRegion(const std::map<std::string, const Rule*>& rules, const std::string& region_code, const Language& language) { AddressData address; address.region_code = region_code; LookupKey lookup_key; lookup_key.FromAddress(address); auto hint = rules.find(lookup_key.ToKeyString(kLookupKeysMaxDepth)); assert(hint != rules.end()); const Rule* rule = hint->second; assert(rule != nullptr); auto* region = new RegionData(region_code); size_t region_max_depth = RegionDataConstants::GetMaxLookupKeyDepth(region_code); if (region_max_depth > 0) { BuildRegionTreeRecursively(rules, hint, lookup_key, region, rule->GetSubKeys(), language.has_latin_script, region_max_depth); } return region; } } RegionDataBuilder::RegionDataBuilder(PreloadSupplier* supplier) : supplier_(supplier), cache_() { assert(supplier_ != nullptr); } RegionDataBuilder::~RegionDataBuilder() { for (const auto& outer : cache_) { assert(outer.second != nullptr); for (const auto& inner : *outer.second) { delete inner.second; } delete outer.second; } } const RegionData& RegionDataBuilder::Build( const std::string& region_code, const std::string& ui_language_tag, std::string* best_region_tree_language_tag) { assert(supplier_->IsLoaded(region_code)); assert(best_region_tree_language_tag != nullptr); auto region_it = cache_.find(region_code); if (region_it == cache_.end()) { region_it = cache_.emplace(region_code, new LanguageRegionMap).first; } Rule rule; rule.ParseSerializedRule(RegionDataConstants::GetRegionData(region_code)); static const Language kUndefinedLanguage("und"); const Language best_language = rule.GetLanguages().empty() ? kUndefinedLanguage : ChooseBestAddressLanguage(rule, Language(ui_language_tag)); *best_region_tree_language_tag = best_language.tag; auto language_it = region_it->second->find(best_language.tag); if (language_it == region_it->second->end()) { const auto& rules = supplier_->GetRulesForRegion(region_code); language_it = region_it->second ->emplace(best_language.tag, BuildRegion(rules, region_code, best_language)) .first; } return *language_it->second; } } }
#include <libaddressinput/region_data_builder.h> #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/preload_supplier.h> #include <libaddressinput/region_data.h> #include <memory> #include <string> #include <gtest/gtest.h> #include "testdata_source.h" namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::NullStorage; using i18n::addressinput::PreloadSupplier; using i18n::addressinput::RegionData; using i18n::addressinput::RegionDataBuilder; using i18n::addressinput::TestdataSource; class RegionDataBuilderTest : public testing::Test { public: RegionDataBuilderTest(const RegionDataBuilderTest&) = delete; RegionDataBuilderTest& operator=(const RegionDataBuilderTest&) = delete; protected: RegionDataBuilderTest() : supplier_(new TestdataSource(true), new NullStorage), builder_(&supplier_), loaded_callback_(BuildCallback(this, &RegionDataBuilderTest::OnLoaded)), best_language_() {} PreloadSupplier supplier_; RegionDataBuilder builder_; const std::unique_ptr<const PreloadSupplier::Callback> loaded_callback_; std::string best_language_; private: void OnLoaded(bool success, const std::string& region_code, int num_rules) { ASSERT_TRUE(success); ASSERT_FALSE(region_code.empty()); ASSERT_LT(0, num_rules); ASSERT_TRUE(supplier_.IsLoaded(region_code)); } }; TEST_F(RegionDataBuilderTest, BuildUsRegionTree) { supplier_.LoadRules("US", *loaded_callback_); const RegionData& tree = builder_.Build("US", "en-US", &best_language_); EXPECT_FALSE(tree.sub_regions().empty()); } TEST_F(RegionDataBuilderTest, BuildCnRegionTree) { supplier_.LoadRules("CN", *loaded_callback_); const RegionData& tree = builder_.Build("CN", "zh-Hans", &best_language_); ASSERT_FALSE(tree.sub_regions().empty()); EXPECT_FALSE(tree.sub_regions().front()->sub_regions().empty()); } TEST_F(RegionDataBuilderTest, BuildChRegionTree) { supplier_.LoadRules("CH", *loaded_callback_); const RegionData& tree = builder_.Build("CH", "de-CH", &best_language_); EXPECT_TRUE(tree.sub_regions().empty()); } TEST_F(RegionDataBuilderTest, BuildZwRegionTree) { supplier_.LoadRules("ZW", *loaded_callback_); const RegionData& tree = builder_.Build("ZW", "en-ZW", &best_language_); EXPECT_TRUE(tree.sub_regions().empty()); } TEST_F(RegionDataBuilderTest, UsTreeHasStateAbbreviationsAndNames) { supplier_.LoadRules("US", *loaded_callback_); const RegionData& tree = builder_.Build("US", "en-US", &best_language_); EXPECT_EQ("en", best_language_); ASSERT_FALSE(tree.sub_regions().empty()); EXPECT_EQ("AL", tree.sub_regions().front()->key()); EXPECT_EQ("Alabama", tree.sub_regions().front()->name()); } TEST_F(RegionDataBuilderTest, KrWithKoLatnLanguageHasKoreanKeysAndLatinScriptNames) { supplier_.LoadRules("KR", *loaded_callback_); const RegionData& tree = builder_.Build("KR", "ko-Latn", &best_language_); EXPECT_EQ("ko-Latn", best_language_); ASSERT_FALSE(tree.sub_regions().empty()); EXPECT_EQ("강원도", tree.sub_regions().front()->key()); EXPECT_EQ("Gangwon", tree.sub_regions().front()->name()); } TEST_F(RegionDataBuilderTest, KrWithKoKrLanguageHasKoreanKeysAndNames) { supplier_.LoadRules("KR", *loaded_callback_); const RegionData& tree = builder_.Build("KR", "ko-KR", &best_language_); EXPECT_EQ("ko", best_language_); ASSERT_FALSE(tree.sub_regions().empty()); EXPECT_EQ("강원도", tree.sub_regions().front()->key()); EXPECT_EQ("강원", tree.sub_regions().front()->name()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/region_data_builder.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/region_data_builder_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
e87f703b-9ab7-41f0-a6af-71cbc58cb452
cpp
google/libaddressinput
address_data
cpp/src/address_data.cc
cpp/test/address_data_test.cc
#include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <algorithm> #include <cassert> #include <cstddef> #include <ostream> #include <string> #include <vector> #include <re2/re2.h> #include "util/size.h" namespace i18n { namespace addressinput { namespace { std::string AddressData::*kStringField[] = { &AddressData::region_code, &AddressData::administrative_area, &AddressData::locality, &AddressData::dependent_locality, &AddressData::sorting_code, &AddressData::postal_code, nullptr, &AddressData::organization, &AddressData::recipient, }; const std::vector<std::string> AddressData::*kVectorStringField[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &AddressData::address_line, nullptr, nullptr, }; static_assert(size(kStringField) == size(kVectorStringField), "field_mapping_array_size_mismatch"); bool IsStringEmpty(const std::string& str) { static const RE2 kMatcher(R"(\S)"); return str.empty() || !RE2::PartialMatch(str, kMatcher); } } bool AddressData::IsFieldEmpty(AddressField field) const { assert(field >= 0); assert(static_cast<size_t>(field) < size(kStringField)); if (kStringField[field] != nullptr) { const auto& value = GetFieldValue(field); return IsStringEmpty(value); } else { const auto& value = GetRepeatedFieldValue(field); return std::find_if_not(value.begin(), value.end(), IsStringEmpty) == value.end(); } } const std::string& AddressData::GetFieldValue(AddressField field) const { assert(field >= 0); assert(static_cast<size_t>(field) < size(kStringField)); assert(kStringField[field] != nullptr); return this->*kStringField[field]; } void AddressData::SetFieldValue(AddressField field, const std::string& value) { assert(field >= 0); assert(static_cast<size_t>(field) < size(kStringField)); assert(kStringField[field] != nullptr); (this->*kStringField[field]).assign(value); } const std::vector<std::string>& AddressData::GetRepeatedFieldValue( AddressField field) const { assert(IsRepeatedFieldValue(field)); return this->*kVectorStringField[field]; } bool AddressData::operator==(const AddressData& other) const { return region_code == other.region_code && address_line == other.address_line && administrative_area == other.administrative_area && locality == other.locality && dependent_locality == other.dependent_locality && postal_code == other.postal_code && sorting_code == other.sorting_code && language_code == other.language_code && organization == other.organization && recipient == other.recipient; } bool AddressData::IsRepeatedFieldValue(AddressField field) { assert(field >= 0); assert(static_cast<size_t>(field) < size(kVectorStringField)); return kVectorStringField[field] != nullptr; } } } std::ostream& operator<<(std::ostream& o, const i18n::addressinput::AddressData& address) { o << "region_code: \"" << address.region_code << "\"\n" "administrative_area: \"" << address.administrative_area << "\"\n" "locality: \"" << address.locality << "\"\n" "dependent_locality: \"" << address.dependent_locality << "\"\n" "postal_code: \"" << address.postal_code << "\"\n" "sorting_code: \"" << address.sorting_code << "\"\n"; for (const auto& line : address.address_line) { o << "address_line: \"" << line << "\"\n"; } o << "language_code: \"" << address.language_code << "\"\n" "organization: \"" << address.organization << "\"\n" "recipient: \"" << address.recipient << "\"\n"; return o; }
#include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <sstream> #include <gtest/gtest.h> namespace { using i18n::addressinput::AddressData; using i18n::addressinput::AddressField; using i18n::addressinput::COUNTRY; using i18n::addressinput::ADMIN_AREA; using i18n::addressinput::LOCALITY; using i18n::addressinput::DEPENDENT_LOCALITY; using i18n::addressinput::SORTING_CODE; using i18n::addressinput::POSTAL_CODE; using i18n::addressinput::STREET_ADDRESS; using i18n::addressinput::ORGANIZATION; using i18n::addressinput::RECIPIENT; TEST(AddressDataTest, GetFieldValue) { const AddressData address{ .region_code = "rrr", .administrative_area = "sss", .locality = "ccc", .dependent_locality = "ddd", .postal_code = "zzz", .sorting_code = "xxx", .organization = "ooo", .recipient = "nnn", }; EXPECT_EQ(address.region_code, address.GetFieldValue(COUNTRY)); EXPECT_EQ(address.administrative_area, address.GetFieldValue(ADMIN_AREA)); EXPECT_EQ(address.locality, address.GetFieldValue(LOCALITY)); EXPECT_EQ(address.dependent_locality, address.GetFieldValue(DEPENDENT_LOCALITY)); EXPECT_EQ(address.sorting_code, address.GetFieldValue(SORTING_CODE)); EXPECT_EQ(address.postal_code, address.GetFieldValue(POSTAL_CODE)); EXPECT_EQ(address.organization, address.GetFieldValue(ORGANIZATION)); EXPECT_EQ(address.recipient, address.GetFieldValue(RECIPIENT)); } TEST(AddressDataTest, GetRepeatedFieldValue) { const AddressData address{.address_line{ "aaa", "222", }}; EXPECT_EQ(address.address_line, address.GetRepeatedFieldValue(STREET_ADDRESS)); } TEST(AddressDataTest, IsFieldEmpty) { AddressData address; EXPECT_TRUE(address.IsFieldEmpty(COUNTRY)); EXPECT_TRUE(address.IsFieldEmpty(ADMIN_AREA)); EXPECT_TRUE(address.IsFieldEmpty(LOCALITY)); EXPECT_TRUE(address.IsFieldEmpty(DEPENDENT_LOCALITY)); EXPECT_TRUE(address.IsFieldEmpty(SORTING_CODE)); EXPECT_TRUE(address.IsFieldEmpty(POSTAL_CODE)); EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS)); EXPECT_TRUE(address.IsFieldEmpty(ORGANIZATION)); EXPECT_TRUE(address.IsFieldEmpty(RECIPIENT)); address = { .region_code = "rrr", .address_line{"aaa"}, .administrative_area = "sss", .locality = "ccc", .dependent_locality = "ddd", .postal_code = "zzz", .sorting_code = "xxx", .organization = "ooo", .recipient = "nnn", }; EXPECT_FALSE(address.IsFieldEmpty(COUNTRY)); EXPECT_FALSE(address.IsFieldEmpty(ADMIN_AREA)); EXPECT_FALSE(address.IsFieldEmpty(LOCALITY)); EXPECT_FALSE(address.IsFieldEmpty(DEPENDENT_LOCALITY)); EXPECT_FALSE(address.IsFieldEmpty(SORTING_CODE)); EXPECT_FALSE(address.IsFieldEmpty(POSTAL_CODE)); EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS)); EXPECT_FALSE(address.IsFieldEmpty(ORGANIZATION)); EXPECT_FALSE(address.IsFieldEmpty(RECIPIENT)); } TEST(AddressDataTest, IsFieldEmptyWhitespace) { AddressData address; address.recipient = " "; EXPECT_TRUE(address.IsFieldEmpty(RECIPIENT)); address.recipient = "abc"; EXPECT_FALSE(address.IsFieldEmpty(RECIPIENT)); address.recipient = " b "; EXPECT_FALSE(address.IsFieldEmpty(RECIPIENT)); } TEST(AddressDataTest, IsFieldEmptyVector) { AddressData address; EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS)); address.address_line.emplace_back(""); EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS)); address.address_line.emplace_back("aaa"); EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS)); address.address_line.emplace_back(""); EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS)); } TEST(AddressDataTest, IsFieldEmptyVectorWhitespace) { AddressData address{.address_line{ " ", " ", " ", }}; EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS)); address.address_line = { "abc", }; EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS)); address.address_line = { " ", " b ", " ", }; EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS)); } TEST(AddressDataTest, StreamFunction) { std::ostringstream oss; const AddressData address{ .region_code = "R", .address_line{ "Line 1", "Line 2", }, .administrative_area = "S", .locality = "C", .dependent_locality = "D", .postal_code = "Z", .sorting_code = "X", .language_code = "zh-Hant", .organization = "O", .recipient = "N", }; oss << address; EXPECT_EQ("region_code: \"R\"\n" "administrative_area: \"S\"\n" "locality: \"C\"\n" "dependent_locality: \"D\"\n" "postal_code: \"Z\"\n" "sorting_code: \"X\"\n" "address_line: \"Line 1\"\n" "address_line: \"Line 2\"\n" "language_code: \"zh-Hant\"\n" "organization: \"O\"\n" "recipient: \"N\"\n", oss.str()); } TEST(AddressDataTest, TestEquals) { const AddressData address{ .region_code = "R", .address_line{ "Line 1", "Line 2", }, .administrative_area = "S", .locality = "C", .dependent_locality = "D", .postal_code = "Z", .sorting_code = "X", .language_code = "zh-Hant", .organization = "O", .recipient = "N", }; AddressData clone = address; EXPECT_EQ(address, clone); clone.language_code.clear(); EXPECT_FALSE(address == clone); } #ifndef NDEBUG TEST(AddressDataTest, GetFieldValueInvalid) { const AddressData address; ASSERT_DEATH_IF_SUPPORTED(address.GetFieldValue(STREET_ADDRESS), "ssertion.*failed"); } TEST(AddressDataTest, GetVectorFieldValueInvalid) { const AddressData address; ASSERT_DEATH_IF_SUPPORTED(address.GetRepeatedFieldValue(COUNTRY), "ssertion.*failed"); } TEST(AddressDataTest, IsFieldEmptyInvalid) { static const auto invalid_field = static_cast<AddressField>(-1); AddressData address; ASSERT_DEATH_IF_SUPPORTED(address.IsFieldEmpty(invalid_field), "ssertion.*failed"); } #endif }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_data.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_data_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
ded06446-76e1-4235-8d69-e8c7e7375965
cpp
google/libaddressinput
address_formatter
cpp/src/address_formatter.cc
cpp/test/address_formatter_test.cc
#include <libaddressinput/address_formatter.h> #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <algorithm> #include <cassert> #include <cstddef> #include <functional> #include <string> #include <vector> #include "format_element.h" #include "language.h" #include "region_data_constants.h" #include "rule.h" #include "util/cctype_tolower_equal.h" #include "util/size.h" namespace i18n { namespace addressinput { namespace { const char kCommaSeparator[] = ", "; const char kSpaceSeparator[] = " "; const char kArabicCommaSeparator[] = "، "; const char kLanguagesThatUseSpace[][3] = { "th", "ko", }; const char kLanguagesThatHaveNoSeparator[][3] = { "ja", "zh", }; const char kLanguagesThatUseAnArabicComma[][3] = { "ar", "fa", "ku", "ps", "ur", }; std::string GetLineSeparatorForLanguage(const std::string& language_tag) { Language address_language(language_tag); if (address_language.has_latin_script) { return kCommaSeparator; } const std::string& base_language = address_language.base; using std::placeholders::_1; if (std::find_if(kLanguagesThatUseSpace, kLanguagesThatUseSpace + size(kLanguagesThatUseSpace), std::bind(&EqualToTolowerString, _1, base_language)) != kLanguagesThatUseSpace + size(kLanguagesThatUseSpace)) { return kSpaceSeparator; } else if (std::find_if( kLanguagesThatHaveNoSeparator, kLanguagesThatHaveNoSeparator + size(kLanguagesThatHaveNoSeparator), std::bind(&EqualToTolowerString, _1, base_language)) != kLanguagesThatHaveNoSeparator + size(kLanguagesThatHaveNoSeparator)) { return ""; } else if (std::find_if( kLanguagesThatUseAnArabicComma, kLanguagesThatUseAnArabicComma + size(kLanguagesThatUseAnArabicComma), std::bind(&EqualToTolowerString, _1, base_language)) != kLanguagesThatUseAnArabicComma + size(kLanguagesThatUseAnArabicComma)) { return kArabicCommaSeparator; } return kCommaSeparator; } void CombineLinesForLanguage(const std::vector<std::string>& lines, const std::string& language_tag, std::string* line) { line->clear(); std::string separator = GetLineSeparatorForLanguage(language_tag); for (auto it = lines.begin(); it != lines.end(); ++it) { if (it != lines.begin()) { line->append(separator); } line->append(*it); } } } void GetFormattedNationalAddress( const AddressData& address_data, std::vector<std::string>* lines) { assert(lines != nullptr); lines->clear(); Rule rule; rule.CopyFrom(Rule::GetDefault()); rule.ParseSerializedRule( RegionDataConstants::GetRegionData(address_data.region_code)); Language language(address_data.language_code); const std::vector<FormatElement>& format = language.has_latin_script && !rule.GetLatinFormat().empty() ? rule.GetLatinFormat() : rule.GetFormat(); std::vector<FormatElement> pruned_format; for (auto element_it = format.begin(); element_it != format.end(); ++element_it) { if (element_it->IsNewline() || (element_it->IsField() && !address_data.IsFieldEmpty(element_it->GetField())) || (!element_it->IsField() && (element_it + 1 == format.end() || !(element_it + 1)->IsField() || !address_data.IsFieldEmpty((element_it + 1)->GetField())) && (element_it == format.begin() || !(element_it - 1)->IsField() || (!pruned_format.empty() && pruned_format.back().IsField())))) { pruned_format.push_back(*element_it); } } std::string line; for (const auto& element : pruned_format) { if (element.IsNewline()) { if (!line.empty()) { lines->push_back(line); line.clear(); } } else if (element.IsField()) { AddressField field = element.GetField(); if (field == STREET_ADDRESS) { if (!address_data.IsFieldEmpty(field)) { line.append(address_data.address_line.front()); if (address_data.address_line.size() > 1U) { lines->push_back(line); line.clear(); const auto last_element_iterator = address_data.address_line.begin() + address_data.address_line.size() - 1; lines->insert(lines->end(), address_data.address_line.begin() + 1, last_element_iterator); line.append(*last_element_iterator); } } } else { line.append(address_data.GetFieldValue(field)); } } else { line.append(element.GetLiteral()); } } if (!line.empty()) { lines->push_back(line); } } void GetFormattedNationalAddressLine( const AddressData& address_data, std::string* line) { std::vector<std::string> address_lines; GetFormattedNationalAddress(address_data, &address_lines); CombineLinesForLanguage(address_lines, address_data.language_code, line); } void GetStreetAddressLinesAsSingleLine( const AddressData& address_data, std::string* line) { CombineLinesForLanguage( address_data.address_line, address_data.language_code, line); } } }
#include <libaddressinput/address_formatter.h> #include <libaddressinput/address_data.h> #include <string> #include <vector> #include <gtest/gtest.h> namespace { using i18n::addressinput::AddressData; using i18n::addressinput::GetFormattedNationalAddress; using i18n::addressinput::GetFormattedNationalAddressLine; using i18n::addressinput::GetStreetAddressLinesAsSingleLine; TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_EmptyAddress) { const AddressData address; std::string result; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_TRUE(result.empty()); } TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_1Line) { AddressData address{ .region_code = "US", .address_line{"Line 1"}, }; std::string result; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1", result); address.language_code = "en"; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1", result); address.language_code = "zh-Hans"; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1", result); } TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_2Lines) { AddressData address{ .region_code = "US", .address_line{ "Line 1", "Line 2", }, }; std::string result; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1, Line 2", result); address.language_code = "en"; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1, Line 2", result); address.language_code = "zh-Hans"; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1Line 2", result); address.language_code = "ko"; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1 Line 2", result); address.language_code = "ar"; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ("Line 1، Line 2", result); } TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_5Lines) { const AddressData address{ .region_code = "US", .address_line{ "Line 1", "Line 2", "Line 3", "Line 4", "Line 5", }, .language_code = "fr", }; std::string result; GetStreetAddressLinesAsSingleLine(address, &result); EXPECT_EQ(result, "Line 1, Line 2, Line 3, Line 4, Line 5"); } TEST(AddressFormatterTest, GetFormattedNationalAddressLocalLanguage) { AddressData address{ .region_code = "NZ", .address_line{ "Rotopapa", "Irwell 3RD", }, .locality = "Leeston", .postal_code = "8704", }; const std::vector<std::string> expected{ "Rotopapa", "Irwell 3RD", "Leeston 8704", }; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.language_code = "en-Latn-CN"; lines.clear(); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); std::string one_line; GetFormattedNationalAddressLine(address, &one_line); EXPECT_EQ("Rotopapa, Irwell 3RD, Leeston 8704", one_line); } TEST(AddressFormatterTest, GetFormattedNationalAddressLatinFormat) { static const char kTaiwanCity[] = "大安區"; static const char kTaiwanAdmin[] = "台北市"; static const char kTaiwanStreetLine[] = "台灣信義路三段33號"; static const char kPostalCode[] = "106"; const AddressData address{ .region_code = "TW", .address_line{kTaiwanStreetLine}, .administrative_area = kTaiwanAdmin, .locality = kTaiwanCity, .postal_code = kPostalCode, .language_code = "zh-Hant", }; const std::vector<std::string> expected{ kPostalCode, std::string(kTaiwanAdmin).append(kTaiwanCity), kTaiwanStreetLine, }; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); std::string one_line; GetFormattedNationalAddressLine(address, &one_line); EXPECT_EQ(std::string(kPostalCode) .append(kTaiwanAdmin) .append(kTaiwanCity) .append(kTaiwanStreetLine), one_line); const AddressData latin_address{ .region_code = "TW", .address_line{"No. 33, Section 3 Xinyi Rd"}, .administrative_area = "Taipei City", .locality = "Da-an District", .postal_code = kPostalCode, .language_code = "zh-Latn", }; const std::vector<std::string> expected_latin{ "No. 33, Section 3 Xinyi Rd", "Da-an District, Taipei City 106", }; lines.clear(); GetFormattedNationalAddress(latin_address, &lines); EXPECT_EQ(expected_latin, lines); GetFormattedNationalAddressLine(latin_address, &one_line); EXPECT_EQ("No. 33, Section 3 Xinyi Rd, Da-an District, Taipei City 106", one_line); } TEST(AddressFormatterTest, GetFormattedNationalAddressMultilingualCountry) { const AddressData address{ .region_code = "CA", .address_line{ "5 Rue du Tresor", "Apt. 4", }, .administrative_area = "QC", .locality = "Montmagny", .postal_code = "G1R 123", .language_code = "fr", }; const std::vector<std::string> expected{ "5 Rue du Tresor", "Apt. 4", "Montmagny QC G1R 123", }; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddress_InlineStreetAddress) { const AddressData address{ .region_code = "CI", .address_line{"32 Boulevard Carde"}, .locality = "Abidjan", .sorting_code = "64", .language_code = "zh-Hant", }; const std::vector<std::string> expected{"64 32 Boulevard Carde Abidjan 64"}; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddressMissingFields_LiteralsAroundField) { AddressData address{.region_code = "CH"}; std::vector<std::string> expected; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.locality = "Zurich"; expected.emplace_back("Zurich"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.postal_code = "8001"; expected.back().assign("CH-8001 Zurich"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.locality.clear(); expected.back().assign("CH-8001"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddressMissingFields_LiteralsBetweenFields) { AddressData address{.region_code = "US"}; std::vector<std::string> expected; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.administrative_area = "CA"; expected.emplace_back("CA"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.locality = "Los Angeles"; expected.back().assign("Los Angeles, CA"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.postal_code = "90291"; expected.back().assign("Los Angeles, CA 90291"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.administrative_area.clear(); expected.back().assign("Los Angeles 90291"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.locality.clear(); address.administrative_area = "CA"; expected.back().assign("CA 90291"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddressMissingFields_LiteralOnSeparateLine) { AddressData address{.region_code = "AX"}; std::vector<std::string> expected{"ÅLAND"}; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.locality = "City"; expected.emplace(expected.begin(), "City"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.postal_code = "123"; expected.front().assign("AX-123 City"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddressMissingFields_LiteralBeforeField) { AddressData address{ .region_code = "JP", .language_code = "ja", }; std::vector<std::string> expected; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.postal_code = "123"; expected.emplace_back("〒123"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.administrative_area = "Prefecture"; expected.emplace_back("Prefecture"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.postal_code.clear(); expected.erase(expected.begin()); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddress_LiteralBeforeOneAddressLine) { const AddressData address{ .region_code = "JP", .address_line{"Roppongi Hills"}, .administrative_area = "Tokyo", .language_code = "ja_Latn", }; const std::vector<std::string> expected{"Roppongi Hills, Tokyo"}; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddress_LiteralBeforeTwoAddressLines) { const AddressData address{ .region_code = "JP", .address_line{ "Roppongi Hills", "Mori Tower", }, .administrative_area = "Tokyo", .language_code = "ja_Latn", }; const std::vector<std::string> expected{ "Roppongi Hills", "Mori Tower, Tokyo", }; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } TEST(AddressFormatterTest, GetFormattedNationalAddressMissingFields_DuplicateField) { AddressData address{.region_code = "CI"}; std::vector<std::string> expected; std::vector<std::string> lines; GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.sorting_code = "123"; expected.emplace_back("123 123"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.address_line.emplace_back("456 Main St"); expected.back().assign("123 456 Main St 123"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.locality = "Yamoussoukro"; expected.back().assign("123 456 Main St Yamoussoukro 123"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.sorting_code.erase(); expected.back().assign("456 Main St Yamoussoukro"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); address.address_line.clear(); expected.back().assign("Yamoussoukro"); GetFormattedNationalAddress(address, &lines); EXPECT_EQ(expected, lines); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_formatter.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_formatter_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
896b5f77-9df8-45ee-8777-37ac3e99637f
cpp
google/libaddressinput
address_normalizer
cpp/src/address_normalizer.cc
cpp/test/address_normalizer_test.cc
#include <libaddressinput/address_normalizer.h> #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/preload_supplier.h> #include <cassert> #include <cstddef> #include <string> #include <vector> #include "lookup_key.h" #include "rule.h" #include "util/size.h" #include "util/string_compare.h" namespace i18n { namespace addressinput { AddressNormalizer::AddressNormalizer(const PreloadSupplier* supplier) : supplier_(supplier), compare_(new StringCompare) { assert(supplier_ != nullptr); } AddressNormalizer::~AddressNormalizer() = default; void AddressNormalizer::Normalize(AddressData* address) const { assert(address != nullptr); assert(supplier_->IsLoaded(address->region_code)); AddressData region_address; region_address.region_code = address->region_code; LookupKey parent_key; parent_key.FromAddress(region_address); const Rule* parent_rule = supplier_->GetRule(parent_key); assert(parent_rule != nullptr); std::vector<std::string> languages(parent_rule->GetLanguages()); if (languages.empty()) { languages.emplace_back(""); } else { languages[0] = ""; } LookupKey lookup_key; for (size_t depth = 1; depth < size(LookupKey::kHierarchy); ++depth) { AddressField field = LookupKey::kHierarchy[depth]; if (address->IsFieldEmpty(field)) { return; } const std::string& field_value = address->GetFieldValue(field); bool no_match_found_yet = true; for (const auto& sub_key : parent_rule->GetSubKeys()) { if (!no_match_found_yet) { break; } for (const std::string& language_tag : languages) { lookup_key.set_language(language_tag); lookup_key.FromLookupKey(parent_key, sub_key); const Rule* rule = supplier_->GetRule(lookup_key); if (rule == nullptr) continue; bool matches_latin_name = compare_->NaturalEquals(field_value, rule->GetLatinName()); bool matches_local_name_id = compare_->NaturalEquals(field_value, sub_key) || compare_->NaturalEquals(field_value, rule->GetName()); if (matches_latin_name || matches_local_name_id) { address->SetFieldValue( field, matches_latin_name ? rule->GetLatinName() : sub_key); no_match_found_yet = false; parent_key.FromLookupKey(parent_key, sub_key); parent_rule = supplier_->GetRule(parent_key); assert(parent_rule != nullptr); break; } } } if (no_match_found_yet) { return; } } } } }
#include <libaddressinput/address_normalizer.h> #include <libaddressinput/address_data.h> #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/preload_supplier.h> #include <memory> #include <string> #include <gtest/gtest.h> #include "testdata_source.h" namespace { using i18n::addressinput::AddressData; using i18n::addressinput::AddressNormalizer; using i18n::addressinput::BuildCallback; using i18n::addressinput::NullStorage; using i18n::addressinput::PreloadSupplier; using i18n::addressinput::TestdataSource; class AddressNormalizerTest : public testing::Test { public: AddressNormalizerTest(const AddressNormalizerTest&) = delete; AddressNormalizerTest& operator=(const AddressNormalizerTest&) = delete; protected: AddressNormalizerTest() : supplier_(new TestdataSource(true), new NullStorage), loaded_(BuildCallback(this, &AddressNormalizerTest::OnLoaded)), normalizer_(&supplier_) {} PreloadSupplier supplier_; const std::unique_ptr<const PreloadSupplier::Callback> loaded_; const AddressNormalizer normalizer_; private: void OnLoaded(bool success, const std::string& region_code, int num_rules) { ASSERT_TRUE(success); ASSERT_FALSE(region_code.empty()); ASSERT_LT(0, num_rules); } }; TEST_F(AddressNormalizerTest, CountryWithNoLanguageNoAdminArea) { supplier_.LoadRules("IR", *loaded_); AddressData address{ .region_code = "IR", .administrative_area = "Tehran", }; normalizer_.Normalize(&address); EXPECT_EQ("Tehran", address.administrative_area); } TEST_F(AddressNormalizerTest, BrazilAdminAreaAndLocality) { supplier_.LoadRules("BR", *loaded_); AddressData address{ .region_code = "BR", .administrative_area = "Maranhão", .locality = "Cantanhede", }; normalizer_.Normalize(&address); EXPECT_EQ("MA", address.administrative_area); EXPECT_EQ("Cantanhede", address.locality); } TEST_F(AddressNormalizerTest, FrenchCanadaNameLanguageNotConsistent) { supplier_.LoadRules("CA", *loaded_); AddressData address{ .region_code = "CA", .administrative_area = "Nouveau-Brunswick", .language_code = "en-CA", }; normalizer_.Normalize(&address); EXPECT_EQ("NB", address.administrative_area); } TEST_F(AddressNormalizerTest, FrenchCanadaName) { supplier_.LoadRules("CA", *loaded_); AddressData address{ .region_code = "CA", .administrative_area = "Nouveau-Brunswick", .language_code = "fr-CA", }; normalizer_.Normalize(&address); EXPECT_EQ("NB", address.administrative_area); } TEST_F(AddressNormalizerTest, FrenchCanadaNameLanguageNotListed) { supplier_.LoadRules("CA", *loaded_); AddressData address{ .region_code = "CA", .administrative_area = "Colombie-Britannique", .language_code = "fa-CA", }; normalizer_.Normalize(&address); EXPECT_EQ("BC", address.administrative_area); } TEST_F(AddressNormalizerTest, CaliforniaShortNameCa) { supplier_.LoadRules("US", *loaded_); AddressData address{ .region_code = "US", .administrative_area = "California", .locality = "Mountain View", .language_code = "en-US", }; normalizer_.Normalize(&address); EXPECT_EQ("CA", address.administrative_area); } TEST_F(AddressNormalizerTest, CountryWithNonStandardData) { supplier_.LoadRules("HK", *loaded_); AddressData address{ .region_code = "HK", .administrative_area = "香港島", }; normalizer_.Normalize(&address); EXPECT_EQ("香港島", address.administrative_area); } TEST_F(AddressNormalizerTest, GangwonLatinNameStaysUnchanged) { supplier_.LoadRules("KR", *loaded_); AddressData address{ .region_code = "KR", .administrative_area = "Gangwon", .language_code = "ko-Latn", }; normalizer_.Normalize(&address); EXPECT_EQ("Gangwon", address.administrative_area); } TEST_F(AddressNormalizerTest, GangwonKoreanName) { supplier_.LoadRules("KR", *loaded_); AddressData address{ .region_code = "KR", .administrative_area = "강원", .language_code = "ko-KR", }; normalizer_.Normalize(&address); EXPECT_EQ("강원도", address.administrative_area); } TEST_F(AddressNormalizerTest, DontSwitchLatinScriptForUnknownLanguage) { supplier_.LoadRules("KR", *loaded_); AddressData address{ .region_code = "KR", .administrative_area = "Gangwon", }; normalizer_.Normalize(&address); EXPECT_EQ("Gangwon", address.administrative_area); } TEST_F(AddressNormalizerTest, DontSwitchLocalScriptForUnknownLanguage) { supplier_.LoadRules("KR", *loaded_); AddressData address{ .region_code = "KR", .administrative_area = "강원", }; normalizer_.Normalize(&address); EXPECT_EQ("강원도", address.administrative_area); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_normalizer.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_normalizer_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
1a315438-fcc1-4394-b61d-58b16b12b0a4
cpp
google/libaddressinput
validation_task
cpp/src/validation_task.cc
cpp/test/validation_task_test.cc
#include "validation_task.h" #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_metadata.h> #include <libaddressinput/address_problem.h> #include <libaddressinput/address_validator.h> #include <libaddressinput/callback.h> #include <libaddressinput/supplier.h> #include <algorithm> #include <cassert> #include <cstddef> #include <string> #include <re2/re2.h> #include "lookup_key.h" #include "post_box_matchers.h" #include "rule.h" #include "util/re2ptr.h" #include "util/size.h" namespace i18n { namespace addressinput { ValidationTask::ValidationTask(const AddressData& address, bool allow_postal, bool require_name, const FieldProblemMap* filter, FieldProblemMap* problems, const AddressValidator::Callback& validated) : address_(address), allow_postal_(allow_postal), require_name_(require_name), filter_(filter), problems_(problems), validated_(validated), supplied_(BuildCallback(this, &ValidationTask::Validate)), lookup_key_(new LookupKey), max_depth_(size(LookupKey::kHierarchy)) { assert(problems_ != nullptr); assert(supplied_ != nullptr); assert(lookup_key_ != nullptr); } ValidationTask::~ValidationTask() = default; void ValidationTask::Run(Supplier* supplier) { assert(supplier != nullptr); problems_->clear(); lookup_key_->FromAddress(address_); max_depth_ = supplier->GetLoadedRuleDepth(lookup_key_->ToKeyString(0)); supplier->SupplyGlobally(*lookup_key_, *supplied_); } void ValidationTask::Validate(bool success, const LookupKey& lookup_key, const Supplier::RuleHierarchy& hierarchy) { assert(&lookup_key == lookup_key_.get()); if (success) { if (address_.IsFieldEmpty(COUNTRY)) { ReportProblemMaybe(COUNTRY, MISSING_REQUIRED_FIELD); } else if (hierarchy.rule[0] == nullptr) { ReportProblemMaybe(COUNTRY, UNKNOWN_VALUE); } else { const std::string& region_code = address_.region_code; CheckUnexpectedField(region_code); CheckMissingRequiredField(region_code); CheckUnknownValue(hierarchy); CheckPostalCodeFormatAndValue(hierarchy); CheckUsesPoBox(hierarchy); CheckUnsupportedField(); } } validated_(success, address_, *problems_); delete this; } void ValidationTask::CheckUnexpectedField( const std::string& region_code) const { static const AddressField kFields[] = { ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY, SORTING_CODE, POSTAL_CODE, STREET_ADDRESS, ORGANIZATION, RECIPIENT, }; for (AddressField field : kFields) { if (!address_.IsFieldEmpty(field) && !IsFieldUsed(field, region_code)) { ReportProblemMaybe(field, UNEXPECTED_FIELD); } } } void ValidationTask::CheckMissingRequiredField( const std::string& region_code) const { static const AddressField kFields[] = { ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY, SORTING_CODE, POSTAL_CODE, STREET_ADDRESS, }; for (AddressField field : kFields) { if (address_.IsFieldEmpty(field) && IsFieldRequired(field, region_code)) { ReportProblemMaybe(field, MISSING_REQUIRED_FIELD); } } if (require_name_ && address_.IsFieldEmpty(RECIPIENT)) { ReportProblemMaybe(RECIPIENT, MISSING_REQUIRED_FIELD); } } void ValidationTask::CheckUnknownValue( const Supplier::RuleHierarchy& hierarchy) const { for (size_t depth = 1; depth < size(LookupKey::kHierarchy); ++depth) { AddressField field = LookupKey::kHierarchy[depth]; if (!(address_.IsFieldEmpty(field) || hierarchy.rule[depth - 1] == nullptr || hierarchy.rule[depth - 1]->GetSubKeys().empty() || hierarchy.rule[depth] != nullptr)) { ReportProblemMaybe(field, UNKNOWN_VALUE); } } } void ValidationTask::CheckUnsupportedField() const { for (size_t depth = max_depth_; depth < size(LookupKey::kHierarchy); ++depth) { ReportProblemMaybe(LookupKey::kHierarchy[depth], UNSUPPORTED_FIELD); } } void ValidationTask::CheckPostalCodeFormatAndValue( const Supplier::RuleHierarchy& hierarchy) const { assert(hierarchy.rule[0] != nullptr); const Rule& country_rule = *hierarchy.rule[0]; if (!(ShouldReport(POSTAL_CODE, INVALID_FORMAT) || ShouldReport(POSTAL_CODE, MISMATCHING_VALUE))) { return; } if (address_.IsFieldEmpty(POSTAL_CODE)) { return; } else if (std::find(problems_->begin(), problems_->end(), FieldProblemMap::value_type(POSTAL_CODE, UNEXPECTED_FIELD)) != problems_->end()) { return; } const RE2ptr* format_ptr = country_rule.GetPostalCodeMatcher(); if (format_ptr != nullptr && !RE2::FullMatch(address_.postal_code, *format_ptr->ptr) && ShouldReport(POSTAL_CODE, INVALID_FORMAT)) { ReportProblem(POSTAL_CODE, INVALID_FORMAT); return; } if (!ShouldReport(POSTAL_CODE, MISMATCHING_VALUE)) { return; } for (size_t depth = size(LookupKey::kHierarchy) - 1; depth > 0; --depth) { if (hierarchy.rule[depth] != nullptr) { const RE2ptr* prefix_ptr = hierarchy.rule[depth]->GetPostalCodeMatcher(); if (prefix_ptr != nullptr) { if (!RE2::PartialMatch(address_.postal_code, *prefix_ptr->ptr)) { ReportProblem(POSTAL_CODE, MISMATCHING_VALUE); } return; } } } } void ValidationTask::CheckUsesPoBox( const Supplier::RuleHierarchy& hierarchy) const { assert(hierarchy.rule[0] != nullptr); const Rule& country_rule = *hierarchy.rule[0]; if (allow_postal_ || !ShouldReport(STREET_ADDRESS, USES_P_O_BOX) || address_.IsFieldEmpty(STREET_ADDRESS)) { return; } const auto matchers = PostBoxMatchers::GetMatchers(country_rule); for (const auto& line : address_.address_line) { for (auto ptr : matchers) { assert(ptr != nullptr); if (RE2::PartialMatch(line, *ptr->ptr)) { ReportProblem(STREET_ADDRESS, USES_P_O_BOX); return; } } } } void ValidationTask::ReportProblem(AddressField field, AddressProblem problem) const { problems_->emplace(field, problem); } void ValidationTask::ReportProblemMaybe(AddressField field, AddressProblem problem) const { if (ShouldReport(field, problem)) { ReportProblem(field, problem); } } bool ValidationTask::ShouldReport(AddressField field, AddressProblem problem) const { return filter_ == nullptr || filter_->empty() || std::find(filter_->begin(), filter_->end(), FieldProblemMap::value_type(field, problem)) != filter_->end(); } } }
#include "validation_task.h" #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_problem.h> #include <libaddressinput/address_validator.h> #include <libaddressinput/callback.h> #include <libaddressinput/supplier.h> #include <cstddef> #include <memory> #include <gtest/gtest.h> #include "lookup_key.h" #include "rule.h" #include "util/size.h" namespace i18n { namespace addressinput { class ValidationTaskTest : public testing::Test { public: ValidationTaskTest(const ValidationTaskTest&) = delete; ValidationTaskTest& operator=(const ValidationTaskTest&) = delete; protected: ValidationTaskTest() : json_(), success_(true), address_(), allow_postal_(false), require_name_(false), filter_{ {COUNTRY, UNEXPECTED_FIELD}, {COUNTRY, MISSING_REQUIRED_FIELD}, {RECIPIENT, UNEXPECTED_FIELD}, {RECIPIENT, MISSING_REQUIRED_FIELD}, }, problems_(), expected_(), called_(false), validated_(BuildCallback(this, &ValidationTaskTest::Validated)) { static const AddressField kFields[] = { COUNTRY, ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY, SORTING_CODE, POSTAL_CODE, STREET_ADDRESS, ORGANIZATION, RECIPIENT, }; static const AddressProblem kProblems[] = { UNKNOWN_VALUE, INVALID_FORMAT, MISMATCHING_VALUE, USES_P_O_BOX, }; for (AddressField field : kFields) { for (AddressProblem problem : kProblems) { filter_.emplace(field, problem); } } } void Validate() { Rule rule[size(LookupKey::kHierarchy)]; auto* task = new ValidationTask( address_, allow_postal_, require_name_, &filter_, &problems_, *validated_); Supplier::RuleHierarchy hierarchy; for (size_t i = 0; i < size(LookupKey::kHierarchy) && json_[i] != nullptr; ++i) { ASSERT_TRUE(rule[i].ParseSerializedRule(json_[i])); hierarchy.rule[i] = &rule[i]; } (*task->supplied_)(success_, *task->lookup_key_, hierarchy); } const char* json_[size(LookupKey::kHierarchy)]; bool success_; AddressData address_; bool allow_postal_; bool require_name_; FieldProblemMap filter_; FieldProblemMap problems_; FieldProblemMap expected_; bool called_; private: void Validated(bool success, const AddressData& address, const FieldProblemMap& problems) { ASSERT_EQ(success_, success); ASSERT_EQ(&address_, &address); ASSERT_EQ(&problems_, &problems); called_ = true; } const std::unique_ptr<const AddressValidator::Callback> validated_; }; namespace { TEST_F(ValidationTaskTest, FailureCountryRuleNull) { success_ = false; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, FailureCountryRuleEmpty) { json_[0] = "{}"; success_ = false; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, SuccessCountryRuleNullNameEmpty) { expected_ = {{COUNTRY, MISSING_REQUIRED_FIELD}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, SuccessCountryRuleNullNameNotEmpty) { address_ = {.region_code = "rrr"}; expected_ = {{COUNTRY, UNKNOWN_VALUE}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, SuccessCountryRuleEmptyNameEmpty) { json_[0] = "{}"; expected_ = {{COUNTRY, MISSING_REQUIRED_FIELD}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, SuccessCountryRuleEmptyNameNotEmpty) { json_[0] = "{}"; address_ = {.region_code = "rrr"}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, MissingRequiredFieldsUS) { json_[0] = "{}"; address_ = {.region_code = "US"}; filter_ = { {ADMIN_AREA, MISSING_REQUIRED_FIELD}, {LOCALITY, MISSING_REQUIRED_FIELD}, {POSTAL_CODE, MISSING_REQUIRED_FIELD}, {STREET_ADDRESS, MISSING_REQUIRED_FIELD}, }; expected_ = { {ADMIN_AREA, MISSING_REQUIRED_FIELD}, {LOCALITY, MISSING_REQUIRED_FIELD}, {POSTAL_CODE, MISSING_REQUIRED_FIELD}, {STREET_ADDRESS, MISSING_REQUIRED_FIELD}, }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, MissingNoRequiredFieldsUS) { json_[0] = "{}"; address_ = { .region_code = "US", .address_line{"aaa"}, .administrative_area = "sss", .locality = "ccc", .postal_code = "zzz", .organization = "ooo", .recipient = "nnn", }; filter_ = { {ADMIN_AREA, MISSING_REQUIRED_FIELD}, {LOCALITY, MISSING_REQUIRED_FIELD}, {POSTAL_CODE, MISSING_REQUIRED_FIELD}, {STREET_ADDRESS, MISSING_REQUIRED_FIELD}, {ORGANIZATION, MISSING_REQUIRED_FIELD}, }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, UnexpectedFieldUS) { json_[0] = "{}"; address_ = { .region_code = "US", .dependent_locality = "ddd", }; filter_ = {{DEPENDENT_LOCALITY, UNEXPECTED_FIELD}}; expected_ = {{DEPENDENT_LOCALITY, UNEXPECTED_FIELD}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, MissingRequiredFieldRequireName) { json_[0] = "{}"; address_ = {.region_code = "rrr"}; require_name_ = true; expected_ = {{RECIPIENT, MISSING_REQUIRED_FIELD}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, UnknownValueRuleNull) { json_[0] = R"({"fmt":"%R%S","require":"RS","sub_keys":"aa~bb"})"; address_ = { .region_code = "rrr", .administrative_area = "sss", }; expected_ = {{ADMIN_AREA, UNKNOWN_VALUE}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, NoUnknownValueRuleNotNull) { json_[0] = R"({"fmt":"%R%S","require":"RS","sub_keys":"aa~bb"})"; json_[1] = "{}"; address_ = { .region_code = "rrr", .administrative_area = "sss", }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeUnrecognizedFormatTooShort) { json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})"; address_ = { .region_code = "rrr", .postal_code = "12", }; expected_ = {{POSTAL_CODE, INVALID_FORMAT}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeUnrecognizedFormatTooLong) { json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})"; address_ = { .region_code = "rrr", .postal_code = "1234", }; expected_ = {{POSTAL_CODE, INVALID_FORMAT}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeRecognizedFormat) { json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})"; address_ = { .region_code = "rrr", .postal_code = "123", }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeMismatchingValue1) { json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})"; json_[1] = R"({"zip":"1"})"; address_ = { .region_code = "rrr", .postal_code = "000", }; expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeMismatchingValue2) { json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})"; json_[1] = R"({"zip":"1"})"; json_[2] = R"({"zip":"12"})"; address_ = { .region_code = "rrr", .postal_code = "100", }; expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeMismatchingValue3) { json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})"; json_[1] = R"({"zip":"1"})"; json_[2] = R"({"zip":"12"})"; json_[3] = R"({"zip":"123"})"; address_ = { .region_code = "rrr", .postal_code = "120", }; expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeMatchingValue) { json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})"; json_[1] = R"({"zip":"1"})"; json_[2] = R"({"zip":"12"})"; json_[3] = R"({"zip":"123"})"; address_ = { .region_code = "rrr", .postal_code = "123", }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodePrefixMismatchingValue) { json_[0] = R"({"fmt":"%Z","zip":"\\d{5}"})"; json_[1] = R"({"zip":"9[0-5]|96[01]"})"; address_ = { .region_code = "rrr", .postal_code = "10960", }; expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, PostalCodeFilterIgnoresMismatching) { json_[0] = R"({"zip":"\\d{3}"})"; json_[1] = R"({"zip":"1"})"; address_ = { .region_code = "rrr", .postal_code = "000", }; filter_ = {{POSTAL_CODE, INVALID_FORMAT}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, UsesPoBoxLanguageUnd) { json_[0] = R"({"fmt":"%A"})"; address_ = { .region_code = "rrr", .address_line{ "aaa", "P.O. Box", "aaa", }, }; expected_ = {{STREET_ADDRESS, USES_P_O_BOX}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, UsesPoBoxLanguageDa) { json_[0] = R"({"fmt":"%A","languages":"da"})"; address_ = { .region_code = "rrr", .address_line{ "aaa", "Postboks", "aaa", }, }; expected_ = {{STREET_ADDRESS, USES_P_O_BOX}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, UsesPoBoxLanguageDaNotMatchDe) { json_[0] = R"({"fmt":"%A","languages":"da"})"; address_ = { .region_code = "rrr", .address_line{ "aaa", "Postfach", "aaa", }, }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_F(ValidationTaskTest, UsesPoBoxAllowPostal) { json_[0] = R"({"fmt":"%A"})"; address_ = { .region_code = "rrr", .address_line{ "aaa", "P.O. Box", "aaa", }, }; allow_postal_ = true; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } } } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/validation_task.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/validation_task_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
64710183-ea4a-40de-abc1-7e74867a301d
cpp
google/libaddressinput
language
cpp/src/language.cc
cpp/test/language_test.cc
#include "language.h" #include <algorithm> #include <cctype> #include <string> #include <vector> #include "rule.h" #include "util/string_split.h" namespace i18n { namespace addressinput { Language::Language(const std::string& language_tag) : tag(language_tag), base(), has_latin_script(false) { static const char kSubtagsSeparator = '-'; static const char kAlternativeSubtagsSeparator = '_'; std::replace( tag.begin(), tag.end(), kAlternativeSubtagsSeparator, kSubtagsSeparator); std::string lowercase = tag; std::transform( lowercase.begin(), lowercase.end(), lowercase.begin(), tolower); base = lowercase.substr(0, lowercase.find(kSubtagsSeparator)); static const char kLowercaseLatinScript[] = "latn"; std::vector<std::string> subtags; SplitString(lowercase, kSubtagsSeparator, &subtags); has_latin_script = (subtags.size() > 1 && subtags[1] == kLowercaseLatinScript) || (subtags.size() > 2 && subtags[2] == kLowercaseLatinScript); } Language::~Language() = default; Language ChooseBestAddressLanguage(const Rule& address_region_rule, const Language& ui_language) { if (address_region_rule.GetLanguages().empty()) { return ui_language; } std::vector<Language> available_languages; for (const auto& language_tag : address_region_rule.GetLanguages()) { available_languages.emplace_back(language_tag); } if (ui_language.tag.empty()) { return available_languages.front(); } bool has_latin_format = !address_region_rule.GetLatinFormat().empty(); static const char kLatinScriptSuffix[] = "-Latn"; Language latin_script_language( available_languages.front().base + kLatinScriptSuffix); if (has_latin_format && ui_language.has_latin_script) { return latin_script_language; } for (const auto& language : available_languages) { if (ui_language.base == language.base) { return language; } } return has_latin_format ? latin_script_language : available_languages.front(); } } }
#include "language.h" #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::Language; struct LanguageTestCase { LanguageTestCase(const std::string& input_language_tag, const std::string& expected_language_tag, const std::string& expected_base_language, bool expected_has_latin_script) : input_language_tag(input_language_tag), expected_language_tag(expected_language_tag), expected_base_language(expected_base_language), expected_has_latin_script(expected_has_latin_script) {} ~LanguageTestCase() = default; const std::string input_language_tag; const std::string expected_language_tag; const std::string expected_base_language; const bool expected_has_latin_script; }; class LanguageTest : public testing::TestWithParam<LanguageTestCase> { public: LanguageTest(const LanguageTest&) = delete; LanguageTest& operator=(const LanguageTest&) = delete; protected: LanguageTest() = default; }; TEST_P(LanguageTest, ExtractedDataIsCorrect) { Language language(GetParam().input_language_tag); EXPECT_EQ(GetParam().expected_language_tag, language.tag); EXPECT_EQ(GetParam().expected_base_language, language.base); EXPECT_EQ(GetParam().expected_has_latin_script, language.has_latin_script); } INSTANTIATE_TEST_SUITE_P( LanguageTestCases, LanguageTest, testing::Values(LanguageTestCase("", "", "", false), LanguageTestCase("en", "en", "en", false), LanguageTestCase("zh-Latn-CN", "zh-Latn-CN", "zh", true), LanguageTestCase("zh-cmn-Latn-CN", "zh-cmn-Latn-CN", "zh", true), LanguageTestCase("zh-Hans", "zh-Hans", "zh", false), LanguageTestCase("en_GB", "en-GB", "en", false))); }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/language.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/language_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
a0ab9f15-16d6-4963-9b2e-a0ac62c97a9f
cpp
google/libaddressinput
address_validator
cpp/src/address_validator.cc
cpp/test/address_validator_test.cc
#include <libaddressinput/address_validator.h> #include <cassert> #include <cstddef> #include "validation_task.h" namespace i18n { namespace addressinput { AddressValidator::AddressValidator(Supplier* supplier) : supplier_(supplier) { assert(supplier_ != nullptr); } void AddressValidator::Validate(const AddressData& address, bool allow_postal, bool require_name, const FieldProblemMap* filter, FieldProblemMap* problems, const Callback& validated) const { (new ValidationTask( address, allow_postal, require_name, filter, problems, validated))->Run(supplier_); } } }
#include <libaddressinput/address_validator.h> #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_problem.h> #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/ondemand_supplier.h> #include <libaddressinput/preload_supplier.h> #include <memory> #include <string> #include <gtest/gtest.h> #include "testdata_source.h" namespace { using i18n::addressinput::AddressData; using i18n::addressinput::AddressValidator; using i18n::addressinput::BuildCallback; using i18n::addressinput::FieldProblemMap; using i18n::addressinput::NullStorage; using i18n::addressinput::OndemandSupplier; using i18n::addressinput::PreloadSupplier; using i18n::addressinput::TestdataSource; using i18n::addressinput::ADMIN_AREA; using i18n::addressinput::COUNTRY; using i18n::addressinput::DEPENDENT_LOCALITY; using i18n::addressinput::LOCALITY; using i18n::addressinput::POSTAL_CODE; using i18n::addressinput::STREET_ADDRESS; using i18n::addressinput::INVALID_FORMAT; using i18n::addressinput::MISMATCHING_VALUE; using i18n::addressinput::MISSING_REQUIRED_FIELD; using i18n::addressinput::UNEXPECTED_FIELD; using i18n::addressinput::UNKNOWN_VALUE; using i18n::addressinput::UNSUPPORTED_FIELD; class ValidatorWrapper { public: virtual ~ValidatorWrapper() = default; virtual void Validate(const AddressData& address, bool allow_postal, bool require_name, const FieldProblemMap* filter, FieldProblemMap* problems, const AddressValidator::Callback& validated) = 0; }; class OndemandValidatorWrapper : public ValidatorWrapper { public: OndemandValidatorWrapper(const OndemandValidatorWrapper&) = delete; OndemandValidatorWrapper& operator=(const OndemandValidatorWrapper&) = delete; static ValidatorWrapper* Build() { return new OndemandValidatorWrapper; } void Validate(const AddressData& address, bool allow_postal, bool require_name, const FieldProblemMap* filter, FieldProblemMap* problems, const AddressValidator::Callback& validated) override { validator_.Validate(address, allow_postal, require_name, filter, problems, validated); } private: OndemandValidatorWrapper() : supplier_(new TestdataSource(false), new NullStorage), validator_(&supplier_) {} OndemandSupplier supplier_; const AddressValidator validator_; }; class PreloadValidatorWrapper : public ValidatorWrapper { public: PreloadValidatorWrapper(const PreloadValidatorWrapper&) = delete; PreloadValidatorWrapper& operator=(const PreloadValidatorWrapper&) = delete; static ValidatorWrapper* Build() { return new PreloadValidatorWrapper; } void Validate(const AddressData& address, bool allow_postal, bool require_name, const FieldProblemMap* filter, FieldProblemMap* problems, const AddressValidator::Callback& validated) override { const std::string& region_code = address.region_code; if (!region_code.empty() && !supplier_.IsLoaded(region_code)) { supplier_.LoadRules(region_code, *loaded_); } validator_.Validate(address, allow_postal, require_name, filter, problems, validated); } private: PreloadValidatorWrapper() : supplier_(new TestdataSource(true), new NullStorage), validator_(&supplier_), loaded_(BuildCallback(this, &PreloadValidatorWrapper::Loaded)) {} void Loaded(bool success, const std::string&, int) { ASSERT_TRUE(success); } PreloadSupplier supplier_; const AddressValidator validator_; const std::unique_ptr<const PreloadSupplier::Callback> loaded_; }; class AddressValidatorTest : public testing::TestWithParam<ValidatorWrapper* (*)()> { public: AddressValidatorTest(const AddressValidatorTest&) = delete; AddressValidatorTest& operator=(const AddressValidatorTest&) = delete; protected: AddressValidatorTest() : address_(), allow_postal_(false), require_name_(false), filter_(), problems_(), expected_(), called_(false), validator_wrapper_((*GetParam())()), validated_(BuildCallback(this, &AddressValidatorTest::Validated)) {} void Validate() { validator_wrapper_->Validate(address_, allow_postal_, require_name_, &filter_, &problems_, *validated_); } AddressData address_; bool allow_postal_; bool require_name_; FieldProblemMap filter_; FieldProblemMap problems_; FieldProblemMap expected_; bool called_; private: void Validated(bool success, const AddressData& address, const FieldProblemMap& problems) { ASSERT_TRUE(success); ASSERT_EQ(&address_, &address); ASSERT_EQ(&problems_, &problems); called_ = true; } const std::unique_ptr<ValidatorWrapper> validator_wrapper_; const std::unique_ptr<const AddressValidator::Callback> validated_; }; INSTANTIATE_TEST_SUITE_P(OndemandSupplier, AddressValidatorTest, testing::Values(&OndemandValidatorWrapper::Build)); INSTANTIATE_TEST_SUITE_P(PreloadSupplier, AddressValidatorTest, testing::Values(&PreloadValidatorWrapper::Build)); TEST_P(AddressValidatorTest, EmptyAddress) { expected_ = {{COUNTRY, MISSING_REQUIRED_FIELD}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, InvalidCountry) { address_ = {.region_code = "QZ"}; expected_ = {{COUNTRY, UNKNOWN_VALUE}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidAddressUS) { address_ = { .region_code = "US", .address_line{"1600 Amphitheatre Parkway"}, .administrative_area = "CA", .locality = "Mountain View", .postal_code = "94043", .language_code = "en", }; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_ = { {LOCALITY, UNSUPPORTED_FIELD}, {DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}, }; } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, InvalidAddressUS) { address_ = { .region_code = "US", .postal_code = "123", }; expected_ = { {ADMIN_AREA, MISSING_REQUIRED_FIELD}, {LOCALITY, MISSING_REQUIRED_FIELD}, {STREET_ADDRESS, MISSING_REQUIRED_FIELD}, {POSTAL_CODE, INVALID_FORMAT}, }; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD); expected_.emplace(LOCALITY, UNSUPPORTED_FIELD); } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidAddressCH) { address_ = { .region_code = "CH", .address_line{"Brandschenkestrasse 110"}, .locality = "ZH", .postal_code = "8002", .language_code = "de", }; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_ = { {LOCALITY, UNSUPPORTED_FIELD}, {DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}, }; } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, InvalidAddressCH) { address_ = { .region_code = "CH", .postal_code = "123", }; expected_ = { {STREET_ADDRESS, MISSING_REQUIRED_FIELD}, {POSTAL_CODE, INVALID_FORMAT}, {LOCALITY, MISSING_REQUIRED_FIELD}, }; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_.emplace(LOCALITY, UNSUPPORTED_FIELD); expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD); } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidPostalCodeMX) { address_ = { .region_code = "MX", .address_line{"Av Gregorio Méndez Magaña 1400"}, .administrative_area = "TAB", .locality = "Villahermosa", .postal_code = "86070", .language_code = "es", }; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_ = { {DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}, {LOCALITY, UNSUPPORTED_FIELD}, }; } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, MismatchingPostalCodeMX) { address_ = { .region_code = "MX", .address_line{"Av Gregorio Méndez Magaña 1400"}, .administrative_area = "TAB", .locality = "Villahermosa", .postal_code = "80000", .language_code = "es", }; expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}}; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_.emplace(LOCALITY, UNSUPPORTED_FIELD); expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD); } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidateFilter) { address_ = { .region_code = "CH", .postal_code = "123", }; filter_ = {{POSTAL_CODE, INVALID_FORMAT}}; expected_ = {{POSTAL_CODE, INVALID_FORMAT}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidateClearsProblems) { address_ = { .region_code = "CH", .address_line{"Brandschenkestrasse 110"}, .locality = "ZH", .postal_code = "123", .language_code = "de", }; problems_ = { {LOCALITY, UNEXPECTED_FIELD}, {LOCALITY, MISSING_REQUIRED_FIELD}, {STREET_ADDRESS, MISSING_REQUIRED_FIELD}, }; expected_ = {{POSTAL_CODE, INVALID_FORMAT}}; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_.emplace(LOCALITY, UNSUPPORTED_FIELD); expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD); } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidKanjiAddressJP) { address_ = { .region_code = "JP", .address_line{"徳島市..."}, .administrative_area = "徳島県", .postal_code = "770-0847", .language_code = "ja", }; if (GetParam() == &PreloadValidatorWrapper::Build) { expected_ = { {DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}, {LOCALITY, UNSUPPORTED_FIELD}, }; } ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidLatinAddressJP) { if (GetParam() == &OndemandValidatorWrapper::Build) return; address_ = { .region_code = "JP", .address_line{"...Tokushima"}, .administrative_area = "Tokushima", .postal_code = "770-0847", .language_code = "ja-Latn", }; expected_ = { {DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}, {LOCALITY, UNSUPPORTED_FIELD}, }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidAddressBR) { if (GetParam() == &OndemandValidatorWrapper::Build) return; address_ = { .region_code = "BR", .address_line{"Rodovia Raposo Tavares, 6388-6682"}, .administrative_area = "São Paulo", .locality = "Presidente Prudente", .postal_code = "19063-008", .language_code = "pt", }; expected_ = {{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}}; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidAddressCA_en) { if (GetParam() == &OndemandValidatorWrapper::Build) return; address_ = { .region_code = "CA", .address_line{"..."}, .administrative_area = "New Brunswick", .locality = "Saint John County", .postal_code = "E2L 4Z6", .language_code = "en", }; expected_ = { {DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}, {LOCALITY, UNSUPPORTED_FIELD}, }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } TEST_P(AddressValidatorTest, ValidAddressCA_fr) { if (GetParam() == &OndemandValidatorWrapper::Build) return; address_ = { .region_code = "CA", .address_line{"..."}, .administrative_area = "Nouveau-Brunswick", .locality = "Comté de Saint-Jean", .postal_code = "E2L 4Z6", .language_code = "fr", }; expected_ = { {DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}, {LOCALITY, UNSUPPORTED_FIELD}, }; ASSERT_NO_FATAL_FAILURE(Validate()); ASSERT_TRUE(called_); EXPECT_EQ(expected_, problems_); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_validator.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_validator_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
0e7b4015-16a6-4cca-abaa-bdd39f477c8e
cpp
google/libaddressinput
region_data_constants
cpp/src/region_data_constants.cc
cpp/test/region_data_constants_test.cc
#include "region_data_constants.h" #include <libaddressinput/address_field.h> #include <algorithm> #include <cassert> #include <cstddef> #include <map> #include <string> #include <vector> #include "address_field_util.h" #include "format_element.h" #include "lookup_key.h" #include "util/size.h" namespace i18n { namespace addressinput { namespace { struct RegionData { const char* const region_code; const char* const data; }; const RegionData kRegionData[] = { {"AC", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"ASCN 1ZZ",)" R"("languages":"en")" "}"}, {"AD", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"AD100,AD501,AD700",)" R"("posturl":"http: R"("languages":"ca")" "}"}, {"AE", "{" R"("fmt":"%N%n%O%n%A%n%S",)" R"("lfmt":"%N%n%O%n%A%n%S",)" R"("require":"AS",)" R"("state_name_type":"emirate",)" R"("languages":"ar")" "}"}, {"AF", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"1001,2601,3801",)" R"("languages":"fa~ps~uz-Arab~tk")" "}"}, {"AG", "{" R"("require":"A",)" R"("languages":"en")" "}"}, {"AI", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"2640",)" R"("languages":"en")" "}"}, {"AL", "{" R"("fmt":"%N%n%O%n%A%n%Z%n%C",)" R"("zipex":"1001,1017,3501",)" R"("languages":"sq")" "}"}, {"AM", "{" R"("fmt":"%N%n%O%n%A%n%Z%n%C%n%S",)" R"("lfmt":"%N%n%O%n%A%n%Z%n%C%n%S",)" R"("zipex":"375010,0002,0010",)" R"("languages":"hy")" "}"}, {"AO", "{" R"("languages":"pt")" "}"}, {"AQ", "{" "}"}, {"AR", "{" R"("fmt":"%N%n%O%n%A%n%Z %C%n%S",)" R"("zipex":"C1070AAM,C1000WAM,B1000TBU,X5187XAB",)" R"("posturl":"http: R"("languages":"es")" "}"}, {"AS", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"96799",)" R"("posturl":"http: R"("languages":"sm~en")" "}"}, {"AT", "{" R"("fmt":"%O%n%N%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"1010,3741",)" R"("posturl":"http: R"("languages":"de~hr~sl~hu")" "}"}, {"AU", "{" R"("fmt":"%O%n%N%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("state_name_type":"state",)" R"("locality_name_type":"suburb",)" R"("zipex":"2060,3171,6430,4000,4006,3001",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"AW", "{" R"("languages":"nl~pap")" "}"}, {"AX", "{" R"("fmt":"%O%n%N%n%A%nAX-%Z %C%nÅLAND",)" R"("require":"ACZ",)" R"("zipex":"22150,22550,22240,22710,22270,22730,22430",)" R"("posturl":"https: R"("languages":"sv")" "}"}, {"AZ", "{" R"("fmt":"%N%n%O%n%A%nAZ %Z %C",)" R"("zipex":"1000",)" R"("languages":"az~az-Cyrl")" "}"}, {"BA", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"71000",)" R"("languages":"bs~bs-Cyrl~hr~sr~sr-Latn")" "}"}, {"BB", "{" R"("fmt":"%N%n%O%n%A%n%C, %S %Z",)" R"("state_name_type":"parish",)" R"("zipex":"BB23026,BB22025",)" R"("languages":"en")" "}"}, {"BD", "{" R"("fmt":"%N%n%O%n%A%n%C - %Z",)" R"("zipex":"1340,1000",)" R"("posturl":"https: R"("languages":"bn")" "}"}, {"BE", "{" R"("fmt":"%O%n%N%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"4000,1000",)" R"("posturl":"https: R"("languages":"nl~fr~de")" "}"}, {"BF", "{" R"("fmt":"%N%n%O%n%A%n%C %X",)" R"("languages":"fr")" "}"}, {"BG", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"1000,1700",)" R"("posturl":"http: R"("languages":"bg")" "}"}, {"BH", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"317",)" R"("languages":"ar")" "}"}, {"BI", "{" R"("languages":"rn~fr~en")" "}"}, {"BJ", "{" R"("languages":"fr")" "}"}, {"BL", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97100",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"BM", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"FL 07,HM GX,HM 12",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"BN", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"BT2328,KA1131,BA1511",)" R"("posturl":"http: R"("languages":"ms~ms-Arab")" "}"}, {"BO", "{" R"("languages":"es~qu~ay")" "}"}, {"BQ", "{" R"("languages":"nl")" "}"}, {"BR", "{" R"("fmt":"%O%n%N%n%A%n%D%n%C-%S%n%Z",)" R"("require":"ASCZ",)" R"("state_name_type":"state",)" R"("sublocality_name_type":"neighborhood",)" R"("zipex":"40301-110,70002-900",)" R"("posturl":"http: R"("languages":"pt")" "}"}, {"BS", "{" R"("fmt":"%N%n%O%n%A%n%C, %S",)" R"("state_name_type":"island",)" R"("languages":"en")" "}"}, {"BT", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"11001,31101,35003",)" R"("posturl":"https: R"("languages":"dz")" "}"}, {"BV", "{" "}"}, {"BW", "{" R"("languages":"en~tn")" "}"}, {"BY", "{" R"("fmt":"%O%n%N%n%A%n%Z, %C%n%S",)" R"("zipex":"223016,225860,220050",)" R"("posturl":"http: R"("languages":"be~ru")" "}"}, {"BZ", "{" R"("languages":"en")" "}"}, {"CA", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("zipex":"H3Z 2Y7,V8X 3X4,T0L 1K0,T0H 1A0,K1A 0B1",)" R"("posturl":"https: R"("languages":"en~fr")" "}"}, {"CC", "{" R"("fmt":"%O%n%N%n%A%n%C %S %Z",)" R"("zipex":"6799",)" R"("languages":"en")" "}"}, {"CD", "{" R"("languages":"sw~lua~fr~ln~kg")" "}"}, {"CF", "{" R"("languages":"fr~sg")" "}"}, {"CG", "{" R"("languages":"fr")" "}"}, {"CH", "{" R"("fmt":"%O%n%N%n%A%nCH-%Z %C",)" R"("require":"ACZ",)" R"("zipex":"2544,1211,1556,3030",)" R"("posturl":"http: R"("languages":"de~gsw~fr~it~rm")" "}"}, {"CI", "{" R"("fmt":"%N%n%O%n%X %A %C %X",)" R"("languages":"fr")" "}"}, {"CK", "{" R"("languages":"en")" "}"}, {"CL", "{" R"("fmt":"%N%n%O%n%A%n%Z %C%n%S",)" R"("zipex":"8340457,8720019,1230000,8329100",)" R"("languages":"es")" "}"}, {"CM", "{" R"("languages":"fr~en")" "}"}, {"CN", "{" R"("fmt":"%Z%n%S%C%D%n%A%n%O%n%N",)" R"("lfmt":"%N%n%O%n%A%n%D%n%C%n%S, %Z",)" R"("require":"ACSZ",)" R"("sublocality_name_type":"district",)" R"("zipex":"266033,317204,100096,100808",)" R"("posturl":"http: R"("languages":"zh")" "}"}, {"CO", "{" R"("fmt":"%N%n%O%n%A%n%D%n%C, %S, %Z",)" R"("require":"AS",)" R"("state_name_type":"department",)" R"("zipex":"111221,130001,760011",)" R"("posturl":"http: R"("languages":"es")" "}"}, {"CR", "{" R"("fmt":"%N%n%O%n%A%n%S, %C%n%Z",)" R"("require":"ACS",)" R"("zipex":"1000,2010,1001",)" R"("posturl":"https: R"("languages":"es")" "}"}, {"CU", "{" R"("fmt":"%N%n%O%n%A%n%C %S%n%Z",)" R"("zipex":"10700",)" R"("languages":"es")" "}"}, {"CV", "{" R"("fmt":"%N%n%O%n%A%n%Z %C%n%S",)" R"("state_name_type":"island",)" R"("zipex":"7600",)" R"("languages":"pt")" "}"}, {"CW", "{" R"("languages":"pap~nl")" "}"}, {"CX", "{" R"("fmt":"%O%n%N%n%A%n%C %S %Z",)" R"("zipex":"6798",)" R"("languages":"en")" "}"}, {"CY", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"2008,3304,1900",)" R"("languages":"el~tr")" "}"}, {"CZ", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"100 00,251 66,530 87,110 00,225 99",)" R"("posturl":"http: R"("languages":"cs")" "}"}, {"DE", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"26133,53225",)" R"("posturl":"http: R"("languages":"de~frr")" "}"}, {"DJ", "{" R"("languages":"ar~fr")" "}"}, {"DK", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"8660,1566",)" R"("posturl":"http: R"("languages":"da~de~kl")" "}"}, {"DM", "{" R"("languages":"en")" "}"}, {"DO", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"11903,10101",)" R"("posturl":"http: R"("languages":"es")" "}"}, {"DZ", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"40304,16027",)" R"("languages":"ar~fr")" "}"}, {"EC", "{" R"("fmt":"%N%n%O%n%A%n%Z%n%C",)" R"("zipex":"090105,092301",)" R"("posturl":"http: R"("languages":"es~qu")" "}"}, {"EE", "{" R"("fmt":"%N%n%O%n%A%n%Z %C %S",)" R"("require":"ACZ",)" R"("zipex":"69501,11212",)" R"("posturl":"https: R"("languages":"et")" "}"}, {"EG", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S%n%Z",)" R"("lfmt":"%N%n%O%n%A%n%C%n%S%n%Z",)" R"("zipex":"4460232,5734356",)" R"("languages":"ar")" "}"}, {"EH", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"70000,72000",)" R"("languages":"ar")" "}"}, {"ER", "{" R"("languages":"ti~en~ar")" "}"}, {"ES", "{" R"("fmt":"%N%n%O%n%A%n%Z %C %S",)" R"("require":"ACSZ",)" R"("zipex":"28039,28300,28070",)" R"("posturl":"http: R"("languages":"es~ca~gl~eu")" "}"}, {"ET", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"1000",)" R"("languages":"am")" "}"}, {"FI", "{" R"("fmt":"%O%n%N%n%A%nFI-%Z %C",)" R"("require":"ACZ",)" R"("zipex":"00550,00011",)" R"("posturl":"https: R"("languages":"fi~sv~sms")" "}"}, {"FJ", "{" R"("languages":"en~hif~fj")" "}"}, {"FK", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"FIQQ 1ZZ",)" R"("languages":"en")" "}"}, {"FM", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"96941,96944",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"FO", "{" R"("fmt":"%N%n%O%n%A%nFO%Z %C",)" R"("zipex":"100",)" R"("posturl":"https: R"("languages":"fo")" "}"}, {"FR", "{" R"("fmt":"%O%n%N%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"33380,34092,33506",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"GA", "{" R"("languages":"fr")" "}"}, {"GB", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"ACZ",)" R"("locality_name_type":"post_town",)" R"("zipex":"EC1Y 8SY,GIR 0AA,M2 5BQ,M34 4AB,CR0 2YR,DN16 9AA,W1A 4ZZ,EC1A 1HQ,OX14 4PG,BS18 8HF,NR25 7HG,RH6 0NP,BH23 6AA,B6 5BA,SO23 9AP,PO1 3AX,BFPO 61",)" R"("posturl":"http: R"("languages":"en~cy~ga~gd")" "}"}, {"GD", "{" R"("languages":"en")" "}"}, {"GE", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"0101",)" R"("posturl":"http: R"("languages":"ka~ab~os")" "}"}, {"GF", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97300",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"GG", "{" R"("fmt":"%N%n%O%n%A%n%C%nGUERNSEY%n%Z",)" R"("require":"ACZ",)" R"("zipex":"GY1 1AA,GY2 2BT",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"GH", "{" R"("languages":"ak~en~ee~gaa")" "}"}, {"GI", "{" R"("fmt":"%N%n%O%n%A%nGIBRALTAR%n%Z",)" R"("require":"A",)" R"("zipex":"GX11 1AA",)" R"("languages":"en")" "}"}, {"GL", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"3900,3950,3911",)" R"("languages":"kl")" "}"}, {"GM", "{" R"("languages":"en")" "}"}, {"GN", "{" R"("fmt":"%N%n%O%n%Z %A %C",)" R"("zipex":"001,200,100",)" R"("languages":"fr")" "}"}, {"GP", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97100",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"GQ", "{" R"("languages":"es~fr~pt")" "}"}, {"GR", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"151 24,151 10,101 88",)" R"("posturl":"https: R"("languages":"el")" "}"}, {"GS", "{" R"("fmt":"%N%n%O%n%A%n%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"SIQQ 1ZZ")" "}"}, {"GT", "{" R"("fmt":"%N%n%O%n%A%n%Z- %C",)" R"("zipex":"09001,01501",)" R"("languages":"es~quc")" "}"}, {"GU", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("require":"ACZ",)" R"("zip_name_type":"zip",)" R"("zipex":"96910,96931",)" R"("posturl":"http: R"("languages":"en~ch")" "}"}, {"GW", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"1000,1011",)" R"("languages":"pt")" "}"}, {"GY", "{" R"("languages":"en")" "}"}, {"HK", "{" R"("fmt":"%S%n%C%n%A%n%O%n%N",)" R"("lfmt":"%N%n%O%n%A%n%C%n%S",)" R"("require":"AS",)" R"("state_name_type":"area",)" R"("locality_name_type":"district",)" R"("languages":"zh-Hant~en")" "}"}, {"HM", "{" R"("fmt":"%O%n%N%n%A%n%C %S %Z",)" R"("zipex":"7050")" "}"}, {"HN", "{" R"("fmt":"%N%n%O%n%A%n%C, %S%n%Z",)" R"("require":"ACS",)" R"("state_name_type":"department",)" R"("zipex":"31301",)" R"("languages":"es")" "}"}, {"HR", "{" R"("fmt":"%N%n%O%n%A%nHR-%Z %C",)" R"("zipex":"10000,21001,10002",)" R"("posturl":"http: R"("languages":"hr~it~vec")" "}"}, {"HT", "{" R"("fmt":"%N%n%O%n%A%nHT%Z %C",)" R"("zipex":"6120,5310,6110,8510",)" R"("languages":"ht~fr")" "}"}, {"HU", "{" R"("fmt":"%N%n%O%n%C%n%A%n%Z",)" R"("require":"ACZ",)" R"("zipex":"1037,2380,1540",)" R"("posturl":"http: R"("languages":"hu")" "}"}, {"ID", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S %Z",)" R"("require":"AS",)" R"("zipex":"40115",)" R"("languages":"id")" "}"}, {"IE", "{" R"("fmt":"%N%n%O%n%A%n%D%n%C%n%S%n%Z",)" R"("zip_name_type":"eircode",)" R"("state_name_type":"county",)" R"("sublocality_name_type":"townland",)" R"("zipex":"A65 F4E2",)" R"("posturl":"https: R"("languages":"en")" "}"}, {"IL", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"9614303",)" R"("posturl":"http: R"("languages":"iw~ar")" "}"}, {"IM", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"IM2 1AA,IM99 1PS",)" R"("posturl":"https: R"("languages":"en~gv")" "}"}, {"IN", "{" R"("fmt":"%N%n%O%n%A%n%T%n%F%n%L%n%C %Z%n%S",)" R"("require":"ACSZ",)" R"("zip_name_type":"pin",)" R"("state_name_type":"state",)" R"("zipex":"110034,110001",)" R"("posturl":"https: R"("languages":"en~hi")" "}"}, {"IO", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"BBND 1ZZ",)" R"("languages":"en")" "}"}, {"IQ", "{" R"("fmt":"%O%n%N%n%A%n%C, %S%n%Z",)" R"("require":"ACS",)" R"("zipex":"31001",)" R"("languages":"ar")" "}"}, {"IR", "{" R"("fmt":"%O%n%N%n%S%n%C, %D%n%A%n%Z",)" R"("sublocality_name_type":"neighborhood",)" R"("zipex":"11936-12345",)" R"("languages":"fa")" "}"}, {"IS", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"320,121,220,110",)" R"("posturl":"https: R"("languages":"is")" "}"}, {"IT", "{" R"("fmt":"%N%n%O%n%A%n%Z %C %S",)" R"("require":"ACSZ",)" R"("zipex":"00144,47037,39049",)" R"("posturl":"http: R"("languages":"it")" "}"}, {"JE", "{" R"("fmt":"%N%n%O%n%A%n%C%nJERSEY%n%Z",)" R"("require":"ACZ",)" R"("zipex":"JE1 1AA,JE2 2BT",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"JM", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S %X",)" R"("require":"ACS",)" R"("state_name_type":"parish",)" R"("languages":"en")" "}"}, {"JO", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"11937,11190",)" R"("languages":"ar")" "}"}, {"JP", "{" R"("fmt":"〒%Z%n%S%n%A%n%O%n%N",)" R"("lfmt":"%N%n%O%n%A, %S%n%Z",)" R"("require":"ASZ",)" R"("state_name_type":"prefecture",)" R"("zipex":"154-0023,350-1106,951-8073,112-0001,208-0032,231-0012",)" R"("posturl":"http: R"("languages":"ja")" "}"}, {"KE", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"20100,00100",)" R"("languages":"sw~en")" "}"}, {"KG", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"720001",)" R"("languages":"ky~ru")" "}"}, {"KH", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"120101,120108",)" R"("posturl":"https: R"("languages":"km")" "}"}, {"KI", "{" R"("fmt":"%N%n%O%n%A%n%S%n%C",)" R"("state_name_type":"island",)" R"("languages":"en~gil")" "}"}, {"KM", "{" R"("languages":"ar~fr~zdj~wni")" "}"}, {"KN", "{" R"("fmt":"%N%n%O%n%A%n%C, %S",)" R"("require":"ACS",)" R"("state_name_type":"island",)" R"("languages":"en")" "}"}, {"KP", "{" R"("fmt":"%Z%n%S%n%C%n%A%n%O%n%N",)" R"("lfmt":"%N%n%O%n%A%n%C%n%S, %Z",)" R"("languages":"ko")" "}"}, {"KR", "{" R"("fmt":"%S %C%D%n%A%n%O%n%N%n%Z",)" R"("lfmt":"%N%n%O%n%A%n%D%n%C%n%S%n%Z",)" R"("require":"ACSZ",)" R"("state_name_type":"do_si",)" R"("sublocality_name_type":"district",)" R"("zipex":"03051",)" R"("posturl":"http: R"("languages":"ko")" "}"}, {"KW", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"54541,54551,54404,13009",)" R"("languages":"ar")" "}"}, {"KY", "{" R"("fmt":"%N%n%O%n%A%n%S %Z",)" R"("require":"AS",)" R"("state_name_type":"island",)" R"("zipex":"KY1-1100,KY1-1702,KY2-2101",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"KZ", "{" R"("fmt":"%Z%n%S%n%C%n%A%n%O%n%N",)" R"("zipex":"040900,050012",)" R"("languages":"kk~ru")" "}"}, {"LA", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"01160,01000",)" R"("languages":"lo")" "}"}, {"LB", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"2038 3054,1107 2810,1000",)" R"("languages":"ar")" "}"}, {"LC", "{" R"("languages":"en")" "}"}, {"LI", "{" R"("fmt":"%O%n%N%n%A%nFL-%Z %C",)" R"("require":"ACZ",)" R"("zipex":"9496,9491,9490,9485",)" R"("posturl":"http: R"("languages":"de~gsw")" "}"}, {"LK", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"20000,00100",)" R"("posturl":"http: R"("languages":"si~ta")" "}"}, {"LR", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"1000",)" R"("languages":"en")" "}"}, {"LS", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"100",)" R"("languages":"st~en")" "}"}, {"LT", "{" R"("fmt":"%O%n%N%n%A%nLT-%Z %C %S",)" R"("require":"ACZ",)" R"("zipex":"04340,03500",)" R"("posturl":"http: R"("languages":"lt")" "}"}, {"LU", "{" R"("fmt":"%O%n%N%n%A%nL-%Z %C",)" R"("require":"ACZ",)" R"("zipex":"4750,2998",)" R"("posturl":"https: R"("languages":"fr~lb~de")" "}"}, {"LV", "{" R"("fmt":"%N%n%O%n%A%n%S%n%C, %Z",)" R"("require":"ACZ",)" R"("zipex":"LV-1073,LV-1000",)" R"("posturl":"https: R"("languages":"lv")" "}"}, {"LY", "{" R"("languages":"ar")" "}"}, {"MA", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"53000,10000,20050,16052",)" R"("languages":"ar~fr~tzm")" "}"}, {"MC", "{" R"("fmt":"%N%n%O%n%A%nMC-%Z %C %X",)" R"("zipex":"98000,98020,98011,98001",)" R"("languages":"fr")" "}"}, {"MD", "{" R"("fmt":"%N%n%O%n%A%nMD-%Z %C",)" R"("zipex":"2012,2019",)" R"("languages":"ro")" "}"}, {"ME", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"81257,81258,81217,84314,85366",)" R"("languages":"sr-Latn")" "}"}, {"MF", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97100",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"MG", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"501,101",)" R"("languages":"mg~fr~en")" "}"}, {"MH", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"96960,96970",)" R"("posturl":"http: R"("languages":"en~mh")" "}"}, {"MK", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"1314,1321,1443,1062",)" R"("languages":"mk~sq")" "}"}, {"ML", "{" R"("languages":"fr")" "}"}, {"MM", "{" R"("fmt":"%N%n%O%n%A%n%C, %Z",)" R"("zipex":"11181",)" R"("languages":"my")" "}"}, {"MN", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S %Z",)" R"("zipex":"65030,65270",)" R"("posturl":"http: R"("languages":"mn")" "}"}, {"MO", "{" R"("fmt":"%A%n%O%n%N",)" R"("lfmt":"%N%n%O%n%A",)" R"("require":"A",)" R"("languages":"zh-Hant~pt")" "}"}, {"MP", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"96950,96951,96952",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"MQ", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97220",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"MR", "{" R"("languages":"ar")" "}"}, {"MS", "{" R"("languages":"en")" "}"}, {"MT", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"NXR 01,ZTN 05,GPO 01,BZN 1130,SPB 6031,VCT 1753",)" R"("posturl":"https: R"("languages":"mt~en")" "}"}, {"MU", "{" R"("fmt":"%N%n%O%n%A%n%Z%n%C",)" R"("zipex":"42602",)" R"("languages":"en~fr")" "}"}, {"MV", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"20026",)" R"("posturl":"http: R"("languages":"dv")" "}"}, {"MW", "{" R"("fmt":"%N%n%O%n%A%n%C %X",)" R"("languages":"en~ny")" "}"}, {"MX", "{" R"("fmt":"%N%n%O%n%A%n%D%n%Z %C, %S",)" R"("require":"ACSZ",)" R"("state_name_type":"state",)" R"("sublocality_name_type":"neighborhood",)" R"("zipex":"02860,77520,06082",)" R"("posturl":"https: R"("languages":"es")" "}"}, {"MY", "{" R"("fmt":"%N%n%O%n%A%n%D%n%Z %C%n%S",)" R"("require":"ACZ",)" R"("state_name_type":"state",)" R"("sublocality_name_type":"village_township",)" R"("zipex":"43000,50754,88990,50670",)" R"("posturl":"http: R"("languages":"ms")" "}"}, {"MZ", "{" R"("fmt":"%N%n%O%n%A%n%Z %C%S",)" R"("zipex":"1102,1119,3212",)" R"("languages":"pt")" "}"}, {"NA", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"10001,10017",)" R"("languages":"en")" "}"}, {"NC", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"98814,98800,98810",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"NE", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"8001",)" R"("languages":"fr")" "}"}, {"NF", "{" R"("fmt":"%O%n%N%n%A%n%C %S %Z",)" R"("zipex":"2899",)" R"("languages":"en")" "}"}, {"NG", "{" R"("fmt":"%N%n%O%n%A%n%D%n%C %Z%n%S",)" R"("state_name_type":"state",)" R"("zipex":"930283,300001,931104",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"NI", "{" R"("fmt":"%N%n%O%n%A%n%Z%n%C, %S",)" R"("state_name_type":"department",)" R"("zipex":"52000",)" R"("posturl":"http: R"("languages":"es")" "}"}, {"NL", "{" R"("fmt":"%O%n%N%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"1234 AB,2490 AA",)" R"("posturl":"http: R"("languages":"nl~fy")" "}"}, {"NO", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("locality_name_type":"post_town",)" R"("zipex":"0025,0107,6631",)" R"("posturl":"http: R"("languages":"no~nn~se")" "}"}, {"NP", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"44601",)" R"("posturl":"http: R"("languages":"ne")" "}"}, {"NR", "{" R"("fmt":"%N%n%O%n%A%n%S",)" R"("require":"AS",)" R"("state_name_type":"district",)" R"("languages":"en")" "}"}, {"NU", "{" R"("languages":"en~niu")" "}"}, {"NZ", "{" R"("fmt":"%N%n%O%n%A%n%D%n%C %Z",)" R"("require":"ACZ",)" R"("zipex":"6001,6015,6332,8252,1030",)" R"("posturl":"https: R"("languages":"en~mi")" "}"}, {"OM", "{" R"("fmt":"%N%n%O%n%A%n%Z%n%C",)" R"("zipex":"133,112,111",)" R"("languages":"ar")" "}"}, {"PA", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S",)" R"("languages":"es")" "}"}, {"PE", "{" R"("fmt":"%N%n%O%n%A%n%C %Z%n%S",)" R"("locality_name_type":"district",)" R"("zipex":"LIMA 23,LIMA 42,CALLAO 2,02001",)" R"("posturl":"http: R"("languages":"es")" "}"}, {"PF", "{" R"("fmt":"%N%n%O%n%A%n%Z %C %S",)" R"("require":"ACSZ",)" R"("state_name_type":"island",)" R"("zipex":"98709",)" R"("languages":"fr~ty")" "}"}, {"PG", "{" R"("fmt":"%N%n%O%n%A%n%C %Z %S",)" R"("require":"ACS",)" R"("zipex":"111",)" R"("languages":"tpi~en~ho")" "}"}, {"PH", "{" R"("fmt":"%N%n%O%n%A%n%D, %C%n%Z %S",)" R"("zipex":"1008,1050,1135,1207,2000,1000",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"PK", "{" R"("fmt":"%N%n%O%n%A%n%D%n%C-%Z",)" R"("zipex":"44000",)" R"("posturl":"http: R"("languages":"ur~en")" "}"}, {"PL", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"00-950,05-470,48-300,32-015,00-940",)" R"("posturl":"http: R"("languages":"pl~de~csb~lt")" "}"}, {"PM", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97500",)" R"("languages":"fr")" "}"}, {"PN", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"PCRN 1ZZ",)" R"("languages":"en")" "}"}, {"PR", "{" R"("fmt":"%N%n%O%n%A%n%C PR %Z",)" R"("require":"ACZ",)" R"("zip_name_type":"zip",)" R"("zipex":"00930",)" R"("posturl":"http: R"("languages":"es~en")" "}"}, {"PS", "{" R"("languages":"ar")" "}"}, {"PT", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"2725-079,1250-096,1201-950,2860-571,1208-148",)" R"("posturl":"http: R"("languages":"pt")" "}"}, {"PW", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"96940",)" R"("posturl":"http: R"("languages":"pau~en")" "}"}, {"PY", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"1536,1538,1209",)" R"("languages":"gn~es")" "}"}, {"QA", "{" R"("languages":"ar")" "}"}, {"RE", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97400",)" R"("posturl":"https: R"("languages":"fr")" "}"}, {"RO", "{" R"("fmt":"%N%n%O%n%A%n%Z %S %C",)" R"("require":"ACZ",)" R"("zipex":"060274,061357,200716",)" R"("posturl":"http: R"("languages":"ro")" "}"}, {"RS", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"106314",)" R"("posturl":"http: R"("languages":"sr~sr-Latn~hu~ro~hr~sk~uk")" "}"}, {"RU", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S%n%Z",)" R"("lfmt":"%N%n%O%n%A%n%C%n%S%n%Z",)" R"("require":"ACSZ",)" R"("state_name_type":"oblast",)" R"("zipex":"247112,103375,188300",)" R"("posturl":"https: R"("languages":"ru")" "}"}, {"RW", "{" R"("languages":"rw~en~fr")" "}"}, {"SA", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"11564,11187,11142",)" R"("languages":"ar")" "}"}, {"SB", "{" R"("languages":"en")" "}"}, {"SC", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S",)" R"("state_name_type":"island",)" R"("languages":"fr~en")" "}"}, {"SD", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("locality_name_type":"district",)" R"("zipex":"11042,11113",)" R"("languages":"ar~en")" "}"}, {"SE", "{" R"("fmt":"%O%n%N%n%A%nSE-%Z %C",)" R"("require":"ACZ",)" R"("locality_name_type":"post_town",)" R"("zipex":"11455,12345,10500",)" R"("posturl":"https: R"("languages":"sv~fi")" "}"}, {"SG", "{" R"("fmt":"%N%n%O%n%A%nSINGAPORE %Z",)" R"("require":"AZ",)" R"("zipex":"546080,308125,408600",)" R"("posturl":"https: R"("languages":"en~zh~ms~ta")" "}"}, {"SH", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"STHL 1ZZ",)" R"("languages":"en")" "}"}, {"SI", "{" R"("fmt":"%N%n%O%n%A%nSI-%Z %C",)" R"("zipex":"4000,1001,2500",)" R"("languages":"sl~vec")" "}"}, {"SJ", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("locality_name_type":"post_town",)" R"("zipex":"9170",)" R"("posturl":"http: R"("languages":"no")" "}"}, {"SK", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"ACZ",)" R"("zipex":"010 01,023 14,972 48,921 01,975 99",)" R"("posturl":"http: R"("languages":"sk")" "}"}, {"SL", "{" R"("languages":"en")" "}"}, {"SM", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("require":"AZ",)" R"("zipex":"47890,47891,47895,47899",)" R"("posturl":"http: R"("languages":"it")" "}"}, {"SN", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"12500,46024,16556,10000",)" R"("languages":"wo~fr~ff~srr~dyo~sav~mfv~bjt~snf~knf~bsc~mey~tnr")" "}"}, {"SO", "{" R"("fmt":"%N%n%O%n%A%n%C, %S %Z",)" R"("require":"ACS",)" R"("zipex":"JH 09010,AD 11010",)" R"("languages":"so")" "}"}, {"SR", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S",)" R"("languages":"nl")" "}"}, {"SS", "{" R"("languages":"en")" "}"}, {"ST", "{" R"("languages":"pt")" "}"}, {"SV", "{" R"("fmt":"%N%n%O%n%A%n%Z-%C%n%S",)" R"("require":"ACS",)" R"("zipex":"1101",)" R"("languages":"es")" "}"}, {"SX", "{" R"("languages":"en~nl")" "}"}, {"SY", "{" R"("locality_name_type":"district",)" R"("languages":"ar~fr")" "}"}, {"SZ", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"H100",)" R"("posturl":"https: R"("languages":"en~ss")" "}"}, {"TA", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"TDCU 1ZZ",)" R"("languages":"en")" "}"}, {"TC", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"TKCA 1ZZ",)" R"("languages":"en")" "}"}, {"TD", "{" R"("languages":"fr~ar")" "}"}, {"TF", "{" R"("languages":"fr")" "}"}, {"TG", "{" R"("languages":"fr")" "}"}, {"TH", "{" R"("fmt":"%N%n%O%n%A%n%D %C%n%S %Z",)" R"("lfmt":"%N%n%O%n%A%n%D, %C%n%S %Z",)" R"("zipex":"10150,10210",)" R"("languages":"th")" "}"}, {"TJ", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"735450,734025",)" R"("languages":"tg")" "}"}, {"TK", "{" R"("languages":"en~tkl")" "}"}, {"TL", "{" R"("languages":"pt~tet")" "}"}, {"TM", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"744000",)" R"("languages":"tk")" "}"}, {"TN", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"1002,8129,3100,1030",)" R"("posturl":"http: R"("languages":"ar~fr")" "}"}, {"TO", "{" R"("languages":"to~en")" "}"}, {"TR", "{" R"("fmt":"%N%n%O%n%A%n%Z %C/%S",)" R"("require":"ACZ",)" R"("locality_name_type":"district",)" R"("zipex":"01960,06101",)" R"("posturl":"http: R"("languages":"tr")" "}"}, {"TT", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("zipex":"500234",)" R"("languages":"en")" "}"}, {"TV", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S",)" R"("state_name_type":"island",)" R"("languages":"tyv")" "}"}, {"TW", "{" R"("fmt":"%Z%n%S%C%n%A%n%O%n%N",)" R"("lfmt":"%N%n%O%n%A%n%C, %S %Z",)" R"("require":"ACSZ",)" R"("state_name_type":"county",)" R"("locality_name_type":"district",)" R"("zipex":"104,106,10603,40867",)" R"("posturl":"http: R"("languages":"zh-Hant")" "}"}, {"TZ", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"6090,34413",)" R"("languages":"sw~en")" "}"}, {"UA", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S%n%Z",)" R"("lfmt":"%N%n%O%n%A%n%C%n%S%n%Z",)" R"("require":"ACZ",)" R"("state_name_type":"oblast",)" R"("zipex":"15432,01055,01001",)" R"("posturl":"http: R"("languages":"uk")" "}"}, {"UG", "{" R"("languages":"sw~en")" "}"}, {"UM", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACS",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"96898",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"US", "{" R"("fmt":"%N%n%O%n%A%n%C, %S %Z",)" R"("require":"ACSZ",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"95014,22162-1010",)" R"("posturl":"https: R"("languages":"en")" "}"}, {"UY", "{" R"("fmt":"%N%n%O%n%A%n%Z %C %S",)" R"("zipex":"11600",)" R"("posturl":"http: R"("languages":"es")" "}"}, {"UZ", "{" R"("fmt":"%N%n%O%n%A%n%Z %C%n%S",)" R"("zipex":"702100,700000",)" R"("posturl":"https: R"("languages":"uz~ru")" "}"}, {"VA", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"00120",)" R"("languages":"it")" "}"}, {"VC", "{" R"("fmt":"%N%n%O%n%A%n%C %Z",)" R"("zipex":"VC0100,VC0110,VC0400",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"VE", "{" R"("fmt":"%N%n%O%n%A%n%C %Z, %S",)" R"("require":"ACS",)" R"("state_name_type":"state",)" R"("zipex":"1010,3001,8011,1020",)" R"("posturl":"http: R"("languages":"es")" "}"}, {"VG", "{" R"("fmt":"%N%n%O%n%A%n%C%n%Z",)" R"("require":"A",)" R"("zipex":"VG1110,VG1150,VG1160",)" R"("languages":"en")" "}"}, {"VI", "{" R"("fmt":"%N%n%O%n%A%n%C %S %Z",)" R"("require":"ACSZ",)" R"("zip_name_type":"zip",)" R"("state_name_type":"state",)" R"("zipex":"00802-1222,00850-9802",)" R"("posturl":"http: R"("languages":"en")" "}"}, {"VN", "{" R"("fmt":"%N%n%O%n%A%n%C%n%S %Z",)" R"("lfmt":"%N%n%O%n%A%n%C%n%S %Z",)" R"("zipex":"70010,55999",)" R"("posturl":"http: R"("languages":"vi")" "}"}, {"VU", "{" R"("languages":"bi~en~fr")" "}"}, {"WF", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"98600",)" R"("languages":"fr")" "}"}, {"WS", "{" R"("languages":"sm~en")" "}"}, {"XK", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"10000",)" R"("languages":"sq~sr~sr-Latn")" "}"}, {"YE", "{" R"("languages":"ar")" "}"}, {"YT", "{" R"("fmt":"%O%n%N%n%A%n%Z %C %X",)" R"("require":"ACZ",)" R"("zipex":"97600",)" R"("languages":"fr")" "}"}, {"ZA", "{" R"("fmt":"%N%n%O%n%A%n%D%n%C%n%Z",)" R"("require":"ACZ",)" R"("zipex":"0083,1451,0001",)" R"("posturl":"https: R"("languages":"en~zu~xh~af~nso~tn~st~ts~ss~ve~nr")" "}"}, {"ZM", "{" R"("fmt":"%N%n%O%n%A%n%Z %C",)" R"("zipex":"50100,50101",)" R"("languages":"en")" "}"}, {"ZW", "{" R"("languages":"sn~en~nd")" "}"}, }; } const std::string& RegionDataConstants::GetDefaultRegionData() { static const std::string kDefaultRegionData( "{" R"("fmt":"%N%n%O%n%A%n%C",)" R"("require":"AC",)" R"("zip_name_type":"postal",)" R"("state_name_type":"province",)" R"("locality_name_type":"city",)" R"("sublocality_name_type":"suburb")" "}"); return kDefaultRegionData; } namespace { bool FindPositionOfRegionCode(const std::string& region_code, size_t* position_out) { assert(position_out != nullptr); size_t left = 0; size_t right = size(kRegionData); while (left < right) { size_t mid = left + (right - left) / 2; int comparison = region_code.compare(kRegionData[mid].region_code); if (comparison == 0) { *position_out = mid; return true; } else if (comparison > 0) { left = mid + 1; } else { right = mid; } } return false; } std::vector<std::string> InitRegionCodes() { std::vector<std::string> region_codes(size(kRegionData)); std::transform(std::begin(kRegionData), std::end(kRegionData), region_codes.begin(), [](const RegionData& region_data) { return region_data.region_code; }); return region_codes; } const std::map<std::string, size_t> InitMaxLookupKeyDepth() { std::map<std::string, size_t> max_depth; for (const auto& region_data : kRegionData) { std::vector<FormatElement> fields; ParseFormatRule(region_data.data, &fields); size_t depth = 1; for (; depth < size(LookupKey::kHierarchy); ++depth) { AddressField field = LookupKey::kHierarchy[depth]; if (std::find(fields.begin(), fields.end(), FormatElement(field)) == fields.end()) { break; } } max_depth.emplace(region_data.region_code, depth - 1); } return max_depth; } } bool RegionDataConstants::IsSupported(const std::string& region_code) { size_t unused; return FindPositionOfRegionCode(region_code, &unused); } const std::vector<std::string>& RegionDataConstants::GetRegionCodes() { static const std::vector<std::string> kRegionCodes(InitRegionCodes()); return kRegionCodes; } std::string RegionDataConstants::GetRegionData( const std::string& region_code) { static const std::string kEmptyString; size_t position; bool found = FindPositionOfRegionCode(region_code, &position); return found ? kRegionData[position].data : kEmptyString; } size_t RegionDataConstants::GetMaxLookupKeyDepth( const std::string& region_code) { static const std::map<std::string, size_t> kMaxDepth(InitMaxLookupKeyDepth()); auto it = kMaxDepth.find(region_code); return it != kMaxDepth.end() ? it->second : 0; } } }
#include "region_data_constants.h" #include <algorithm> #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::RegionDataConstants; class RegionCodeTest : public testing::TestWithParam<std::string> { public: RegionCodeTest(const RegionCodeTest&) = delete; RegionCodeTest& operator=(const RegionCodeTest&) = delete; protected: RegionCodeTest() = default; }; TEST_P(RegionCodeTest, RegionCodeHasTwoCharacters) { EXPECT_EQ(2, GetParam().length()); } INSTANTIATE_TEST_SUITE_P( AllRegionCodes, RegionCodeTest, testing::ValuesIn(RegionDataConstants::GetRegionCodes())); testing::AssertionResult HasCurlyBraces(const std::string& data) { if (data.empty()) { return testing::AssertionFailure() << "data is empty"; } if (data[0] != '{') { return testing::AssertionFailure() << data << " does not start with '{'"; } if (data[data.length() - 1] != '}') { return testing::AssertionFailure() << data << " does not end with '}'"; } return testing::AssertionSuccess(); } TEST(DefaultRegionDataTest, DefaultRegionHasCurlyBraces) { EXPECT_TRUE(HasCurlyBraces(RegionDataConstants::GetDefaultRegionData())); } class RegionDataTest : public testing::TestWithParam<std::string> { public: RegionDataTest(const RegionDataTest&) = delete; RegionDataTest& operator=(const RegionDataTest&) = delete; protected: RegionDataTest() = default; std::string GetData() const { return RegionDataConstants::GetRegionData(GetParam()); } }; TEST_P(RegionDataTest, RegionDataHasCurlyBraces) { EXPECT_TRUE(HasCurlyBraces(GetData())); } INSTANTIATE_TEST_SUITE_P( AllRegionData, RegionDataTest, testing::ValuesIn(RegionDataConstants::GetRegionCodes())); TEST(RegionDataConstantsTest, GetMaxLookupKeyDepth) { EXPECT_EQ(0, RegionDataConstants::GetMaxLookupKeyDepth("NZ")); EXPECT_EQ(1, RegionDataConstants::GetMaxLookupKeyDepth("KY")); EXPECT_EQ(2, RegionDataConstants::GetMaxLookupKeyDepth("US")); EXPECT_EQ(3, RegionDataConstants::GetMaxLookupKeyDepth("CN")); } TEST(RegionDataConstantsTest, RegionCodesSorted) { EXPECT_TRUE(std::is_sorted(RegionDataConstants::GetRegionCodes().begin(), RegionDataConstants::GetRegionCodes().end())); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/region_data_constants.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/region_data_constants_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
28d9d3a2-ed77-490f-a92c-b11cef165408
cpp
google/libaddressinput
address_field
cpp/src/address_field.cc
cpp/test/address_field_test.cc
#include <libaddressinput/address_field.h> #include <cstddef> #include <ostream> #include "util/size.h" using i18n::addressinput::AddressField; using i18n::addressinput::COUNTRY; using i18n::addressinput::RECIPIENT; using i18n::addressinput::size; std::ostream& operator<<(std::ostream& o, AddressField field) { static const char* const kFieldNames[] = { "COUNTRY", "ADMIN_AREA", "LOCALITY", "DEPENDENT_LOCALITY", "SORTING_CODE", "POSTAL_CODE", "STREET_ADDRESS", "ORGANIZATION", "RECIPIENT", }; static_assert(COUNTRY == 0, "bad_base"); static_assert(RECIPIENT == size(kFieldNames) - 1, "bad_length"); if (field < 0 || static_cast<size_t>(field) >= size(kFieldNames)) { o << "[INVALID ENUM VALUE " << static_cast<int>(field) << "]"; } else { o << kFieldNames[field]; } return o; }
#include <libaddressinput/address_field.h> #include <sstream> #include <gtest/gtest.h> namespace { using i18n::addressinput::SORTING_CODE; TEST(AddressFieldTest, ValidEnumValue) { std::ostringstream oss; oss << SORTING_CODE; EXPECT_EQ("SORTING_CODE", oss.str()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_field.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_field_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
18d69bf5-16fa-4ed1-b717-955a47cf33ac
cpp
google/libaddressinput
retriever
cpp/src/retriever.cc
cpp/test/retriever_test.cc
#include "retriever.h" #include <libaddressinput/callback.h> #include <libaddressinput/source.h> #include <libaddressinput/storage.h> #include <cassert> #include <cstddef> #include <memory> #include <string> #include "validating_storage.h" namespace i18n { namespace addressinput { namespace { class Helper { public: Helper(const Helper&) = delete; Helper& operator=(const Helper&) = delete; Helper(const std::string& key, const Retriever::Callback& retrieved, const Source& source, ValidatingStorage* storage) : retrieved_(retrieved), source_(source), storage_(storage), fresh_data_ready_(BuildCallback(this, &Helper::OnFreshDataReady)), validated_data_ready_( BuildCallback(this, &Helper::OnValidatedDataReady)), stale_data_() { assert(storage_ != nullptr); storage_->Get(key, *validated_data_ready_); } private: ~Helper() = default; void OnValidatedDataReady(bool success, const std::string& key, std::string* data) { if (success) { assert(data != nullptr); retrieved_(success, key, *data); delete this; } else { if (data != nullptr && !data->empty()) { stale_data_ = *data; } source_.Get(key, *fresh_data_ready_); } delete data; } void OnFreshDataReady(bool success, const std::string& key, std::string* data) { if (success) { assert(data != nullptr); retrieved_(true, key, *data); storage_->Put(key, data); data = nullptr; } else if (!stale_data_.empty()) { retrieved_(true, key, stale_data_); } else { retrieved_(false, key, std::string()); } delete data; delete this; } const Retriever::Callback& retrieved_; const Source& source_; ValidatingStorage* storage_; const std::unique_ptr<const Source::Callback> fresh_data_ready_; const std::unique_ptr<const Storage::Callback> validated_data_ready_; std::string stale_data_; }; } Retriever::Retriever(const Source* source, Storage* storage) : source_(source), storage_(new ValidatingStorage(storage)) { assert(source_ != nullptr); assert(storage_ != nullptr); } Retriever::~Retriever() = default; void Retriever::Retrieve(const std::string& key, const Callback& retrieved) const { new Helper(key, retrieved, *source_, storage_.get()); } } }
#include "retriever.h" #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/storage.h> #include <cstddef> #include <memory> #include <string> #include <gtest/gtest.h> #include "mock_source.h" #include "testdata_source.h" #define CHECKSUM "dd63dafcbd4d5b28badfcaf86fb6fcdb" #define DATA "{'foo': 'bar'}" #define OLD_TIMESTAMP "0" namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::MockSource; using i18n::addressinput::NullStorage; using i18n::addressinput::Retriever; using i18n::addressinput::Storage; using i18n::addressinput::TestdataSource; const char kKey[] = "data/CA/AB--fr"; const char kEmptyData[] = "{}"; const char kStaleData[] = DATA; const char kStaleWrappedData[] = "timestamp=" OLD_TIMESTAMP "\n" "checksum=" CHECKSUM "\n" DATA; class RetrieverTest : public testing::Test { public: RetrieverTest(const RetrieverTest&) = delete; RetrieverTest& operator=(const RetrieverTest&) = delete; protected: RetrieverTest() : retriever_(new TestdataSource(false), new NullStorage), success_(false), key_(), data_(), data_ready_(BuildCallback(this, &RetrieverTest::OnDataReady)) {} Retriever retriever_; bool success_; std::string key_; std::string data_; const std::unique_ptr<const Retriever::Callback> data_ready_; private: void OnDataReady(bool success, const std::string& key, const std::string& data) { success_ = success; key_ = key; data_ = data; } }; TEST_F(RetrieverTest, RetrieveData) { retriever_.Retrieve(kKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kKey, key_); EXPECT_FALSE(data_.empty()); EXPECT_NE(kEmptyData, data_); } TEST_F(RetrieverTest, ReadDataFromStorage) { retriever_.Retrieve(kKey, *data_ready_); retriever_.Retrieve(kKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kKey, key_); EXPECT_FALSE(data_.empty()); EXPECT_NE(kEmptyData, data_); } TEST_F(RetrieverTest, MissingKeyReturnsEmptyData) { static const char kMissingKey[] = "junk"; retriever_.Retrieve(kMissingKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kMissingKey, key_); EXPECT_EQ(kEmptyData, data_); } TEST_F(RetrieverTest, FaultySource) { Retriever bad_retriever(new MockSource, new NullStorage); bad_retriever.Retrieve(kKey, *data_ready_); EXPECT_FALSE(success_); EXPECT_EQ(kKey, key_); EXPECT_TRUE(data_.empty()); } class StaleStorage : public Storage { public: StaleStorage(const StaleStorage&) = delete; StaleStorage& operator=(const StaleStorage&) = delete; StaleStorage() : data_updated_(false) {} ~StaleStorage() override = default; void Get(const std::string& key, const Callback& data_ready) const override { data_ready(true, key, new std::string(kStaleWrappedData)); } void Put(const std::string& key, std::string* value) override { ASSERT_TRUE(value != nullptr); data_updated_ = true; delete value; } bool data_updated_; }; TEST_F(RetrieverTest, UseStaleDataWhenSourceFails) { auto* stale_storage = new StaleStorage; Retriever resilient_retriever(new MockSource, stale_storage); resilient_retriever.Retrieve(kKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kKey, key_); EXPECT_EQ(kStaleData, data_); EXPECT_FALSE(stale_storage->data_updated_); } TEST_F(RetrieverTest, DoNotUseStaleDataWhenSourceSucceeds) { auto* stale_storage = new StaleStorage; Retriever resilient_retriever(new TestdataSource(false), stale_storage); resilient_retriever.Retrieve(kKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kKey, key_); EXPECT_FALSE(data_.empty()); EXPECT_NE(kEmptyData, data_); EXPECT_NE(kStaleData, data_); EXPECT_TRUE(stale_storage->data_updated_); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/retriever.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/retriever_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
2653932b-4768-456b-9d5e-d90084229d4f
cpp
google/libaddressinput
null_storage
cpp/src/null_storage.cc
cpp/test/null_storage_test.cc
#include <libaddressinput/null_storage.h> #include <cassert> #include <cstddef> #include <string> namespace i18n { namespace addressinput { NullStorage::NullStorage() = default; NullStorage::~NullStorage() = default; void NullStorage::Put(const std::string& key, std::string* data) { assert(data != nullptr); delete data; } void NullStorage::Get(const std::string& key, const Callback& data_ready) const { data_ready(false, key, nullptr); } } }
#include <libaddressinput/null_storage.h> #include <libaddressinput/callback.h> #include <libaddressinput/storage.h> #include <cstddef> #include <memory> #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::NullStorage; using i18n::addressinput::Storage; class NullStorageTest : public testing::Test { public: NullStorageTest(const NullStorageTest&) = delete; NullStorageTest& operator=(const NullStorageTest&) = delete; protected: NullStorageTest() : data_ready_(BuildCallback(this, &NullStorageTest::OnDataReady)) {} NullStorage storage_; bool success_; std::string key_; std::string data_; const std::unique_ptr<const Storage::Callback> data_ready_; static const char kKey[]; private: void OnDataReady(bool success, const std::string& key, std::string* data) { ASSERT_FALSE(success && data == nullptr); success_ = success; key_ = key; if (data != nullptr) { data_ = *data; delete data; } } }; const char NullStorageTest::kKey[] = "foo"; TEST_F(NullStorageTest, Put) { storage_.Put(kKey, new std::string("bar")); } TEST_F(NullStorageTest, Get) { storage_.Get(kKey, *data_ready_); EXPECT_FALSE(success_); EXPECT_EQ(kKey, key_); EXPECT_TRUE(data_.empty()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/null_storage.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/null_storage_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
13bd3235-e3de-4413-be34-c4c9024651b4
cpp
google/libaddressinput
address_problem
cpp/src/address_problem.cc
cpp/test/address_problem_test.cc
#include <libaddressinput/address_problem.h> #include <cstddef> #include <ostream> #include "util/size.h" using i18n::addressinput::AddressProblem; using i18n::addressinput::size; using i18n::addressinput::UNEXPECTED_FIELD; using i18n::addressinput::UNSUPPORTED_FIELD; std::ostream& operator<<(std::ostream& o, AddressProblem problem) { static const char* const kProblemNames[] = { "UNEXPECTED_FIELD", "MISSING_REQUIRED_FIELD", "UNKNOWN_VALUE", "INVALID_FORMAT", "MISMATCHING_VALUE", "USES_P_O_BOX", "UNSUPPORTED_FIELD", }; static_assert(UNEXPECTED_FIELD == 0, "bad_base"); static_assert(UNSUPPORTED_FIELD == size(kProblemNames) - 1, "bad_length"); if (problem < 0 || static_cast<size_t>(problem) >= size(kProblemNames)) { o << "[INVALID ENUM VALUE " << static_cast<int>(problem) << "]"; } else { o << kProblemNames[problem]; } return o; }
#include <libaddressinput/address_problem.h> #include <sstream> #include <gtest/gtest.h> namespace { using i18n::addressinput::UNKNOWN_VALUE; TEST(AddressProblemTest, ValidEnumValue) { std::ostringstream oss; oss << UNKNOWN_VALUE; EXPECT_EQ("UNKNOWN_VALUE", oss.str()); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_problem.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_problem_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
52912676-1d27-4223-896a-7a47d097c056
cpp
google/libaddressinput
address_metadata
cpp/src/address_metadata.cc
cpp/test/address_metadata_test.cc
#include <libaddressinput/address_metadata.h> #include <libaddressinput/address_field.h> #include <algorithm> #include <string> #include "format_element.h" #include "region_data_constants.h" #include "rule.h" namespace i18n { namespace addressinput { bool IsFieldRequired(AddressField field, const std::string& region_code) { if (field == COUNTRY) { return true; } Rule rule; rule.CopyFrom(Rule::GetDefault()); if (!rule.ParseSerializedRule( RegionDataConstants::GetRegionData(region_code))) { return false; } return std::find(rule.GetRequired().begin(), rule.GetRequired().end(), field) != rule.GetRequired().end(); } bool IsFieldUsed(AddressField field, const std::string& region_code) { if (field == COUNTRY) { return true; } Rule rule; rule.CopyFrom(Rule::GetDefault()); if (!rule.ParseSerializedRule( RegionDataConstants::GetRegionData(region_code))) { return false; } return std::find(rule.GetFormat().begin(), rule.GetFormat().end(), FormatElement(field)) != rule.GetFormat().end(); } } }
#include <libaddressinput/address_metadata.h> #include <libaddressinput/address_field.h> #include <gtest/gtest.h> namespace { using i18n::addressinput::IsFieldRequired; using i18n::addressinput::IsFieldUsed; using i18n::addressinput::COUNTRY; using i18n::addressinput::ADMIN_AREA; using i18n::addressinput::DEPENDENT_LOCALITY; TEST(AddressMetadataTest, IsFieldRequiredCountry) { EXPECT_TRUE(IsFieldRequired(COUNTRY, "US")); EXPECT_TRUE(IsFieldRequired(COUNTRY, "CH")); EXPECT_TRUE(IsFieldRequired(COUNTRY, "rrr")); } TEST(AddressMetadataTest, IsUsedRequiredCountry) { EXPECT_TRUE(IsFieldUsed(COUNTRY, "US")); EXPECT_TRUE(IsFieldUsed(COUNTRY, "CH")); EXPECT_TRUE(IsFieldUsed(COUNTRY, "rrr")); } TEST(AddressMetadataTest, IsFieldRequiredAdminAreaUS) { EXPECT_TRUE(IsFieldRequired(ADMIN_AREA, "US")); } TEST(AddressMetadataTest, IsFieldRequiredAdminAreaAT) { EXPECT_FALSE(IsFieldRequired(ADMIN_AREA, "AT")); } TEST(AddressMetadataTest, IsFieldRequiredAdminAreaSU) { EXPECT_FALSE(IsFieldRequired(ADMIN_AREA, "SU")); } TEST(AddressMetadataTest, IsFieldUsedDependentLocalityUS) { EXPECT_FALSE(IsFieldUsed(DEPENDENT_LOCALITY, "US")); } TEST(AddressMetadataTest, IsFieldUsedDependentLocalityCN) { EXPECT_TRUE(IsFieldUsed(DEPENDENT_LOCALITY, "CN")); } TEST(AddressMetadataTest, IsFieldUsedDependentLocalitySU) { EXPECT_FALSE(IsFieldUsed(DEPENDENT_LOCALITY, "SU")); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_metadata.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_metadata_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
60a2d5c4-a0f9-4d53-bec3-8f58bc8d6417
cpp
google/libaddressinput
address_ui
cpp/src/address_ui.cc
cpp/test/address_ui_test.cc
#include <libaddressinput/address_ui.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_ui_component.h> #include <libaddressinput/localization.h> #include <cassert> #include <cstddef> #include <set> #include <string> #include <vector> #include "format_element.h" #include "grit.h" #include "language.h" #include "messages.h" #include "region_data_constants.h" #include "rule.h" namespace i18n { namespace addressinput { namespace { std::string GetLabelForField(const Localization& localization, AddressField field, int admin_area_name_message_id, int postal_code_name_message_id, int locality_name_message_id, int sublocality_name_message_id) { int message_id; switch (field) { case SORTING_CODE: return "CEDEX"; case COUNTRY: message_id = IDS_LIBADDRESSINPUT_COUNTRY_OR_REGION_LABEL; break; case ADMIN_AREA: message_id = admin_area_name_message_id; break; case LOCALITY: message_id = locality_name_message_id; break; case DEPENDENT_LOCALITY: message_id = sublocality_name_message_id; break; case POSTAL_CODE: message_id = postal_code_name_message_id; break; case STREET_ADDRESS: message_id = IDS_LIBADDRESSINPUT_ADDRESS_LINE_1_LABEL; break; case ORGANIZATION: message_id = IDS_LIBADDRESSINPUT_ORGANIZATION_LABEL; break; case RECIPIENT: message_id = IDS_LIBADDRESSINPUT_RECIPIENT_LABEL; break; default: message_id = INVALID_MESSAGE_ID; } return localization.GetString(message_id); } std::vector<AddressUiComponent> BuildComponents( const std::string& region_code, const Localization& localization, const std::string& ui_language_tag, bool include_literals, std::string* best_address_language_tag) { assert(best_address_language_tag != nullptr); std::vector<AddressUiComponent> result; Rule rule; rule.CopyFrom(Rule::GetDefault()); if (!rule.ParseSerializedRule( RegionDataConstants::GetRegionData(region_code))) { return result; } const Language best_address_language = ChooseBestAddressLanguage(rule, Language(ui_language_tag)); *best_address_language_tag = best_address_language.tag; const std::vector<FormatElement>& format = !rule.GetLatinFormat().empty() && best_address_language.has_latin_script ? rule.GetLatinFormat() : rule.GetFormat(); std::set<AddressField> fields; bool preceded_by_newline = true; bool followed_by_newline = true; for (auto format_it = format.begin(); format_it != format.end(); ++format_it) { if (!format_it->IsField()) { if (include_literals) { AddressUiComponent component; component.literal = format_it->GetLiteral(); result.push_back(component); } if (format_it->IsNewline()) preceded_by_newline = true; continue; } else if (!fields.insert(format_it->GetField()).second) { continue; } AddressUiComponent component; auto next_format_it = format_it + 1; followed_by_newline = next_format_it == format.end() || next_format_it->IsNewline(); component.length_hint = preceded_by_newline && followed_by_newline ? AddressUiComponent::HINT_LONG : AddressUiComponent::HINT_SHORT; preceded_by_newline = false; component.field = format_it->GetField(); component.name = GetLabelForField(localization, format_it->GetField(), rule.GetAdminAreaNameMessageId(), rule.GetPostalCodeNameMessageId(), rule.GetLocalityNameMessageId(), rule.GetSublocalityNameMessageId()); result.push_back(component); } return result; } } const std::vector<std::string>& GetRegionCodes() { return RegionDataConstants::GetRegionCodes(); } std::vector<AddressUiComponent> BuildComponents( const std::string& region_code, const Localization& localization, const std::string& ui_language_tag, std::string* best_address_language_tag) { return BuildComponents(region_code, localization, ui_language_tag, false, best_address_language_tag); } std::vector<AddressUiComponent> BuildComponentsWithLiterals( const std::string& region_code, const Localization& localization, const std::string& ui_language_tag, std::string* best_address_language_tag) { return BuildComponents(region_code, localization, ui_language_tag, true, best_address_language_tag); } } }
#include <libaddressinput/address_ui.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_ui_component.h> #include <libaddressinput/localization.h> #include <set> #include <string> #include <vector> #include <gtest/gtest.h> namespace { using i18n::addressinput::AddressField; using i18n::addressinput::AddressUiComponent; using i18n::addressinput::BuildComponents; using i18n::addressinput::GetRegionCodes; using i18n::addressinput::Localization; using i18n::addressinput::COUNTRY; using i18n::addressinput::ADMIN_AREA; using i18n::addressinput::POSTAL_CODE; using i18n::addressinput::STREET_ADDRESS; using i18n::addressinput::ORGANIZATION; using i18n::addressinput::RECIPIENT; const char kUiLanguageTag[] = "en"; testing::AssertionResult ComponentsAreValid( const std::vector<AddressUiComponent>& components) { if (components.empty()) { return testing::AssertionFailure() << "no components"; } for (const auto& component : components) { static const AddressField kMinAddressField = COUNTRY; static const AddressField kMaxAddressField = RECIPIENT; if (component.literal.empty()) { if (component.field < kMinAddressField || component.field > kMaxAddressField) { return testing::AssertionFailure() << "unexpected field " << component.field; } if (component.name.empty()) { return testing::AssertionFailure() << "empty field name for field " << component.field; } } else { if (!component.name.empty()) { return testing::AssertionFailure() << "literals don't have names"; } } } return testing::AssertionSuccess(); } class AddressUiTest : public testing::TestWithParam<std::string> { public: AddressUiTest(const AddressUiTest&) = delete; AddressUiTest& operator=(const AddressUiTest&) = delete; protected: AddressUiTest() = default; Localization localization_; std::string best_address_language_tag_; }; TEST_P(AddressUiTest, RegionCodeHasTwoCharacters) { EXPECT_EQ(2, GetParam().size()); } TEST_P(AddressUiTest, ComponentsAreValid) { EXPECT_TRUE(ComponentsAreValid(BuildComponents( GetParam(), localization_, kUiLanguageTag, &best_address_language_tag_))); } TEST_P(AddressUiTest, ComponentsWithLiteralsAreValid) { EXPECT_TRUE(ComponentsAreValid(BuildComponentsWithLiterals( GetParam(), localization_, kUiLanguageTag, &best_address_language_tag_))); } TEST_P(AddressUiTest, UniqueFieldTypes) { std::set<AddressField> fields; const std::vector<AddressUiComponent>& components = BuildComponents(GetParam(), localization_, kUiLanguageTag, &best_address_language_tag_); for (const auto& component : components) { EXPECT_TRUE(fields.insert(component.field).second); } } TEST_P(AddressUiTest, UniqueFieldTypesByBuildComponentsWithLiterals) { std::set<AddressField> fields; const std::vector<AddressUiComponent>& components = BuildComponentsWithLiterals(GetParam(), localization_, kUiLanguageTag, &best_address_language_tag_); for (const auto& component : components) { if (component.literal.empty()) { EXPECT_TRUE(fields.insert(component.field).second); } } } INSTANTIATE_TEST_SUITE_P(AllRegions, AddressUiTest, testing::ValuesIn(GetRegionCodes())); TEST_F(AddressUiTest, InvalidRegionCodeReturnsEmptyVector) { EXPECT_TRUE(BuildComponents( "INVALID-REGION-CODE", localization_, kUiLanguageTag, &best_address_language_tag_).empty()); } TEST_F(AddressUiTest, ComponentsWithLiteralsReadsLiteralsForLV) { const std::vector<AddressUiComponent>& components = BuildComponentsWithLiterals("LV", localization_, kUiLanguageTag, &best_address_language_tag_); std::string literal; int newlines_count = 0; for (const auto& component : components) { if (!component.literal.empty()) { if (component.literal == "\n") { newlines_count++; continue; } EXPECT_TRUE(literal.empty()); literal = component.literal; } } EXPECT_EQ(", ", literal); EXPECT_EQ(4, newlines_count); } struct LanguageTestCase { LanguageTestCase(const std::string& region_code, const std::string& ui_language_tag, const std::string& expected_best_address_language_tag, AddressField expected_first_field) : region_code(region_code), ui_language_tag(ui_language_tag), expected_best_address_language_tag(expected_best_address_language_tag), expected_first_field(expected_first_field) {} ~LanguageTestCase() = default; const std::string region_code; const std::string ui_language_tag; const std::string expected_best_address_language_tag; const AddressField expected_first_field; }; class BestAddressLanguageTagTest : public testing::TestWithParam<LanguageTestCase> { public: BestAddressLanguageTagTest(const BestAddressLanguageTagTest&) = delete; BestAddressLanguageTagTest& operator=(const BestAddressLanguageTagTest&) = delete; protected: BestAddressLanguageTagTest() = default; Localization localization_; std::string best_address_language_tag_; }; std::string GetterStub(int) { return std::string(); } TEST_P(BestAddressLanguageTagTest, CorrectBestAddressLanguageTag) { localization_.SetGetter(&GetterStub); const std::vector<AddressUiComponent>& components = BuildComponents( GetParam().region_code, localization_, GetParam().ui_language_tag, &best_address_language_tag_); EXPECT_EQ(GetParam().expected_best_address_language_tag, best_address_language_tag_); ASSERT_FALSE(components.empty()); EXPECT_EQ(GetParam().expected_first_field, components.front().field); } INSTANTIATE_TEST_SUITE_P( LanguageTestCases, BestAddressLanguageTagTest, testing::Values( LanguageTestCase("AM", "", "hy", RECIPIENT), LanguageTestCase("AM", "hy", "hy", RECIPIENT), LanguageTestCase("AM", "en", "hy-Latn", RECIPIENT), LanguageTestCase("CN", "zh-hans", "zh", POSTAL_CODE), LanguageTestCase("CN", "zh-hant", "zh", POSTAL_CODE), LanguageTestCase("CN", "zh-hans-CN", "zh", POSTAL_CODE), LanguageTestCase("CN", "zh", "zh", POSTAL_CODE), LanguageTestCase("CN", "ZH_HANS", "zh", POSTAL_CODE), LanguageTestCase("CN", "zh-cmn-Hans-CN", "zh", POSTAL_CODE), LanguageTestCase("CN", "zh-Latn", "zh-Latn", RECIPIENT), LanguageTestCase("CN", "zh-latn-CN", "zh-Latn", RECIPIENT), LanguageTestCase("CN", "en", "zh-Latn", RECIPIENT), LanguageTestCase("CN", "ja", "zh-Latn", RECIPIENT), LanguageTestCase("CN", "ko", "zh-Latn", RECIPIENT), LanguageTestCase("CN", "ZH_LATN", "zh-Latn", RECIPIENT), LanguageTestCase("CN", "cmn-Hans-CN", "zh-Latn", RECIPIENT), LanguageTestCase("HK", "zh", "zh-Hant", ADMIN_AREA), LanguageTestCase("HK", "zh-hans", "zh-Hant", ADMIN_AREA), LanguageTestCase("HK", "zh-hant", "zh-Hant", ADMIN_AREA), LanguageTestCase("HK", "zh-yue-HK", "zh-Hant", ADMIN_AREA), LanguageTestCase("HK", "en", "en", ADMIN_AREA), LanguageTestCase("HK", "zh-latn", "zh-Latn", RECIPIENT), LanguageTestCase("HK", "fr", "zh-Latn", RECIPIENT), LanguageTestCase("HK", "ja", "zh-Latn", RECIPIENT), LanguageTestCase("HK", "ko", "zh-Latn", RECIPIENT), LanguageTestCase("HK", "yue-HK", "zh-Latn", RECIPIENT), LanguageTestCase("MO", "zh", "zh-Hant", STREET_ADDRESS), LanguageTestCase("MO", "zh-Hant", "zh-Hant", STREET_ADDRESS), LanguageTestCase("MO", "pt", "pt", STREET_ADDRESS), LanguageTestCase("MO", "zh-Latn", "zh-Latn", RECIPIENT), LanguageTestCase("MO", "en", "zh-Latn", RECIPIENT), LanguageTestCase("CH", "de", "de", ORGANIZATION), LanguageTestCase("CH", "de-DE", "de", ORGANIZATION), LanguageTestCase("CH", "de-Latn-DE", "de", ORGANIZATION), LanguageTestCase("CH", "fr", "fr", ORGANIZATION), LanguageTestCase("CH", "it", "it", ORGANIZATION), LanguageTestCase("CH", "en", "de", ORGANIZATION), LanguageTestCase("AQ", "en", "en", RECIPIENT), LanguageTestCase("AQ", "fr", "fr", RECIPIENT), LanguageTestCase("AQ", "es", "es", RECIPIENT), LanguageTestCase("AQ", "zh-Hans", "zh-Hans", RECIPIENT), LanguageTestCase("EG", "ar", "ar", RECIPIENT), LanguageTestCase("EG", "ar-Arab", "ar", RECIPIENT), LanguageTestCase("EG", "ar-Latn", "ar-Latn", RECIPIENT), LanguageTestCase("EG", "fr", "ar-Latn", RECIPIENT), LanguageTestCase("EG", "fa", "ar-Latn", RECIPIENT), LanguageTestCase("EG", "fa-Arab", "ar-Latn", RECIPIENT))); }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_ui.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_ui_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
f95141df-9320-4751-adec-45d0c142a291
cpp
google/libaddressinput
validating_storage
cpp/src/validating_storage.cc
cpp/test/validating_storage_test.cc
#include "validating_storage.h" #include <libaddressinput/callback.h> #include <libaddressinput/storage.h> #include <cassert> #include <cstddef> #include <ctime> #include <memory> #include <string> #include "validating_util.h" namespace i18n { namespace addressinput { namespace { class Helper { public: Helper(const Helper&) = delete; Helper& operator=(const Helper&) = delete; Helper(const std::string& key, const ValidatingStorage::Callback& data_ready, const Storage& wrapped_storage) : data_ready_(data_ready), wrapped_data_ready_(BuildCallback(this, &Helper::OnWrappedDataReady)) { wrapped_storage.Get(key, *wrapped_data_ready_); } private: ~Helper() = default; void OnWrappedDataReady(bool success, const std::string& key, std::string* data) { if (success) { assert(data != nullptr); bool is_stale = !ValidatingUtil::UnwrapTimestamp(data, std::time(nullptr)); bool is_corrupted = !ValidatingUtil::UnwrapChecksum(data); success = !is_corrupted && !is_stale; if (is_corrupted) { delete data; data = nullptr; } } else { delete data; data = nullptr; } data_ready_(success, key, data); delete this; } const Storage::Callback& data_ready_; const std::unique_ptr<const Storage::Callback> wrapped_data_ready_; }; } ValidatingStorage::ValidatingStorage(Storage* storage) : wrapped_storage_(storage) { assert(wrapped_storage_ != nullptr); } ValidatingStorage::~ValidatingStorage() = default; void ValidatingStorage::Put(const std::string& key, std::string* data) { assert(data != nullptr); ValidatingUtil::Wrap(std::time(nullptr), data); wrapped_storage_->Put(key, data); } void ValidatingStorage::Get(const std::string& key, const Callback& data_ready) const { new Helper(key, data_ready, *wrapped_storage_); } } }
#include "validating_storage.h" #include <libaddressinput/callback.h> #include <libaddressinput/storage.h> #include <cstddef> #include <memory> #include <string> #include <gtest/gtest.h> #include "fake_storage.h" #define CHECKSUM "dd63dafcbd4d5b28badfcaf86fb6fcdb" #define DATA "{'foo': 'bar'}" #define OLD_TIMESTAMP "0" namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::FakeStorage; using i18n::addressinput::Storage; using i18n::addressinput::ValidatingStorage; const char kKey[] = "key"; const char kValidatedData[] = DATA; const char kStaleWrappedData[] = "timestamp=" OLD_TIMESTAMP "\n" "checksum=" CHECKSUM "\n" DATA; const char kEmptyData[] = ""; class ValidatingStorageTest : public testing::Test { public: ValidatingStorageTest(const ValidatingStorageTest&) = delete; ValidatingStorageTest& operator=(const ValidatingStorageTest&) = delete; protected: ValidatingStorageTest() : wrapped_storage_(new FakeStorage), storage_(wrapped_storage_), success_(false), key_(), data_(), data_ready_(BuildCallback(this, &ValidatingStorageTest::OnDataReady)) {} Storage* const wrapped_storage_; ValidatingStorage storage_; bool success_; std::string key_; std::string data_; const std::unique_ptr<const ValidatingStorage::Callback> data_ready_; private: void OnDataReady(bool success, const std::string& key, std::string* data) { ASSERT_FALSE(success && data == nullptr); success_ = success; key_ = key; if (data != nullptr) { data_ = *data; delete data; } } }; TEST_F(ValidatingStorageTest, GoodData) { storage_.Put(kKey, new std::string(kValidatedData)); storage_.Get(kKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kKey, key_); EXPECT_EQ(kValidatedData, data_); } TEST_F(ValidatingStorageTest, EmptyData) { storage_.Put(kKey, new std::string(kEmptyData)); storage_.Get(kKey, *data_ready_); EXPECT_TRUE(success_); EXPECT_EQ(kKey, key_); EXPECT_EQ(kEmptyData, data_); } TEST_F(ValidatingStorageTest, MissingKey) { storage_.Get(kKey, *data_ready_); EXPECT_FALSE(success_); EXPECT_EQ(kKey, key_); EXPECT_TRUE(data_.empty()); } TEST_F(ValidatingStorageTest, GarbageData) { storage_.Put(kKey, new std::string(kValidatedData)); wrapped_storage_->Put(kKey, new std::string("garbage")); storage_.Get(kKey, *data_ready_); EXPECT_FALSE(success_); EXPECT_EQ(kKey, key_); EXPECT_TRUE(data_.empty()); } TEST_F(ValidatingStorageTest, StaleData) { storage_.Put(kKey, new std::string(kValidatedData)); wrapped_storage_->Put(kKey, new std::string(kStaleWrappedData)); storage_.Get(kKey, *data_ready_); EXPECT_FALSE(success_); EXPECT_EQ(kKey, key_); EXPECT_EQ(kValidatedData, data_); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/validating_storage.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/validating_storage_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
a4b804a5-f049-4acf-8e49-e228c9af3aaa
cpp
google/libaddressinput
ondemand_supply_task
cpp/src/ondemand_supply_task.cc
cpp/test/ondemand_supply_task_test.cc
#include "ondemand_supply_task.h" #include <libaddressinput/address_field.h> #include <libaddressinput/callback.h> #include <libaddressinput/supplier.h> #include <algorithm> #include <cassert> #include <cstddef> #include <map> #include <string> #include "lookup_key.h" #include "retriever.h" #include "rule.h" #include "util/size.h" namespace i18n { namespace addressinput { OndemandSupplyTask::OndemandSupplyTask( const LookupKey& lookup_key, std::map<std::string, const Rule*>* rules, const Supplier::Callback& supplied) : hierarchy_(), pending_(), lookup_key_(lookup_key), rule_cache_(rules), supplied_(supplied), retrieved_(BuildCallback(this, &OndemandSupplyTask::Load)), success_(true) { assert(rule_cache_ != nullptr); assert(retrieved_ != nullptr); } OndemandSupplyTask::~OndemandSupplyTask() = default; void OndemandSupplyTask::Queue(const std::string& key) { assert(pending_.find(key) == pending_.end()); pending_.insert(key); } void OndemandSupplyTask::Retrieve(const Retriever& retriever) { if (pending_.empty()) { Loaded(); } else { bool done = false; for (auto it = pending_.begin(); !done;) { const std::string& key = *it++; done = it == pending_.end(); retriever.Retrieve(key, *retrieved_); } } } void OndemandSupplyTask::Load(bool success, const std::string& key, const std::string& data) { size_t depth = std::count(key.begin(), key.end(), '/') - 1; assert(depth < size(LookupKey::kHierarchy)); size_t status = pending_.erase(key); assert(status == 1); (void)status; if (success) { if (data != "{}") { auto* rule = new Rule; if (LookupKey::kHierarchy[depth] == COUNTRY) { rule->CopyFrom(Rule::GetDefault()); } if (rule->ParseSerializedRule(data)) { auto result = rule_cache_->emplace(rule->GetId(), rule); if (!result.second) { delete rule; } hierarchy_.rule[depth] = result.first->second; } else { delete rule; success_ = false; } } } else { success_ = false; } if (pending_.empty()) { Loaded(); } } void OndemandSupplyTask::Loaded() { supplied_(success_, lookup_key_, hierarchy_); delete this; } } }
#include "ondemand_supply_task.h" #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/supplier.h> #include <cstddef> #include <cstring> #include <map> #include <memory> #include <string> #include <gtest/gtest.h> #include "lookup_key.h" #include "mock_source.h" #include "retriever.h" #include "rule.h" #include "util/size.h" namespace { using i18n::addressinput::BuildCallback; using i18n::addressinput::LookupKey; using i18n::addressinput::MockSource; using i18n::addressinput::NullStorage; using i18n::addressinput::OndemandSupplyTask; using i18n::addressinput::Retriever; using i18n::addressinput::Rule; using i18n::addressinput::Supplier; class OndemandSupplyTaskTest : public testing::Test { public: OndemandSupplyTaskTest(const OndemandSupplyTaskTest&) = delete; OndemandSupplyTaskTest& operator=(const OndemandSupplyTaskTest&) = delete; protected: OndemandSupplyTaskTest() : success_(true), lookup_key_(), rule_(), called_(false), source_(new MockSource), rule_cache_(), retriever_(new Retriever(source_, new NullStorage)), supplied_(BuildCallback(this, &OndemandSupplyTaskTest::Supplied)), task_(new OndemandSupplyTask(lookup_key_, &rule_cache_, *supplied_)) {} ~OndemandSupplyTaskTest() override { for (const auto& pair : rule_cache_) { delete pair.second; } } void Queue(const std::string& key) { task_->Queue(key); } void Retrieve() { task_->Retrieve(*retriever_); } bool success_; LookupKey lookup_key_; const Rule* rule_[size(LookupKey::kHierarchy)]; bool called_; MockSource* const source_; private: void Supplied(bool success, const LookupKey& lookup_key, const Supplier::RuleHierarchy& hierarchy) { ASSERT_EQ(success_, success); ASSERT_EQ(&lookup_key_, &lookup_key); ASSERT_EQ(&task_->hierarchy_, &hierarchy); std::memcpy(rule_, hierarchy.rule, sizeof rule_); called_ = true; } std::map<std::string, const Rule*> rule_cache_; const std::unique_ptr<Retriever> retriever_; const std::unique_ptr<const Supplier::Callback> supplied_; OndemandSupplyTask* const task_; }; TEST_F(OndemandSupplyTaskTest, Empty) { ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] == nullptr); EXPECT_TRUE(rule_[1] == nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_F(OndemandSupplyTaskTest, Invalid) { Queue("data/XA"); success_ = false; ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); } TEST_F(OndemandSupplyTaskTest, Valid) { source_->data_ = {{"data/XA", R"({"id":"data/XA"})"}}; Queue("data/XA"); ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] == nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); EXPECT_EQ("data/XA", rule_[0]->GetId()); EXPECT_FALSE(rule_[0]->GetFormat().empty()); EXPECT_FALSE(rule_[0]->GetRequired().empty()); EXPECT_TRUE(rule_[0]->GetPostalCodeMatcher() == nullptr); } TEST_F(OndemandSupplyTaskTest, ValidHierarchy) { source_->data_ = { {"data/XA", R"({"id":"data/XA"})"}, {"data/XA/aa", R"({"id":"data/XA/aa"})"}, {"data/XA/aa/bb", R"({"id":"data/XA/aa/bb"})"}, {"data/XA/aa/bb/cc", R"({"id":"data/XA/aa/bb/cc"})"}, }; Queue("data/XA"); Queue("data/XA/aa"); Queue("data/XA/aa/bb"); Queue("data/XA/aa/bb/cc"); ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] != nullptr); EXPECT_TRUE(rule_[2] != nullptr); EXPECT_TRUE(rule_[3] != nullptr); EXPECT_EQ("data/XA", rule_[0]->GetId()); EXPECT_EQ("data/XA/aa", rule_[1]->GetId()); EXPECT_EQ("data/XA/aa/bb", rule_[2]->GetId()); EXPECT_EQ("data/XA/aa/bb/cc", rule_[3]->GetId()); EXPECT_FALSE(rule_[0]->GetFormat().empty()); EXPECT_FALSE(rule_[0]->GetRequired().empty()); EXPECT_TRUE(rule_[1]->GetFormat().empty()); EXPECT_TRUE(rule_[1]->GetRequired().empty()); EXPECT_TRUE(rule_[2]->GetFormat().empty()); EXPECT_TRUE(rule_[2]->GetRequired().empty()); EXPECT_TRUE(rule_[3]->GetFormat().empty()); EXPECT_TRUE(rule_[3]->GetRequired().empty()); } TEST_F(OndemandSupplyTaskTest, InvalidJson1) { source_->data_ = {{"data/XA", ":"}}; success_ = false; Queue("data/XA"); ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); } TEST_F(OndemandSupplyTaskTest, InvalidJson2) { source_->data_ = { {"data/XA", R"({"id":"data/XA"})"}, {"data/XA/aa", ":"}, }; success_ = false; Queue("data/XA"); Queue("data/XA/aa"); ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); } TEST_F(OndemandSupplyTaskTest, EmptyJsonJustMeansServerKnowsNothingAboutKey) { source_->data_ = { {"data/XA", R"({"id":"data/XA"})"}, {"data/XA/aa", "{}"}, }; Queue("data/XA"); Queue("data/XA/aa"); ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] == nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); EXPECT_EQ("data/XA", rule_[0]->GetId()); } TEST_F(OndemandSupplyTaskTest, IfCountryFailsAllFails) { source_->data_ = {{"data/XA/aa", R"({"id":"data/XA/aa"})"}}; success_ = false; Queue("data/XA"); Queue("data/XA/aa"); ASSERT_NO_FATAL_FAILURE(Retrieve()); ASSERT_TRUE(called_); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/ondemand_supply_task.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/ondemand_supply_task_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
fad28bcd-2f8e-4dd8-b982-85cf806a6dab
cpp
google/libaddressinput
address_input_helper
cpp/src/address_input_helper.cc
cpp/test/address_input_helper_test.cc
#include <libaddressinput/address_input_helper.h> #include <libaddressinput/address_data.h> #include <libaddressinput/address_field.h> #include <libaddressinput/address_metadata.h> #include <libaddressinput/preload_supplier.h> #include <cassert> #include <cstddef> #include <string> #include <vector> #include <re2/re2.h> #include "language.h" #include "lookup_key.h" #include "region_data_constants.h" #include "rule.h" #include "util/re2ptr.h" #include "util/size.h" namespace i18n { namespace addressinput { struct Node { const Node* parent; const Rule* rule; }; namespace { const char kLookupKeySeparator = '/'; const size_t kHierarchyDepth = size(LookupKey::kHierarchy); std::string GetBestName(const Language& language, const Rule& rule) { if (language.has_latin_script) { const std::string& name = rule.GetLatinName(); if (!name.empty()) { return name; } } const std::string& id = rule.GetId(); std::string::size_type pos = id.rfind(kLookupKeySeparator); assert(pos != std::string::npos); return id.substr(pos + 1); } void FillAddressFromMatchedRules( const std::vector<Node>* hierarchy, AddressData* address) { assert(hierarchy != nullptr); assert(address != nullptr); Language language(address->language_code); for (size_t depth = kHierarchyDepth - 1; depth > 0; --depth) { if (hierarchy[depth].size() == 1) { for (const Node* node = &hierarchy[depth].front(); node != nullptr; node = node->parent, --depth) { const Rule* rule = node->rule; assert(rule != nullptr); AddressField field = LookupKey::kHierarchy[depth]; if (address->IsFieldEmpty(field)) { address->SetFieldValue(field, GetBestName(language, *rule)); } } break; } } } } AddressInputHelper::AddressInputHelper(PreloadSupplier* supplier) : supplier_(supplier) { assert(supplier_ != nullptr); } void AddressInputHelper::FillAddress(AddressData* address) const { assert(address != nullptr); const std::string& region_code = address->region_code; if (!RegionDataConstants::IsSupported(region_code)) { return; } AddressData lookup_key_address; lookup_key_address.region_code = region_code; LookupKey lookup_key; lookup_key.FromAddress(lookup_key_address); const Rule* region_rule = supplier_->GetRule(lookup_key); assert(region_rule != nullptr); const RE2ptr* postal_code_reg_exp = region_rule->GetPostalCodeMatcher(); if (postal_code_reg_exp != nullptr) { if (address->postal_code.empty()) { address->postal_code = region_rule->GetSolePostalCode(); } if (!address->postal_code.empty() && RE2::FullMatch(address->postal_code, *postal_code_reg_exp->ptr)) { std::vector<Node> hierarchy[kHierarchyDepth]; CheckChildrenForPostCodeMatches(*address, lookup_key, nullptr, hierarchy); FillAddressFromMatchedRules(hierarchy, address); } } } void AddressInputHelper::CheckChildrenForPostCodeMatches( const AddressData& address, const LookupKey& lookup_key, const Node* parent, std::vector<Node>* hierarchy) const { const Rule* rule = supplier_->GetRule(lookup_key); assert(rule != nullptr); const RE2ptr* postal_code_prefix = rule->GetPostalCodeMatcher(); if (postal_code_prefix == nullptr || RE2::PartialMatch(address.postal_code, *postal_code_prefix->ptr)) { size_t depth = lookup_key.GetDepth(); assert(depth < size(LookupKey::kHierarchy)); hierarchy[depth].emplace_back(); Node* node = &hierarchy[depth].back(); node->parent = parent; node->rule = rule; if (depth < size(LookupKey::kHierarchy) - 1 && IsFieldUsed(LookupKey::kHierarchy[depth + 1], address.region_code)) { for (const auto& sub_key : rule->GetSubKeys()) { LookupKey child_key; child_key.FromLookupKey(lookup_key, sub_key); CheckChildrenForPostCodeMatches(address, child_key, node, hierarchy); } } } } } }
#include <libaddressinput/address_input_helper.h> #include <libaddressinput/address_data.h> #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/preload_supplier.h> #include <memory> #include <string> #include <gtest/gtest.h> #include "mock_source.h" #include "testdata_source.h" namespace { using i18n::addressinput::AddressData; using i18n::addressinput::AddressInputHelper; using i18n::addressinput::BuildCallback; using i18n::addressinput::MockSource; using i18n::addressinput::NullStorage; using i18n::addressinput::PreloadSupplier; using i18n::addressinput::TestdataSource; class AddressInputHelperTest : public testing::Test { public: AddressInputHelperTest(const AddressInputHelperTest&) = delete; AddressInputHelperTest& operator=(const AddressInputHelperTest&) = delete; protected: AddressInputHelperTest() : supplier_(new TestdataSource(true), new NullStorage), address_input_helper_(&supplier_), loaded_(BuildCallback(this, &AddressInputHelperTest::Loaded)) {} void FillAddress(AddressData* address) { const std::string& region_code = address->region_code; if (!region_code.empty()) { supplier_.LoadRules(region_code, *loaded_); } address_input_helper_.FillAddress(address); } private: void Loaded(bool success, const std::string&, int) { ASSERT_TRUE(success); } PreloadSupplier supplier_; const AddressInputHelper address_input_helper_; const std::unique_ptr<const PreloadSupplier::Callback> loaded_; }; TEST_F(AddressInputHelperTest, AddressWithMissingPostalCode) { AddressData address{ .region_code = "CX", .administrative_area = "WA", }; AddressData expected = address; expected.postal_code = "6798"; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingAdmin) { AddressData address{ .region_code = "US", .address_line{"10 High St"}, .postal_code = "58098", }; AddressData expected = address; expected.administrative_area = "ND"; FillAddress(&address); EXPECT_EQ(expected, address); address.administrative_area = "CA"; expected.administrative_area = "CA"; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingLowerLevel) { AddressData address{ .region_code = "TW", .postal_code = "53012", }; AddressData expected = address; expected.administrative_area = "彰化縣"; expected.locality = "二水鄉"; FillAddress(&address); EXPECT_EQ(expected, address); address.administrative_area = "Already filled in"; expected.administrative_area = "Already filled in"; address.locality = ""; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingLowerLevelLatin) { AddressData address{ .region_code = "TW", .postal_code = "53012", .language_code = "zh-Latn", }; AddressData expected = address; expected.locality = "Ershuei Township"; expected.administrative_area = "Changhua County"; FillAddress(&address); EXPECT_EQ(expected, address); address.administrative_area = "Already filled in"; expected.administrative_area = "Already filled in"; address.locality = ""; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingDependentLocality) { AddressData address{ .region_code = "KR", .postal_code = "425-111", }; AddressData expected = address; expected.administrative_area = "경기도"; expected.locality = "안산시"; expected.dependent_locality = "단원구"; FillAddress(&address); EXPECT_EQ(expected, address); AddressData address_ko_latn{ .region_code = "KR", .postal_code = "425-111", .language_code = "ko-Latn", }; expected = address_ko_latn; expected.administrative_area = "Gyeonggi"; expected.locality = "Ansan-si"; expected.dependent_locality = "Danwon-gu"; FillAddress(&address_ko_latn); EXPECT_EQ(expected, address_ko_latn); } TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingMultipleValues) { AddressData address{ .region_code = "KR", .postal_code = "527-111", }; AddressData expected = address; expected.administrative_area = "전라남도"; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, AddressWithInvalidPostalCode) { AddressData address{ .region_code = "US", .postal_code = "970", }; AddressData expected = address; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, AddressWithNoPostalCodeValidation) { AddressData address{ .region_code = "GA", .postal_code = "123", }; AddressData expected = address; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, AddressWithInvalidOrMissingRegionCode) { AddressData address{ .administrative_area = "YYY", .postal_code = "XXX", }; AddressData expected = address; FillAddress(&address); EXPECT_EQ(expected, address); address.region_code = "XXXX"; expected.region_code = "XXXX"; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperTest, RegionWithUnusedAdminAreaNames) { AddressData address{ .region_code = "CH", .postal_code = "1111", .language_code = "de-CH", }; AddressData expected = address; FillAddress(&address); EXPECT_EQ(expected, address); } class AddressInputHelperMockDataTest : public testing::Test { public: AddressInputHelperMockDataTest( const AddressInputHelperMockDataTest&) = delete; AddressInputHelperMockDataTest& operator=( const AddressInputHelperMockDataTest&) = delete; protected: AddressInputHelperMockDataTest() : source_(new MockSource), supplier_(source_, new NullStorage), address_input_helper_(&supplier_), loaded_(BuildCallback(this, &AddressInputHelperMockDataTest::Loaded)) {} void FillAddress(AddressData* address) { const std::string& region_code = address->region_code; if (!region_code.empty()) { supplier_.LoadRules(region_code, *loaded_); } address_input_helper_.FillAddress(address); } MockSource* const source_; private: void Loaded(bool success, const std::string&, int) { ASSERT_TRUE(success); } PreloadSupplier supplier_; const AddressInputHelper address_input_helper_; const std::unique_ptr<const PreloadSupplier::Callback> loaded_; }; TEST_F(AddressInputHelperMockDataTest, PostalCodeSharedAcrossDifferentHierarchies) { source_->data_ = { { "data/KR", R"({"data/KR": )" R"({"id":"data/KR", "sub_keys":"A~B", "zip":"\\d{5}"}, )" R"("data/KR/A": )" R"({"id":"data/KR/A", "sub_keys":"A1"}, )" R"("data/KR/A/A1": )" R"({"id":"data/KR/A/A1", "zip":"1"}, )" R"("data/KR/B": )" R"({"id":"data/KR/B", "sub_keys":"B1"}, )" R"("data/KR/B/B1": )" R"({"id":"data/KR/B/B1", "zip":"12"}})"}}; AddressData address{ .region_code = "KR", .administrative_area = "", .postal_code = "12345", }; AddressData expected = address; FillAddress(&address); EXPECT_EQ(expected, address); } TEST_F(AddressInputHelperMockDataTest, PostalCodeSharedAcrossDifferentHierarchiesSameState) { source_->data_ = { { "data/KR", R"({"data/KR": )" R"({"id":"data/KR", "sub_keys":"A~B", "zip":"\\d{5}"}, )" R"("data/KR/A": )" R"({"id":"data/KR/A", "sub_keys":"A1~A2"}, )" R"("data/KR/A/A1": )" R"({"id":"data/KR/A/A1", "sub_keys":"A1a", "zip":"1"}, )" R"("data/KR/A/A1/A1a": )" R"({"id":"data/KR/A/A1/A1a", "zip":"12"}, )" R"("data/KR/A/A2": )" R"({"id":"data/KR/A/A2", "sub_keys":"A2a", "zip":"1"}, )" R"("data/KR/A/A2/A2a": )" R"({"id":"data/KR/A/A2/A2a", "zip":"123"}, )" R"("data/KR/B": )" R"({"id":"data/KR/B", "zip":"2"}})"}}; AddressData address{ .region_code = "KR", .administrative_area = "", .postal_code = "12345", }; AddressData expected = address; expected.administrative_area = "A"; FillAddress(&address); EXPECT_EQ(expected, address); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/address_input_helper.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/address_input_helper_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
375e2f7a-4a22-46ac-afa3-43124a386696
cpp
google/libaddressinput
post_box_matchers
cpp/src/post_box_matchers.cc
cpp/test/post_box_matchers_test.cc
#include "post_box_matchers.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstring> #include <string> #include <vector> #include <re2/re2.h> #include "language.h" #include "rule.h" #include "util/re2ptr.h" #include "util/size.h" namespace i18n { namespace addressinput { namespace { struct LanguageInfo { const char* language; const char* regexp; static bool less(const LanguageInfo& a, const LanguageInfo& b) { return strcmp(a.language, b.language) < 0; } }; constexpr const LanguageInfo kLanguageInfoMap[] = { {"ar", R"(صندوق بريد|ص[-. ]ب)"}, {"cs", R"((?i)p\.? ?p\.? \d)"}, {"da", R"((?i)Postboks)"}, {"de", R"((?i)Postfach)"}, {"el", R"((?i)T\.? ?Θ\.? \d{2})"}, {"en", R"(Private Bag|Post(?:al)? Box)"}, {"es", R"((?i)(?:Apartado|Casillas) de correos?)"}, {"fi", R"((?i)Postilokero|P\.?L\.? \d)"}, {"fr", R"((?i)Bo(?:[iî]|î)te Postale|BP \d|CEDEX \d)"}, {"hr", R"((?i)p\.? ?p\.? \d)"}, {"hu", R"((?i)Postafi(?:[oó]|ó)k|Pf\.? \d)"}, {"ja", R"(私書箱\d{1,5}号)"}, {"nl", R"((?i)Postbus)"}, {"no", R"((?i)Postboks)"}, {"pl", R"((?i)Skr(?:\.?|ytka) poczt(?:\.?|owa))"}, {"pt", R"((?i)Apartado)"}, {"ru", R"((?i)абонентский ящик|[аa]"я (?:(?:№|#|N) ?)?\d)"}, {"sv", R"((?i)Box \d)"}, {"und", R"(P\.? ?O\.? Box)"}, {"zh", R"(郵政信箱.{1,5}號|郵局第.{1,10}號信箱)"}, }; constexpr size_t kLanguageInfoMapSize = size(kLanguageInfoMap); constexpr bool StrLessOrEqualConstexpr(const char* a, const char* b) { return (*a == '\0') ? true : ( (*a == *b) ? StrLessOrEqualConstexpr(a + 1, b + 1) : (*a < *b)); } static_assert(StrLessOrEqualConstexpr("", ""), ""); static_assert(StrLessOrEqualConstexpr("", "foo"), ""); static_assert(!StrLessOrEqualConstexpr("foo", ""), ""); static_assert(StrLessOrEqualConstexpr("foo", "foo"), ""); static_assert(!StrLessOrEqualConstexpr("foo", "bar"), ""); static_assert(StrLessOrEqualConstexpr("bar", "foo"), ""); static_assert(StrLessOrEqualConstexpr("foo", "foobar"), ""); static_assert(!StrLessOrEqualConstexpr("foobar", "foo"), ""); constexpr bool CheckLanguageInfoMapOrderConstexpr(size_t n = 0) { return !StrLessOrEqualConstexpr(kLanguageInfoMap[n].language, kLanguageInfoMap[n + 1].language) ? false : ( (n + 2 < kLanguageInfoMapSize) ? CheckLanguageInfoMapOrderConstexpr(n + 1) : true); } static_assert(CheckLanguageInfoMapOrderConstexpr(), "kLanguageInfoMap is not correctly sorted!"); const LanguageInfo* FindLanguageInfoFor(const std::string& language) { const LanguageInfo* begin = kLanguageInfoMap; const LanguageInfo* end = begin + kLanguageInfoMapSize; LanguageInfo key = { language.c_str(), }; const LanguageInfo* probe = std::lower_bound(begin, end, key, LanguageInfo::less); if (probe != end && language == probe->language) { return probe; } return nullptr; } class StaticRE2Array { public: StaticRE2Array() { for (size_t n = 0; n < kLanguageInfoMapSize; ++n) { re2s_[n].ptr = new RE2(kLanguageInfoMap[n].regexp); } } ~StaticRE2Array() { for (auto& entry : re2s_) { delete entry.ptr; } } const RE2PlainPtr* FindMatcherFor(const std::string& language) const { const LanguageInfo* info = FindLanguageInfoFor(language); if (!info) { return nullptr; } size_t idx = info - kLanguageInfoMap; assert(idx < kLanguageInfoMapSize); return &re2s_[idx]; } private: RE2PlainPtr re2s_[kLanguageInfoMapSize]; }; } std::vector<const RE2PlainPtr*> PostBoxMatchers::GetMatchers( const Rule& country_rule) { static const StaticRE2Array kMatchers; std::vector<std::string> languages{"und"}; for (const auto& language_tag : country_rule.GetLanguages()) { Language language(language_tag); languages.push_back(language.base); } std::vector<const RE2PlainPtr*> result; for (const auto& language_tag : languages) { const RE2PlainPtr* matcher = kMatchers.FindMatcherFor(language_tag); if (matcher != nullptr) { result.push_back(matcher); } } return result; } } }
#include "post_box_matchers.h" #include <gtest/gtest.h> #include "rule.h" namespace { using i18n::addressinput::PostBoxMatchers; using i18n::addressinput::Rule; TEST(PostBoxMatchersTest, AlwaysGetMatcherForLanguageUnd) { Rule rule; const auto& matchers = PostBoxMatchers::GetMatchers(rule); EXPECT_EQ(1, matchers.size()); EXPECT_TRUE(matchers[0] != nullptr); } TEST(PostBoxMatchersTest, NoMatcherForInvalidLanguage) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"xx\"}")); const auto& matchers = PostBoxMatchers::GetMatchers(rule); EXPECT_EQ(1, matchers.size()); EXPECT_TRUE(matchers[0] != nullptr); } TEST(PostBoxMatchersTest, HasMatcherForValidLanguage) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"sv\"}")); const auto& matchers = PostBoxMatchers::GetMatchers(rule); EXPECT_EQ(2, matchers.size()); EXPECT_TRUE(matchers[0] != nullptr); EXPECT_TRUE(matchers[1] != nullptr); } TEST(PostBoxMatchersTest, MixValidAndInvalidLanguage) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"xx~sv\"}")); const auto& matchers = PostBoxMatchers::GetMatchers(rule); EXPECT_EQ(2, matchers.size()); EXPECT_TRUE(matchers[0] != nullptr); EXPECT_TRUE(matchers[1] != nullptr); } TEST(PostBoxMatchersTest, UseBaseLanguageForMatching) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"sv-SE\"}")); const auto& matchers = PostBoxMatchers::GetMatchers(rule); EXPECT_EQ(2, matchers.size()); EXPECT_TRUE(matchers[0] != nullptr); EXPECT_TRUE(matchers[1] != nullptr); } TEST(PostBoxMatchersTest, LenientLanguageTagParsing) { Rule rule; ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"SV_SE\"}")); const auto& matchers = PostBoxMatchers::GetMatchers(rule); EXPECT_EQ(2, matchers.size()); EXPECT_TRUE(matchers[0] != nullptr); EXPECT_TRUE(matchers[1] != nullptr); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/post_box_matchers.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/post_box_matchers_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
01ae2344-ebd7-4587-9659-10c56b01874f
cpp
google/libaddressinput
md5
cpp/src/util/md5.cc
cpp/test/util/md5_unittest.cc
#include "md5.h" #include <cstddef> #include <string> #include <string.h> namespace { struct Context { uint32_t buf[4]; uint32_t bits[2]; uint8_t in[64]; }; void byteReverse(uint8_t* buf, unsigned longs) { do { uint32_t temp = static_cast<uint32_t>( static_cast<unsigned>(buf[3]) << 8 | buf[2]) << 16 | (static_cast<unsigned>(buf[1]) << 8 | buf[0]); *reinterpret_cast<uint32_t*>(buf) = temp; buf += 4; } while (--longs); } #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) #define MD5STEP(f, w, x, y, z, data, s) \ (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) void MD5Transform(uint32_t buf[4], const uint32_t in[16]) { uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } } namespace i18n { namespace addressinput { void MD5Init(MD5Context* context) { struct Context* ctx = reinterpret_cast<struct Context*>(context); ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } void MD5Update(MD5Context* context, const std::string& data) { struct Context* ctx = reinterpret_cast<struct Context*>(context); const uint8_t* buf = reinterpret_cast<const uint8_t*>(data.data()); size_t len = data.size(); uint32_t t = ctx->bits[0]; if ((ctx->bits[0] = t + (static_cast<uint32_t>(len) << 3)) < t) ctx->bits[1]++; ctx->bits[1] += static_cast<uint32_t>(len >> 29); t = (t >> 3) & 0x3f; if (t) { uint8_t* p = static_cast<uint8_t*>(ctx->in + t); t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in)); buf += t; len -= t; } while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in)); buf += 64; len -= 64; } memcpy(ctx->in, buf, len); } void MD5Final(MD5Digest* digest, MD5Context* context) { struct Context* ctx = reinterpret_cast<struct Context*>(context); unsigned count; uint8_t* p; count = (ctx->bits[0] >> 3) & 0x3F; p = ctx->in + count; *p++ = 0x80; count = 64 - 1 - count; if (count < 8) { memset(p, 0, count); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in)); memset(ctx->in, 0, 56); } else { memset(p, 0, count - 8); } byteReverse(ctx->in, 14); memcpy(&ctx->in[14 * sizeof(ctx->bits[0])], &ctx->bits[0], sizeof(ctx->bits[0])); memcpy(&ctx->in[15 * sizeof(ctx->bits[1])], &ctx->bits[1], sizeof(ctx->bits[1])); MD5Transform(ctx->buf, reinterpret_cast<uint32_t*>(ctx->in)); byteReverse(reinterpret_cast<uint8_t*>(ctx->buf), 4); memcpy(digest->a, ctx->buf, 16); memset(ctx, 0, sizeof(*ctx)); } void MD5IntermediateFinal(MD5Digest* digest, const MD5Context* context) { MD5Context context_copy; memcpy(&context_copy, context, sizeof(context_copy)); MD5Final(digest, &context_copy); } std::string MD5DigestToBase16(const MD5Digest& digest) { static char const zEncode[] = "0123456789abcdef"; std::string ret; ret.resize(32); for (int i = 0, j = 0; i < 16; i++, j += 2) { uint8_t a = digest.a[i]; ret[j] = zEncode[(a >> 4) & 0xf]; ret[j + 1] = zEncode[a & 0xf]; } return ret; } void MD5Sum(const void* data, size_t length, MD5Digest* digest) { MD5Context ctx; MD5Init(&ctx); MD5Update(&ctx, std::string(reinterpret_cast<const char*>(data), length)); MD5Final(digest, &ctx); } std::string MD5String(const std::string& str) { MD5Digest digest; MD5Sum(str.data(), str.length(), &digest); return MD5DigestToBase16(digest); } } }
#include "util/md5.h" #include <cstring> #include <memory> #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::MD5Context; using i18n::addressinput::MD5Digest; using i18n::addressinput::MD5Init; using i18n::addressinput::MD5String; using i18n::addressinput::MD5Update; TEST(MD5, DigestToBase16) { MD5Digest digest; int data[] = { 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e }; for (int i = 0; i < 16; ++i) digest.a[i] = data[i] & 0xff; std::string actual = MD5DigestToBase16(digest); std::string expected = "d41d8cd98f00b204e9800998ecf8427e"; EXPECT_EQ(expected, actual); } TEST(MD5, MD5SumEmtpyData) { MD5Digest digest; const char data[] = ""; MD5Sum(data, strlen(data), &digest); int expected[] = { 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e }; for (int i = 0; i < 16; ++i) EXPECT_EQ(expected[i], digest.a[i] & 0xFF); } TEST(MD5, MD5SumOneByteData) { MD5Digest digest; const char data[] = "a"; MD5Sum(data, strlen(data), &digest); int expected[] = { 0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61 }; for (int i = 0; i < 16; ++i) EXPECT_EQ(expected[i], digest.a[i] & 0xFF); } TEST(MD5, MD5SumLongData) { const int length = 10 * 1024 * 1024 + 1; std::unique_ptr<char[]> data(new char[length]); for (int i = 0; i < length; ++i) data[i] = i & 0xFF; MD5Digest digest; MD5Sum(data.get(), length, &digest); int expected[] = { 0x90, 0xbd, 0x6a, 0xd9, 0x0a, 0xce, 0xf5, 0xad, 0xaa, 0x92, 0x20, 0x3e, 0x21, 0xc7, 0xa1, 0x3e }; for (int i = 0; i < 16; ++i) EXPECT_EQ(expected[i], digest.a[i] & 0xFF); } TEST(MD5, ContextWithEmptyData) { MD5Context ctx; MD5Init(&ctx); MD5Digest digest; MD5Final(&digest, &ctx); int expected[] = { 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e }; for (int i = 0; i < 16; ++i) EXPECT_EQ(expected[i], digest.a[i] & 0xFF); } TEST(MD5, ContextWithLongData) { MD5Context ctx; MD5Init(&ctx); const int length = 10 * 1024 * 1024 + 1; std::unique_ptr<char[]> data(new char[length]); for (int i = 0; i < length; ++i) data[i] = i & 0xFF; int total = 0; while (total < length) { int len = 4097; if (len > length - total) len = length - total; MD5Update(&ctx, std::string(reinterpret_cast<char*>(data.get() + total), len)); total += len; } EXPECT_EQ(length, total); MD5Digest digest; MD5Final(&digest, &ctx); int expected[] = { 0x90, 0xbd, 0x6a, 0xd9, 0x0a, 0xce, 0xf5, 0xad, 0xaa, 0x92, 0x20, 0x3e, 0x21, 0xc7, 0xa1, 0x3e }; for (int i = 0; i < 16; ++i) EXPECT_EQ(expected[i], digest.a[i] & 0xFF); } TEST(MD5, MD5StringTestSuite1) { std::string actual = MD5String(""); std::string expected = "d41d8cd98f00b204e9800998ecf8427e"; EXPECT_EQ(expected, actual); } TEST(MD5, MD5StringTestSuite2) { std::string actual = MD5String("a"); std::string expected = "0cc175b9c0f1b6a831c399e269772661"; EXPECT_EQ(expected, actual); } TEST(MD5, MD5StringTestSuite3) { std::string actual = MD5String("abc"); std::string expected = "900150983cd24fb0d6963f7d28e17f72"; EXPECT_EQ(expected, actual); } TEST(MD5, MD5StringTestSuite4) { std::string actual = MD5String("message digest"); std::string expected = "f96b697d7cb7938d525a2f31aaf161d0"; EXPECT_EQ(expected, actual); } TEST(MD5, MD5StringTestSuite5) { std::string actual = MD5String("abcdefghijklmnopqrstuvwxyz"); std::string expected = "c3fcd3d76192e4007dfb496cca67e13b"; EXPECT_EQ(expected, actual); } TEST(MD5, MD5StringTestSuite6) { std::string actual = MD5String("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789"); std::string expected = "d174ab98d277d9f5a5611c2c9f419d9f"; EXPECT_EQ(expected, actual); } TEST(MD5, MD5StringTestSuite7) { std::string actual = MD5String("12345678901234567890" "12345678901234567890" "12345678901234567890" "12345678901234567890"); std::string expected = "57edf4a22be3c955ac49da2e2107b67a"; EXPECT_EQ(expected, actual); } TEST(MD5, ContextWithStringData) { MD5Context ctx; MD5Init(&ctx); MD5Update(&ctx, "abc"); MD5Digest digest; MD5Final(&digest, &ctx); std::string actual = MD5DigestToBase16(digest); std::string expected = "900150983cd24fb0d6963f7d28e17f72"; EXPECT_EQ(expected, actual); } TEST(MD5, IntermediateFinal) { MD5Context check_header_context; MD5Init(&check_header_context); MD5Context check_full_context; MD5Init(&check_full_context); MD5Context context; MD5Init(&context); static const char kHeader[] = "header data"; static const char kBody[] = "payload data"; MD5Update(&context, kHeader); MD5Update(&check_header_context, kHeader); MD5Update(&check_full_context, kHeader); MD5Digest check_header_digest; MD5Final(&check_header_digest, &check_header_context); MD5Digest header_digest; MD5IntermediateFinal(&header_digest, &context); MD5Update(&context, kBody); MD5Update(&check_full_context, kBody); MD5Digest check_full_digest; MD5Final(&check_full_digest, &check_full_context); MD5Digest digest; MD5Final(&digest, &context); EXPECT_TRUE(!memcmp(&header_digest, &check_header_digest, sizeof(header_digest))); EXPECT_TRUE(!memcmp(&digest, &check_full_digest, sizeof(digest))); EXPECT_TRUE(memcmp(&digest, &header_digest, sizeof(digest))); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/util/md5.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/util/md5_unittest.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
a2ee7d71-f029-422d-9d19-69394fa2a722
cpp
google/libaddressinput
json
cpp/src/util/json.cc
cpp/test/util/json_test.cc
#include "json.h" #include <cassert> #include <cstddef> #include <memory> #include <string> #include <vector> #include <rapidjson/document.h> #include <rapidjson/reader.h> namespace i18n { namespace addressinput { using rapidjson::Document; using rapidjson::kParseValidateEncodingFlag; using rapidjson::Value; class Json::JsonImpl { public: JsonImpl(const JsonImpl&) = delete; JsonImpl& operator=(const JsonImpl&) = delete; explicit JsonImpl(const std::string& json) : document_(new Document), value_(document_.get()), dictionaries_(), valid_(false) { document_->Parse<kParseValidateEncodingFlag>(json.c_str()); valid_ = !document_->HasParseError() && document_->IsObject(); } ~JsonImpl() { for (auto ptr : dictionaries_) { delete ptr; } } bool valid() const { return valid_; } const std::vector<const Json*>& GetSubDictionaries() { if (dictionaries_.empty()) { for (Value::ConstMemberIterator member = value_->MemberBegin(); member != value_->MemberEnd(); ++member) { if (member->value.IsObject()) { dictionaries_.push_back(new Json(new JsonImpl(&member->value))); } } } return dictionaries_; } bool GetStringValueForKey(const std::string& key, std::string* value) const { assert(value != nullptr); Value::ConstMemberIterator member = value_->FindMember(key.c_str()); if (member == value_->MemberEnd() || !member->value.IsString()) { return false; } value->assign(member->value.GetString(), member->value.GetStringLength()); return true; } private: explicit JsonImpl(const Value* value) : document_(), value_(value), dictionaries_(), valid_(true) { assert(value_ != nullptr); assert(value_->IsObject()); } const std::unique_ptr<Document> document_; const Value* const value_; std::vector<const Json*> dictionaries_; bool valid_; }; Json::Json() : impl_() {} Json::~Json() = default; bool Json::ParseObject(const std::string& json) { assert(impl_ == nullptr); impl_.reset(new JsonImpl(json)); if (!impl_->valid()) { impl_.reset(); } return impl_ != nullptr; } const std::vector<const Json*>& Json::GetSubDictionaries() const { assert(impl_ != nullptr); return impl_->GetSubDictionaries(); } bool Json::GetStringValueForKey(const std::string& key, std::string* value) const { assert(impl_ != nullptr); return impl_->GetStringValueForKey(key, value); } Json::Json(JsonImpl* impl) : impl_(impl) {} } }
#include "util/json.h" #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::Json; TEST(JsonTest, EmptyStringIsNotValid) { Json json; EXPECT_FALSE(json.ParseObject(std::string())); } TEST(JsonTest, EmptyDictionaryContainsNoKeys) { Json json; ASSERT_TRUE(json.ParseObject("{}")); std::string not_checked; EXPECT_FALSE(json.GetStringValueForKey("key", &not_checked)); EXPECT_FALSE(json.GetStringValueForKey(std::string(), &not_checked)); } TEST(JsonTest, InvalidJsonIsNotValid) { Json json; EXPECT_FALSE(json.ParseObject("{")); } TEST(JsonTest, OneKeyIsValid) { Json json; ASSERT_TRUE(json.ParseObject(R"({"key": "value"})")); std::string value; EXPECT_TRUE(json.GetStringValueForKey("key", &value)); EXPECT_EQ("value", value); } TEST(JsonTest, EmptyStringKeyIsNotInObject) { Json json; ASSERT_TRUE(json.ParseObject(R"({"key": "value"})")); std::string not_checked; EXPECT_FALSE(json.GetStringValueForKey(std::string(), &not_checked)); } TEST(JsonTest, EmptyKeyIsValid) { Json json; ASSERT_TRUE(json.ParseObject(R"({"": "value"})")); std::string value; EXPECT_TRUE(json.GetStringValueForKey(std::string(), &value)); EXPECT_EQ("value", value); } TEST(JsonTest, EmptyValueIsValid) { Json json; ASSERT_TRUE(json.ParseObject(R"({"key": ""})")); std::string value; EXPECT_TRUE(json.GetStringValueForKey("key", &value)); EXPECT_TRUE(value.empty()); } TEST(JsonTest, Utf8EncodingIsValid) { Json json; ASSERT_TRUE(json.ParseObject(R"({"key": "Ü"})")); std::string value; EXPECT_TRUE(json.GetStringValueForKey("key", &value)); EXPECT_EQ("Ü", value); } TEST(JsonTest, InvalidUtf8IsNotValid) { Json json; EXPECT_FALSE(json.ParseObject("{\"key\": \"\xC3\x28\"}")); } TEST(JsonTest, NullInMiddleIsNotValid) { Json json; static const char kJson[] = "{\"key\": \"val\0ue\"}"; EXPECT_FALSE(json.ParseObject(std::string(kJson, sizeof kJson - 1))); } TEST(JsonTest, TwoKeysAreValid) { Json json; ASSERT_TRUE(json.ParseObject(R"({"key1": "value1", "key2": "value2"})")); std::string value; EXPECT_TRUE(json.GetStringValueForKey("key1", &value)); EXPECT_EQ("value1", value); EXPECT_TRUE(json.GetStringValueForKey("key2", &value)); EXPECT_EQ("value2", value); } TEST(JsonTest, ListIsNotValid) { Json json; EXPECT_FALSE(json.ParseObject("[]")); } TEST(JsonTest, StringIsNotValid) { Json json; EXPECT_FALSE(json.ParseObject(R"("value")")); } TEST(JsonTest, NumberIsNotValid) { Json json; EXPECT_FALSE(json.ParseObject("3")); } TEST(JsonTest, NoDictionaryFound) { Json json; ASSERT_TRUE(json.ParseObject(R"({"key":"value"})")); EXPECT_TRUE(json.GetSubDictionaries().empty()); } TEST(JsonTest, DictionaryFound) { Json json; ASSERT_TRUE(json.ParseObject(R"({"key":{"inner_key":"value"}})")); const auto& sub_dicts = json.GetSubDictionaries(); ASSERT_EQ(1U, sub_dicts.size()); std::string value; EXPECT_TRUE(sub_dicts.front()->GetStringValueForKey("inner_key", &value)); EXPECT_EQ("value", value); } TEST(JsonTest, DictionariesHaveSubDictionaries) { Json json; ASSERT_TRUE(json.ParseObject( R"({"key":{"inner_key":{"inner_inner_key":"value"}}})")); const auto& sub_dicts = json.GetSubDictionaries(); ASSERT_EQ(1U, sub_dicts.size()); const auto& sub_sub_dicts = sub_dicts.front()->GetSubDictionaries(); ASSERT_EQ(1U, sub_sub_dicts.size()); std::string value; EXPECT_TRUE( sub_sub_dicts.front()->GetStringValueForKey("inner_inner_key", &value)); EXPECT_EQ("value", value); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/util/json.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/util/json_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
a0a5c0c3-6389-4956-96d2-7c74e77154df
cpp
google/libaddressinput
string_split
cpp/src/util/string_split.cc
cpp/test/util/string_split_unittest.cc
#include "string_split.h" #include <cassert> #include <cstddef> #include <string> #include <vector> namespace i18n { namespace addressinput { void SplitString(const std::string& str, char s, std::vector<std::string>* r) { assert(r != nullptr); r->clear(); size_t last = 0; size_t c = str.size(); for (size_t i = 0; i <= c; ++i) { if (i == c || str[i] == s) { std::string tmp(str, last, i - last); if (i != c || !r->empty() || !tmp.empty()) { r->push_back(tmp); } last = i + 1; } } } } }
#include "util/string_split.h" #include <string> #include <vector> #include <gtest/gtest.h> namespace { using i18n::addressinput::SplitString; TEST(StringSplitTest, SplitString) { std::vector<std::string> r; SplitString(std::string(), ',', &r); EXPECT_EQ(0U, r.size()); SplitString("a,b,c", ',', &r); ASSERT_EQ(3U, r.size()); EXPECT_EQ(r[0], "a"); EXPECT_EQ(r[1], "b"); EXPECT_EQ(r[2], "c"); SplitString("a, b, c", ',', &r); ASSERT_EQ(3U, r.size()); EXPECT_EQ(r[0], "a"); EXPECT_EQ(r[1], " b"); EXPECT_EQ(r[2], " c"); SplitString("a,,c", ',', &r); ASSERT_EQ(3U, r.size()); EXPECT_EQ(r[0], "a"); EXPECT_EQ(r[1], ""); EXPECT_EQ(r[2], "c"); SplitString(" ", '*', &r); EXPECT_EQ(1U, r.size()); SplitString("foo", '*', &r); ASSERT_EQ(1U, r.size()); EXPECT_EQ(r[0], "foo"); SplitString("foo ,", ',', &r); ASSERT_EQ(2U, r.size()); EXPECT_EQ(r[0], "foo "); EXPECT_EQ(r[1], ""); SplitString(",", ',', &r); ASSERT_EQ(2U, r.size()); EXPECT_EQ(r[0], ""); EXPECT_EQ(r[1], ""); SplitString("\t\ta\t", '\t', &r); ASSERT_EQ(4U, r.size()); EXPECT_EQ(r[0], ""); EXPECT_EQ(r[1], ""); EXPECT_EQ(r[2], "a"); EXPECT_EQ(r[3], ""); SplitString("\ta\t\nb\tcc", '\n', &r); ASSERT_EQ(2U, r.size()); EXPECT_EQ(r[0], "\ta\t"); EXPECT_EQ(r[1], "b\tcc"); SplitString(" ", '*', &r); ASSERT_EQ(1U, r.size()); EXPECT_EQ(r[0], " "); SplitString("\t \ta\t ", '\t', &r); ASSERT_EQ(4U, r.size()); EXPECT_EQ(r[0], ""); EXPECT_EQ(r[1], " "); EXPECT_EQ(r[2], "a"); EXPECT_EQ(r[3], " "); SplitString("\ta\t\nb\tcc", '\n', &r); ASSERT_EQ(2U, r.size()); EXPECT_EQ(r[0], "\ta\t"); EXPECT_EQ(r[1], "b\tcc"); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/util/string_split.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/util/string_split_unittest.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
ef1402fc-707f-440d-bf71-7892e6bea482
cpp
google/libaddressinput
string_util
cpp/src/util/string_util.cc
cpp/test/util/string_util_test.cc
#include "string_util.h" #include <cassert> #include <cstddef> #include <stdint.h> #include <string> #include <vector> namespace i18n { namespace addressinput { std::string DoReplaceStringPlaceholders(const std::string& format_string, const std::vector<std::string>& subst) { size_t substitutions = subst.size(); size_t sub_length = 0; for (std::vector<std::string>::const_iterator iter = subst.begin(); iter != subst.end(); ++iter) { sub_length += iter->length(); } std::string formatted; formatted.reserve(format_string.length() + sub_length); for (std::string::const_iterator i = format_string.begin(); i != format_string.end(); ++i) { if ('$' == *i) { if (i + 1 != format_string.end()) { ++i; assert('$' == *i || '1' <= *i); if ('$' == *i) { while (i != format_string.end() && '$' == *i) { formatted.push_back('$'); ++i; } --i; } else { uintptr_t index = 0; while (i != format_string.end() && '0' <= *i && *i <= '9') { index *= 10; index += *i - '0'; ++i; } --i; index -= 1; if (index < substitutions) formatted.append(subst.at(index)); } } } else { formatted.push_back(*i); } } return formatted; } } }
#include "util/string_util.h" #include <string> #include <vector> #include <gtest/gtest.h> namespace { using i18n::addressinput::DoReplaceStringPlaceholders; TEST(StringUtilTest, Ok) { const std::vector<std::string> subst{ "A", "B", "C", }; EXPECT_EQ("aA,bB,cC", DoReplaceStringPlaceholders("a$1,b$2,c$3", subst)); } TEST(StringUtilTest, FewParameters) { const std::vector<std::string> subst{ "A", "B", "C", }; EXPECT_EQ("aA,bB,cC,d,aA", DoReplaceStringPlaceholders("a$1,b$2,c$3,d$4,a$1", subst)); } TEST(StringUtilTest, MoreThan9Parameters) { const std::vector<std::string> subst{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", }; EXPECT_EQ("aA,bB,cC,dD,eE,fF,gG,hH,iI,jJ,kK,aA", DoReplaceStringPlaceholders("a$1,b$2,c$3,d$4,e$5,f$6,g$7,h$8,i$9," "j$10,k$11,a$1", subst)); } TEST(StringUtilTest, ConsecutiveDollarSigns) { const std::vector<std::string> subst{ "A", "B", "C", }; EXPECT_EQ("$1 $$2 $$$3", DoReplaceStringPlaceholders("$$1 $$$2 $$$$3", subst)); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/util/string_util.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/util/string_util_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
192067b9-dcb3-4c41-ba76-bea5ade8ddb1
cpp
google/libaddressinput
string_compare
cpp/src/util/string_compare.cc
cpp/test/util/string_compare_test.cc
#include "string_compare.h" #include <cassert> #include <string> #include <re2/re2.h> #include "lru_cache_using_std.h" namespace { std::string ComputeMinPossibleMatch(const std::string& str) { std::string min, max; RE2::Options options; options.set_literal(true); options.set_case_sensitive(false); RE2 matcher(str, options); bool success = matcher.PossibleMatchRange(&min, &max, str.size()); assert(success); (void)success; return min; } } namespace i18n { namespace addressinput { class StringCompare::Impl { enum { MAX_CACHE_SIZE = 1 << 15 }; public: Impl(const Impl&) = delete; Impl& operator=(const Impl&) = delete; Impl() : min_possible_match_(&ComputeMinPossibleMatch, MAX_CACHE_SIZE) { options_.set_literal(true); options_.set_case_sensitive(false); } ~Impl() = default; bool NaturalEquals(const std::string& a, const std::string& b) const { RE2 matcher(b, options_); return RE2::FullMatch(a, matcher); } bool NaturalLess(const std::string& a, const std::string& b) const { const std::string& min_a(min_possible_match_(a)); const std::string& min_b(min_possible_match_(b)); return min_a < min_b; } private: RE2::Options options_; mutable lru_cache_using_std<std::string, std::string> min_possible_match_; }; StringCompare::StringCompare() : impl_(new Impl) {} StringCompare::~StringCompare() = default; bool StringCompare::NaturalEquals(const std::string& a, const std::string& b) const { return impl_->NaturalEquals(a, b); } bool StringCompare::NaturalLess(const std::string& a, const std::string& b) const { return impl_->NaturalLess(a, b); } } }
#include "util/string_compare.h" #include <string> #include <gtest/gtest.h> namespace { using i18n::addressinput::StringCompare; struct TestCase { TestCase(const std::string& left, const std::string& right, bool should_be_equal, bool should_be_less) : left(left), right(right), should_be_equal(should_be_equal), should_be_less(should_be_less) {} ~TestCase() = default; std::string left; std::string right; bool should_be_equal; bool should_be_less; }; class StringCompareTest : public testing::TestWithParam<TestCase> { public: StringCompareTest(const StringCompareTest&) = delete; StringCompareTest& operator=(const StringCompareTest&) = delete; protected: StringCompareTest() = default; StringCompare compare_; }; TEST_P(StringCompareTest, CorrectComparison) { if (GetParam().should_be_equal) { EXPECT_TRUE(compare_.NaturalEquals(GetParam().left, GetParam().right)); } else { EXPECT_FALSE(compare_.NaturalEquals(GetParam().left, GetParam().right)); } } TEST_P(StringCompareTest, CorrectLess) { if (GetParam().should_be_less) { EXPECT_TRUE(compare_.NaturalLess(GetParam().left, GetParam().right)); } else { EXPECT_FALSE(compare_.NaturalLess(GetParam().left, GetParam().right)); } } INSTANTIATE_TEST_SUITE_P( Comparisons, StringCompareTest, testing::Values(TestCase("foo", "foo", true, false), TestCase("foo", "FOO", true, false), TestCase("bar", "foo", false, true), TestCase("강원도", "강원도", true, false), TestCase("강원도", "대구광역시", false, true), TestCase("ZÜRICH", "zürich", true, false), TestCase("абв", "где", false, true), TestCase("абв", "ГДЕ", false, true), TestCase("где", "абв", false, false), TestCase("где", "АБВ", false, false))); }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/src/util/string_compare.cc
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/util/string_compare_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
73972d77-4a96-4dd2-9317-ea35ef86c645
cpp
google/libaddressinput
supplier
cpp/include/libaddressinput/supplier.h
cpp/test/supplier_test.cc
#ifndef I18N_ADDRESSINPUT_SUPPLIER_H_ #define I18N_ADDRESSINPUT_SUPPLIER_H_ #include <libaddressinput/callback.h> #include <string> namespace i18n { namespace addressinput { class LookupKey; class Rule; class Supplier { public: struct RuleHierarchy; using Callback = i18n::addressinput::Callback<const LookupKey&, const RuleHierarchy&>; virtual ~Supplier() = default; virtual void Supply(const LookupKey& lookup_key, const Callback& supplied) = 0; virtual void SupplyGlobally(const LookupKey& lookup_key, const Callback& supplied) = 0; virtual size_t GetLoadedRuleDepth(const std::string& region_code) const { return 0; } struct RuleHierarchy { RuleHierarchy() : rule() {} const Rule* rule[4]; }; }; } } #endif
#include <libaddressinput/supplier.h> #include <libaddressinput/address_data.h> #include <libaddressinput/callback.h> #include <libaddressinput/null_storage.h> #include <libaddressinput/ondemand_supplier.h> #include <libaddressinput/preload_supplier.h> #include <cstddef> #include <cstring> #include <memory> #include <string> #include <gtest/gtest.h> #include "lookup_key.h" #include "rule.h" #include "testdata_source.h" #include "util/size.h" namespace { using i18n::addressinput::AddressData; using i18n::addressinput::BuildCallback; using i18n::addressinput::LookupKey; using i18n::addressinput::NullStorage; using i18n::addressinput::OndemandSupplier; using i18n::addressinput::PreloadSupplier; using i18n::addressinput::Rule; using i18n::addressinput::Supplier; using i18n::addressinput::TestdataSource; class SupplierWrapper { public: virtual ~SupplierWrapper() = default; virtual void Supply(const LookupKey& lookup_key, const Supplier::Callback& supplied) = 0; }; class OndemandSupplierWrapper : public SupplierWrapper { public: OndemandSupplierWrapper(const OndemandSupplierWrapper&) = delete; OndemandSupplierWrapper& operator=(const OndemandSupplierWrapper&) = delete; static SupplierWrapper* Build() { return new OndemandSupplierWrapper; } void Supply(const LookupKey& lookup_key, const Supplier::Callback& supplied) override { ondemand_supplier_.Supply(lookup_key, supplied); } private: OndemandSupplierWrapper() : ondemand_supplier_(new TestdataSource(false), new NullStorage) {} OndemandSupplier ondemand_supplier_; }; class PreloadSupplierWrapper : public SupplierWrapper { public: PreloadSupplierWrapper(const PreloadSupplierWrapper&) = delete; PreloadSupplierWrapper& operator=(const PreloadSupplierWrapper&) = delete; static SupplierWrapper* Build() { return new PreloadSupplierWrapper; } void Supply(const LookupKey& lookup_key, const Supplier::Callback& supplied) override { const std::string& region_code = lookup_key.GetRegionCode(); if (!region_code.empty() && !preload_supplier_.IsLoaded(region_code)) { preload_supplier_.LoadRules(region_code, *loaded_); } preload_supplier_.Supply(lookup_key, supplied); } private: PreloadSupplierWrapper() : preload_supplier_(new TestdataSource(true), new NullStorage), loaded_(BuildCallback(this, &PreloadSupplierWrapper::Loaded)) {} void Loaded(bool success, const std::string&, int) { ASSERT_TRUE(success); } PreloadSupplier preload_supplier_; const std::unique_ptr<const PreloadSupplier::Callback> loaded_; }; class SupplierTest : public testing::TestWithParam<SupplierWrapper* (*)()> { public: SupplierTest(const SupplierTest&) = delete; SupplierTest& operator=(const SupplierTest&) = delete; protected: SupplierTest() : address_(), rule_(), called_(false), lookup_key_(), supplier_wrapper_((*GetParam())()), supplied_(BuildCallback(this, &SupplierTest::Supplied)) {} void Supply() { lookup_key_.FromAddress(address_); supplier_wrapper_->Supply(lookup_key_, *supplied_); } AddressData address_; const Rule* rule_[size(LookupKey::kHierarchy)]; bool called_; private: void Supplied(bool success, const LookupKey& lookup_key, const Supplier::RuleHierarchy& hierarchy) { ASSERT_TRUE(success); ASSERT_EQ(&lookup_key_, &lookup_key); std::memcpy(rule_, hierarchy.rule, sizeof rule_); called_ = true; } LookupKey lookup_key_; const std::unique_ptr<SupplierWrapper> supplier_wrapper_; const std::unique_ptr<const Supplier::Callback> supplied_; }; INSTANTIATE_TEST_SUITE_P(OndemandSupplier, SupplierTest, testing::Values(&OndemandSupplierWrapper::Build)); INSTANTIATE_TEST_SUITE_P(PreloadSupplier, SupplierTest, testing::Values(&PreloadSupplierWrapper::Build)); TEST_P(SupplierTest, Invalid) { address_ = {.region_code = "QZ"}; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] == nullptr); EXPECT_TRUE(rule_[1] == nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_P(SupplierTest, Valid) { address_ = {.region_code = "SE"}; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] == nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); EXPECT_EQ("data/SE", rule_[0]->GetId()); EXPECT_FALSE(rule_[0]->GetRequired().empty()); EXPECT_FALSE(rule_[0]->GetFormat().empty()); EXPECT_TRUE(rule_[0]->GetPostalCodeMatcher() != nullptr); } TEST_P(SupplierTest, KeyDepthEqualsMaxDepth) { address_ = { .region_code = "HK", .administrative_area = "九龍", }; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] != nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_P(SupplierTest, KeyDepthLargerThanMaxDepth) { address_ = { .region_code = "HK", .administrative_area = "九龍", .locality = "bbb", }; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] != nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_P(SupplierTest, KeyDepthSmallerThanMaxDepth) { address_ = {.region_code = "HK"}; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] == nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_P(SupplierTest, KeyDepth0) { address_ = {.region_code = "CN"}; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] == nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_P(SupplierTest, KeyDepth1) { address_ = { .region_code = "CN", .administrative_area = "新疆维吾尔自治区", }; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] != nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_P(SupplierTest, KeyDepth2) { address_ = { .region_code = "CN", .administrative_area = "新疆维吾尔自治区", .locality = "喀什地区", }; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] != nullptr); EXPECT_TRUE(rule_[2] != nullptr); EXPECT_TRUE(rule_[3] == nullptr); } TEST_P(SupplierTest, KeyDepth3) { address_ = { .region_code = "CN", .administrative_area = "新疆维吾尔自治区", .locality = "喀什地区", .dependent_locality = "喀什市", }; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] != nullptr); EXPECT_TRUE(rule_[2] != nullptr); EXPECT_TRUE(rule_[3] != nullptr); } TEST_P(SupplierTest, RuleCache) { address_ = { .region_code = "US", .administrative_area = "CA", }; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_TRUE(rule_[0] != nullptr); EXPECT_TRUE(rule_[1] != nullptr); EXPECT_TRUE(rule_[2] == nullptr); EXPECT_TRUE(rule_[3] == nullptr); const Rule* rule[size(LookupKey::kHierarchy)]; std::memcpy(rule, rule_, sizeof rule); called_ = false; ASSERT_NO_FATAL_FAILURE(Supply()); ASSERT_TRUE(called_); EXPECT_EQ(rule[0], rule_[0]); EXPECT_EQ(rule[1], rule_[1]); EXPECT_EQ(rule[2], rule_[2]); EXPECT_EQ(rule[3], rule_[3]); } }
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/include/libaddressinput/supplier.h
https://github.com/google/libaddressinput/blob/2610f7b1043d6784ada41392fc9392d1ea09ea07/cpp/test/supplier_test.cc
2610f7b1043d6784ada41392fc9392d1ea09ea07
3cc6f1dd-b9a5-40e3-8a3b-8fd2c90fa35c
cpp
abseil/abseil-cpp
match
absl/strings/match.cc
absl/strings/match_test.cc
#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"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/match.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/match_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
665eee65-107c-4ecb-aba4-6b8f68295dca
cpp
abseil/abseil-cpp
cord_buffer
absl/strings/cord_buffer.cc
absl/strings/cord_buffer_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/cord_buffer.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/cord_buffer_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ff8b0f41-e158-42d4-9735-cdca12d747b8
cpp
abseil/abseil-cpp
string_view
absl/strings/string_view.cc
absl/strings/string_view_test.cc
#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 (rpad) WritePadding(o, rpad); o.width(0); } return o; } string_view::size_type string_view::find(string_view s, size_type pos) const noexcept { if (empty() || pos > length_) { if (empty() && pos == 0 && s.empty()) return 0; return npos; } const char* result = memmatch(ptr_ + pos, length_ - pos, s.ptr_, s.length_); return result ? static_cast<size_type>(result - ptr_) : npos; } string_view::size_type string_view::find(char c, size_type pos) const noexcept { if (empty() || pos >= length_) { return npos; } const char* result = static_cast<const char*>(memchr(ptr_ + pos, c, length_ - pos)); return result != nullptr ? static_cast<size_type>(result - ptr_) : npos; } string_view::size_type string_view::rfind(string_view s, size_type pos) const noexcept { if (length_ < s.length_) return npos; if (s.empty()) return std::min(length_, pos); const char* last = ptr_ + std::min(length_ - s.length_, pos) + s.length_; const char* result = std::find_end(ptr_, last, s.ptr_, s.ptr_ + s.length_); return result != last ? static_cast<size_type>(result - ptr_) : npos; } string_view::size_type string_view::rfind(char c, size_type pos) const noexcept { if (empty()) return npos; for (size_type i = std::min(pos, length_ - 1);; --i) { if (ptr_[i] == c) { return i; } if (i == 0) break; } return npos; } string_view::size_type string_view::find_first_of( string_view s, size_type pos) const noexcept { if (empty() || s.empty()) { return npos; } if (s.length_ == 1) return find_first_of(s.ptr_[0], pos); LookupTable tbl(s); for (size_type i = pos; i < length_; ++i) { if (tbl[ptr_[i]]) { return i; } } return npos; } string_view::size_type string_view::find_first_not_of( string_view s, size_type pos) const noexcept { if (empty()) return npos; if (s.length_ == 1) return find_first_not_of(s.ptr_[0], pos); LookupTable tbl(s); for (size_type i = pos; i < length_; ++i) { if (!tbl[ptr_[i]]) { return i; } } return npos; } string_view::size_type string_view::find_first_not_of( char c, size_type pos) const noexcept { if (empty()) return npos; for (; pos < length_; ++pos) { if (ptr_[pos] != c) { return pos; } } return npos; } string_view::size_type string_view::find_last_of(string_view s, size_type pos) const noexcept { if (empty() || s.empty()) return npos; if (s.length_ == 1) return find_last_of(s.ptr_[0], pos); LookupTable tbl(s); for (size_type i = std::min(pos, length_ - 1);; --i) { if (tbl[ptr_[i]]) { return i; } if (i == 0) break; } return npos; } string_view::size_type string_view::find_last_not_of( string_view s, size_type pos) const noexcept { if (empty()) return npos; size_type i = std::min(pos, length_ - 1); if (s.empty()) return i; if (s.length_ == 1) return find_last_not_of(s.ptr_[0], pos); LookupTable tbl(s); for (;; --i) { if (!tbl[ptr_[i]]) { return i; } if (i == 0) break; } return npos; } string_view::size_type string_view::find_last_not_of( char c, size_type pos) const noexcept { if (empty()) return npos; size_type i = std::min(pos, length_ - 1); for (;; --i) { if (ptr_[i] != c) { return i; } if (i == 0) break; } return npos; } #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr string_view::size_type string_view::npos; constexpr string_view::size_type string_view::kMaxSize; #endif ABSL_NAMESPACE_END } #else #ifdef __APPLE__ namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { extern const char kAvoidEmptyStringViewLibraryWarning; const char kAvoidEmptyStringViewLibraryWarning = 0; } ABSL_NAMESPACE_END } #endif #endif
#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 char* null_str = nullptr; s = absl::string_view(null_str); 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(StringViewTest, StartsWith) { const absl::string_view a("foobar"); const absl::string_view b("123\0abc", 7); const absl::string_view e; EXPECT_TRUE(a.starts_with(a)); EXPECT_TRUE(a.starts_with("foo")); EXPECT_TRUE(a.starts_with('f')); EXPECT_TRUE(a.starts_with(e)); EXPECT_TRUE(b.starts_with(b)); EXPECT_TRUE(b.starts_with('1')); EXPECT_TRUE(b.starts_with(e)); EXPECT_TRUE(e.starts_with("")); EXPECT_FALSE(a.starts_with(b)); EXPECT_FALSE(b.starts_with(a)); EXPECT_FALSE(e.starts_with(a)); EXPECT_FALSE(a.starts_with('r')); EXPECT_FALSE(a.starts_with('\0')); EXPECT_FALSE(e.starts_with('r')); EXPECT_FALSE(e.starts_with('\0')); constexpr absl::string_view kFooBar("foobar"); constexpr absl::string_view kFoo("foo"); constexpr absl::string_view kBar("bar"); constexpr bool k1 = kFooBar.starts_with(kFoo); EXPECT_TRUE(k1); constexpr bool k2 = kFooBar.starts_with(kBar); EXPECT_FALSE(k2); constexpr bool k3 = kFooBar.starts_with('f'); EXPECT_TRUE(k3); constexpr bool k4 = kFooBar.starts_with("fo"); EXPECT_TRUE(k4); } TEST(StringViewTest, EndsWith) { const absl::string_view a("foobar"); const absl::string_view b("123\0abc", 7); const absl::string_view e; EXPECT_TRUE(a.ends_with(a)); EXPECT_TRUE(a.ends_with('r')); EXPECT_TRUE(a.ends_with("bar")); EXPECT_TRUE(a.ends_with(e)); EXPECT_TRUE(b.ends_with(b)); EXPECT_TRUE(b.ends_with('c')); EXPECT_TRUE(b.ends_with(e)); EXPECT_TRUE(e.ends_with("")); EXPECT_FALSE(a.ends_with(b)); EXPECT_FALSE(b.ends_with(a)); EXPECT_FALSE(e.ends_with(a)); EXPECT_FALSE(a.ends_with('f')); EXPECT_FALSE(a.ends_with('\0')); EXPECT_FALSE(e.ends_with('r')); EXPECT_FALSE(e.ends_with('\0')); constexpr absl::string_view kFooBar("foobar"); constexpr absl::string_view kFoo("foo"); constexpr absl::string_view kBar("bar"); constexpr bool k1 = kFooBar.ends_with(kFoo); EXPECT_FALSE(k1); constexpr bool k2 = kFooBar.ends_with(kBar); EXPECT_TRUE(k2); constexpr bool k3 = kFooBar.ends_with('r'); EXPECT_TRUE(k3); constexpr bool k4 = kFooBar.ends_with("ar"); EXPECT_TRUE(k4); } #endif struct MyCharAlloc : std::allocator<char> {}; TEST(StringViewTest, ExplicitConversionOperator) { absl::string_view sp = "hi"; EXPECT_EQ(sp, std::string(sp)); } TEST(StringViewTest, NullSafeStringView) { { absl::string_view s = absl::NullSafeStringView(nullptr); EXPECT_EQ(nullptr, s.data()); EXPECT_EQ(0u, s.size()); EXPECT_EQ(absl::string_view(), s); } { static const char kHi[] = "hi"; absl::string_view s = absl::NullSafeStringView(kHi); EXPECT_EQ(kHi, s.data()); EXPECT_EQ(strlen(kHi), s.size()); EXPECT_EQ(absl::string_view("hi"), s); } } TEST(StringViewTest, ConstexprNullSafeStringView) { { constexpr absl::string_view s = absl::NullSafeStringView(nullptr); EXPECT_EQ(nullptr, s.data()); EXPECT_EQ(0u, s.size()); EXPECT_EQ(absl::string_view(), s); } { static constexpr char kHi[] = "hi"; absl::string_view s = absl::NullSafeStringView(kHi); EXPECT_EQ(kHi, s.data()); EXPECT_EQ(strlen(kHi), s.size()); EXPECT_EQ(absl::string_view("hi"), s); } { constexpr absl::string_view s = absl::NullSafeStringView("hello"); EXPECT_EQ(s.size(), 5u); EXPECT_EQ("hello", s); } } TEST(StringViewTest, ConstexprCompiles) { constexpr absl::string_view sp; #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnonnull" #endif #ifdef ABSL_HAVE_STRING_VIEW_FROM_NULLPTR constexpr absl::string_view cstr(nullptr); #endif #if defined(__clang__) #pragma clang diagnostic pop #endif constexpr absl::string_view cstr_len("cstr", 4); #if defined(ABSL_USES_STD_STRING_VIEW) #if !defined(__GLIBCXX__) #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR 1 #endif #else #if ABSL_HAVE_BUILTIN(__builtin_strlen) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR 1 #elif defined(__GNUC__) #error GCC/clang should have constexpr string_view. #endif #if defined(_MSC_VER) && _MSC_VER >= 1910 #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR 1 #endif #endif #ifdef ABSL_HAVE_CONSTEXPR_STRING_VIEW_FROM_CSTR constexpr absl::string_view cstr_strlen("foo"); EXPECT_EQ(cstr_strlen.length(), 3u); constexpr absl::string_view cstr_strlen2 = "bar"; EXPECT_EQ(cstr_strlen2, "bar"); #if ABSL_HAVE_BUILTIN(__builtin_memcmp) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_HAVE_CONSTEXPR_STRING_VIEW_COMPARISON 1 #endif #ifdef ABSL_HAVE_CONSTEXPR_STRING_VIEW_COMPARISON constexpr absl::string_view foo = "foo"; constexpr absl::string_view bar = "bar"; constexpr bool foo_eq_bar = foo == bar; constexpr bool foo_ne_bar = foo != bar; constexpr bool foo_lt_bar = foo < bar; constexpr bool foo_le_bar = foo <= bar; constexpr bool foo_gt_bar = foo > bar; constexpr bool foo_ge_bar = foo >= bar; constexpr int foo_compare_bar = foo.compare(bar); EXPECT_FALSE(foo_eq_bar); EXPECT_TRUE(foo_ne_bar); EXPECT_FALSE(foo_lt_bar); EXPECT_FALSE(foo_le_bar); EXPECT_TRUE(foo_gt_bar); EXPECT_TRUE(foo_ge_bar); EXPECT_GT(foo_compare_bar, 0); #endif #endif #if !defined(__clang__) || 3 < __clang_major__ || \ (3 == __clang_major__ && 4 < __clang_minor__) constexpr absl::string_view::iterator const_begin_empty = sp.begin(); constexpr absl::string_view::iterator const_end_empty = sp.end(); EXPECT_EQ(const_begin_empty, const_end_empty); #ifdef ABSL_HAVE_STRING_VIEW_FROM_NULLPTR constexpr absl::string_view::iterator const_begin_nullptr = cstr.begin(); constexpr absl::string_view::iterator const_end_nullptr = cstr.end(); EXPECT_EQ(const_begin_nullptr, const_end_nullptr); #endif #endif constexpr absl::string_view::iterator const_begin = cstr_len.begin(); constexpr absl::string_view::iterator const_end = cstr_len.end(); constexpr absl::string_view::size_type const_size = cstr_len.size(); constexpr absl::string_view::size_type const_length = cstr_len.length(); static_assert(const_begin + const_size == const_end, "pointer arithmetic check"); static_assert(const_begin + const_length == const_end, "pointer arithmetic check"); #ifndef _MSC_VER EXPECT_EQ(const_begin + const_size, const_end); EXPECT_EQ(const_begin + const_length, const_end); #endif constexpr bool isempty = sp.empty(); EXPECT_TRUE(isempty); constexpr const char c = cstr_len[2]; EXPECT_EQ(c, 't'); constexpr const char cfront = cstr_len.front(); constexpr const char cback = cstr_len.back(); EXPECT_EQ(cfront, 'c'); EXPECT_EQ(cback, 'r'); constexpr const char* np = sp.data(); constexpr const char* cstr_ptr = cstr_len.data(); EXPECT_EQ(np, nullptr); EXPECT_NE(cstr_ptr, nullptr); constexpr size_t sp_npos = sp.npos; EXPECT_EQ(sp_npos, static_cast<size_t>(-1)); } constexpr char ConstexprMethodsHelper() { #if defined(__cplusplus) && __cplusplus >= 201402L absl::string_view str("123", 3); str.remove_prefix(1); str.remove_suffix(1); absl::string_view bar; str.swap(bar); return bar.front(); #else return '2'; #endif } TEST(StringViewTest, ConstexprMethods) { static_assert(ConstexprMethodsHelper() == '2', ""); constexpr absl::string_view foobar("foobar", 6); constexpr absl::string_view foo = foobar.substr(0, 3); constexpr absl::string_view bar = foobar.substr(3); EXPECT_EQ(foo, "foo"); EXPECT_EQ(bar, "bar"); } TEST(StringViewTest, Noexcept) { EXPECT_TRUE((std::is_nothrow_constructible<absl::string_view, const std::string&>::value)); EXPECT_TRUE((std::is_nothrow_constructible<absl::string_view, const std::string&>::value)); EXPECT_TRUE(std::is_nothrow_constructible<absl::string_view>::value); constexpr absl::string_view sp; EXPECT_TRUE(noexcept(sp.begin())); EXPECT_TRUE(noexcept(sp.end())); EXPECT_TRUE(noexcept(sp.cbegin())); EXPECT_TRUE(noexcept(sp.cend())); EXPECT_TRUE(noexcept(sp.rbegin())); EXPECT_TRUE(noexcept(sp.rend())); EXPECT_TRUE(noexcept(sp.crbegin())); EXPECT_TRUE(noexcept(sp.crend())); EXPECT_TRUE(noexcept(sp.size())); EXPECT_TRUE(noexcept(sp.length())); EXPECT_TRUE(noexcept(sp.empty())); EXPECT_TRUE(noexcept(sp.data())); EXPECT_TRUE(noexcept(sp.compare(sp))); EXPECT_TRUE(noexcept(sp.find(sp))); EXPECT_TRUE(noexcept(sp.find('f'))); EXPECT_TRUE(noexcept(sp.rfind(sp))); EXPECT_TRUE(noexcept(sp.rfind('f'))); EXPECT_TRUE(noexcept(sp.find_first_of(sp))); EXPECT_TRUE(noexcept(sp.find_first_of('f'))); EXPECT_TRUE(noexcept(sp.find_last_of(sp))); EXPECT_TRUE(noexcept(sp.find_last_of('f'))); EXPECT_TRUE(noexcept(sp.find_first_not_of(sp))); EXPECT_TRUE(noexcept(sp.find_first_not_of('f'))); EXPECT_TRUE(noexcept(sp.find_last_not_of(sp))); EXPECT_TRUE(noexcept(sp.find_last_not_of('f'))); } TEST(StringViewTest, BoundsCheck) { #ifndef ABSL_USES_STD_STRING_VIEW #if !defined(NDEBUG) || ABSL_OPTION_HARDENED absl::string_view h = "hello"; ABSL_EXPECT_DEATH_IF_SUPPORTED(h[5], ""); ABSL_EXPECT_DEATH_IF_SUPPORTED(h[static_cast<size_t>(-1)], ""); #endif #endif } TEST(ComparisonOpsTest, StringCompareNotAmbiguous) { EXPECT_EQ("hello", std::string("hello")); EXPECT_LT("hello", std::string("world")); } TEST(ComparisonOpsTest, HeterogeneousStringViewEquals) { EXPECT_EQ(absl::string_view("hello"), std::string("hello")); EXPECT_EQ("hello", absl::string_view("hello")); } TEST(FindOneCharTest, EdgeCases) { absl::string_view a("xxyyyxx"); a.remove_prefix(1); a.remove_suffix(1); EXPECT_EQ(0u, a.find('x')); EXPECT_EQ(0u, a.find('x', 0)); EXPECT_EQ(4u, a.find('x', 1)); EXPECT_EQ(4u, a.find('x', 4)); EXPECT_EQ(absl::string_view::npos, a.find('x', 5)); EXPECT_EQ(4u, a.rfind('x')); EXPECT_EQ(4u, a.rfind('x', 5)); EXPECT_EQ(4u, a.rfind('x', 4)); EXPECT_EQ(0u, a.rfind('x', 3)); EXPECT_EQ(0u, a.rfind('x', 0)); a.remove_prefix(1); a.remove_suffix(1); EXPECT_EQ(absl::string_view::npos, a.find('x')); EXPECT_EQ(absl::string_view::npos, a.rfind('x')); } #ifndef ABSL_HAVE_THREAD_SANITIZER TEST(HugeStringView, TwoPointTwoGB) { if (sizeof(size_t) <= 4) return; const size_t size = size_t{2200} * 1000 * 1000; std::string s(size, 'a'); absl::string_view sp(s); EXPECT_EQ(size, sp.length()); sp.remove_prefix(1); EXPECT_EQ(size - 1, sp.length()); sp.remove_suffix(2); EXPECT_EQ(size - 1 - 2, sp.length()); } #endif #if !defined(NDEBUG) && !defined(ABSL_USES_STD_STRING_VIEW) TEST(NonNegativeLenTest, NonNegativeLen) { ABSL_EXPECT_DEATH_IF_SUPPORTED( absl::string_view("xyz", static_cast<size_t>(-1)), "len <= kMaxSize"); } TEST(LenExceedsMaxSizeTest, LenExceedsMaxSize) { auto max_size = absl::string_view().max_size(); absl::string_view ok_view("", max_size); ABSL_EXPECT_DEATH_IF_SUPPORTED(absl::string_view("", max_size + 1), "len <= kMaxSize"); } #endif class StringViewStreamTest : public ::testing::Test { public: template <typename T> std::string Pad(const T& s, int width, char fill = 0) { std::ostringstream oss; if (fill != 0) { oss << std::setfill(fill); } if (width < 0) { width = -width; oss << std::right; } oss << std::setw(width) << s; return oss.str(); } }; TEST_F(StringViewStreamTest, Padding) { std::string s("hello"); absl::string_view sp(s); for (int w = -64; w < 64; ++w) { SCOPED_TRACE(w); EXPECT_EQ(Pad(s, w), Pad(sp, w)); } for (int w = -64; w < 64; ++w) { SCOPED_TRACE(w); EXPECT_EQ(Pad(s, w, '#'), Pad(sp, w, '#')); } } TEST_F(StringViewStreamTest, ResetsWidth) { std::string s = "hi"; absl::string_view sp = s; { std::ostringstream oss; oss << "[" << std::setfill('#') << std::setw(5) << s << "]"; ASSERT_EQ("[###hi]", oss.str()); } { std::ostringstream oss; oss << "[" << std::setfill('#') << std::setw(5) << sp << "]"; EXPECT_EQ("[###hi]", oss.str()); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/string_view.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/string_view_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
55da78bf-faae-4166-88d4-884db9fc1158
cpp
abseil/abseil-cpp
str_cat
absl/strings/str_cat.cc
absl/strings/str_cat_test.cc
#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>(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_cat.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_cat_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ee656456-6508-4e0d-a5f3-d0b511981a26
cpp
abseil/abseil-cpp
cord
absl/strings/cord.cc
absl/strings/cord_test.cc
#include "absl/strings/cord.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <ios> #include <iostream> #include <limits> #include <memory> #include <ostream> #include <sstream> #include <string> #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/nullability.h" #include "absl/container/inlined_vector.h" #include "absl/crc/crc32c.h" #include "absl/crc/internal/crc_cord_state.h" #include "absl/functional/function_ref.h" #include "absl/strings/cord_buffer.h" #include "absl/strings/escaping.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_crc.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/internal/cordz_update_tracker.h" #include "absl/strings/internal/resize_uninitialized.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/types/optional.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN using ::absl::cord_internal::CordRep; using ::absl::cord_internal::CordRepBtree; 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::InlineData; using ::absl::cord_internal::kMaxFlatLength; using ::absl::cord_internal::kMinFlatLength; using ::absl::cord_internal::kInlinedVectorSize; using ::absl::cord_internal::kMaxBytesToCopy; static void DumpNode(absl::Nonnull<CordRep*> nonnull_rep, bool include_data, absl::Nonnull<std::ostream*> os, int indent = 0); static bool VerifyNode(absl::Nonnull<CordRep*> root, absl::Nonnull<CordRep*> start_node); static inline absl::Nullable<CordRep*> VerifyTree( absl::Nullable<CordRep*> node) { assert(node == nullptr || VerifyNode(node, node)); static_cast<void>(&VerifyNode); return node; } static absl::Nonnull<CordRepFlat*> CreateFlat(absl::Nonnull<const char*> data, size_t length, size_t alloc_hint) { CordRepFlat* flat = CordRepFlat::New(length + alloc_hint); flat->length = length; memcpy(flat->Data(), data, length); return flat; } static absl::Nonnull<CordRep*> NewBtree(absl::Nonnull<const char*> data, size_t length, size_t alloc_hint) { if (length <= kMaxFlatLength) { return CreateFlat(data, length, alloc_hint); } CordRepFlat* flat = CreateFlat(data, kMaxFlatLength, 0); data += kMaxFlatLength; length -= kMaxFlatLength; auto* root = CordRepBtree::Create(flat); return CordRepBtree::Append(root, {data, length}, alloc_hint); } static absl::Nullable<CordRep*> NewTree(absl::Nullable<const char*> data, size_t length, size_t alloc_hint) { if (length == 0) return nullptr; return NewBtree(data, length, alloc_hint); } namespace cord_internal { void InitializeCordRepExternal(absl::string_view data, absl::Nonnull<CordRepExternal*> rep) { assert(!data.empty()); rep->length = data.size(); rep->tag = EXTERNAL; rep->base = data.data(); VerifyTree(rep); } } static absl::Nonnull<CordRep*> CordRepFromString(std::string&& src) { assert(src.length() > cord_internal::kMaxInline); if ( src.size() <= kMaxBytesToCopy || src.size() < src.capacity() / 2 ) { return NewTree(src.data(), src.size(), 0); } struct StringReleaser { void operator()(absl::string_view ) {} std::string data; }; const absl::string_view original_data = src; auto* rep = static_cast<::absl::cord_internal::CordRepExternalImpl<StringReleaser>*>( absl::cord_internal::NewExternalRep(original_data, StringReleaser{std::move(src)})); rep->base = rep->template get<0>().data.data(); return rep; } #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr unsigned char Cord::InlineRep::kMaxInline; #endif inline void Cord::InlineRep::set_data(absl::Nonnull<const char*> data, size_t n) { static_assert(kMaxInline == 15, "set_data is hard-coded for a length of 15"); data_.set_inline_data(data, n); } inline absl::Nonnull<char*> Cord::InlineRep::set_data(size_t n) { assert(n <= kMaxInline); ResetToEmpty(); set_inline_size(n); return data_.as_chars(); } inline void Cord::InlineRep::reduce_size(size_t n) { size_t tag = inline_size(); assert(tag <= kMaxInline); assert(tag >= n); tag -= n; memset(data_.as_chars() + tag, 0, n); set_inline_size(tag); } inline void Cord::InlineRep::remove_prefix(size_t n) { cord_internal::SmallMemmove(data_.as_chars(), data_.as_chars() + n, inline_size() - n); reduce_size(n); } static absl::Nonnull<CordRepBtree*> ForceBtree(CordRep* rep) { return rep->IsBtree() ? rep->btree() : CordRepBtree::Create(cord_internal::RemoveCrcNode(rep)); } void Cord::InlineRep::AppendTreeToInlined(absl::Nonnull<CordRep*> tree, MethodIdentifier method) { assert(!is_tree()); if (!data_.is_empty()) { CordRepFlat* flat = MakeFlatWithExtraCapacity(0); tree = CordRepBtree::Append(CordRepBtree::Create(flat), tree); } EmplaceTree(tree, method); } void Cord::InlineRep::AppendTreeToTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method) { assert(is_tree()); const CordzUpdateScope scope(data_.cordz_info(), method); tree = CordRepBtree::Append(ForceBtree(data_.as_tree()), tree); SetTree(tree, scope); } void Cord::InlineRep::AppendTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method) { assert(tree != nullptr); assert(tree->length != 0); assert(!tree->IsCrc()); if (data_.is_tree()) { AppendTreeToTree(tree, method); } else { AppendTreeToInlined(tree, method); } } void Cord::InlineRep::PrependTreeToInlined(absl::Nonnull<CordRep*> tree, MethodIdentifier method) { assert(!is_tree()); if (!data_.is_empty()) { CordRepFlat* flat = MakeFlatWithExtraCapacity(0); tree = CordRepBtree::Prepend(CordRepBtree::Create(flat), tree); } EmplaceTree(tree, method); } void Cord::InlineRep::PrependTreeToTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method) { assert(is_tree()); const CordzUpdateScope scope(data_.cordz_info(), method); tree = CordRepBtree::Prepend(ForceBtree(data_.as_tree()), tree); SetTree(tree, scope); } void Cord::InlineRep::PrependTree(absl::Nonnull<CordRep*> tree, MethodIdentifier method) { assert(tree != nullptr); assert(tree->length != 0); assert(!tree->IsCrc()); if (data_.is_tree()) { PrependTreeToTree(tree, method); } else { PrependTreeToInlined(tree, method); } } static inline bool PrepareAppendRegion( absl::Nonnull<CordRep*> root, absl::Nonnull<absl::Nullable<char*>*> region, absl::Nonnull<size_t*> size, size_t max_length) { if (root->IsBtree() && root->refcount.IsOne()) { Span<char> span = root->btree()->GetAppendBuffer(max_length); if (!span.empty()) { *region = span.data(); *size = span.size(); return true; } } CordRep* dst = root; if (!dst->IsFlat() || !dst->refcount.IsOne()) { *region = nullptr; *size = 0; return false; } const size_t in_use = dst->length; const size_t capacity = dst->flat()->Capacity(); if (in_use == capacity) { *region = nullptr; *size = 0; return false; } const size_t size_increase = std::min(capacity - in_use, max_length); dst->length += size_increase; *region = dst->flat()->Data() + in_use; *size = size_increase; return true; } void Cord::InlineRep::AssignSlow(const Cord::InlineRep& src) { assert(&src != this); assert(is_tree() || src.is_tree()); auto constexpr method = CordzUpdateTracker::kAssignCord; if (ABSL_PREDICT_TRUE(!is_tree())) { EmplaceTree(CordRep::Ref(src.as_tree()), src.data_, method); return; } CordRep* tree = as_tree(); if (CordRep* src_tree = src.tree()) { data_.set_tree(CordRep::Ref(src_tree)); CordzInfo::MaybeTrackCord(data_, src.data_, method); } else { CordzInfo::MaybeUntrackCord(data_.cordz_info()); data_ = src.data_; } CordRep::Unref(tree); } void Cord::InlineRep::UnrefTree() { if (is_tree()) { CordzInfo::MaybeUntrackCord(data_.cordz_info()); CordRep::Unref(tree()); } } Cord::Cord(absl::string_view src, MethodIdentifier method) : contents_(InlineData::kDefaultInit) { const size_t n = src.size(); if (n <= InlineRep::kMaxInline) { contents_.set_data(src.data(), n); } else { CordRep* rep = NewTree(src.data(), n, 0); contents_.EmplaceTree(rep, method); } } template <typename T, Cord::EnableIfString<T>> Cord::Cord(T&& src) : contents_(InlineData::kDefaultInit) { if (src.size() <= InlineRep::kMaxInline) { contents_.set_data(src.data(), src.size()); } else { CordRep* rep = CordRepFromString(std::forward<T>(src)); contents_.EmplaceTree(rep, CordzUpdateTracker::kConstructorString); } } template Cord::Cord(std::string&& src); void Cord::DestroyCordSlow() { assert(contents_.is_tree()); CordzInfo::MaybeUntrackCord(contents_.cordz_info()); CordRep::Unref(VerifyTree(contents_.as_tree())); } void Cord::Clear() { if (CordRep* tree = contents_.clear()) { CordRep::Unref(tree); } } Cord& Cord::AssignLargeString(std::string&& src) { auto constexpr method = CordzUpdateTracker::kAssignString; assert(src.size() > kMaxBytesToCopy); CordRep* rep = CordRepFromString(std::move(src)); if (CordRep* tree = contents_.tree()) { CordzUpdateScope scope(contents_.cordz_info(), method); contents_.SetTree(rep, scope); CordRep::Unref(tree); } else { contents_.EmplaceTree(rep, method); } return *this; } Cord& Cord::operator=(absl::string_view src) { auto constexpr method = CordzUpdateTracker::kAssignString; const char* data = src.data(); size_t length = src.size(); CordRep* tree = contents_.tree(); if (length <= InlineRep::kMaxInline) { if (tree != nullptr) CordzInfo::MaybeUntrackCord(contents_.cordz_info()); contents_.set_data(data, length); if (tree != nullptr) CordRep::Unref(tree); return *this; } if (tree != nullptr) { CordzUpdateScope scope(contents_.cordz_info(), method); if (tree->IsFlat() && tree->flat()->Capacity() >= length && tree->refcount.IsOne()) { memmove(tree->flat()->Data(), data, length); tree->length = length; VerifyTree(tree); return *this; } contents_.SetTree(NewTree(data, length, 0), scope); CordRep::Unref(tree); } else { contents_.EmplaceTree(NewTree(data, length, 0), method); } return *this; } void Cord::InlineRep::AppendArray(absl::string_view src, MethodIdentifier method) { if (src.empty()) return; MaybeRemoveEmptyCrcNode(); size_t appended = 0; CordRep* rep = tree(); const CordRep* const root = rep; CordzUpdateScope scope(root ? cordz_info() : nullptr, method); if (root != nullptr) { rep = cord_internal::RemoveCrcNode(rep); char* region; if (PrepareAppendRegion(rep, &region, &appended, src.size())) { memcpy(region, src.data(), appended); } } else { size_t inline_length = inline_size(); if (src.size() <= kMaxInline - inline_length) { set_inline_size(inline_length + src.size()); memcpy(data_.as_chars() + inline_length, src.data(), src.size()); return; } rep = CordRepFlat::New(inline_length + src.size()); appended = std::min(src.size(), rep->flat()->Capacity() - inline_length); memcpy(rep->flat()->Data(), data_.as_chars(), inline_length); memcpy(rep->flat()->Data() + inline_length, src.data(), appended); rep->length = inline_length + appended; } src.remove_prefix(appended); if (src.empty()) { CommitTree(root, rep, scope, method); return; } rep = ForceBtree(rep); const size_t min_growth = std::max<size_t>(rep->length / 10, src.size()); rep = CordRepBtree::Append(rep->btree(), src, min_growth - src.size()); CommitTree(root, rep, scope, method); } inline absl::Nonnull<CordRep*> Cord::TakeRep() const& { return CordRep::Ref(contents_.tree()); } inline absl::Nonnull<CordRep*> Cord::TakeRep() && { CordRep* rep = contents_.tree(); contents_.clear(); return rep; } template <typename C> inline void Cord::AppendImpl(C&& src) { auto constexpr method = CordzUpdateTracker::kAppendCord; contents_.MaybeRemoveEmptyCrcNode(); if (src.empty()) return; if (empty()) { if (src.contents_.is_tree()) { CordRep* rep = cord_internal::RemoveCrcNode(std::forward<C>(src).TakeRep()); contents_.EmplaceTree(rep, method); } else { contents_.data_ = src.contents_.data_; } return; } const size_t src_size = src.contents_.size(); if (src_size <= kMaxBytesToCopy) { CordRep* src_tree = src.contents_.tree(); if (src_tree == nullptr) { contents_.AppendArray({src.contents_.data(), src_size}, method); return; } if (src_tree->IsFlat()) { contents_.AppendArray({src_tree->flat()->Data(), src_size}, method); return; } if (&src == this) { Append(Cord(src)); return; } for (absl::string_view chunk : src.Chunks()) { Append(chunk); } return; } CordRep* rep = cord_internal::RemoveCrcNode(std::forward<C>(src).TakeRep()); contents_.AppendTree(rep, CordzUpdateTracker::kAppendCord); } static CordRep::ExtractResult ExtractAppendBuffer(absl::Nonnull<CordRep*> rep, size_t min_capacity) { switch (rep->tag) { case cord_internal::BTREE: return CordRepBtree::ExtractAppendBuffer(rep->btree(), min_capacity); default: if (rep->IsFlat() && rep->refcount.IsOne() && rep->flat()->Capacity() - rep->length >= min_capacity) { return {nullptr, rep}; } return {rep, nullptr}; } } static CordBuffer CreateAppendBuffer(InlineData& data, size_t block_size, size_t capacity) { const size_t size = data.inline_size(); const size_t max_capacity = std::numeric_limits<size_t>::max() - size; capacity = (std::min)(max_capacity, capacity) + size; CordBuffer buffer = block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity) : CordBuffer::CreateWithDefaultLimit(capacity); cord_internal::SmallMemmove(buffer.data(), data.as_chars(), size); buffer.SetLength(size); data = {}; return buffer; } CordBuffer Cord::GetAppendBufferSlowPath(size_t block_size, size_t capacity, size_t min_capacity) { auto constexpr method = CordzUpdateTracker::kGetAppendBuffer; CordRep* tree = contents_.tree(); if (tree != nullptr) { CordzUpdateScope scope(contents_.cordz_info(), method); CordRep::ExtractResult result = ExtractAppendBuffer(tree, min_capacity); if (result.extracted != nullptr) { contents_.SetTreeOrEmpty(result.tree, scope); return CordBuffer(result.extracted->flat()); } return block_size ? CordBuffer::CreateWithCustomLimit(block_size, capacity) : CordBuffer::CreateWithDefaultLimit(capacity); } return CreateAppendBuffer(contents_.data_, block_size, capacity); } void Cord::Append(const Cord& src) { AppendImpl(src); } void Cord::Append(Cord&& src) { AppendImpl(std::move(src)); } template <typename T, Cord::EnableIfString<T>> void Cord::Append(T&& src) { if (src.size() <= kMaxBytesToCopy) { Append(absl::string_view(src)); } else { CordRep* rep = CordRepFromString(std::forward<T>(src)); contents_.AppendTree(rep, CordzUpdateTracker::kAppendString); } } template void Cord::Append(std::string&& src); void Cord::Prepend(const Cord& src) { contents_.MaybeRemoveEmptyCrcNode(); if (src.empty()) return; CordRep* src_tree = src.contents_.tree(); if (src_tree != nullptr) { CordRep::Ref(src_tree); contents_.PrependTree(cord_internal::RemoveCrcNode(src_tree), CordzUpdateTracker::kPrependCord); return; } absl::string_view src_contents(src.contents_.data(), src.contents_.size()); return Prepend(src_contents); } void Cord::PrependArray(absl::string_view src, MethodIdentifier method) { contents_.MaybeRemoveEmptyCrcNode(); if (src.empty()) return; if (!contents_.is_tree()) { size_t cur_size = contents_.inline_size(); if (cur_size + src.size() <= InlineRep::kMaxInline) { InlineData data; data.set_inline_size(cur_size + src.size()); memcpy(data.as_chars(), src.data(), src.size()); memcpy(data.as_chars() + src.size(), contents_.data(), cur_size); contents_.data_ = data; return; } } CordRep* rep = NewTree(src.data(), src.size(), 0); contents_.PrependTree(rep, method); } void Cord::AppendPrecise(absl::string_view src, MethodIdentifier method) { assert(!src.empty()); assert(src.size() <= cord_internal::kMaxFlatLength); if (contents_.remaining_inline_capacity() >= src.size()) { const size_t inline_length = contents_.inline_size(); contents_.set_inline_size(inline_length + src.size()); memcpy(contents_.data_.as_chars() + inline_length, src.data(), src.size()); } else { contents_.AppendTree(CordRepFlat::Create(src), method); } } void Cord::PrependPrecise(absl::string_view src, MethodIdentifier method) { assert(!src.empty()); assert(src.size() <= cord_internal::kMaxFlatLength); if (contents_.remaining_inline_capacity() >= src.size()) { const size_t cur_size = contents_.inline_size(); InlineData data; data.set_inline_size(cur_size + src.size()); memcpy(data.as_chars(), src.data(), src.size()); memcpy(data.as_chars() + src.size(), contents_.data(), cur_size); contents_.data_ = data; } else { contents_.PrependTree(CordRepFlat::Create(src), method); } } template <typename T, Cord::EnableIfString<T>> inline void Cord::Prepend(T&& src) { if (src.size() <= kMaxBytesToCopy) { Prepend(absl::string_view(src)); } else { CordRep* rep = CordRepFromString(std::forward<T>(src)); contents_.PrependTree(rep, CordzUpdateTracker::kPrependString); } } template void Cord::Prepend(std::string&& src); void Cord::RemovePrefix(size_t n) { ABSL_INTERNAL_CHECK(n <= size(), absl::StrCat("Requested prefix size ", n, " exceeds Cord's size ", size())); contents_.MaybeRemoveEmptyCrcNode(); CordRep* tree = contents_.tree(); if (tree == nullptr) { contents_.remove_prefix(n); } else { auto constexpr method = CordzUpdateTracker::kRemovePrefix; CordzUpdateScope scope(contents_.cordz_info(), method); tree = cord_internal::RemoveCrcNode(tree); if (n >= tree->length) { CordRep::Unref(tree); tree = nullptr; } else if (tree->IsBtree()) { CordRep* old = tree; tree = tree->btree()->SubTree(n, tree->length - n); CordRep::Unref(old); } else if (tree->IsSubstring() && tree->refcount.IsOne()) { tree->substring()->start += n; tree->length -= n; } else { CordRep* rep = CordRepSubstring::Substring(tree, n, tree->length - n); CordRep::Unref(tree); tree = rep; } contents_.SetTreeOrEmpty(tree, scope); } } void Cord::RemoveSuffix(size_t n) { ABSL_INTERNAL_CHECK(n <= size(), absl::StrCat("Requested suffix size ", n, " exceeds Cord's size ", size())); contents_.MaybeRemoveEmptyCrcNode(); CordRep* tree = contents_.tree(); if (tree == nullptr) { contents_.reduce_size(n); } else { auto constexpr method = CordzUpdateTracker::kRemoveSuffix; CordzUpdateScope scope(contents_.cordz_info(), method); tree = cord_internal::RemoveCrcNode(tree); if (n >= tree->length) { CordRep::Unref(tree); tree = nullptr; } else if (tree->IsBtree()) { tree = CordRepBtree::RemoveSuffix(tree->btree(), n); } else if (!tree->IsExternal() && tree->refcount.IsOne()) { assert(tree->IsFlat() || tree->IsSubstring()); tree->length -= n; } else { CordRep* rep = CordRepSubstring::Substring(tree, 0, tree->length - n); CordRep::Unref(tree); tree = rep; } contents_.SetTreeOrEmpty(tree, scope); } } Cord Cord::Subcord(size_t pos, size_t new_size) const { Cord sub_cord; size_t length = size(); if (pos > length) pos = length; if (new_size > length - pos) new_size = length - pos; if (new_size == 0) return sub_cord; CordRep* tree = contents_.tree(); if (tree == nullptr) { sub_cord.contents_.set_data(contents_.data() + pos, new_size); return sub_cord; } if (new_size <= InlineRep::kMaxInline) { sub_cord.contents_.set_inline_size(new_size); char* dest = sub_cord.contents_.data_.as_chars(); Cord::ChunkIterator it = chunk_begin(); it.AdvanceBytes(pos); size_t remaining_size = new_size; while (remaining_size > it->size()) { cord_internal::SmallMemmove(dest, it->data(), it->size()); remaining_size -= it->size(); dest += it->size(); ++it; } cord_internal::SmallMemmove(dest, it->data(), remaining_size); return sub_cord; } tree = cord_internal::SkipCrcNode(tree); if (tree->IsBtree()) { tree = tree->btree()->SubTree(pos, new_size); } else { tree = CordRepSubstring::Substring(tree, pos, new_size); } sub_cord.contents_.EmplaceTree(tree, contents_.data_, CordzUpdateTracker::kSubCord); return sub_cord; } namespace { int ClampResult(int memcmp_res) { return static_cast<int>(memcmp_res > 0) - static_cast<int>(memcmp_res < 0); } int CompareChunks(absl::Nonnull<absl::string_view*> lhs, absl::Nonnull<absl::string_view*> rhs, absl::Nonnull<size_t*> size_to_compare) { size_t compared_size = std::min(lhs->size(), rhs->size()); assert(*size_to_compare >= compared_size); *size_to_compare -= compared_size; int memcmp_res = ::memcmp(lhs->data(), rhs->data(), compared_size); if (memcmp_res != 0) return memcmp_res; lhs->remove_prefix(compared_size); rhs->remove_prefix(compared_size); return 0; } template <typename ResultType> ResultType ComputeCompareResult(int memcmp_res) { return ClampResult(memcmp_res); } template <> bool ComputeCompareResult<bool>(int memcmp_res) { return memcmp_res == 0; } } inline absl::string_view Cord::InlineRep::FindFlatStartPiece() const { if (!is_tree()) { return absl::string_view(data_.as_chars(), data_.inline_size()); } CordRep* node = cord_internal::SkipCrcNode(tree()); if (node->IsFlat()) { return absl::string_view(node->flat()->Data(), node->length); } if (node->IsExternal()) { return absl::string_view(node->external()->base, node->length); } if (node->IsBtree()) { CordRepBtree* tree = node->btree(); int height = tree->height(); while (--height >= 0) { tree = tree->Edge(CordRepBtree::kFront)->btree(); } return tree->Data(tree->begin()); } size_t offset = 0; size_t length = node->length; assert(length != 0); if (node->IsSubstring()) { offset = node->substring()->start; node = node->substring()->child; } if (node->IsFlat()) { return absl::string_view(node->flat()->Data() + offset, length); } assert(node->IsExternal() && "Expect FLAT or EXTERNAL node here"); return absl::string_view(node->external()->base + offset, length); } void Cord::SetCrcCordState(crc_internal::CrcCordState state) { auto constexpr method = CordzUpdateTracker::kSetExpectedChecksum; if (empty()) { contents_.MaybeRemoveEmptyCrcNode(); CordRep* rep = CordRepCrc::New(nullptr, std::move(state)); contents_.EmplaceTree(rep, method); } else if (!contents_.is_tree()) { CordRep* rep = contents_.MakeFlatWithExtraCapacity(0); rep = CordRepCrc::New(rep, std::move(state)); contents_.EmplaceTree(rep, method); } else { const CordzUpdateScope scope(contents_.data_.cordz_info(), method); CordRep* rep = CordRepCrc::New(contents_.data_.as_tree(), std::move(state)); contents_.SetTree(rep, scope); } } void Cord::SetExpectedChecksum(uint32_t crc) { crc_internal::CrcCordState state; state.mutable_rep()->prefix_crc.push_back( crc_internal::CrcCordState::PrefixCrc(size(), absl::crc32c_t{crc})); SetCrcCordState(std::move(state)); } absl::Nullable<const crc_internal::CrcCordState*> Cord::MaybeGetCrcCordState() const { if (!contents_.is_tree() || !contents_.tree()->IsCrc()) { return nullptr; } return &contents_.tree()->crc()->crc_cord_state; } absl::optional<uint32_t> Cord::ExpectedChecksum() const { if (!contents_.is_tree() || !contents_.tree()->IsCrc()) { return absl::nullopt; } return static_cast<uint32_t>( contents_.tree()->crc()->crc_cord_state.Checksum()); } inline int Cord::CompareSlowPath(absl::string_view rhs, size_t compared_size, size_t size_to_compare) const { auto advance = [](absl::Nonnull<Cord::ChunkIterator*> it, absl::Nonnull<absl::string_view*> chunk) { if (!chunk->empty()) return true; ++*it; if (it->bytes_remaining_ == 0) return false; *chunk = **it; return true; }; Cord::ChunkIterator lhs_it = chunk_begin(); absl::string_view lhs_chunk = (lhs_it.bytes_remaining_ != 0) ? *lhs_it : absl::string_view(); assert(compared_size <= lhs_chunk.size()); assert(compared_size <= rhs.size()); lhs_chunk.remove_prefix(compared_size); rhs.remove_prefix(compared_size); size_to_compare -= compared_size; while (advance(&lhs_it, &lhs_chunk) && !rhs.empty()) { int comparison_result = CompareChunks(&lhs_chunk, &rhs, &size_to_compare); if (comparison_result != 0) return comparison_result; if (size_to_compare == 0) return 0; } return static_cast<int>(rhs.empty()) - static_cast<int>(lhs_chunk.empty()); } inline int Cord::CompareSlowPath(const Cord& rhs, size_t compared_size, size_t size_to_compare) const { auto advance = [](absl::Nonnull<Cord::ChunkIterator*> it, absl::Nonnull<absl::string_view*> chunk) { if (!chunk->empty()) return true; ++*it; if (it->bytes_remaining_ == 0) return false; *chunk = **it; return true; }; Cord::ChunkIterator lhs_it = chunk_begin(); Cord::ChunkIterator rhs_it = rhs.chunk_begin(); absl::string_view lhs_chunk = (lhs_it.bytes_remaining_ != 0) ? *lhs_it : absl::string_view(); absl::string_view rhs_chunk = (rhs_it.bytes_remaining_ != 0) ? *rhs_it : absl::string_view(); assert(compared_size <= lhs_chunk.size()); assert(compared_size <= rhs_chunk.size()); lhs_chunk.remove_prefix(compared_size); rhs_chunk.remove_prefix(compared_size); size_to_compare -= compared_size; while (advance(&lhs_it, &lhs_chunk) && advance(&rhs_it, &rhs_chunk)) { int memcmp_res = CompareChunks(&lhs_chunk, &rhs_chunk, &size_to_compare); if (memcmp_res != 0) return memcmp_res; if (size_to_compare == 0) return 0; } return static_cast<int>(rhs_chunk.empty()) - static_cast<int>(lhs_chunk.empty()); } inline absl::string_view Cord::GetFirstChunk(const Cord& c) { if (c.empty()) return {}; return c.contents_.FindFlatStartPiece(); } inline absl::string_view Cord::GetFirstChunk(absl::string_view sv) { return sv; } template <typename ResultType, typename RHS> ResultType GenericCompare(const Cord& lhs, const RHS& rhs, size_t size_to_compare) { absl::string_view lhs_chunk = Cord::GetFirstChunk(lhs); absl::string_view rhs_chunk = Cord::GetFirstChunk(rhs); size_t compared_size = std::min(lhs_chunk.size(), rhs_chunk.size()); assert(size_to_compare >= compared_size); int memcmp_res = ::memcmp(lhs_chunk.data(), rhs_chunk.data(), compared_size); if (compared_size == size_to_compare || memcmp_res != 0) { return ComputeCompareResult<ResultType>(memcmp_res); } return ComputeCompareResult<ResultType>( lhs.CompareSlowPath(rhs, compared_size, size_to_compare)); } bool Cord::EqualsImpl(absl::string_view rhs, size_t size_to_compare) const { return GenericCompare<bool>(*this, rhs, size_to_compare); } bool Cord::EqualsImpl(const Cord& rhs, size_t size_to_compare) const { return GenericCompare<bool>(*this, rhs, size_to_compare); } template <typename RHS> inline int SharedCompareImpl(const Cord& lhs, const RHS& rhs) { size_t lhs_size = lhs.size(); size_t rhs_size = rhs.size(); if (lhs_size == rhs_size) { return GenericCompare<int>(lhs, rhs, lhs_size); } if (lhs_size < rhs_size) { auto data_comp_res = GenericCompare<int>(lhs, rhs, lhs_size); return data_comp_res == 0 ? -1 : data_comp_res; } auto data_comp_res = GenericCompare<int>(lhs, rhs, rhs_size); return data_comp_res == 0 ? +1 : data_comp_res; } int Cord::Compare(absl::string_view rhs) const { return SharedCompareImpl(*this, rhs); } int Cord::CompareImpl(const Cord& rhs) const { return SharedCompareImpl(*this, rhs); } bool Cord::EndsWith(absl::string_view rhs) const { size_t my_size = size(); size_t rhs_size = rhs.size(); if (my_size < rhs_size) return false; Cord tmp(*this); tmp.RemovePrefix(my_size - rhs_size); return tmp.EqualsImpl(rhs, rhs_size); } bool Cord::EndsWith(const Cord& rhs) const { size_t my_size = size(); size_t rhs_size = rhs.size(); if (my_size < rhs_size) return false; Cord tmp(*this); tmp.RemovePrefix(my_size - rhs_size); return tmp.EqualsImpl(rhs, rhs_size); } Cord::operator std::string() const { std::string s; absl::CopyCordToString(*this, &s); return s; } void CopyCordToString(const Cord& src, absl::Nonnull<std::string*> dst) { if (!src.contents_.is_tree()) { src.contents_.CopyTo(dst); } else { absl::strings_internal::STLStringResizeUninitialized(dst, src.size()); src.CopyToArraySlowPath(&(*dst)[0]); } } void AppendCordToString(const Cord& src, absl::Nonnull<std::string*> dst) { const size_t cur_dst_size = dst->size(); const size_t new_dst_size = cur_dst_size + src.size(); absl::strings_internal::STLStringResizeUninitializedAmortized(dst, new_dst_size); char* append_ptr = &(*dst)[cur_dst_size]; src.CopyToArrayImpl(append_ptr); } void Cord::CopyToArraySlowPath(absl::Nonnull<char*> dst) const { assert(contents_.is_tree()); absl::string_view fragment; if (GetFlatAux(contents_.tree(), &fragment)) { memcpy(dst, fragment.data(), fragment.size()); return; } for (absl::string_view chunk : Chunks()) { memcpy(dst, chunk.data(), chunk.size()); dst += chunk.size(); } } Cord Cord::ChunkIterator::AdvanceAndReadBytes(size_t n) { ABSL_HARDENING_ASSERT(bytes_remaining_ >= n && "Attempted to iterate past `end()`"); Cord subcord; auto constexpr method = CordzUpdateTracker::kCordReader; if (n <= InlineRep::kMaxInline) { char* data = subcord.contents_.set_data(n); while (n > current_chunk_.size()) { memcpy(data, current_chunk_.data(), current_chunk_.size()); data += current_chunk_.size(); n -= current_chunk_.size(); ++*this; } memcpy(data, current_chunk_.data(), n); if (n < current_chunk_.size()) { RemoveChunkPrefix(n); } else if (n > 0) { ++*this; } return subcord; } if (btree_reader_) { size_t chunk_size = current_chunk_.size(); if (n <= chunk_size && n <= kMaxBytesToCopy) { subcord = Cord(current_chunk_.substr(0, n), method); if (n < chunk_size) { current_chunk_.remove_prefix(n); } else { current_chunk_ = btree_reader_.Next(); } } else { CordRep* rep; current_chunk_ = btree_reader_.Read(n, chunk_size, rep); subcord.contents_.EmplaceTree(rep, method); } bytes_remaining_ -= n; return subcord; } assert(current_leaf_ != nullptr); if (n == current_leaf_->length) { bytes_remaining_ = 0; current_chunk_ = {}; CordRep* tree = CordRep::Ref(current_leaf_); subcord.contents_.EmplaceTree(VerifyTree(tree), method); return subcord; } CordRep* payload = current_leaf_->IsSubstring() ? current_leaf_->substring()->child : current_leaf_; const char* data = payload->IsExternal() ? payload->external()->base : payload->flat()->Data(); const size_t offset = static_cast<size_t>(current_chunk_.data() - data); auto* tree = CordRepSubstring::Substring(payload, offset, n); subcord.contents_.EmplaceTree(VerifyTree(tree), method); bytes_remaining_ -= n; current_chunk_.remove_prefix(n); return subcord; } char Cord::operator[](size_t i) const { ABSL_HARDENING_ASSERT(i < size()); size_t offset = i; const CordRep* rep = contents_.tree(); if (rep == nullptr) { return contents_.data()[i]; } rep = cord_internal::SkipCrcNode(rep); while (true) { assert(rep != nullptr); assert(offset < rep->length); if (rep->IsFlat()) { return rep->flat()->Data()[offset]; } else if (rep->IsBtree()) { return rep->btree()->GetCharacter(offset); } else if (rep->IsExternal()) { return rep->external()->base[offset]; } else { assert(rep->IsSubstring()); offset += rep->substring()->start; rep = rep->substring()->child; } } } namespace { bool IsSubstringInCordAt(absl::Cord::CharIterator position, absl::string_view needle) { auto haystack_chunk = absl::Cord::ChunkRemaining(position); while (true) { assert(!haystack_chunk.empty()); auto min_length = std::min(haystack_chunk.size(), needle.size()); if (!absl::ConsumePrefix(&needle, haystack_chunk.substr(0, min_length))) { return false; } if (needle.empty()) { return true; } absl::Cord::Advance(&position, min_length); haystack_chunk = absl::Cord::ChunkRemaining(position); } } } absl::Cord::CharIterator absl::Cord::FindImpl(CharIterator it, absl::string_view needle) const { assert(!needle.empty()); assert(it.chunk_iterator_.bytes_remaining_ >= needle.size()); while (it.chunk_iterator_.bytes_remaining_ >= needle.size()) { auto haystack_chunk = Cord::ChunkRemaining(it); assert(!haystack_chunk.empty()); auto idx = haystack_chunk.find(needle.front()); if (idx == absl::string_view::npos) { Cord::Advance(&it, haystack_chunk.size()); continue; } Cord::Advance(&it, idx); if (it.chunk_iterator_.bytes_remaining_ < needle.size()) { break; } if (IsSubstringInCordAt(it, needle)) { return it; } Cord::Advance(&it, 1); } return char_end(); } absl::Cord::CharIterator absl::Cord::Find(absl::string_view needle) const { if (needle.empty()) { return char_begin(); } if (needle.size() > size()) { return char_end(); } if (needle.size() == size()) { return *this == needle ? char_begin() : char_end(); } return FindImpl(char_begin(), needle); } namespace { bool IsSubcordInCordAt(absl::Cord::CharIterator haystack, absl::Cord::CharIterator needle_begin, absl::Cord::CharIterator needle_end) { while (needle_begin != needle_end) { auto haystack_chunk = absl::Cord::ChunkRemaining(haystack); assert(!haystack_chunk.empty()); auto needle_chunk = absl::Cord::ChunkRemaining(needle_begin); auto min_length = std::min(haystack_chunk.size(), needle_chunk.size()); if (haystack_chunk.substr(0, min_length) != needle_chunk.substr(0, min_length)) { return false; } absl::Cord::Advance(&haystack, min_length); absl::Cord::Advance(&needle_begin, min_length); } return true; } bool IsSubcordInCordAt(absl::Cord::CharIterator position, const absl::Cord& needle) { return IsSubcordInCordAt(position, needle.char_begin(), needle.char_end()); } } absl::Cord::CharIterator absl::Cord::Find(const absl::Cord& needle) const { if (needle.empty()) { return char_begin(); } const auto needle_size = needle.size(); if (needle_size > size()) { return char_end(); } if (needle_size == size()) { return *this == needle ? char_begin() : char_end(); } const auto needle_chunk = Cord::ChunkRemaining(needle.char_begin()); auto haystack_it = char_begin(); while (true) { haystack_it = FindImpl(haystack_it, needle_chunk); if (haystack_it == char_end() || haystack_it.chunk_iterator_.bytes_remaining_ < needle_size) { break; } auto haystack_advanced_it = haystack_it; auto needle_it = needle.char_begin(); Cord::Advance(&haystack_advanced_it, needle_chunk.size()); Cord::Advance(&needle_it, needle_chunk.size()); if (IsSubcordInCordAt(haystack_advanced_it, needle_it, needle.char_end())) { return haystack_it; } Cord::Advance(&haystack_it, 1); if (haystack_it.chunk_iterator_.bytes_remaining_ < needle_size) { break; } if (haystack_it.chunk_iterator_.bytes_remaining_ == needle_size) { if (IsSubcordInCordAt(haystack_it, needle)) { return haystack_it; } break; } } return char_end(); } bool Cord::Contains(absl::string_view rhs) const { return rhs.empty() || Find(rhs) != char_end(); } bool Cord::Contains(const absl::Cord& rhs) const { return rhs.empty() || Find(rhs) != char_end(); } absl::string_view Cord::FlattenSlowPath() { assert(contents_.is_tree()); size_t total_size = size(); CordRep* new_rep; char* new_buffer; if (total_size <= kMaxFlatLength) { new_rep = CordRepFlat::New(total_size); new_rep->length = total_size; new_buffer = new_rep->flat()->Data(); CopyToArraySlowPath(new_buffer); } else { new_buffer = std::allocator<char>().allocate(total_size); CopyToArraySlowPath(new_buffer); new_rep = absl::cord_internal::NewExternalRep( absl::string_view(new_buffer, total_size), [](absl::string_view s) { std::allocator<char>().deallocate(const_cast<char*>(s.data()), s.size()); }); } CordzUpdateScope scope(contents_.cordz_info(), CordzUpdateTracker::kFlatten); CordRep::Unref(contents_.as_tree()); contents_.SetTree(new_rep, scope); return absl::string_view(new_buffer, total_size); } bool Cord::GetFlatAux(absl::Nonnull<CordRep*> rep, absl::Nonnull<absl::string_view*> fragment) { assert(rep != nullptr); if (rep->length == 0) { *fragment = absl::string_view(); return true; } rep = cord_internal::SkipCrcNode(rep); if (rep->IsFlat()) { *fragment = absl::string_view(rep->flat()->Data(), rep->length); return true; } else if (rep->IsExternal()) { *fragment = absl::string_view(rep->external()->base, rep->length); return true; } else if (rep->IsBtree()) { return rep->btree()->IsFlat(fragment); } else if (rep->IsSubstring()) { CordRep* child = rep->substring()->child; if (child->IsFlat()) { *fragment = absl::string_view( child->flat()->Data() + rep->substring()->start, rep->length); return true; } else if (child->IsExternal()) { *fragment = absl::string_view( child->external()->base + rep->substring()->start, rep->length); return true; } else if (child->IsBtree()) { return child->btree()->IsFlat(rep->substring()->start, rep->length, fragment); } } return false; } void Cord::ForEachChunkAux( absl::Nonnull<absl::cord_internal::CordRep*> rep, absl::FunctionRef<void(absl::string_view)> callback) { assert(rep != nullptr); if (rep->length == 0) return; rep = cord_internal::SkipCrcNode(rep); if (rep->IsBtree()) { ChunkIterator it(rep), end; while (it != end) { callback(*it); ++it; } return; } absl::cord_internal::CordRep* current_node = cord_internal::SkipCrcNode(rep); absl::string_view chunk; bool success = GetFlatAux(current_node, &chunk); assert(success); if (success) { callback(chunk); } } static void DumpNode(absl::Nonnull<CordRep*> nonnull_rep, bool include_data, absl::Nonnull<std::ostream*> os, int indent) { CordRep* rep = nonnull_rep; const int kIndentStep = 1; for (;;) { *os << std::setw(3) << (rep == nullptr ? 0 : rep->refcount.Get()); *os << " " << std::setw(7) << (rep == nullptr ? 0 : rep->length); *os << " ["; if (include_data) *os << static_cast<void*>(rep); *os << "]"; *os << " " << std::setw(indent) << ""; bool leaf = false; if (rep == nullptr) { *os << "NULL\n"; leaf = true; } else if (rep->IsCrc()) { *os << "CRC crc=" << rep->crc()->crc_cord_state.Checksum() << "\n"; indent += kIndentStep; rep = rep->crc()->child; } else if (rep->IsSubstring()) { *os << "SUBSTRING @ " << rep->substring()->start << "\n"; indent += kIndentStep; rep = rep->substring()->child; } else { leaf = true; if (rep->IsExternal()) { *os << "EXTERNAL ["; if (include_data) *os << absl::CEscape( absl::string_view(rep->external()->base, rep->length)); *os << "]\n"; } else if (rep->IsFlat()) { *os << "FLAT cap=" << rep->flat()->Capacity() << " ["; if (include_data) *os << absl::CEscape( absl::string_view(rep->flat()->Data(), rep->length)); *os << "]\n"; } else { CordRepBtree::Dump(rep, "", include_data, *os); } } if (leaf) { break; } } } static std::string ReportError(absl::Nonnull<CordRep*> root, absl::Nonnull<CordRep*> node) { std::ostringstream buf; buf << "Error at node " << node << " in:"; DumpNode(root, true, &buf); return buf.str(); } static bool VerifyNode(absl::Nonnull<CordRep*> root, absl::Nonnull<CordRep*> start_node) { absl::InlinedVector<absl::Nonnull<CordRep*>, 2> worklist; worklist.push_back(start_node); do { CordRep* node = worklist.back(); worklist.pop_back(); ABSL_INTERNAL_CHECK(node != nullptr, ReportError(root, node)); if (node != root) { ABSL_INTERNAL_CHECK(node->length != 0, ReportError(root, node)); ABSL_INTERNAL_CHECK(!node->IsCrc(), ReportError(root, node)); } if (node->IsFlat()) { ABSL_INTERNAL_CHECK(node->length <= node->flat()->Capacity(), ReportError(root, node)); } else if (node->IsExternal()) { ABSL_INTERNAL_CHECK(node->external()->base != nullptr, ReportError(root, node)); } else if (node->IsSubstring()) { ABSL_INTERNAL_CHECK( node->substring()->start < node->substring()->child->length, ReportError(root, node)); ABSL_INTERNAL_CHECK(node->substring()->start + node->length <= node->substring()->child->length, ReportError(root, node)); } else if (node->IsCrc()) { ABSL_INTERNAL_CHECK( node->crc()->child != nullptr || node->crc()->length == 0, ReportError(root, node)); if (node->crc()->child != nullptr) { ABSL_INTERNAL_CHECK(node->crc()->length == node->crc()->child->length, ReportError(root, node)); worklist.push_back(node->crc()->child); } } } while (!worklist.empty()); return true; } std::ostream& operator<<(std::ostream& out, const Cord& cord) { for (absl::string_view chunk : cord.Chunks()) { out.write(chunk.data(), static_cast<std::streamsize>(chunk.size())); } return out; } namespace strings_internal { size_t CordTestAccess::FlatOverhead() { return cord_internal::kFlatOverhead; } size_t CordTestAccess::MaxFlatLength() { return cord_internal::kMaxFlatLength; } size_t CordTestAccess::FlatTagToLength(uint8_t tag) { return cord_internal::TagToLength(tag); } uint8_t CordTestAccess::LengthToTag(size_t s) { ABSL_INTERNAL_CHECK(s <= kMaxFlatLength, absl::StrCat("Invalid length ", s)); return cord_internal::AllocatedSizeToTag(s + cord_internal::kFlatOverhead); } size_t CordTestAccess::SizeofCordRepExternal() { return sizeof(CordRepExternal); } size_t CordTestAccess::SizeofCordRepSubstring() { return sizeof(CordRepSubstring); } } ABSL_NAMESPACE_END }
#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/compare.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, GetAppendBufferOnFlat) { absl::Cord cord; absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500); const size_t expected_capacity = buffer.capacity(); buffer.SetLength(3); memcpy(buffer.data(), "Abc", 3); cord.Append(std::move(buffer)); buffer = GetAppendBuffer(cord, 6); EXPECT_EQ(buffer.capacity(), expected_capacity); EXPECT_EQ(buffer.length(), 3); EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc"); EXPECT_TRUE(cord.empty()); } TEST_P(CordAppendBufferTest, GetAppendBufferOnFlatWithoutMinCapacity) { absl::Cord cord; absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500); buffer.SetLength(30); memset(buffer.data(), 'x', 30); cord.Append(std::move(buffer)); buffer = GetAppendBuffer(cord, 1000, 900); EXPECT_GE(buffer.capacity(), 1000); EXPECT_EQ(buffer.length(), 0); EXPECT_EQ(cord, std::string(30, 'x')); } TEST_P(CordAppendBufferTest, GetAppendBufferOnTree) { RandomEngine rng; for (int num_flats : {2, 3, 100}) { absl::Cord cord; std::string prefix; std::string last; for (int i = 0; i < num_flats - 1; ++i) { prefix += last; last = RandomLowercaseString(&rng, 10); absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500); buffer.SetLength(10); memcpy(buffer.data(), last.data(), 10); cord.Append(std::move(buffer)); } absl::CordBuffer buffer = GetAppendBuffer(cord, 6); EXPECT_GE(buffer.capacity(), 500); EXPECT_EQ(buffer.length(), 10); EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), last); EXPECT_EQ(cord, prefix); } } TEST_P(CordAppendBufferTest, GetAppendBufferOnTreeWithoutMinCapacity) { absl::Cord cord; for (int i = 0; i < 2; ++i) { absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500); buffer.SetLength(3); memcpy(buffer.data(), i ? "def" : "Abc", 3); cord.Append(std::move(buffer)); } absl::CordBuffer buffer = GetAppendBuffer(cord, 1000, 900); EXPECT_GE(buffer.capacity(), 1000); EXPECT_EQ(buffer.length(), 0); EXPECT_EQ(cord, "Abcdef"); } TEST_P(CordAppendBufferTest, GetAppendBufferOnSubstring) { absl::Cord cord; absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500); buffer.SetLength(450); memset(buffer.data(), 'x', 450); cord.Append(std::move(buffer)); cord.RemovePrefix(1); buffer = GetAppendBuffer(cord, 6); EXPECT_EQ(buffer.length(), 0); EXPECT_EQ(cord, std::string(449, 'x')); } TEST_P(CordAppendBufferTest, GetAppendBufferOnSharedCord) { absl::Cord cord; absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500); buffer.SetLength(3); memcpy(buffer.data(), "Abc", 3); cord.Append(std::move(buffer)); absl::Cord shared_cord = cord; buffer = GetAppendBuffer(cord, 6); EXPECT_EQ(buffer.length(), 0); EXPECT_EQ(cord, "Abc"); buffer = absl::CordBuffer::CreateWithDefaultLimit(500); buffer.SetLength(3); memcpy(buffer.data(), "def", 3); cord.Append(std::move(buffer)); shared_cord = cord; buffer = GetAppendBuffer(cord, 6); EXPECT_EQ(buffer.length(), 0); EXPECT_EQ(cord, "Abcdef"); } TEST_P(CordTest, TryFlatEmpty) { absl::Cord c; EXPECT_EQ(c.TryFlat(), ""); } TEST_P(CordTest, TryFlatFlat) { absl::Cord c("hello"); MaybeHarden(c); EXPECT_EQ(c.TryFlat(), "hello"); } TEST_P(CordTest, TryFlatSubstrInlined) { absl::Cord c("hello"); c.RemovePrefix(1); MaybeHarden(c); EXPECT_EQ(c.TryFlat(), "ello"); } TEST_P(CordTest, TryFlatSubstrFlat) { absl::Cord c("longer than 15 bytes"); absl::Cord sub = absl::CordTestPeer::MakeSubstring(c, 1, c.size() - 1); MaybeHarden(sub); EXPECT_EQ(sub.TryFlat(), "onger than 15 bytes"); } TEST_P(CordTest, TryFlatConcat) { absl::Cord c = absl::MakeFragmentedCord({"hel", "lo"}); MaybeHarden(c); EXPECT_EQ(c.TryFlat(), absl::nullopt); } TEST_P(CordTest, TryFlatExternal) { absl::Cord c = absl::MakeCordFromExternal("hell", [](absl::string_view) {}); MaybeHarden(c); EXPECT_EQ(c.TryFlat(), "hell"); } TEST_P(CordTest, TryFlatSubstrExternal) { absl::Cord c = absl::MakeCordFromExternal("hell", [](absl::string_view) {}); absl::Cord sub = absl::CordTestPeer::MakeSubstring(c, 1, c.size() - 1); MaybeHarden(sub); EXPECT_EQ(sub.TryFlat(), "ell"); } TEST_P(CordTest, TryFlatCommonlyAssumedInvariants) { absl::string_view fragments[] = {"A fragmented test", " cord", " to test subcords", " of ", "a", " cord for", " each chunk " "returned by the ", "iterator"}; absl::Cord c = absl::MakeFragmentedCord(fragments); MaybeHarden(c); int fragment = 0; int offset = 0; absl::Cord::CharIterator itc = c.char_begin(); for (absl::string_view sv : c.Chunks()) { absl::string_view expected = fragments[fragment]; absl::Cord subcord1 = c.Subcord(offset, sv.length()); absl::Cord subcord2 = absl::Cord::AdvanceAndRead(&itc, sv.size()); EXPECT_EQ(subcord1.TryFlat(), expected); EXPECT_EQ(subcord2.TryFlat(), expected); ++fragment; offset += sv.length(); } } static bool IsFlat(const absl::Cord& c) { return c.chunk_begin() == c.chunk_end() || ++c.chunk_begin() == c.chunk_end(); } static void VerifyFlatten(absl::Cord c) { std::string old_contents(c); absl::string_view old_flat; bool already_flat_and_non_empty = IsFlat(c) && !c.empty(); if (already_flat_and_non_empty) { old_flat = *c.chunk_begin(); } absl::string_view new_flat = c.Flatten(); EXPECT_EQ(new_flat, old_contents); EXPECT_EQ(std::string(c), old_contents); if (already_flat_and_non_empty) { EXPECT_EQ(old_flat.data(), new_flat.data()) << "Allocated new memory even though the Cord was already flat."; } EXPECT_TRUE(IsFlat(c)); } TEST_P(CordTest, Flatten) { VerifyFlatten(absl::Cord()); VerifyFlatten(MaybeHardened(absl::Cord("small cord"))); VerifyFlatten( MaybeHardened(absl::Cord("larger than small buffer optimization"))); VerifyFlatten(MaybeHardened( absl::MakeFragmentedCord({"small ", "fragmented ", "cord"}))); RandomEngine rng(GTEST_FLAG_GET(random_seed)); VerifyFlatten(MaybeHardened(absl::Cord(RandomLowercaseString(&rng, 8192)))); } namespace { class TestData { private: std::vector<std::string> data_; static std::string MakeString(int length) { std::string result; char buf[30]; snprintf(buf, sizeof(buf), "(%d)", length); while (result.size() < length) { result += buf; } result.resize(length); return result; } public: TestData() { for (int i = 0; i < 30; i++) { data_.push_back(MakeString(i)); } static const int kMaxFlatLength = 4096 - 9; static const int kHalf = kMaxFlatLength / 2; for (int i = -10; i <= +10; i++) { data_.push_back(MakeString(kHalf + i)); } for (int i = -10; i <= +10; i++) { data_.push_back(MakeString(kMaxFlatLength + i)); } } size_t size() const { return data_.size(); } const std::string& data(size_t i) const { return data_[i]; } }; } TEST_P(CordTest, MultipleLengths) { TestData d; for (size_t i = 0; i < d.size(); i++) { std::string a = d.data(i); { absl::Cord tmp(a); absl::Cord x(tmp); MaybeHarden(x); EXPECT_EQ(a, std::string(x)) << "'" << a << "'"; } { absl::Cord x(a); MaybeHarden(x); EXPECT_EQ(a, std::string(x)) << "'" << a << "'"; } { absl::Cord self(a); MaybeHarden(self); self.Append(self); EXPECT_EQ(a + a, std::string(self)) << "'" << a << "' + '" << a << "'"; } { absl::Cord self(a); MaybeHarden(self); self.Prepend(self); EXPECT_EQ(a + a, std::string(self)) << "'" << a << "' + '" << a << "'"; } for (size_t j = 0; j < d.size(); j++) { std::string b = d.data(j); { absl::Cord x(a); absl::Cord y(b); MaybeHarden(x); x = y; EXPECT_EQ(b, std::string(x)) << "'" << a << "' + '" << b << "'"; } { absl::Cord x(a); MaybeHarden(x); x = b; EXPECT_EQ(b, std::string(x)) << "'" << a << "' + '" << b << "'"; } { absl::Cord x(a); absl::Cord y(b); MaybeHarden(x); x.Append(y); EXPECT_EQ(a + b, std::string(x)) << "'" << a << "' + '" << b << "'"; } { absl::Cord x(a); MaybeHarden(x); x.Append(b); EXPECT_EQ(a + b, std::string(x)) << "'" << a << "' + '" << b << "'"; } { absl::Cord x(a); absl::Cord y(b); MaybeHarden(x); x.Prepend(y); EXPECT_EQ(b + a, std::string(x)) << "'" << b << "' + '" << a << "'"; } { absl::Cord x(a); MaybeHarden(x); x.Prepend(b); EXPECT_EQ(b + a, std::string(x)) << "'" << b << "' + '" << a << "'"; } } } } namespace { TEST_P(CordTest, RemoveSuffixWithExternalOrSubstring) { absl::Cord cord = absl::MakeCordFromExternal( "foo bar baz", [](absl::string_view s) { DoNothing(s, nullptr); }); EXPECT_EQ("foo bar baz", std::string(cord)); MaybeHarden(cord); cord.RemoveSuffix(4); EXPECT_EQ("foo bar", std::string(cord)); MaybeHarden(cord); cord.RemoveSuffix(4); EXPECT_EQ("foo", std::string(cord)); } TEST_P(CordTest, RemoveSuffixMakesZeroLengthNode) { absl::Cord c; c.Append(absl::Cord(std::string(100, 'x'))); absl::Cord other_ref = c; EXPECT_THAT(other_ref, testing::Eq(c)); MaybeHarden(c); c.Append(absl::Cord(std::string(200, 'y'))); c.RemoveSuffix(200); EXPECT_EQ(std::string(100, 'x'), std::string(c)); } } namespace { absl::Cord CordWithZedBlock(size_t size) { char* data = new char[size]; if (size > 0) { memset(data, 'z', size); } absl::Cord cord = absl::MakeCordFromExternal( absl::string_view(data, size), [](absl::string_view s) { delete[] s.data(); }); return cord; } TEST_P(CordTest, CordSpliceTestZedBlock) { absl::Cord blob = CordWithZedBlock(10); MaybeHarden(blob); EXPECT_EQ(10, blob.size()); std::string s; absl::CopyCordToString(blob, &s); EXPECT_EQ("zzzzzzzzzz", s); } TEST_P(CordTest, CordSpliceTestZedBlock0) { absl::Cord blob = CordWithZedBlock(0); MaybeHarden(blob); EXPECT_EQ(0, blob.size()); std::string s; absl::CopyCordToString(blob, &s); EXPECT_EQ("", s); } TEST_P(CordTest, CordSpliceTestZedBlockSuffix1) { absl::Cord blob = CordWithZedBlock(10); MaybeHarden(blob); EXPECT_EQ(10, blob.size()); absl::Cord suffix(blob); suffix.RemovePrefix(9); EXPECT_EQ(1, suffix.size()); std::string s; absl::CopyCordToString(suffix, &s); EXPECT_EQ("z", s); } TEST_P(CordTest, CordSpliceTestZedBlockSuffix0) { absl::Cord blob = CordWithZedBlock(10); MaybeHarden(blob); EXPECT_EQ(10, blob.size()); absl::Cord suffix(blob); suffix.RemovePrefix(10); EXPECT_EQ(0, suffix.size()); std::string s; absl::CopyCordToString(suffix, &s); EXPECT_EQ("", s); } absl::Cord BigCord(size_t len, char v) { std::string s(len, v); return absl::Cord(s); } absl::Cord SpliceCord(const absl::Cord& blob, int64_t offset, const absl::Cord& block) { CHECK_GE(offset, 0); CHECK_LE(static_cast<size_t>(offset) + block.size(), blob.size()); absl::Cord result(blob); result.RemoveSuffix(blob.size() - offset); result.Append(block); absl::Cord suffix(blob); suffix.RemovePrefix(offset + block.size()); result.Append(suffix); CHECK_EQ(blob.size(), result.size()); return result; } TEST_P(CordTest, CordSpliceTestRemoveEntireBlock1) { absl::Cord zero = CordWithZedBlock(10); MaybeHarden(zero); absl::Cord suffix(zero); suffix.RemovePrefix(10); absl::Cord result; result.Append(suffix); } TEST_P(CordTest, CordSpliceTestRemoveEntireBlock2) { absl::Cord zero = CordWithZedBlock(10); MaybeHarden(zero); absl::Cord prefix(zero); prefix.RemoveSuffix(10); absl::Cord suffix(zero); suffix.RemovePrefix(10); absl::Cord result(prefix); result.Append(suffix); } TEST_P(CordTest, CordSpliceTestRemoveEntireBlock3) { absl::Cord blob = CordWithZedBlock(10); absl::Cord block = BigCord(10, 'b'); MaybeHarden(blob); MaybeHarden(block); blob = SpliceCord(blob, 0, block); } struct CordCompareTestCase { template <typename LHS, typename RHS> CordCompareTestCase(const LHS& lhs, const RHS& rhs, bool use_crc) : lhs_cord(lhs), rhs_cord(rhs) { if (use_crc) { lhs_cord.SetExpectedChecksum(1); } } absl::Cord lhs_cord; absl::Cord rhs_cord; }; const auto sign = [](int x) { return x == 0 ? 0 : (x > 0 ? 1 : -1); }; void VerifyComparison(const CordCompareTestCase& test_case) { std::string lhs_string(test_case.lhs_cord); std::string rhs_string(test_case.rhs_cord); int expected = sign(lhs_string.compare(rhs_string)); EXPECT_EQ(expected, test_case.lhs_cord.Compare(test_case.rhs_cord)) << "LHS=" << lhs_string << "; RHS=" << rhs_string; EXPECT_EQ(expected, test_case.lhs_cord.Compare(rhs_string)) << "LHS=" << lhs_string << "; RHS=" << rhs_string; EXPECT_EQ(-expected, test_case.rhs_cord.Compare(test_case.lhs_cord)) << "LHS=" << rhs_string << "; RHS=" << lhs_string; EXPECT_EQ(-expected, test_case.rhs_cord.Compare(lhs_string)) << "LHS=" << rhs_string << "; RHS=" << lhs_string; } TEST_P(CordTest, Compare) { absl::Cord subcord("aaaaaBBBBBcccccDDDDD"); subcord = subcord.Subcord(3, 10); absl::Cord tmp("aaaaaaaaaaaaaaaa"); tmp.Append("BBBBBBBBBBBBBBBB"); absl::Cord concat = absl::Cord("cccccccccccccccc"); concat.Append("DDDDDDDDDDDDDDDD"); concat.Prepend(tmp); absl::Cord concat2("aaaaaaaaaaaaa"); concat2.Append("aaaBBBBBBBBBBBBBBBBccccc"); concat2.Append("cccccccccccDDDDDDDDDDDDDD"); concat2.Append("DD"); const bool use_crc = UseCrc(); std::vector<CordCompareTestCase> test_cases = {{ {"abcdef", "abcdef", use_crc}, {"abcdef", "abcdee", use_crc}, {"abcdef", "abcdeg", use_crc}, {"bbcdef", "abcdef", use_crc}, {"bbcdef", "abcdeg", use_crc}, {"abcdefa", "abcdef", use_crc}, {"abcdef", "abcdefa", use_crc}, {"aaaaaBBBBBcccccDDDDD", "aaaaaBBBBBcccccDDDDD", use_crc}, {"aaaaaBBBBBcccccDDDDD", "aaaaaBBBBBxccccDDDDD", use_crc}, {"aaaaaBBBBBcxcccDDDDD", "aaaaaBBBBBcccccDDDDD", use_crc}, {"aaaaaBBBBBxccccDDDDD", "aaaaaBBBBBcccccDDDDX", use_crc}, {"aaaaaBBBBBcccccDDDDDa", "aaaaaBBBBBcccccDDDDD", use_crc}, {"aaaaaBBBBBcccccDDDDD", "aaaaaBBBBBcccccDDDDDa", use_crc}, {subcord, subcord, use_crc}, {subcord, "aaBBBBBccc", use_crc}, {subcord, "aaBBBBBccd", use_crc}, {subcord, "aaBBBBBccb", use_crc}, {subcord, "aaBBBBBxcb", use_crc}, {subcord, "aaBBBBBccca", use_crc}, {subcord, "aaBBBBBcc", use_crc}, {concat, concat, use_crc}, {concat, "aaaaaaaaaaaaaaaaBBBBBBBBBBBBBBBBccccccccccccccccDDDDDDDDDDDDDDDD", use_crc}, {concat, "aaaaaaaaaaaaaaaaBBBBBBBBBBBBBBBBcccccccccccccccxDDDDDDDDDDDDDDDD", use_crc}, {concat, "aaaaaaaaaaaaaaaaBBBBBBBBBBBBBBBBacccccccccccccccDDDDDDDDDDDDDDDD", use_crc}, {concat, "aaaaaaaaaaaaaaaaBBBBBBBBBBBBBBBBccccccccccccccccDDDDDDDDDDDDDDD", use_crc}, {concat, "aaaaaaaaaaaaaaaaBBBBBBBBBBBBBBBBccccccccccccccccDDDDDDDDDDDDDDDDe", use_crc}, {concat, concat2, use_crc}, }}; for (const auto& tc : test_cases) { VerifyComparison(tc); } } TEST_P(CordTest, CompareAfterAssign) { absl::Cord a("aaaaaa1111111"); absl::Cord b("aaaaaa2222222"); MaybeHarden(a); a = "cccccc"; b = "cccccc"; EXPECT_EQ(a, b); EXPECT_FALSE(a < b); a = "aaaa"; b = "bbbbb"; a = ""; b = ""; EXPECT_EQ(a, b); EXPECT_FALSE(a < b); } static void TestCompare(const absl::Cord& c, const absl::Cord& d, RandomEngine* rng) { int expected = sign(std::string(c).compare(std::string(d))); EXPECT_EQ(expected, sign(c.Compare(d))) << c << ", " << d; } TEST_P(CordTest, CompareComparisonIsUnsigned) { RandomEngine rng(GTEST_FLAG_GET(random_seed)); std::uniform_int_distribution<uint32_t> uniform_uint8(0, 255); char x = static_cast<char>(uniform_uint8(rng)); TestCompare( absl::Cord(std::string(GetUniformRandomUpTo(&rng, 100), x)), absl::Cord(std::string(GetUniformRandomUpTo(&rng, 100), x ^ 0x80)), &rng); } TEST_P(CordTest, CompareRandomComparisons) { const int kIters = 5000; RandomEngine rng(GTEST_FLAG_GET(random_seed)); int n = GetUniformRandomUpTo(&rng, 5000); absl::Cord a[] = {MakeExternalCord(n), absl::Cord("ant"), absl::Cord("elephant"), absl::Cord("giraffe"), absl::Cord(std::string(GetUniformRandomUpTo(&rng, 100), GetUniformRandomUpTo(&rng, 100))), absl::Cord(""), absl::Cord("x"), absl::Cord("A"), absl::Cord("B"), absl::Cord("C")}; for (int i = 0; i < kIters; i++) { absl::Cord c, d; for (int j = 0; j < (i % 7) + 1; j++) { c.Append(a[GetUniformRandomUpTo(&rng, ABSL_ARRAYSIZE(a))]); d.Append(a[GetUniformRandomUpTo(&rng, ABSL_ARRAYSIZE(a))]); } std::bernoulli_distribution coin_flip(0.5); MaybeHarden(c); MaybeHarden(d); TestCompare(coin_flip(rng) ? c : absl::Cord(std::string(c)), coin_flip(rng) ? d : absl::Cord(std::string(d)), &rng); } } template <typename T1, typename T2> void CompareOperators() { const T1 a("a"); const T2 b("b"); EXPECT_TRUE(a == a); EXPECT_TRUE(std::is_pointer<T1>::value || a == T1("a")); EXPECT_TRUE(std::is_pointer<T2>::value || a == T2("a")); EXPECT_FALSE(a == b); EXPECT_TRUE(a != b); EXPECT_FALSE(a != a); EXPECT_TRUE(a < b); EXPECT_FALSE(b < a); EXPECT_TRUE(b > a); EXPECT_FALSE(a > b); EXPECT_TRUE(a >= a); EXPECT_TRUE(b >= a); EXPECT_FALSE(a >= b); EXPECT_TRUE(a <= a); EXPECT_TRUE(a <= b); EXPECT_FALSE(b <= a); } TEST_P(CordTest, ComparisonOperators_Cord_Cord) { CompareOperators<absl::Cord, absl::Cord>(); } TEST_P(CordTest, ComparisonOperators_Cord_StringPiece) { CompareOperators<absl::Cord, absl::string_view>(); } TEST_P(CordTest, ComparisonOperators_StringPiece_Cord) { CompareOperators<absl::string_view, absl::Cord>(); } TEST_P(CordTest, ComparisonOperators_Cord_string) { CompareOperators<absl::Cord, std::string>(); } TEST_P(CordTest, ComparisonOperators_string_Cord) { CompareOperators<std::string, absl::Cord>(); } TEST_P(CordTest, ComparisonOperators_stdstring_Cord) { CompareOperators<std::string, absl::Cord>(); } TEST_P(CordTest, ComparisonOperators_Cord_stdstring) { CompareOperators<absl::Cord, std::string>(); } TEST_P(CordTest, ComparisonOperators_charstar_Cord) { CompareOperators<const char*, absl::Cord>(); } TEST_P(CordTest, ComparisonOperators_Cord_charstar) { CompareOperators<absl::Cord, const char*>(); } TEST_P(CordTest, ConstructFromExternalReleaserInvoked) { { bool invoked = false; auto releaser = [&invoked](absl::string_view) { invoked = true; }; { auto c = absl::MakeCordFromExternal("", releaser); EXPECT_THAT(c, testing::Eq("")); EXPECT_TRUE(invoked); } } std::string large_dummy(2048, 'c'); { bool invoked = false; auto releaser = [&invoked](absl::string_view) { invoked = true; }; { auto c = absl::MakeCordFromExternal(large_dummy, releaser); EXPECT_THAT(c, testing::Eq(large_dummy)); EXPECT_FALSE(invoked); } EXPECT_TRUE(invoked); } { bool invoked = false; auto releaser = [&invoked](absl::string_view) { invoked = true; }; { absl::Cord copy; { auto c = absl::MakeCordFromExternal(large_dummy, releaser); copy = c; EXPECT_FALSE(invoked); } EXPECT_FALSE(invoked); } EXPECT_TRUE(invoked); } } TEST_P(CordTest, ConstructFromExternalCompareContents) { RandomEngine rng(GTEST_FLAG_GET(random_seed)); for (int length = 1; length <= 2048; length *= 2) { std::string data = RandomLowercaseString(&rng, length); auto* external = new std::string(data); auto cord = absl::MakeCordFromExternal(*external, [external](absl::string_view sv) { EXPECT_EQ(external->data(), sv.data()); EXPECT_EQ(external->size(), sv.size()); delete external; }); MaybeHarden(cord); EXPECT_EQ(data, cord); } } TEST_P(CordTest, ConstructFromExternalLargeReleaser) { RandomEngine rng(GTEST_FLAG_GET(random_seed)); constexpr size_t kLength = 256; std::string data = RandomLowercaseString(&rng, kLength); std::array<char, kLength> data_array; for (size_t i = 0; i < kLength; ++i) data_array[i] = data[i]; bool invoked = false; auto releaser = [data_array, &invoked](absl::string_view data) { EXPECT_EQ(data, absl::string_view(data_array.data(), data_array.size())); invoked = true; }; (void)MaybeHardened(absl::MakeCordFromExternal(data, releaser)); EXPECT_TRUE(invoked); } TEST_P(CordTest, ConstructFromExternalFunctionPointerReleaser) { static absl::string_view data("hello world"); static bool invoked; auto* releaser = static_cast<void (*)(absl::string_view)>([](absl::string_view sv) { EXPECT_EQ(data, sv); invoked = true; }); invoked = false; (void)MaybeHardened(absl::MakeCordFromExternal(data, releaser)); EXPECT_TRUE(invoked); invoked = false; (void)MaybeHardened(absl::MakeCordFromExternal(data, *releaser)); EXPECT_TRUE(invoked); } TEST_P(CordTest, ConstructFromExternalMoveOnlyReleaser) { struct Releaser { explicit Releaser(bool* invoked) : invoked(invoked) {} Releaser(Releaser&& other) noexcept : invoked(other.invoked) {} void operator()(absl::string_view) const { *invoked = true; } bool* invoked; }; bool invoked = false; (void)MaybeHardened(absl::MakeCordFromExternal("dummy", Releaser(&invoked))); EXPECT_TRUE(invoked); } TEST_P(CordTest, ConstructFromExternalNoArgLambda) { bool invoked = false; (void)MaybeHardened( absl::MakeCordFromExternal("dummy", [&invoked]() { invoked = true; })); EXPECT_TRUE(invoked); } TEST_P(CordTest, ConstructFromExternalStringViewArgLambda) { bool invoked = false; (void)MaybeHardened(absl::MakeCordFromExternal( "dummy", [&invoked](absl::string_view) { invoked = true; })); EXPECT_TRUE(invoked); } TEST_P(CordTest, ConstructFromExternalNonTrivialReleaserDestructor) { struct Releaser { explicit Releaser(bool* destroyed) : destroyed(destroyed) {} ~Releaser() { *destroyed = true; } void operator()(absl::string_view) const {} bool* destroyed; }; bool destroyed = false; Releaser releaser(&destroyed); (void)MaybeHardened(absl::MakeCordFromExternal("dummy", releaser)); EXPECT_TRUE(destroyed); } TEST_P(CordTest, ConstructFromExternalReferenceQualifierOverloads) { enum InvokedAs { kMissing, kLValue, kRValue }; enum CopiedAs { kNone, kMove, kCopy }; struct Tracker { CopiedAs copied_as = kNone; InvokedAs invoked_as = kMissing; void Record(InvokedAs rhs) { ASSERT_EQ(invoked_as, kMissing); invoked_as = rhs; } void Record(CopiedAs rhs) { if (copied_as == kNone || rhs == kCopy) copied_as = rhs; } } tracker; class Releaser { public: explicit Releaser(Tracker* tracker) : tr_(tracker) { *tracker = Tracker(); } Releaser(Releaser&& rhs) : tr_(rhs.tr_) { tr_->Record(kMove); } Releaser(const Releaser& rhs) : tr_(rhs.tr_) { tr_->Record(kCopy); } void operator()(absl::string_view) & { tr_->Record(kLValue); } void operator()(absl::string_view) && { tr_->Record(kRValue); } private: Tracker* tr_; }; const Releaser releaser1(&tracker); (void)MaybeHardened(absl::MakeCordFromExternal("", releaser1)); EXPECT_EQ(tracker.copied_as, kCopy); EXPECT_EQ(tracker.invoked_as, kRValue); const Releaser releaser2(&tracker); (void)MaybeHardened(absl::MakeCordFromExternal("", releaser2)); EXPECT_EQ(tracker.copied_as, kCopy); EXPECT_EQ(tracker.invoked_as, kRValue); Releaser releaser3(&tracker); (void)MaybeHardened(absl::MakeCordFromExternal("", std::move(releaser3))); EXPECT_EQ(tracker.copied_as, kMove); EXPECT_EQ(tracker.invoked_as, kRValue); Releaser releaser4(&tracker); (void)MaybeHardened(absl::MakeCordFromExternal("dummy", releaser4)); EXPECT_EQ(tracker.copied_as, kCopy); EXPECT_EQ(tracker.invoked_as, kRValue); const Releaser releaser5(&tracker); (void)MaybeHardened(absl::MakeCordFromExternal("dummy", releaser5)); EXPECT_EQ(tracker.copied_as, kCopy); EXPECT_EQ(tracker.invoked_as, kRValue); Releaser releaser6(&tracker); (void)MaybeHardened(absl::MakeCordFromExternal("foo", std::move(releaser6))); EXPECT_EQ(tracker.copied_as, kMove); EXPECT_EQ(tracker.invoked_as, kRValue); } TEST_P(CordTest, ExternalMemoryBasicUsage) { static const char* strings[] = {"", "hello", "there"}; for (const char* str : strings) { absl::Cord dst("(prefix)"); MaybeHarden(dst); AddExternalMemory(str, &dst); MaybeHarden(dst); dst.Append("(suffix)"); EXPECT_EQ((std::string("(prefix)") + str + std::string("(suffix)")), std::string(dst)); } } TEST_P(CordTest, ExternalMemoryRemovePrefixSuffix) { absl::Cord cord = MakeComposite(); std::string s = std::string(cord); for (int offset = 0; offset <= s.size(); offset++) { for (int length = 0; length <= s.size() - offset; length++) { absl::Cord result(cord); MaybeHarden(result); result.RemovePrefix(offset); MaybeHarden(result); result.RemoveSuffix(result.size() - length); EXPECT_EQ(s.substr(offset, length), std::string(result)) << offset << " " << length; } } } TEST_P(CordTest, ExternalMemoryGet) { absl::Cord cord("hello"); AddExternalMemory(" world!", &cord); MaybeHarden(cord); AddExternalMemory(" how are ", &cord); cord.Append(" you?"); MaybeHarden(cord); std::string s = std::string(cord); for (int i = 0; i < s.size(); i++) { EXPECT_EQ(s[i], cord[i]); } } constexpr auto kFairShare = absl::CordMemoryAccounting::kFairShare; constexpr auto kTotalMorePrecise = absl::CordMemoryAccounting::kTotalMorePrecise; absl::Cord MakeCord(size_t n, char c) { const std::string s(n, c); return absl::Cord(s); } TEST(CordTest, CordMemoryUsageEmpty) { absl::Cord cord; EXPECT_EQ(sizeof(absl::Cord), cord.EstimatedMemoryUsage()); EXPECT_EQ(sizeof(absl::Cord), cord.EstimatedMemoryUsage(kFairShare)); EXPECT_EQ(sizeof(absl::Cord), cord.EstimatedMemoryUsage(kTotalMorePrecise)); } TEST(CordTest, CordMemoryUsageInlined) { absl::Cord a("hello"); EXPECT_EQ(a.EstimatedMemoryUsage(), sizeof(absl::Cord)); EXPECT_EQ(a.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord)); EXPECT_EQ(a.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord)); } TEST(CordTest, CordMemoryUsageExternalMemory) { absl::Cord cord; AddExternalMemory(std::string(1000, 'x'), &cord); const size_t expected = sizeof(absl::Cord) + 1000 + sizeof(CordRepExternal) + sizeof(intptr_t); EXPECT_EQ(cord.EstimatedMemoryUsage(), expected); EXPECT_EQ(cord.EstimatedMemoryUsage(kFairShare), expected); EXPECT_EQ(cord.EstimatedMemoryUsage(kTotalMorePrecise), expected); } TEST(CordTest, CordMemoryUsageFlat) { absl::Cord cord = MakeCord(1000, 'a'); const size_t flat_size = absl::CordTestPeer::Tree(cord)->flat()->AllocatedSize(); EXPECT_EQ(cord.EstimatedMemoryUsage(), sizeof(absl::Cord) + flat_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + flat_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + flat_size); } TEST(CordTest, CordMemoryUsageSubStringSharedFlat) { absl::Cord flat = MakeCord(2000, 'a'); const size_t flat_size = absl::CordTestPeer::Tree(flat)->flat()->AllocatedSize(); absl::Cord cord = flat.Subcord(500, 1000); EXPECT_EQ(cord.EstimatedMemoryUsage(), sizeof(absl::Cord) + sizeof(CordRepSubstring) + flat_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + sizeof(CordRepSubstring) + flat_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + sizeof(CordRepSubstring) + flat_size / 2); } TEST(CordTest, CordMemoryUsageFlatShared) { absl::Cord shared = MakeCord(1000, 'a'); absl::Cord cord(shared); const size_t flat_size = absl::CordTestPeer::Tree(cord)->flat()->AllocatedSize(); EXPECT_EQ(cord.EstimatedMemoryUsage(), sizeof(absl::Cord) + flat_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + flat_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + flat_size / 2); } TEST(CordTest, CordMemoryUsageFlatHardenedAndShared) { absl::Cord shared = MakeCord(1000, 'a'); absl::Cord cord(shared); const size_t flat_size = absl::CordTestPeer::Tree(cord)->flat()->AllocatedSize(); cord.SetExpectedChecksum(1); EXPECT_EQ(cord.EstimatedMemoryUsage(), sizeof(absl::Cord) + sizeof(CordRepCrc) + flat_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + sizeof(CordRepCrc) + flat_size / 2); absl::Cord cord2(cord); EXPECT_EQ(cord2.EstimatedMemoryUsage(), sizeof(absl::Cord) + sizeof(CordRepCrc) + flat_size); EXPECT_EQ(cord2.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + sizeof(CordRepCrc) + flat_size); EXPECT_EQ(cord2.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + (sizeof(CordRepCrc) + flat_size / 2) / 2); } TEST(CordTest, CordMemoryUsageBTree) { absl::Cord cord1; size_t flats1_size = 0; absl::Cord flats1[4] = {MakeCord(1000, 'a'), MakeCord(1100, 'a'), MakeCord(1200, 'a'), MakeCord(1300, 'a')}; for (absl::Cord flat : flats1) { flats1_size += absl::CordTestPeer::Tree(flat)->flat()->AllocatedSize(); cord1.Append(std::move(flat)); } if (!absl::CordTestPeer::Tree(cord1)->IsBtree()) { LOG(WARNING) << "Cord library code not respecting btree flag"; return; } size_t rep1_size = sizeof(CordRepBtree) + flats1_size; size_t rep1_shared_size = sizeof(CordRepBtree) + flats1_size / 2; EXPECT_EQ(cord1.EstimatedMemoryUsage(), sizeof(absl::Cord) + rep1_size); EXPECT_EQ(cord1.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + rep1_size); EXPECT_EQ(cord1.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + rep1_shared_size); absl::Cord cord2; size_t flats2_size = 0; absl::Cord flats2[4] = {MakeCord(600, 'a'), MakeCord(700, 'a'), MakeCord(800, 'a'), MakeCord(900, 'a')}; for (absl::Cord& flat : flats2) { flats2_size += absl::CordTestPeer::Tree(flat)->flat()->AllocatedSize(); cord2.Append(std::move(flat)); } size_t rep2_size = sizeof(CordRepBtree) + flats2_size; EXPECT_EQ(cord2.EstimatedMemoryUsage(), sizeof(absl::Cord) + rep2_size); EXPECT_EQ(cord2.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + rep2_size); EXPECT_EQ(cord2.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + rep2_size); absl::Cord cord(cord1); cord.Append(std::move(cord2)); EXPECT_EQ(cord.EstimatedMemoryUsage(), sizeof(absl::Cord) + sizeof(CordRepBtree) + rep1_size + rep2_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + sizeof(CordRepBtree) + rep1_size + rep2_size); EXPECT_EQ(cord.EstimatedMemoryUsage(kFairShare), sizeof(absl::Cord) + sizeof(CordRepBtree) + rep1_shared_size / 2 + rep2_size); } TEST(CordTest, TestHashFragmentation) { EXPECT_EQ(1024, absl::hash_internal::PiecewiseChunkSize()); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ absl::Cord(), absl::MakeFragmentedCord({std::string(600, 'a'), std::string(600, 'a')}), absl::MakeFragmentedCord({std::string(1200, 'a')}), absl::MakeFragmentedCord({std::string(900, 'b'), std::string(900, 'b')}), absl::MakeFragmentedCord({std::string(1800, 'b')}), absl::MakeFragmentedCord( {std::string(2000, 'c'), std::string(2000, 'c')}), absl::MakeFragmentedCord({std::string(4000, 'c')}), absl::MakeFragmentedCord({std::string(1024, 'd')}), absl::MakeFragmentedCord({std::string(1023, 'd'), "d"}), absl::MakeFragmentedCord({std::string(1025, 'e')}), absl::MakeFragmentedCord({std::string(1024, 'e'), "e"}), absl::MakeFragmentedCord({std::string(1023, 'e'), "e", "e"}), })); } TEST_P(CordTest, CordMemoryUsageInlineRep) { constexpr size_t kMaxInline = 15; const std::string small_string(kMaxInline, 'x'); absl::Cord c1(small_string); absl::Cord c2; c2.Append(small_string); EXPECT_EQ(c1, c2); EXPECT_EQ(c1.EstimatedMemoryUsage(), c2.EstimatedMemoryUsage()); } TEST_P(CordTest, CordMemoryUsageTotalMorePreciseMode) { constexpr size_t kChunkSize = 2000; std::string tmp_str(kChunkSize, 'x'); const absl::Cord flat(std::move(tmp_str)); absl::Cord fragmented(flat); fragmented.Append(flat); const size_t flat_internal_usage = flat.EstimatedMemoryUsage() - sizeof(absl::Cord); EXPECT_EQ(fragmented.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + sizeof(CordRepBtree) + flat_internal_usage); EXPECT_EQ(fragmented.EstimatedMemoryUsage(), sizeof(absl::Cord) + sizeof(CordRepBtree) + 2 * flat_internal_usage); } TEST_P(CordTest, CordMemoryUsageTotalMorePreciseModeWithSubstring) { constexpr size_t kChunkSize = 2000; std::string tmp_str(kChunkSize, 'x'); const absl::Cord flat(std::move(tmp_str)); absl::Cord fragmented; fragmented.Append(flat.Subcord(1, kChunkSize - 2)); fragmented.Append(flat.Subcord(1, kChunkSize - 2)); const size_t flat_internal_usage = flat.EstimatedMemoryUsage() - sizeof(absl::Cord); EXPECT_EQ(fragmented.EstimatedMemoryUsage(kTotalMorePrecise), sizeof(absl::Cord) + sizeof(CordRepBtree) + 2 * sizeof(CordRepSubstring) + flat_internal_usage); EXPECT_EQ(fragmented.EstimatedMemoryUsage(), sizeof(absl::Cord) + sizeof(CordRepBtree) + 2 * sizeof(CordRepSubstring) + 2 * flat_internal_usage); } } TEST_P(CordTest, Concat_Append) { absl::Cord s1("foobarbarbarbarbar"); MaybeHarden(s1); s1.Append("abcdefgabcdefgabcdefgabcdefgabcdefgabcdefgabcdefg"); size_t size = s1.size(); absl::Cord s2 = s1; MaybeHarden(s2); s2.Append("x"); EXPECT_EQ(s1.size(), size); EXPECT_EQ(s2.size(), size + 1); } TEST_P(CordTest, DiabolicalGrowth) { RandomEngine rng(GTEST_FLAG_GET(random_seed)); const std::string expected = RandomLowercaseString(&rng, 5000); absl::Cord cord; for (char c : expected) { absl::Cord shared(cord); EXPECT_THAT(cord, testing::Eq(shared)); cord.Append(absl::string_view(&c, 1)); MaybeHarden(cord); } std::string value; absl::CopyCordToString(cord, &value); EXPECT_EQ(value, expected); LOG(INFO) << "Diabolical size allocated = " << cord.EstimatedMemoryUsage(); } static absl::Cord MakeHuge(absl::string_view prefix) { absl::Cord cord; if (sizeof(size_t) > 4) { const size_t size = static_cast<size_t>(std::numeric_limits<uint32_t>::max()) + 314; cord.Append(absl::MakeCordFromExternal( absl::string_view(prefix.data(), size), [](absl::string_view s) { DoNothing(s, nullptr); })); } else { const size_t s1 = (1u << 31) - 1; const size_t s2 = 600; cord.Append(absl::MakeCordFromExternal( absl::string_view(prefix.data(), s1), [](absl::string_view s) { DoNothing(s, nullptr); })); cord.Append(absl::MakeCordFromExternal( absl::string_view("", s2), [](absl::string_view s) { DoNothing(s, nullptr); })); } return cord; } TEST_P(CordTest, HugeCord) { absl::Cord cord = MakeHuge("huge cord"); MaybeHarden(cord); const size_t acceptable_delta = 100 + (UseCrc() ? sizeof(absl::cord_internal::CordRepCrc) : 0); EXPECT_LE(cord.size(), cord.EstimatedMemoryUsage()); EXPECT_GE(cord.size() + acceptable_delta, cord.EstimatedMemoryUsage()); } TEST_P(CordTest, AppendSelf) { absl::Cord empty; MaybeHarden(empty); empty.Append(empty); ASSERT_EQ(empty, ""); std::string control_data = "Abc"; absl::Cord data(control_data); while (control_data.length() < 0x4000) { MaybeHarden(data); data.Append(data); control_data.append(control_data); ASSERT_EQ(control_data, data); } } TEST_P(CordTest, MakeFragmentedCordFromInitializerList) { absl::Cord fragmented = absl::MakeFragmentedCord({"A ", "fragmented ", "Cord"}); MaybeHarden(fragmented); EXPECT_EQ("A fragmented Cord", fragmented); auto chunk_it = fragmented.chunk_begin(); ASSERT_TRUE(chunk_it != fragmented.chunk_end()); EXPECT_EQ("A ", *chunk_it); ASSERT_TRUE(++chunk_it != fragmented.chunk_end()); EXPECT_EQ("fragmented ", *chunk_it); ASSERT_TRUE(++chunk_it != fragmented.chunk_end()); EXPECT_EQ("Cord", *chunk_it); ASSERT_TRUE(++chunk_it == fragmented.chunk_end()); } TEST_P(CordTest, MakeFragmentedCordFromVector) { std::vector<absl::string_view> chunks = {"A ", "fragmented ", "Cord"}; absl::Cord fragmented = absl::MakeFragmentedCord(chunks); MaybeHarden(fragmented); EXPECT_EQ("A fragmented Cord", fragmented); auto chunk_it = fragmented.chunk_begin(); ASSERT_TRUE(chunk_it != fragmented.chunk_end()); EXPECT_EQ("A ", *chunk_it); ASSERT_TRUE(++chunk_it != fragmented.chunk_end()); EXPECT_EQ("fragmented ", *chunk_it); ASSERT_TRUE(++chunk_it != fragmented.chunk_end()); EXPECT_EQ("Cord", *chunk_it); ASSERT_TRUE(++chunk_it == fragmented.chunk_end()); } TEST_P(CordTest, CordChunkIteratorTraits) { static_assert(std::is_copy_constructible<absl::Cord::ChunkIterator>::value, ""); static_assert(std::is_copy_assignable<absl::Cord::ChunkIterator>::value, ""); static_assert(std::is_move_constructible<absl::Cord::ChunkIterator>::value, ""); static_assert(std::is_move_assignable<absl::Cord::ChunkIterator>::value, ""); static_assert( std::is_same< std::iterator_traits<absl::Cord::ChunkIterator>::iterator_category, std::input_iterator_tag>::value, ""); static_assert( std::is_same<std::iterator_traits<absl::Cord::ChunkIterator>::value_type, absl::string_view>::value, ""); static_assert( std::is_same< std::iterator_traits<absl::Cord::ChunkIterator>::difference_type, ptrdiff_t>::value, ""); static_assert( std::is_same<std::iterator_traits<absl::Cord::ChunkIterator>::pointer, const absl::string_view*>::value, ""); static_assert( std::is_same<std::iterator_traits<absl::Cord::ChunkIterator>::reference, absl::string_view>::value, ""); } static void VerifyChunkIterator(const absl::Cord& cord, size_t expected_chunks) { EXPECT_EQ(cord.chunk_begin() == cord.chunk_end(), cord.empty()) << cord; EXPECT_EQ(cord.chunk_begin() != cord.chunk_end(), !cord.empty()); absl::Cord::ChunkRange range = cord.Chunks(); EXPECT_EQ(range.begin() == range.end(), cord.empty()); EXPECT_EQ(range.begin() != range.end(), !cord.empty()); std::string content(cord); size_t pos = 0; auto pre_iter = cord.chunk_begin(), post_iter = cord.chunk_begin(); size_t n_chunks = 0; while (pre_iter != cord.chunk_end() && post_iter != cord.chunk_end()) { EXPECT_FALSE(pre_iter == cord.chunk_end()); EXPECT_FALSE(post_iter == cord.chunk_end()); EXPECT_EQ(pre_iter, post_iter); EXPECT_EQ(*pre_iter, *post_iter); EXPECT_EQ(pre_iter->data(), (*pre_iter).data()); EXPECT_EQ(pre_iter->size(), (*pre_iter).size()); absl::string_view chunk = *pre_iter; EXPECT_FALSE(chunk.empty()); EXPECT_LE(pos + chunk.size(), content.size()); EXPECT_EQ(absl::string_view(content.c_str() + pos, chunk.size()), chunk); int n_equal_iterators = 0; for (absl::Cord::ChunkIterator it = range.begin(); it != range.end(); ++it) { n_equal_iterators += static_cast<int>(it == pre_iter); } EXPECT_EQ(n_equal_iterators, 1); ++pre_iter; EXPECT_EQ(*post_iter++, chunk); pos += chunk.size(); ++n_chunks; } EXPECT_EQ(expected_chunks, n_chunks); EXPECT_EQ(pos, content.size()); EXPECT_TRUE(pre_iter == cord.chunk_end()); EXPECT_TRUE(post_iter == cord.chunk_end()); } TEST_P(CordTest, CordChunkIteratorOperations) { absl::Cord empty_cord; VerifyChunkIterator(empty_cord, 0); absl::Cord small_buffer_cord("small cord"); MaybeHarden(small_buffer_cord); VerifyChunkIterator(small_buffer_cord, 1); absl::Cord flat_node_cord("larger than small buffer optimization"); MaybeHarden(flat_node_cord); VerifyChunkIterator(flat_node_cord, 1); VerifyChunkIterator(MaybeHardened(absl::MakeFragmentedCord( {"a ", "small ", "fragmented ", "cord ", "for ", "testing ", "chunk ", "iterations."})), 8); absl::Cord reused_nodes_cord(std::string(40, 'c')); reused_nodes_cord.Prepend(absl::Cord(std::string(40, 'b'))); MaybeHarden(reused_nodes_cord); reused_nodes_cord.Prepend(absl::Cord(std::string(40, 'a'))); size_t expected_chunks = 3; for (int i = 0; i < 8; ++i) { reused_nodes_cord.Prepend(reused_nodes_cord); MaybeHarden(reused_nodes_cord); expected_chunks *= 2; VerifyChunkIterator(reused_nodes_cord, expected_chunks); } RandomEngine rng(GTEST_FLAG_GET(random_seed)); absl::Cord flat_cord(RandomLowercaseString(&rng, 256)); absl::Cord subcords; for (int i = 0; i < 128; ++i) subcords.Prepend(flat_cord.Subcord(i, 128)); VerifyChunkIterator(subcords, 128); } TEST_P(CordTest, AdvanceAndReadOnDataEdge) { RandomEngine rng(GTEST_FLAG_GET(random_seed)); const std::string data = RandomLowercaseString(&rng, 2000); for (bool as_flat : {true, false}) { SCOPED_TRACE(as_flat ? "Flat" : "External"); absl::Cord cord = as_flat ? absl::Cord(data) : absl::MakeCordFromExternal(data, [](absl::string_view) {}); auto it = cord.Chars().begin(); #if !defined(NDEBUG) || ABSL_OPTION_HARDENED EXPECT_DEATH_IF_SUPPORTED(cord.AdvanceAndRead(&it, 2001), ".*"); #endif it = cord.Chars().begin(); absl::Cord frag = cord.AdvanceAndRead(&it, 2000); EXPECT_EQ(frag, data); EXPECT_TRUE(it == cord.Chars().end()); it = cord.Chars().begin(); frag = cord.AdvanceAndRead(&it, 200); EXPECT_EQ(frag, data.substr(0, 200)); EXPECT_FALSE(it == cord.Chars().end()); frag = cord.AdvanceAndRead(&it, 1500); EXPECT_EQ(frag, data.substr(200, 1500)); EXPECT_FALSE(it == cord.Chars().end()); frag = cord.AdvanceAndRead(&it, 300); EXPECT_EQ(frag, data.substr(1700, 300)); EXPECT_TRUE(it == cord.Chars().end()); } } TEST_P(CordTest, AdvanceAndReadOnSubstringDataEdge) { RandomEngine rng(GTEST_FLAG_GET(random_seed)); const std::string data = RandomLowercaseString(&rng, 2500); for (bool as_flat : {true, false}) { SCOPED_TRACE(as_flat ? "Flat" : "External"); absl::Cord cord = as_flat ? absl::Cord(data) : absl::MakeCordFromExternal(data, [](absl::string_view) {}); cord = cord.Subcord(200, 2000); const std::string substr = data.substr(200, 2000); auto it = cord.Chars().begin(); #if !defined(NDEBUG) || ABSL_OPTION_HARDENED EXPECT_DEATH_IF_SUPPORTED(cord.AdvanceAndRead(&it, 2001), ".*"); #endif it = cord.Chars().begin(); absl::Cord frag = cord.AdvanceAndRead(&it, 2000); EXPECT_EQ(frag, substr); EXPECT_TRUE(it == cord.Chars().end()); it = cord.Chars().begin(); frag = cord.AdvanceAndRead(&it, 200); EXPECT_EQ(frag, substr.substr(0, 200)); EXPECT_FALSE(it == cord.Chars().end()); frag = cord.AdvanceAndRead(&it, 1500); EXPECT_EQ(frag, substr.substr(200, 1500)); EXPECT_FALSE(it == cord.Chars().end()); frag = cord.AdvanceAndRead(&it, 300); EXPECT_EQ(frag, substr.substr(1700, 300)); EXPECT_TRUE(it == cord.Chars().end()); } } TEST_P(CordTest, CharIteratorTraits) { static_assert(std::is_copy_constructible<absl::Cord::CharIterator>::value, ""); static_assert(std::is_copy_assignable<absl::Cord::CharIterator>::value, ""); static_assert(std::is_move_constructible<absl::Cord::CharIterator>::value, ""); static_assert(std::is_move_assignable<absl::Cord::CharIterator>::value, ""); static_assert( std::is_same< std::iterator_traits<absl::Cord::CharIterator>::iterator_category, std::input_iterator_tag>::value, ""); static_assert( std::is_same<std::iterator_traits<absl::Cord::CharIterator>::value_type, char>::value, ""); static_assert( std::is_same< std::iterator_traits<absl::Cord::CharIterator>::difference_type, ptrdiff_t>::value, ""); static_assert( std::is_same<std::iterator_traits<absl::Cord::CharIterator>::pointer, const char*>::value, ""); static_assert( std::is_same<std::iterator_traits<absl::Cord::CharIterator>::reference, const char&>::value, ""); } static void VerifyCharIterator(const absl::Cord& cord) { EXPECT_EQ(cord.char_begin() == cord.char_end(), cord.empty()); EXPECT_EQ(cord.char_begin() != cord.char_end(), !cord.empty()); absl::Cord::CharRange range = cord.Chars(); EXPECT_EQ(range.begin() == range.end(), cord.empty()); EXPECT_EQ(range.begin() != range.end(), !cord.empty()); size_t i = 0; absl::Cord::CharIterator pre_iter = cord.char_begin(); absl::Cord::CharIterator post_iter = cord.char_begin(); std::string content(cord); while (pre_iter != cord.char_end() && post_iter != cord.char_end()) { EXPECT_FALSE(pre_iter == cord.char_end()); EXPECT_FALSE(post_iter == cord.char_end()); EXPECT_LT(i, cord.size()); EXPECT_EQ(content[i], *pre_iter); EXPECT_EQ(pre_iter, post_iter); EXPECT_EQ(*pre_iter, *post_iter); EXPECT_EQ(&*pre_iter, &*post_iter); const char* character_address = &*pre_iter; absl::Cord::CharIterator copy = pre_iter; ++copy; EXPECT_EQ(character_address, &*pre_iter); int n_equal_iterators = 0; for (absl::Cord::CharIterator it = range.begin(); it != range.end(); ++it) { n_equal_iterators += static_cast<int>(it == pre_iter); } EXPECT_EQ(n_equal_iterators, 1); absl::Cord::CharIterator advance_iter = range.begin(); absl::Cord::Advance(&advance_iter, i); EXPECT_EQ(pre_iter, advance_iter); advance_iter = range.begin(); EXPECT_EQ(absl::Cord::AdvanceAndRead(&advance_iter, i), cord.Subcord(0, i)); EXPECT_EQ(pre_iter, advance_iter); advance_iter = pre_iter; absl::Cord::Advance(&advance_iter, cord.size() - i); EXPECT_EQ(range.end(), advance_iter); advance_iter = pre_iter; EXPECT_EQ(absl::Cord::AdvanceAndRead(&advance_iter, cord.size() - i), cord.Subcord(i, cord.size() - i)); EXPECT_EQ(range.end(), advance_iter); ++i; ++pre_iter; post_iter++; } EXPECT_EQ(i, cord.size()); EXPECT_TRUE(pre_iter == cord.char_end()); EXPECT_TRUE(post_iter == cord.char_end()); absl::Cord::CharIterator zero_advanced_end = cord.char_end(); absl::Cord::Advance(&zero_advanced_end, 0); EXPECT_EQ(zero_advanced_end, cord.char_end()); absl::Cord::CharIterator it = cord.char_begin(); for (absl::string_view chunk : cord.Chunks()) { while (!chunk.empty()) { EXPECT_EQ(absl::Cord::ChunkRemaining(it), chunk); chunk.remove_prefix(1); ++it; } } } TEST_P(CordTest, CharIteratorOperations) { absl::Cord empty_cord; VerifyCharIterator(empty_cord); absl::Cord small_buffer_cord("small cord"); MaybeHarden(small_buffer_cord); VerifyCharIterator(small_buffer_cord); absl::Cord flat_node_cord("larger than small buffer optimization"); MaybeHarden(flat_node_cord); VerifyCharIterator(flat_node_cord); VerifyCharIterator(MaybeHardened( absl::MakeFragmentedCord({"a ", "small ", "fragmented ", "cord ", "for ", "testing ", "character ", "iteration."}))); absl::Cord reused_nodes_cord("ghi"); reused_nodes_cord.Prepend(absl::Cord("def")); reused_nodes_cord.Prepend(absl::Cord("abc")); for (int i = 0; i < 4; ++i) { reused_nodes_cord.Prepend(reused_nodes_cord); MaybeHarden(reused_nodes_cord); VerifyCharIterator(reused_nodes_cord); } RandomEngine rng(GTEST_FLAG_GET(random_seed)); absl::Cord flat_cord(RandomLowercaseString(&rng, 256)); absl::Cord subcords; for (int i = 0; i < 4; ++i) { subcords.Prepend(flat_cord.Subcord(16 * i, 128)); MaybeHarden(subcords); } VerifyCharIterator(subcords); } TEST_P(CordTest, CharIteratorAdvanceAndRead) { constexpr int kBlocks = 6; constexpr size_t kBlockSize = 2500; constexpr size_t kChunkSize1 = 1500; constexpr size_t kChunkSize2 = 2500; constexpr size_t kChunkSize3 = 3000; constexpr size_t kChunkSize4 = 150; RandomEngine rng; std::string data = RandomLowercaseString(&rng, kBlocks * kBlockSize); absl::Cord cord; for (int i = 0; i < kBlocks; ++i) { const std::string block = data.substr(i * kBlockSize, kBlockSize); cord.Append(absl::Cord(block)); } MaybeHarden(cord); for (size_t chunk_size : {kChunkSize1, kChunkSize2, kChunkSize3, kChunkSize4}) { absl::Cord::CharIterator it = cord.char_begin(); size_t offset = 0; while (offset < data.length()) { const size_t n = std::min<size_t>(data.length() - offset, chunk_size); absl::Cord chunk = cord.AdvanceAndRead(&it, n); ASSERT_EQ(chunk.size(), n); ASSERT_EQ(chunk.Compare(data.substr(offset, n)), 0); offset += n; } } } TEST_P(CordTest, StreamingOutput) { absl::Cord c = absl::MakeFragmentedCord({"A ", "small ", "fragmented ", "Cord", "."}); MaybeHarden(c); std::stringstream output; output << c; EXPECT_EQ("A small fragmented Cord.", output.str()); } TEST_P(CordTest, ForEachChunk) { for (int num_elements : {1, 10, 200}) { SCOPED_TRACE(num_elements); std::vector<std::string> cord_chunks; for (int i = 0; i < num_elements; ++i) { cord_chunks.push_back(absl::StrCat("[", i, "]")); } absl::Cord c = absl::MakeFragmentedCord(cord_chunks); MaybeHarden(c); std::vector<std::string> iterated_chunks; absl::CordTestPeer::ForEachChunk(c, [&iterated_chunks](absl::string_view sv) { iterated_chunks.emplace_back(sv); }); EXPECT_EQ(iterated_chunks, cord_chunks); } } TEST_P(CordTest, SmallBufferAssignFromOwnData) { constexpr size_t kMaxInline = 15; std::string contents = "small buff cord"; EXPECT_EQ(contents.size(), kMaxInline); for (size_t pos = 0; pos < contents.size(); ++pos) { for (size_t count = contents.size() - pos; count > 0; --count) { absl::Cord c(contents); MaybeHarden(c); absl::string_view flat = c.Flatten(); c = flat.substr(pos, count); EXPECT_EQ(c, contents.substr(pos, count)) << "pos = " << pos << "; count = " << count; } } } TEST_P(CordTest, Format) { absl::Cord c; absl::Format(&c, "There were %04d little %s.", 3, "pigs"); EXPECT_EQ(c, "There were 0003 little pigs."); MaybeHarden(c); absl::Format(&c, "And %-3llx bad wolf!", 1); MaybeHarden(c); EXPECT_EQ(c, "There were 0003 little pigs.And 1 bad wolf!"); } TEST_P(CordTest, Stringify) { absl::Cord c = absl::MakeFragmentedCord({"A ", "small ", "fragmented ", "Cord", "."}); MaybeHarden(c); EXPECT_EQ(absl::StrCat(c), "A small fragmented Cord."); } TEST_P(CordTest, Hardening) { absl::Cord cord("hello"); MaybeHarden(cord); EXPECT_DEATH_IF_SUPPORTED(cord.RemovePrefix(6), ""); EXPECT_DEATH_IF_SUPPORTED(cord.RemoveSuffix(6), ""); bool test_hardening = false; ABSL_HARDENING_ASSERT([&]() { test_hardening = true; return true; }()); if (!test_hardening) return; EXPECT_DEATH_IF_SUPPORTED(cord[5], ""); EXPECT_DEATH_IF_SUPPORTED(*cord.chunk_end(), ""); EXPECT_DEATH_IF_SUPPORTED(static_cast<void>(cord.chunk_end()->empty()), ""); EXPECT_DEATH_IF_SUPPORTED(++cord.chunk_end(), ""); } TEST_P(CordTest, BtreeHostileSplitInsertJoin) { absl::BitGen bitgen; std::string data(1 << 10, 'x'); absl::Cord buffer(data); absl::Cord cord; for (int i = 0; i < 1000000; ++i) { cord.Append(buffer); } for (int j = 0; j < 1000; ++j) { MaybeHarden(cord); size_t offset = absl::Uniform(bitgen, 0u, cord.size()); size_t length = absl::Uniform(bitgen, 100u, data.size()); if (cord.size() == offset) { cord.Append(absl::string_view(data.data(), length)); } else { absl::Cord suffix; if (offset + length < cord.size()) { suffix = cord; suffix.RemovePrefix(offset + length); } if (cord.size() > offset) { cord.RemoveSuffix(cord.size() - offset); } cord.Append(absl::string_view(data.data(), length)); if (!suffix.empty()) { cord.Append(suffix); } } } } class AfterExitCordTester { public: bool Set(absl::Cord* cord, absl::string_view expected) { cord_ = cord; expected_ = expected; return true; } ~AfterExitCordTester() { EXPECT_EQ(*cord_, expected_); } private: absl::Cord* cord_; absl::string_view expected_; }; template <typename Str> void TestAfterExit(Str) { const auto expected = Str::value; static AfterExitCordTester exit_tester; static absl::NoDestructor<absl::Cord> cord_leaker(Str{}); static absl::Cord& cord = *cord_leaker; static bool init_exit_tester = exit_tester.Set(&cord, expected); (void)init_exit_tester; EXPECT_EQ(cord, expected); { absl::Cord copy = cord; EXPECT_EQ(copy, expected); } EXPECT_EQ(cord, expected); { absl::Cord copy = cord; std::string expected_copy(expected); for (int i = 0; i < 10; ++i) { copy.Append(cord); absl::StrAppend(&expected_copy, expected); EXPECT_EQ(copy, expected_copy); } } EXPECT_EQ(absl::CordTestPeer::IsTree(cord), cord.size() >= 16); for (int i = 0; i < 10; ++i) { EXPECT_EQ(expected, absl::Cord(Str{})); } } constexpr int SimpleStrlen(const char* p) { return *p ? 1 + SimpleStrlen(p + 1) : 0; } struct ShortView { constexpr absl::string_view operator()() const { return absl::string_view("SSO string", SimpleStrlen("SSO string")); } }; struct LongView { constexpr absl::string_view operator()() const { return absl::string_view("String that does not fit SSO.", SimpleStrlen("String that does not fit SSO.")); } }; TEST_P(CordTest, AfterExit) { TestAfterExit(absl::strings_internal::MakeStringConstant(ShortView{})); TestAfterExit(absl::strings_internal::MakeStringConstant(LongView{})); } namespace { class PopulatedCordFactory { public: constexpr PopulatedCordFactory(absl::string_view name, absl::Cord (*generator)()) : name_(name), generator_(generator) {} absl::string_view Name() const { return name_; } absl::Cord Generate() const { return generator_(); } private: absl::string_view name_; absl::Cord (*generator_)(); }; PopulatedCordFactory cord_factories[] = { {"sso", [] { return absl::Cord("abcde"); }}, {"flat", [] { absl::Cord flat(absl::StrCat("abcde", std::string(1000, 'x'))); flat.Flatten(); return flat; }}, {"external", [] { return absl::MakeCordFromExternal("abcde External!", []{}); }}, {"external substring", [] { absl::Cord ext = absl::MakeCordFromExternal("-abcde External!", []{}); return absl::CordTestPeer::MakeSubstring(ext, 1, ext.size() - 1); }}, {"substring", [] { absl::Cord flat(absl::StrCat("-abcde", std::string(1000, 'x'))); flat.Flatten(); return flat.Subcord(1, 998); }}, {"fragmented", [] { std::string fragment = absl::StrCat("abcde", std::string(195, 'x')); std::vector<std::string> fragments(200, fragment); absl::Cord cord = absl::MakeFragmentedCord(fragments); assert(cord.size() == 40000); return cord; }}, }; class CordMutator { public: constexpr CordMutator(absl::string_view name, void (*mutate)(absl::Cord&), void (*undo)(absl::Cord&) = nullptr) : name_(name), mutate_(mutate), undo_(undo) {} absl::string_view Name() const { return name_; } void Mutate(absl::Cord& cord) const { mutate_(cord); } bool CanUndo() const { return undo_ != nullptr; } void Undo(absl::Cord& cord) const { undo_(cord); } private: absl::string_view name_; void (*mutate_)(absl::Cord&); void (*undo_)(absl::Cord&); }; CordMutator cord_mutators[] = { {"clear", [](absl::Cord& c) { c.Clear(); }}, {"overwrite", [](absl::Cord& c) { c = "overwritten"; }}, { "append string", [](absl::Cord& c) { c.Append("0123456789"); }, [](absl::Cord& c) { c.RemoveSuffix(10); } }, { "append cord", [](absl::Cord& c) { c.Append(absl::MakeFragmentedCord({"12345", "67890"})); }, [](absl::Cord& c) { c.RemoveSuffix(10); } }, { "append checksummed cord", [](absl::Cord& c) { absl::Cord to_append = absl::MakeFragmentedCord({"12345", "67890"}); to_append.SetExpectedChecksum(999); c.Append(to_append); }, [](absl::Cord& c) { c.RemoveSuffix(10); } }, { "append self", [](absl::Cord& c) { c.Append(c); }, [](absl::Cord& c) { c.RemoveSuffix(c.size() / 2); } }, { "append empty string", [](absl::Cord& c) { c.Append(""); }, [](absl::Cord& c) { } }, { "append empty cord", [](absl::Cord& c) { c.Append(absl::Cord()); }, [](absl::Cord& c) { } }, { "append empty checksummed cord", [](absl::Cord& c) { absl::Cord to_append; to_append.SetExpectedChecksum(999); c.Append(to_append); }, [](absl::Cord& c) { } }, { "prepend string", [](absl::Cord& c) { c.Prepend("9876543210"); }, [](absl::Cord& c) { c.RemovePrefix(10); } }, { "prepend cord", [](absl::Cord& c) { c.Prepend(absl::MakeFragmentedCord({"98765", "43210"})); }, [](absl::Cord& c) { c.RemovePrefix(10); } }, { "prepend checksummed cord", [](absl::Cord& c) { absl::Cord to_prepend = absl::MakeFragmentedCord({"98765", "43210"}); to_prepend.SetExpectedChecksum(999); c.Prepend(to_prepend); }, [](absl::Cord& c) { c.RemovePrefix(10); } }, { "prepend empty string", [](absl::Cord& c) { c.Prepend(""); }, [](absl::Cord& c) { } }, { "prepend empty cord", [](absl::Cord& c) { c.Prepend(absl::Cord()); }, [](absl::Cord& c) { } }, { "prepend empty checksummed cord", [](absl::Cord& c) { absl::Cord to_prepend; to_prepend.SetExpectedChecksum(999); c.Prepend(to_prepend); }, [](absl::Cord& c) { } }, { "prepend self", [](absl::Cord& c) { c.Prepend(c); }, [](absl::Cord& c) { c.RemovePrefix(c.size() / 2); } }, {"remove prefix", [](absl::Cord& c) { c.RemovePrefix(c.size() / 2); }}, {"remove suffix", [](absl::Cord& c) { c.RemoveSuffix(c.size() / 2); }}, {"remove 0-prefix", [](absl::Cord& c) { c.RemovePrefix(0); }}, {"remove 0-suffix", [](absl::Cord& c) { c.RemoveSuffix(0); }}, {"subcord", [](absl::Cord& c) { c = c.Subcord(1, c.size() - 2); }}, { "swap inline", [](absl::Cord& c) { absl::Cord other("swap"); c.swap(other); } }, { "swap tree", [](absl::Cord& c) { absl::Cord other(std::string(10000, 'x')); c.swap(other); } }, }; } TEST_P(CordTest, ExpectedChecksum) { for (const PopulatedCordFactory& factory : cord_factories) { SCOPED_TRACE(factory.Name()); for (bool shared : {false, true}) { SCOPED_TRACE(shared); absl::Cord shared_cord_source = factory.Generate(); auto make_instance = [=] { return shared ? shared_cord_source : factory.Generate(); }; const absl::Cord base_value = factory.Generate(); const std::string base_value_as_string(factory.Generate().Flatten()); absl::Cord c1 = make_instance(); EXPECT_FALSE(c1.ExpectedChecksum().has_value()); c1.SetExpectedChecksum(12345); EXPECT_EQ(c1.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1, base_value); c1.SetExpectedChecksum(12345); EXPECT_EQ(c1.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1, base_value); absl::Cord c1_copy_construct = c1; EXPECT_EQ(c1_copy_construct.ExpectedChecksum().value_or(0), 12345); absl::Cord c1_copy_assign; c1_copy_assign = c1; EXPECT_EQ(c1_copy_assign.ExpectedChecksum().value_or(0), 12345); absl::Cord c1_move(std::move(c1_copy_assign)); EXPECT_EQ(c1_move.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1, make_instance()); for (const CordMutator& mutator : cord_mutators) { SCOPED_TRACE(mutator.Name()); absl::Cord c2 = make_instance(); c2.SetExpectedChecksum(24680); mutator.Mutate(c2); if (c1 == c2) { continue; } EXPECT_EQ(c2.ExpectedChecksum(), absl::nullopt); if (mutator.CanUndo()) { mutator.Undo(c2); EXPECT_EQ(c2, base_value); EXPECT_EQ(c2.ExpectedChecksum(), absl::nullopt); } } absl::Cord c3 = make_instance(); c3.SetExpectedChecksum(999); const absl::Cord& cc3 = c3; ASSERT_TRUE(cc3.StartsWith("abcde")); EXPECT_EQ(cc3.size(), base_value_as_string.size()); EXPECT_FALSE(cc3.empty()); EXPECT_EQ(cc3.Compare(base_value), 0); EXPECT_EQ(cc3.Compare(base_value_as_string), 0); EXPECT_EQ(cc3.Compare("wxyz"), -1); EXPECT_EQ(cc3.Compare(absl::Cord("wxyz")), -1); EXPECT_EQ(cc3.Compare("aaaa"), 1); EXPECT_EQ(cc3.Compare(absl::Cord("aaaa")), 1); EXPECT_EQ(absl::Cord("wxyz").Compare(cc3), 1); EXPECT_EQ(absl::Cord("aaaa").Compare(cc3), -1); EXPECT_TRUE(cc3.StartsWith("abcd")); EXPECT_EQ(std::string(cc3), base_value_as_string); std::string dest; absl::CopyCordToString(cc3, &dest); EXPECT_EQ(dest, base_value_as_string); bool first_pass = true; for (absl::string_view chunk : cc3.Chunks()) { if (first_pass) { EXPECT_TRUE(absl::StartsWith(chunk, "abcde")); } first_pass = false; } first_pass = true; for (char ch : cc3.Chars()) { if (first_pass) { EXPECT_EQ(ch, 'a'); } first_pass = false; } EXPECT_TRUE(absl::StartsWith(*cc3.chunk_begin(), "abcde")); EXPECT_EQ(*cc3.char_begin(), 'a'); auto char_it = cc3.char_begin(); absl::Cord::Advance(&char_it, 2); EXPECT_EQ(absl::Cord::AdvanceAndRead(&char_it, 2), "cd"); EXPECT_EQ(*char_it, 'e'); char_it = cc3.char_begin(); absl::Cord::Advance(&char_it, 2); EXPECT_TRUE(absl::StartsWith(absl::Cord::ChunkRemaining(char_it), "cde")); EXPECT_EQ(cc3[0], 'a'); EXPECT_EQ(cc3[4], 'e'); EXPECT_EQ(absl::HashOf(cc3), absl::HashOf(base_value)); EXPECT_EQ(absl::HashOf(cc3), absl::HashOf(base_value_as_string)); } } } TEST_P(CordTest, ChecksummedEmptyCord) { absl::Cord c1; EXPECT_FALSE(c1.ExpectedChecksum().has_value()); c1.SetExpectedChecksum(12345); EXPECT_EQ(c1.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1, ""); EXPECT_TRUE(c1.empty()); c1.SetExpectedChecksum(12345); EXPECT_EQ(c1.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1, ""); EXPECT_TRUE(c1.empty()); absl::Cord c1_copy_construct = c1; EXPECT_EQ(c1_copy_construct.ExpectedChecksum().value_or(0), 12345); absl::Cord c1_copy_assign; c1_copy_assign = c1; EXPECT_EQ(c1_copy_assign.ExpectedChecksum().value_or(0), 12345); absl::Cord c1_move(std::move(c1_copy_assign)); EXPECT_EQ(c1_move.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1.ExpectedChecksum().value_or(0), 12345); EXPECT_EQ(c1, absl::Cord()); for (const CordMutator& mutator : cord_mutators) { SCOPED_TRACE(mutator.Name()); absl::Cord c2; c2.SetExpectedChecksum(24680); mutator.Mutate(c2); if (c2.empty()) { continue; } EXPECT_EQ(c2.ExpectedChecksum(), absl::nullopt); if (mutator.CanUndo()) { mutator.Undo(c2); } } absl::Cord c3; c3.SetExpectedChecksum(999); const absl::Cord& cc3 = c3; EXPECT_TRUE(cc3.StartsWith("")); EXPECT_TRUE(cc3.EndsWith("")); EXPECT_TRUE(cc3.empty()); EXPECT_EQ(cc3, ""); EXPECT_EQ(cc3, absl::Cord()); EXPECT_EQ(cc3.size(), 0); EXPECT_EQ(cc3.Compare(absl::Cord()), 0); EXPECT_EQ(cc3.Compare(c1), 0); EXPECT_EQ(cc3.Compare(cc3), 0); EXPECT_EQ(cc3.Compare(""), 0); EXPECT_EQ(cc3.Compare("wxyz"), -1); EXPECT_EQ(cc3.Compare(absl::Cord("wxyz")), -1); EXPECT_EQ(absl::Cord("wxyz").Compare(cc3), 1); EXPECT_EQ(std::string(cc3), ""); std::string dest; absl::CopyCordToString(cc3, &dest); EXPECT_EQ(dest, ""); for (absl::string_view chunk : cc3.Chunks()) { static_cast<void>(chunk); GTEST_FAIL() << "no chunks expected"; } EXPECT_TRUE(cc3.chunk_begin() == cc3.chunk_end()); for (char ch : cc3.Chars()) { static_cast<void>(ch); GTEST_FAIL() << "no chars expected"; } EXPECT_TRUE(cc3.char_begin() == cc3.char_end()); EXPECT_EQ(cc3.TryFlat(), ""); EXPECT_EQ(absl::HashOf(c3), absl::HashOf(absl::Cord())); EXPECT_EQ(absl::HashOf(c3), absl::HashOf(absl::string_view())); } ABSL_ATTRIBUTE_WEAK size_t FalseReport(const absl::Cord& a, bool f); ABSL_ATTRIBUTE_NOINLINE size_t FalseReport(const absl::Cord& a, bool f) { absl::Cord b; const absl::Cord& ref = f ? b : a; return ref.size(); } TEST(CordSanitizerTest, SanitizesCordFalseReport) { absl::Cord c; for (int i = 0; i < 1000; ++i) c.Append("a"); FalseReport(c, false); } TEST(CrcCordTest, ChecksummedEmptyCordEstimateMemoryUsage) { absl::Cord cord; cord.SetExpectedChecksum(0); EXPECT_NE(cord.EstimatedMemoryUsage(), 0); } TEST(CordThreeWayComparisonTest, CompareCords) { #ifndef __cpp_impl_three_way_comparison GTEST_SKIP() << "C++20 three-way <=> comparison not supported"; #else EXPECT_EQ(absl::Cord("a") <=> absl::Cord("a"), std::strong_ordering::equal); EXPECT_EQ(absl::Cord("aaaa") <=> absl::Cord("aaab"), std::strong_ordering::less); EXPECT_EQ(absl::Cord("baaa") <=> absl::Cord("a"), std::strong_ordering::greater); #endif } TEST(CordThreeWayComparisonTest, CompareCordsAndStringViews) { #ifndef __cpp_impl_three_way_comparison GTEST_SKIP() << "C++20 three-way <=> comparison not supported"; #else EXPECT_EQ(absl::string_view("a") <=> absl::Cord("a"), std::strong_ordering::equal); EXPECT_EQ(absl::Cord("a") <=> absl::string_view("b"), std::strong_ordering::less); EXPECT_EQ(absl::string_view("b") <=> absl::Cord("a"), std::strong_ordering::greater); #endif } #if defined(GTEST_HAS_DEATH_TEST) && defined(ABSL_INTERNAL_CORD_HAVE_SANITIZER) const char* MASanDeathExpr() { return "(use-after-poison|use-of-uninitialized-value)"; } TEST(CordSanitizerTest, SanitizesEmptyCord) { absl::Cord cord; const char* data = cord.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[0], 0), MASanDeathExpr()); } TEST(CordSanitizerTest, SanitizesSmallCord) { absl::Cord cord("Hello"); const char* data = cord.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[5], 0), MASanDeathExpr()); } TEST(CordSanitizerTest, SanitizesCordOnSetSSOValue) { absl::Cord cord("String that is too big to be an SSO value"); cord = "Hello"; const char* data = cord.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[5], 0), MASanDeathExpr()); } TEST(CordSanitizerTest, SanitizesCordOnCopyCtor) { absl::Cord src("hello"); absl::Cord dst(src); const char* data = dst.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[5], 0), MASanDeathExpr()); } TEST(CordSanitizerTest, SanitizesCordOnMoveCtor) { absl::Cord src("hello"); absl::Cord dst(std::move(src)); const char* data = dst.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[5], 0), MASanDeathExpr()); } TEST(CordSanitizerTest, SanitizesCordOnAssign) { absl::Cord src("hello"); absl::Cord dst; dst = src; const char* data = dst.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[5], 0), MASanDeathExpr()); } TEST(CordSanitizerTest, SanitizesCordOnMoveAssign) { absl::Cord src("hello"); absl::Cord dst; dst = std::move(src); const char* data = dst.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[5], 0), MASanDeathExpr()); } TEST(CordSanitizerTest, SanitizesCordOnSsoAssign) { absl::Cord src("hello"); absl::Cord dst("String that is too big to be an SSO value"); dst = src; const char* data = dst.Flatten().data(); EXPECT_DEATH(EXPECT_EQ(data[5], 0), MASanDeathExpr()); } #endif
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/cord.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/cord_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
d6ca0ddf-27db-4719-896a-96d263713763
cpp
abseil/abseil-cpp
ascii
absl/strings/ascii.cc
absl/strings/ascii_test.cc
#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*> dst, absl::Nullable<const char*> src, size_t size) { constexpr unsigned char kAsciiCaseBitFlip = 'a' ^ 'A'; for (size_t i = 0; i < size; ++i) { unsigned char v = static_cast<unsigned char>(src[i]); v ^= AsciiInAZRange<ToUpper>(v) ? kAsciiCaseBitFlip : 0; dst[i] = static_cast<char>(v); } } constexpr size_t kCaseFoldThreshold = 16; template <bool ToUpper> ABSL_ATTRIBUTE_NOINLINE constexpr void AsciiStrCaseFoldLong( absl::Nonnull<char*> dst, absl::Nullable<const char*> src, size_t size) { ABSL_ASSUME(size >= kCaseFoldThreshold); AsciiStrCaseFoldImpl<ToUpper>(dst, src, size); } template <bool ToUpper> constexpr void AsciiStrCaseFold(absl::Nonnull<char*> dst, absl::Nullable<const char*> src, size_t size) { size < kCaseFoldThreshold ? AsciiStrCaseFoldImpl<ToUpper>(dst, src, size) : AsciiStrCaseFoldLong<ToUpper>(dst, src, size); } void AsciiStrToLower(absl::Nonnull<char*> dst, absl::Nullable<const char*> src, size_t n) { return AsciiStrCaseFold<false>(dst, src, n); } void AsciiStrToUpper(absl::Nonnull<char*> dst, absl::Nullable<const char*> src, size_t n) { return AsciiStrCaseFold<true>(dst, src, n); } 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], &lowered[0], num_chars); AsciiStrCaseFold<true>(&uppered[0], &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) { char* p = &(*s)[0]; return ascii_internal::AsciiStrCaseFold<false>(p, p, s->size()); } void AsciiStrToUpper(absl::Nonnull<std::string*> s) { char* p = &(*s)[0]; return ascii_internal::AsciiStrCaseFold<true>(p, p, 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"); auto fun = []() -> std::string { return "PQRSTU"; }; 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)); EXPECT_EQ("pqrstu", absl::AsciiStrToLower(fun())); EXPECT_EQ("", absl::AsciiStrToLower(absl::string_view())); 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"); auto fun = []() -> std::string { return "pqrstu"; }; 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)); EXPECT_EQ("PQRSTU", absl::AsciiStrToUpper(fun())); EXPECT_EQ("", absl::AsciiStrToUpper(absl::string_view())); 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); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/ascii.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/ascii_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
35359af9-1cd7-46ca-b0f6-e0043cbb8f1d
cpp
abseil/abseil-cpp
numbers
absl/strings/numbers.cc
absl/strings/numbers_test.cc
#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); mantissa <<= 1; exp2 -= 64; std::pair<uint64_t, uint64_t> edge, val; if (exp >= 6) { edge = PowFive(2 * dddddd + 1, exp - 5); val.first = mantissa; val.second = 0; } else { edge = PowFive(2 * dddddd + 1, 0); val = PowFive(mantissa, 5 - exp); } if (val > edge) { dddddd++; } else if (val == edge) { dddddd += (dddddd & 1); } } else { dddddd = static_cast<uint32_t>((d64k + 32768) / 65536); } if (dddddd == 1000000) { dddddd = 100000; exp += 1; } exp_dig.exponent = exp; uint32_t two_digits = dddddd / 10000; dddddd -= two_digits * 10000; numbers_internal::PutTwoDigits(two_digits, &exp_dig.digits[0]); two_digits = dddddd / 100; dddddd -= two_digits * 100; numbers_internal::PutTwoDigits(two_digits, &exp_dig.digits[2]); numbers_internal::PutTwoDigits(dddddd, &exp_dig.digits[4]); return exp_dig; } size_t numbers_internal::SixDigitsToBuffer(double d, absl::Nonnull<char*> const buffer) { static_assert(std::numeric_limits<float>::is_iec559, "IEEE-754/IEC-559 support only"); char* out = buffer; if (std::isnan(d)) { strcpy(out, "nan"); return 3; } if (d == 0) { if (std::signbit(d)) *out++ = '-'; *out++ = '0'; *out = 0; return static_cast<size_t>(out - buffer); } if (d < 0) { *out++ = '-'; d = -d; } if (d > std::numeric_limits<double>::max()) { strcpy(out, "inf"); return static_cast<size_t>(out + 3 - buffer); } auto exp_dig = SplitToSix(d); int exp = exp_dig.exponent; const char* digits = exp_dig.digits; out[0] = '0'; out[1] = '.'; switch (exp) { case 5: memcpy(out, &digits[0], 6), out += 6; *out = 0; return static_cast<size_t>(out - buffer); case 4: memcpy(out, &digits[0], 5), out += 5; if (digits[5] != '0') { *out++ = '.'; *out++ = digits[5]; } *out = 0; return static_cast<size_t>(out - buffer); case 3: memcpy(out, &digits[0], 4), out += 4; if ((digits[5] | digits[4]) != '0') { *out++ = '.'; *out++ = digits[4]; if (digits[5] != '0') *out++ = digits[5]; } *out = 0; return static_cast<size_t>(out - buffer); case 2: memcpy(out, &digits[0], 3), out += 3; *out++ = '.'; memcpy(out, &digits[3], 3); out += 3; while (out[-1] == '0') --out; if (out[-1] == '.') --out; *out = 0; return static_cast<size_t>(out - buffer); case 1: memcpy(out, &digits[0], 2), out += 2; *out++ = '.'; memcpy(out, &digits[2], 4); out += 4; while (out[-1] == '0') --out; if (out[-1] == '.') --out; *out = 0; return static_cast<size_t>(out - buffer); case 0: memcpy(out, &digits[0], 1), out += 1; *out++ = '.'; memcpy(out, &digits[1], 5); out += 5; while (out[-1] == '0') --out; if (out[-1] == '.') --out; *out = 0; return static_cast<size_t>(out - buffer); case -4: out[2] = '0'; ++out; ABSL_FALLTHROUGH_INTENDED; case -3: out[2] = '0'; ++out; ABSL_FALLTHROUGH_INTENDED; case -2: out[2] = '0'; ++out; ABSL_FALLTHROUGH_INTENDED; case -1: out += 2; memcpy(out, &digits[0], 6); out += 6; while (out[-1] == '0') --out; *out = 0; return static_cast<size_t>(out - buffer); } assert(exp < -4 || exp >= 6); out[0] = digits[0]; assert(out[1] == '.'); out += 2; memcpy(out, &digits[1], 5), out += 5; while (out[-1] == '0') --out; if (out[-1] == '.') --out; *out++ = 'e'; if (exp > 0) { *out++ = '+'; } else { *out++ = '-'; exp = -exp; } if (exp > 99) { int dig1 = exp / 100; exp -= dig1 * 100; *out++ = '0' + static_cast<char>(dig1); } PutTwoDigits(static_cast<uint32_t>(exp), out); out += 2; *out = 0; return static_cast<size_t>(out - buffer); } namespace { static const int8_t kAsciiToInt[256] = { 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 36, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36}; inline bool safe_parse_sign_and_base( absl::Nonnull<absl::string_view*> text , absl::Nonnull<int*> base_ptr , absl::Nonnull<bool*> negative_ptr ) { if (text->data() == nullptr) { return false; } const char* start = text->data(); const char* end = start + text->size(); int base = *base_ptr; while (start < end && absl::ascii_isspace(static_cast<unsigned char>(start[0]))) { ++start; } while (start < end && absl::ascii_isspace(static_cast<unsigned char>(end[-1]))) { --end; } if (start >= end) { return false; } *negative_ptr = (start[0] == '-'); if (*negative_ptr || start[0] == '+') { ++start; if (start >= end) { return false; } } if (base == 0) { if (end - start >= 2 && start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) { base = 16; start += 2; if (start >= end) { return false; } } else if (end - start >= 1 && start[0] == '0') { base = 8; start += 1; } else { base = 10; } } else if (base == 16) { if (end - start >= 2 && start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) { start += 2; if (start >= end) { return false; } } } else if (base >= 2 && base <= 36) { } else { return false; } *text = absl::string_view(start, static_cast<size_t>(end - start)); *base_ptr = base; return true; } template <typename IntType> struct LookupTables { ABSL_CONST_INIT static const IntType kVmaxOverBase[]; ABSL_CONST_INIT static const IntType kVminOverBase[]; }; #define X_OVER_BASE_INITIALIZER(X) \ { \ 0, 0, X / 2, X / 3, X / 4, X / 5, X / 6, X / 7, X / 8, X / 9, X / 10, \ X / 11, X / 12, X / 13, X / 14, X / 15, X / 16, X / 17, X / 18, \ X / 19, X / 20, X / 21, X / 22, X / 23, X / 24, X / 25, X / 26, \ X / 27, X / 28, X / 29, X / 30, X / 31, X / 32, X / 33, X / 34, \ X / 35, X / 36, \ } template <> ABSL_CONST_INIT const uint128 LookupTables<uint128>::kVmaxOverBase[] = { 0, 0, MakeUint128(9223372036854775807u, 18446744073709551615u), MakeUint128(6148914691236517205u, 6148914691236517205u), MakeUint128(4611686018427387903u, 18446744073709551615u), MakeUint128(3689348814741910323u, 3689348814741910323u), MakeUint128(3074457345618258602u, 12297829382473034410u), MakeUint128(2635249153387078802u, 5270498306774157604u), MakeUint128(2305843009213693951u, 18446744073709551615u), MakeUint128(2049638230412172401u, 14347467612885206812u), MakeUint128(1844674407370955161u, 11068046444225730969u), MakeUint128(1676976733973595601u, 8384883669867978007u), MakeUint128(1537228672809129301u, 6148914691236517205u), MakeUint128(1418980313362273201u, 4256940940086819603u), MakeUint128(1317624576693539401u, 2635249153387078802u), MakeUint128(1229782938247303441u, 1229782938247303441u), MakeUint128(1152921504606846975u, 18446744073709551615u), MakeUint128(1085102592571150095u, 1085102592571150095u), MakeUint128(1024819115206086200u, 16397105843297379214u), MakeUint128(970881267037344821u, 16504981539634861972u), MakeUint128(922337203685477580u, 14757395258967641292u), MakeUint128(878416384462359600u, 14054662151397753612u), MakeUint128(838488366986797800u, 13415813871788764811u), MakeUint128(802032351030850070u, 4812194106185100421u), MakeUint128(768614336404564650u, 12297829382473034410u), MakeUint128(737869762948382064u, 11805916207174113034u), MakeUint128(709490156681136600u, 11351842506898185609u), MakeUint128(683212743470724133u, 17080318586768103348u), MakeUint128(658812288346769700u, 10540996613548315209u), MakeUint128(636094623231363848u, 15266270957552732371u), MakeUint128(614891469123651720u, 9838263505978427528u), MakeUint128(595056260442243600u, 9520900167075897608u), MakeUint128(576460752303423487u, 18446744073709551615u), MakeUint128(558992244657865200u, 8943875914525843207u), MakeUint128(542551296285575047u, 9765923333140350855u), MakeUint128(527049830677415760u, 8432797290838652167u), MakeUint128(512409557603043100u, 8198552921648689607u), }; template <> ABSL_CONST_INIT const int128 LookupTables<int128>::kVmaxOverBase[] = { 0, 0, MakeInt128(4611686018427387903, 18446744073709551615u), MakeInt128(3074457345618258602, 12297829382473034410u), MakeInt128(2305843009213693951, 18446744073709551615u), MakeInt128(1844674407370955161, 11068046444225730969u), MakeInt128(1537228672809129301, 6148914691236517205u), MakeInt128(1317624576693539401, 2635249153387078802u), MakeInt128(1152921504606846975, 18446744073709551615u), MakeInt128(1024819115206086200, 16397105843297379214u), MakeInt128(922337203685477580, 14757395258967641292u), MakeInt128(838488366986797800, 13415813871788764811u), MakeInt128(768614336404564650, 12297829382473034410u), MakeInt128(709490156681136600, 11351842506898185609u), MakeInt128(658812288346769700, 10540996613548315209u), MakeInt128(614891469123651720, 9838263505978427528u), MakeInt128(576460752303423487, 18446744073709551615u), MakeInt128(542551296285575047, 9765923333140350855u), MakeInt128(512409557603043100, 8198552921648689607u), MakeInt128(485440633518672410, 17475862806672206794u), MakeInt128(461168601842738790, 7378697629483820646u), MakeInt128(439208192231179800, 7027331075698876806u), MakeInt128(419244183493398900, 6707906935894382405u), MakeInt128(401016175515425035, 2406097053092550210u), MakeInt128(384307168202282325, 6148914691236517205u), MakeInt128(368934881474191032, 5902958103587056517u), MakeInt128(354745078340568300, 5675921253449092804u), MakeInt128(341606371735362066, 17763531330238827482u), MakeInt128(329406144173384850, 5270498306774157604u), MakeInt128(318047311615681924, 7633135478776366185u), MakeInt128(307445734561825860, 4919131752989213764u), MakeInt128(297528130221121800, 4760450083537948804u), MakeInt128(288230376151711743, 18446744073709551615u), MakeInt128(279496122328932600, 4471937957262921603u), MakeInt128(271275648142787523, 14106333703424951235u), MakeInt128(263524915338707880, 4216398645419326083u), MakeInt128(256204778801521550, 4099276460824344803u), }; template <> ABSL_CONST_INIT const int128 LookupTables<int128>::kVminOverBase[] = { 0, 0, MakeInt128(-4611686018427387904, 0u), MakeInt128(-3074457345618258603, 6148914691236517206u), MakeInt128(-2305843009213693952, 0u), MakeInt128(-1844674407370955162, 7378697629483820647u), MakeInt128(-1537228672809129302, 12297829382473034411u), MakeInt128(-1317624576693539402, 15811494920322472814u), MakeInt128(-1152921504606846976, 0u), MakeInt128(-1024819115206086201, 2049638230412172402u), MakeInt128(-922337203685477581, 3689348814741910324u), MakeInt128(-838488366986797801, 5030930201920786805u), MakeInt128(-768614336404564651, 6148914691236517206u), MakeInt128(-709490156681136601, 7094901566811366007u), MakeInt128(-658812288346769701, 7905747460161236407u), MakeInt128(-614891469123651721, 8608480567731124088u), MakeInt128(-576460752303423488, 0u), MakeInt128(-542551296285575048, 8680820740569200761u), MakeInt128(-512409557603043101, 10248191152060862009u), MakeInt128(-485440633518672411, 970881267037344822u), MakeInt128(-461168601842738791, 11068046444225730970u), MakeInt128(-439208192231179801, 11419412998010674810u), MakeInt128(-419244183493398901, 11738837137815169211u), MakeInt128(-401016175515425036, 16040647020617001406u), MakeInt128(-384307168202282326, 12297829382473034411u), MakeInt128(-368934881474191033, 12543785970122495099u), MakeInt128(-354745078340568301, 12770822820260458812u), MakeInt128(-341606371735362067, 683212743470724134u), MakeInt128(-329406144173384851, 13176245766935394012u), MakeInt128(-318047311615681925, 10813608594933185431u), MakeInt128(-307445734561825861, 13527612320720337852u), MakeInt128(-297528130221121801, 13686293990171602812u), MakeInt128(-288230376151711744, 0u), MakeInt128(-279496122328932601, 13974806116446630013u), MakeInt128(-271275648142787524, 4340410370284600381u), MakeInt128(-263524915338707881, 14230345428290225533u), MakeInt128(-256204778801521551, 14347467612885206813u), }; template <typename IntType> ABSL_CONST_INIT const IntType LookupTables<IntType>::kVmaxOverBase[] = X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::max()); template <typename IntType> ABSL_CONST_INIT const IntType LookupTables<IntType>::kVminOverBase[] = X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::min()); #undef X_OVER_BASE_INITIALIZER template <typename IntType> inline bool safe_parse_positive_int(absl::string_view text, int base, absl::Nonnull<IntType*> value_p) { IntType value = 0; const IntType vmax = std::numeric_limits<IntType>::max(); assert(vmax > 0); assert(base >= 0); const IntType base_inttype = static_cast<IntType>(base); assert(vmax >= base_inttype); const IntType vmax_over_base = LookupTables<IntType>::kVmaxOverBase[base]; assert(base < 2 || std::numeric_limits<IntType>::max() / base_inttype == vmax_over_base); const char* start = text.data(); const char* end = start + text.size(); for (; start < end; ++start) { unsigned char c = static_cast<unsigned char>(start[0]); IntType digit = static_cast<IntType>(kAsciiToInt[c]); if (digit >= base_inttype) { *value_p = value; return false; } if (value > vmax_over_base) { *value_p = vmax; return false; } value *= base_inttype; if (value > vmax - digit) { *value_p = vmax; return false; } value += digit; } *value_p = value; return true; } template <typename IntType> inline bool safe_parse_negative_int(absl::string_view text, int base, absl::Nonnull<IntType*> value_p) { IntType value = 0; const IntType vmin = std::numeric_limits<IntType>::min(); assert(vmin < 0); assert(vmin <= 0 - base); IntType vmin_over_base = LookupTables<IntType>::kVminOverBase[base]; assert(base < 2 || std::numeric_limits<IntType>::min() / base == vmin_over_base); if (vmin % base > 0) { vmin_over_base += 1; } const char* start = text.data(); const char* end = start + text.size(); for (; start < end; ++start) { unsigned char c = static_cast<unsigned char>(start[0]); int digit = kAsciiToInt[c]; if (digit >= base) { *value_p = value; return false; } if (value < vmin_over_base) { *value_p = vmin; return false; } value *= base; if (value < vmin + digit) { *value_p = vmin; return false; } value -= digit; } *value_p = value; return true; } template <typename IntType> inline bool safe_int_internal(absl::string_view text, absl::Nonnull<IntType*> value_p, int base) { *value_p = 0; bool negative; if (!safe_parse_sign_and_base(&text, &base, &negative)) { return false; } if (!negative) { return safe_parse_positive_int(text, base, value_p); } else { return safe_parse_negative_int(text, base, value_p); } } template <typename IntType> inline bool safe_uint_internal(absl::string_view text, absl::Nonnull<IntType*> value_p, int base) { *value_p = 0; bool negative; if (!safe_parse_sign_and_base(&text, &base, &negative) || negative) { return false; } return safe_parse_positive_int(text, base, value_p); } } namespace numbers_internal { ABSL_CONST_INIT ABSL_DLL const char kHexChar[] = "0123456789abcdef"; ABSL_CONST_INIT ABSL_DLL const char kHexTable[513] = "000102030405060708090a0b0c0d0e0f" "101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f" "303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f" "505152535455565758595a5b5c5d5e5f" "606162636465666768696a6b6c6d6e6f" "707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf" "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"; bool safe_strto32_base(absl::string_view text, absl::Nonnull<int32_t*> value, int base) { return safe_int_internal<int32_t>(text, value, base); } bool safe_strto64_base(absl::string_view text, absl::Nonnull<int64_t*> value, int base) { return safe_int_internal<int64_t>(text, value, base); } bool safe_strto128_base(absl::string_view text, absl::Nonnull<int128*> value, int base) { return safe_int_internal<absl::int128>(text, value, base); } bool safe_strtou32_base(absl::string_view text, absl::Nonnull<uint32_t*> value, int base) { return safe_uint_internal<uint32_t>(text, value, base); } bool safe_strtou64_base(absl::string_view text, absl::Nonnull<uint64_t*> value, int base) { return safe_uint_internal<uint64_t>(text, value, base); } bool safe_strtou128_base(absl::string_view text, absl::Nonnull<uint128*> value, int base) { return safe_uint_internal<absl::uint128>(text, value, base); } } ABSL_NAMESPACE_END }
#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_strto32_base("34234324 \t\n ", &value, 16)); EXPECT_EQ(0x34234324, value); } TEST(stringtest, safe_strto32_base) { 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("34234324", &value, 16)); EXPECT_EQ(0x34234324, value); EXPECT_TRUE(safe_strto32_base("0", &value, 16)); EXPECT_EQ(0, value); EXPECT_TRUE(safe_strto32_base(" \t\n -0x34234324", &value, 16)); EXPECT_EQ(-0x34234324, value); EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 16)); EXPECT_EQ(-0x34234324, value); EXPECT_TRUE(safe_strto32_base("7654321", &value, 8)); EXPECT_EQ(07654321, value); EXPECT_TRUE(safe_strto32_base("-01234", &value, 8)); EXPECT_EQ(-01234, value); EXPECT_FALSE(safe_strto32_base("1834", &value, 8)); EXPECT_TRUE(safe_strto32_base("0", &value, 0)); EXPECT_EQ(0, value); EXPECT_TRUE(safe_strto32_base("077", &value, 0)); EXPECT_EQ(077, value); EXPECT_FALSE(safe_strto32_base("088", &value, 0)); EXPECT_FALSE(safe_strto32_base("0xG", &value, 0)); EXPECT_TRUE(safe_strto32_base("34234324", &value, 10)); EXPECT_EQ(34234324, value); EXPECT_TRUE(safe_strto32_base("0", &value, 10)); EXPECT_EQ(0, value); EXPECT_TRUE(safe_strto32_base(" \t\n -34234324", &value, 10)); EXPECT_EQ(-34234324, value); EXPECT_TRUE(safe_strto32_base("34234324 \n\t ", &value, 10)); EXPECT_EQ(34234324, value); EXPECT_FALSE(safe_strto32_base("", &value, 10)); EXPECT_FALSE(safe_strto32_base(" ", &value, 10)); EXPECT_FALSE(safe_strto32_base("abc", &value, 10)); EXPECT_FALSE(safe_strto32_base("34234324a", &value, 10)); EXPECT_FALSE(safe_strto32_base("34234.3", &value, 10)); EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10)); EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10)); EXPECT_TRUE(safe_strto32_base(std::string("0x1234"), &value, 16)); EXPECT_EQ(0x1234, value); EXPECT_TRUE(safe_strto32_base("1234", &value, 10)); EXPECT_EQ(1234, value); } TEST(stringtest, safe_strto32_range) { int32_t value; EXPECT_FALSE(safe_strto32_base("2147483648", &value, 10)); EXPECT_EQ(std::numeric_limits<int32_t>::max(), value); EXPECT_TRUE(safe_strto32_base("-2147483648", &value, 10)); EXPECT_EQ(std::numeric_limits<int32_t>::min(), value); EXPECT_FALSE(safe_strto32_base("-2147483649", &value, 10)); EXPECT_EQ(std::numeric_limits<int32_t>::min(), value); } TEST(stringtest, safe_strto64_range) { int64_t value; EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10)); EXPECT_EQ(std::numeric_limits<int64_t>::max(), value); EXPECT_TRUE(safe_strto64_base("-9223372036854775808", &value, 10)); EXPECT_EQ(std::numeric_limits<int64_t>::min(), value); EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10)); EXPECT_EQ(std::numeric_limits<int64_t>::min(), value); } TEST(stringtest, safe_strto32_leading_substring) { int32_t value; EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 10)); EXPECT_EQ(4069, value); EXPECT_FALSE(safe_strto32_base("04069@@@", &value, 8)); EXPECT_EQ(0406, value); EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 10)); EXPECT_EQ(4069, value); EXPECT_FALSE(safe_strto32_base("04069balloons", &value, 16)); EXPECT_EQ(0x4069ba, value); EXPECT_FALSE(safe_strto32_base("@@@", &value, 10)); EXPECT_EQ(0, value); } TEST(stringtest, safe_strto64_leading_substring) { int64_t value; EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 10)); EXPECT_EQ(4069, value); EXPECT_FALSE(safe_strto64_base("04069@@@", &value, 8)); EXPECT_EQ(0406, value); EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 10)); EXPECT_EQ(4069, value); EXPECT_FALSE(safe_strto64_base("04069balloons", &value, 16)); EXPECT_EQ(0x4069ba, value); EXPECT_FALSE(safe_strto64_base("@@@", &value, 10)); EXPECT_EQ(0, value); } TEST(stringtest, safe_strto64_base) { int64_t value; EXPECT_TRUE(safe_strto64_base("0x3423432448783446", &value, 16)); EXPECT_EQ(int64_t{0x3423432448783446}, value); EXPECT_TRUE(safe_strto64_base("3423432448783446", &value, 16)); EXPECT_EQ(int64_t{0x3423432448783446}, value); EXPECT_TRUE(safe_strto64_base("0", &value, 16)); EXPECT_EQ(0, value); EXPECT_TRUE(safe_strto64_base(" \t\n -0x3423432448783446", &value, 16)); EXPECT_EQ(int64_t{-0x3423432448783446}, value); EXPECT_TRUE(safe_strto64_base(" \t\n -3423432448783446", &value, 16)); EXPECT_EQ(int64_t{-0x3423432448783446}, value); EXPECT_TRUE(safe_strto64_base("123456701234567012", &value, 8)); EXPECT_EQ(int64_t{0123456701234567012}, value); EXPECT_TRUE(safe_strto64_base("-017777777777777", &value, 8)); EXPECT_EQ(int64_t{-017777777777777}, value); EXPECT_FALSE(safe_strto64_base("19777777777777", &value, 8)); EXPECT_TRUE(safe_strto64_base("0", &value, 0)); EXPECT_EQ(0, value); EXPECT_TRUE(safe_strto64_base("077", &value, 0)); EXPECT_EQ(077, value); EXPECT_FALSE(safe_strto64_base("088", &value, 0)); EXPECT_FALSE(safe_strto64_base("0xG", &value, 0)); EXPECT_TRUE(safe_strto64_base("34234324487834466", &value, 10)); EXPECT_EQ(int64_t{34234324487834466}, value); EXPECT_TRUE(safe_strto64_base("0", &value, 10)); EXPECT_EQ(0, value); EXPECT_TRUE(safe_strto64_base(" \t\n -34234324487834466", &value, 10)); EXPECT_EQ(int64_t{-34234324487834466}, value); EXPECT_TRUE(safe_strto64_base("34234324487834466 \n\t ", &value, 10)); EXPECT_EQ(int64_t{34234324487834466}, value); EXPECT_FALSE(safe_strto64_base("", &value, 10)); EXPECT_FALSE(safe_strto64_base(" ", &value, 10)); EXPECT_FALSE(safe_strto64_base("abc", &value, 10)); EXPECT_FALSE(safe_strto64_base("34234324487834466a", &value, 10)); EXPECT_FALSE(safe_strto64_base("34234487834466.3", &value, 10)); EXPECT_FALSE(safe_strto64_base("9223372036854775808", &value, 10)); EXPECT_FALSE(safe_strto64_base("-9223372036854775809", &value, 10)); EXPECT_TRUE(safe_strto64_base(std::string("0x1234"), &value, 16)); EXPECT_EQ(0x1234, value); EXPECT_TRUE(safe_strto64_base("1234", &value, 10)); EXPECT_EQ(1234, value); } const size_t kNumRandomTests = 10000; template <typename IntType> void test_random_integer_parse_base(bool (*parse_func)(absl::string_view, IntType* value, int base)) { using RandomEngine = std::minstd_rand0; std::random_device rd; RandomEngine rng(rd()); std::uniform_int_distribution<IntType> random_int( std::numeric_limits<IntType>::min()); std::uniform_int_distribution<int> random_base(2, 35); for (size_t i = 0; i < kNumRandomTests; i++) { IntType value = random_int(rng); int base = random_base(rng); std::string str_value; EXPECT_TRUE(Itoa<IntType>(value, base, &str_value)); IntType parsed_value; EXPECT_TRUE(parse_func(str_value, &parsed_value, base)); EXPECT_EQ(parsed_value, value); EXPECT_FALSE( parse_func(absl::StrCat(std::numeric_limits<IntType>::max(), value), &parsed_value, base)); if (std::numeric_limits<IntType>::min() < 0) { EXPECT_FALSE( parse_func(absl::StrCat(std::numeric_limits<IntType>::min(), value), &parsed_value, base)); } else { EXPECT_FALSE(parse_func(absl::StrCat("-", value), &parsed_value, base)); } } } TEST(stringtest, safe_strto32_random) { test_random_integer_parse_base<int32_t>(&safe_strto32_base); } TEST(stringtest, safe_strto64_random) { test_random_integer_parse_base<int64_t>(&safe_strto64_base); } TEST(stringtest, safe_strtou32_random) { test_random_integer_parse_base<uint32_t>(&safe_strtou32_base); } TEST(stringtest, safe_strtou64_random) { test_random_integer_parse_base<uint64_t>(&safe_strtou64_base); } TEST(stringtest, safe_strtou128_random) { using RandomEngine = std::minstd_rand0; using IntType = absl::uint128; constexpr auto parse_func = &absl::numbers_internal::safe_strtou128_base; std::random_device rd; RandomEngine rng(rd()); std::uniform_int_distribution<uint64_t> random_uint64( std::numeric_limits<uint64_t>::min()); std::uniform_int_distribution<int> random_base(2, 35); for (size_t i = 0; i < kNumRandomTests; i++) { IntType value = random_uint64(rng); value = (value << 64) + random_uint64(rng); int base = random_base(rng); std::string str_value; EXPECT_TRUE(Itoa<IntType>(value, base, &str_value)); IntType parsed_value; EXPECT_TRUE(parse_func(str_value, &parsed_value, base)); EXPECT_EQ(parsed_value, value); std::string s; absl::strings_internal::OStringStream(&s) << std::numeric_limits<IntType>::max() << value; EXPECT_FALSE(parse_func(s, &parsed_value, base)); s.clear(); absl::strings_internal::OStringStream(&s) << "-" << value; EXPECT_FALSE(parse_func(s, &parsed_value, base)); } } TEST(stringtest, safe_strto128_random) { using RandomEngine = std::minstd_rand0; using IntType = absl::int128; constexpr auto parse_func = &absl::numbers_internal::safe_strto128_base; std::random_device rd; RandomEngine rng(rd()); std::uniform_int_distribution<int64_t> random_int64( std::numeric_limits<int64_t>::min()); std::uniform_int_distribution<uint64_t> random_uint64( std::numeric_limits<uint64_t>::min()); std::uniform_int_distribution<int> random_base(2, 35); for (size_t i = 0; i < kNumRandomTests; ++i) { int64_t high = random_int64(rng); uint64_t low = random_uint64(rng); IntType value = absl::MakeInt128(high, low); int base = random_base(rng); std::string str_value; EXPECT_TRUE(Itoa<IntType>(value, base, &str_value)); IntType parsed_value; EXPECT_TRUE(parse_func(str_value, &parsed_value, base)); EXPECT_EQ(parsed_value, value); std::string s; absl::strings_internal::OStringStream(&s) << std::numeric_limits<IntType>::max() << value; EXPECT_FALSE(parse_func(s, &parsed_value, base)); s.clear(); absl::strings_internal::OStringStream(&s) << std::numeric_limits<IntType>::min() << value; EXPECT_FALSE(parse_func(s, &parsed_value, base)); } } TEST(stringtest, safe_strtou32_base) { for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) { const auto& e = strtouint32_test_cases()[i]; uint32_t value; EXPECT_EQ(e.expect_ok, safe_strtou32_base(e.str, &value, e.base)) << "str=\"" << e.str << "\" base=" << e.base; if (e.expect_ok) { EXPECT_EQ(e.expected, value) << "i=" << i << " str=\"" << e.str << "\" base=" << e.base; } } } TEST(stringtest, safe_strtou32_base_length_delimited) { for (int i = 0; strtouint32_test_cases()[i].str != nullptr; ++i) { const auto& e = strtouint32_test_cases()[i]; std::string tmp(e.str); tmp.append("12"); uint32_t value; EXPECT_EQ(e.expect_ok, safe_strtou32_base(absl::string_view(tmp.data(), strlen(e.str)), &value, e.base)) << "str=\"" << e.str << "\" base=" << e.base; if (e.expect_ok) { EXPECT_EQ(e.expected, value) << "i=" << i << " str=" << e.str << " base=" << e.base; } } } TEST(stringtest, safe_strtou64_base) { for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) { const auto& e = strtouint64_test_cases()[i]; uint64_t value; EXPECT_EQ(e.expect_ok, safe_strtou64_base(e.str, &value, e.base)) << "str=\"" << e.str << "\" base=" << e.base; if (e.expect_ok) { EXPECT_EQ(e.expected, value) << "str=" << e.str << " base=" << e.base; } } } TEST(stringtest, safe_strtou64_base_length_delimited) { for (int i = 0; strtouint64_test_cases()[i].str != nullptr; ++i) { const auto& e = strtouint64_test_cases()[i]; std::string tmp(e.str); tmp.append("12"); uint64_t value; EXPECT_EQ(e.expect_ok, safe_strtou64_base(absl::string_view(tmp.data(), strlen(e.str)), &value, e.base)) << "str=\"" << e.str << "\" base=" << e.base; if (e.expect_ok) { EXPECT_EQ(e.expected, value) << "str=\"" << e.str << "\" base=" << e.base; } } } #if defined(__GLIBC__) || defined(__BIONIC__) #define ABSL_HAVE_FEENABLEEXCEPT 1 #define ABSL_HAVE_FEDISABLEEXCEPT 1 #endif class SimpleDtoaTest : public testing::Test { protected: void SetUp() override { feholdexcept(&fp_env_); #ifdef ABSL_HAVE_FEENABLEEXCEPT feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif } void TearDown() override { #ifdef ABSL_HAVE_FEDISABLEEXCEPT fedisableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif fesetenv(&fp_env_); } std::string ToNineDigits(double value) { char buffer[16]; snprintf(buffer, sizeof(buffer), "%.9g", value); return buffer; } fenv_t fp_env_; }; template <typename R> void ExhaustiveFloat(uint32_t cases, R&& runnable) { runnable(0.0f); runnable(-0.0f); if (cases >= 2e9) { for (float f = 0; f < std::numeric_limits<float>::max(); ) { f = nextafterf(f, std::numeric_limits<float>::max()); runnable(-f); runnable(f); } return; } std::set<float> floats = {3.4028234e38f}; for (float f : {1.0, 3.14159265, 2.718281828, 1 / 2.718281828}) { for (float testf = f; testf != 0; testf *= 0.1f) floats.insert(testf); for (float testf = f; testf != 0; testf *= 0.5f) floats.insert(testf); for (float testf = f; testf < 3e38f / 2; testf *= 2.0f) floats.insert(testf); for (float testf = f; testf < 3e38f / 10; testf *= 10) floats.insert(testf); } float last = *floats.begin(); runnable(last); runnable(-last); int iters_per_float = cases / floats.size(); if (iters_per_float == 0) iters_per_float = 1; for (float f : floats) { if (f == last) continue; float testf = std::nextafter(last, std::numeric_limits<float>::max()); runnable(testf); runnable(-testf); last = testf; if (f == last) continue; double step = (double{f} - last) / iters_per_float; for (double d = last + step; d < f; d += step) { testf = d; if (testf != last) { runnable(testf); runnable(-testf); last = testf; } } testf = std::nextafter(f, 0.0f); if (testf > last) { runnable(testf); runnable(-testf); last = testf; } if (f != last) { runnable(f); runnable(-f); last = f; } } } TEST_F(SimpleDtoaTest, ExhaustiveDoubleToSixDigits) { uint64_t test_count = 0; std::vector<double> mismatches; auto checker = [&](double d) { if (d != d) return; ++test_count; char sixdigitsbuf[kSixDigitsToBufferSize] = {0}; SixDigitsToBuffer(d, sixdigitsbuf); char snprintfbuf[kSixDigitsToBufferSize] = {0}; snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d); if (strcmp(sixdigitsbuf, snprintfbuf) != 0) { mismatches.push_back(d); if (mismatches.size() < 10) { LOG(ERROR) << "Six-digit failure with double. d=" << d << " sixdigits=" << sixdigitsbuf << " printf(%g)=" << snprintfbuf; } } }; checker(5e-324); checker(1e-308); checker(1.0); checker(1.000005); checker(1.7976931348623157e308); checker(0.00390625); #ifndef _MSC_VER checker(0.001953125); #endif checker(0.005859375); checker(1.089095e-15); checker(3.274195e-55); checker(6.534355e-146); checker(2.920845e+234); if (mismatches.empty()) { test_count = 0; ExhaustiveFloat(kFloatNumCases, checker); test_count = 0; std::vector<int> digit_testcases{ 100000, 100001, 100002, 100005, 100010, 100020, 100050, 100100, 195312, 195313, 200000, 500000, 800000, 585937, 585938, 900000, 990000, 999000, 999900, 999990, 999996, 999997, 999998, 999999}; if (kFloatNumCases >= 1e9) { constexpr int min_mantissa = 100000, max_mantissa = 999999; digit_testcases.resize(max_mantissa - min_mantissa + 1); std::iota(digit_testcases.begin(), digit_testcases.end(), min_mantissa); } for (int exponent = -324; exponent <= 308; ++exponent) { double powten = absl::strings_internal::Pow10(exponent); if (powten == 0) powten = 5e-324; if (kFloatNumCases >= 1e9) { char buf[kSixDigitsToBufferSize]; LOG(INFO) << "Exp " << exponent << " powten=" << powten << "(" << powten << ") (" << absl::string_view(buf, SixDigitsToBuffer(powten, buf)) << ")"; } for (int digits : digit_testcases) { if (exponent == 308 && digits >= 179769) break; double digiform = (digits + 0.5) * 0.00001; double testval = digiform * powten; double pretestval = nextafter(testval, 0); double posttestval = nextafter(testval, 1.7976931348623157e308); checker(testval); checker(pretestval); checker(posttestval); } } } else { EXPECT_EQ(mismatches.size(), 0); for (size_t i = 0; i < mismatches.size(); ++i) { if (i > 100) i = mismatches.size() - 1; double d = mismatches[i]; char sixdigitsbuf[kSixDigitsToBufferSize] = {0}; SixDigitsToBuffer(d, sixdigitsbuf); char snprintfbuf[kSixDigitsToBufferSize] = {0}; snprintf(snprintfbuf, kSixDigitsToBufferSize, "%g", d); double before = nextafter(d, 0.0); double after = nextafter(d, 1.7976931348623157e308); char b1[32], b2[kSixDigitsToBufferSize]; LOG(ERROR) << "Mismatch #" << i << " d=" << d << " (" << ToNineDigits(d) << ") sixdigits='" << sixdigitsbuf << "' snprintf='" << snprintfbuf << "' Before.=" << PerfectDtoa(before) << " " << (SixDigitsToBuffer(before, b2), b2) << " vs snprintf=" << (snprintf(b1, sizeof(b1), "%g", before), b1) << " Perfect=" << PerfectDtoa(d) << " " << (SixDigitsToBuffer(d, b2), b2) << " vs snprintf=" << (snprintf(b1, sizeof(b1), "%g", d), b1) << " After.=." << PerfectDtoa(after) << " " << (SixDigitsToBuffer(after, b2), b2) << " vs snprintf=" << (snprintf(b1, sizeof(b1), "%g", after), b1); } } } TEST(StrToInt32, Partial) { struct Int32TestLine { std::string input; bool status; int32_t value; }; const int32_t int32_min = std::numeric_limits<int32_t>::min(); const int32_t int32_max = std::numeric_limits<int32_t>::max(); Int32TestLine int32_test_line[] = { {"", false, 0}, {" ", false, 0}, {"-", false, 0}, {"123@@@", false, 123}, {absl::StrCat(int32_min, int32_max), false, int32_min}, {absl::StrCat(int32_max, int32_max), false, int32_max}, }; for (const Int32TestLine& test_line : int32_test_line) { int32_t value = -2; bool status = safe_strto32_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = -2; status = safe_strto32_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = -2; status = safe_strto32_base(absl::string_view(test_line.input), &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; } } TEST(StrToUint32, Partial) { struct Uint32TestLine { std::string input; bool status; uint32_t value; }; const uint32_t uint32_max = std::numeric_limits<uint32_t>::max(); Uint32TestLine uint32_test_line[] = { {"", false, 0}, {" ", false, 0}, {"-", false, 0}, {"123@@@", false, 123}, {absl::StrCat(uint32_max, uint32_max), false, uint32_max}, }; for (const Uint32TestLine& test_line : uint32_test_line) { uint32_t value = 2; bool status = safe_strtou32_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = 2; status = safe_strtou32_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = 2; status = safe_strtou32_base(absl::string_view(test_line.input), &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; } } TEST(StrToInt64, Partial) { struct Int64TestLine { std::string input; bool status; int64_t value; }; const int64_t int64_min = std::numeric_limits<int64_t>::min(); const int64_t int64_max = std::numeric_limits<int64_t>::max(); Int64TestLine int64_test_line[] = { {"", false, 0}, {" ", false, 0}, {"-", false, 0}, {"123@@@", false, 123}, {absl::StrCat(int64_min, int64_max), false, int64_min}, {absl::StrCat(int64_max, int64_max), false, int64_max}, }; for (const Int64TestLine& test_line : int64_test_line) { int64_t value = -2; bool status = safe_strto64_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = -2; status = safe_strto64_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = -2; status = safe_strto64_base(absl::string_view(test_line.input), &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; } } TEST(StrToUint64, Partial) { struct Uint64TestLine { std::string input; bool status; uint64_t value; }; const uint64_t uint64_max = std::numeric_limits<uint64_t>::max(); Uint64TestLine uint64_test_line[] = { {"", false, 0}, {" ", false, 0}, {"-", false, 0}, {"123@@@", false, 123}, {absl::StrCat(uint64_max, uint64_max), false, uint64_max}, }; for (const Uint64TestLine& test_line : uint64_test_line) { uint64_t value = 2; bool status = safe_strtou64_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = 2; status = safe_strtou64_base(test_line.input, &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; value = 2; status = safe_strtou64_base(absl::string_view(test_line.input), &value, 10); EXPECT_EQ(test_line.status, status) << test_line.input; EXPECT_EQ(test_line.value, value) << test_line.input; } } TEST(StrToInt32Base, PrefixOnly) { struct Int32TestLine { std::string input; bool status; int32_t value; }; Int32TestLine int32_test_line[] = { { "", false, 0 }, { "-", false, 0 }, { "-0", true, 0 }, { "0", true, 0 }, { "0x", false, 0 }, { "-0x", false, 0 }, }; const int base_array[] = { 0, 2, 8, 10, 16 }; for (const Int32TestLine& line : int32_test_line) { for (const int base : base_array) { int32_t value = 2; bool status = safe_strto32_base(line.input.c_str(), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strto32_base(line.input, &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strto32_base(absl::string_view(line.input), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; } } } TEST(StrToUint32Base, PrefixOnly) { struct Uint32TestLine { std::string input; bool status; uint32_t value; }; Uint32TestLine uint32_test_line[] = { { "", false, 0 }, { "0", true, 0 }, { "0x", false, 0 }, }; const int base_array[] = { 0, 2, 8, 10, 16 }; for (const Uint32TestLine& line : uint32_test_line) { for (const int base : base_array) { uint32_t value = 2; bool status = safe_strtou32_base(line.input.c_str(), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strtou32_base(line.input, &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strtou32_base(absl::string_view(line.input), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; } } } TEST(StrToInt64Base, PrefixOnly) { struct Int64TestLine { std::string input; bool status; int64_t value; }; Int64TestLine int64_test_line[] = { { "", false, 0 }, { "-", false, 0 }, { "-0", true, 0 }, { "0", true, 0 }, { "0x", false, 0 }, { "-0x", false, 0 }, }; const int base_array[] = { 0, 2, 8, 10, 16 }; for (const Int64TestLine& line : int64_test_line) { for (const int base : base_array) { int64_t value = 2; bool status = safe_strto64_base(line.input.c_str(), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strto64_base(line.input, &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strto64_base(absl::string_view(line.input), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; } } } TEST(StrToUint64Base, PrefixOnly) { struct Uint64TestLine { std::string input; bool status; uint64_t value; }; Uint64TestLine uint64_test_line[] = { { "", false, 0 }, { "0", true, 0 }, { "0x", false, 0 }, }; const int base_array[] = { 0, 2, 8, 10, 16 }; for (const Uint64TestLine& line : uint64_test_line) { for (const int base : base_array) { uint64_t value = 2; bool status = safe_strtou64_base(line.input.c_str(), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strtou64_base(line.input, &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; value = 2; status = safe_strtou64_base(absl::string_view(line.input), &value, base); EXPECT_EQ(line.status, status) << line.input << " " << base; EXPECT_EQ(line.value, value) << line.input << " " << base; } } } void TestFastHexToBufferZeroPad16(uint64_t v) { char buf[16]; auto digits = absl::numbers_internal::FastHexToBufferZeroPad16(v, buf); absl::string_view res(buf, 16); char buf2[17]; snprintf(buf2, sizeof(buf2), "%016" PRIx64, v); EXPECT_EQ(res, buf2) << v; size_t expected_digits = snprintf(buf2, sizeof(buf2), "%" PRIx64, v); EXPECT_EQ(digits, expected_digits) << v; } TEST(FastHexToBufferZeroPad16, Smoke) { TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::min()); TestFastHexToBufferZeroPad16(std::numeric_limits<uint64_t>::max()); TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::min()); TestFastHexToBufferZeroPad16(std::numeric_limits<int64_t>::max()); absl::BitGen rng; for (int i = 0; i < 100000; ++i) { TestFastHexToBufferZeroPad16( absl::LogUniform(rng, std::numeric_limits<uint64_t>::min(), std::numeric_limits<uint64_t>::max())); } } template <typename Int> void ExpectWritesNull() { { char buf[absl::numbers_internal::kFastToBufferSize]; Int x = std::numeric_limits<Int>::min(); EXPECT_THAT(absl::numbers_internal::FastIntToBuffer(x, buf), Pointee('\0')); } { char buf[absl::numbers_internal::kFastToBufferSize]; Int x = std::numeric_limits<Int>::max(); EXPECT_THAT(absl::numbers_internal::FastIntToBuffer(x, buf), Pointee('\0')); } } TEST(FastIntToBuffer, WritesNull) { ExpectWritesNull<int32_t>(); ExpectWritesNull<uint32_t>(); ExpectWritesNull<int64_t>(); ExpectWritesNull<uint32_t>(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/numbers.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/numbers_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
1d2091bf-92ce-4eb9-be25-2a47e7d5068d
cpp
abseil/abseil-cpp
charconv
absl/strings/charconv.cc
absl/strings/charconv_test.cc
#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) { if (MustRoundUp(binary_mantissa, binary_exponent, parsed_decimal)) { binary_mantissa += 1; } } return CalculatedFloatFromRawValues<FloatType>(binary_mantissa, binary_exponent); } template <typename FloatType> bool EiselLemire(const strings_internal::ParsedFloat& input, bool negative, absl::Nonnull<FloatType*> value, absl::Nonnull<std::errc*> ec) { uint64_t man = input.mantissa; int exp10 = input.exponent; if (exp10 < FloatTraits<FloatType>::kEiselLemireMinInclusiveExp10) { *value = negative ? -0.0 : 0.0; *ec = std::errc::result_out_of_range; return true; } else if (exp10 >= FloatTraits<FloatType>::kEiselLemireMaxExclusiveExp10) { *value = negative ? -std::numeric_limits<FloatType>::max() : std::numeric_limits<FloatType>::max(); *ec = std::errc::result_out_of_range; return true; } static_assert( FloatTraits<FloatType>::kEiselLemireMinInclusiveExp10 >= kPower10TableMinInclusive, "(exp10-kPower10TableMinInclusive) in kPower10MantissaHighTable bounds"); static_assert( FloatTraits<FloatType>::kEiselLemireMaxExclusiveExp10 <= kPower10TableMaxExclusive, "(exp10-kPower10TableMinInclusive) in kPower10MantissaHighTable bounds"); int clz = countl_zero(man); man <<= static_cast<unsigned int>(clz); uint64_t ret_exp2 = static_cast<uint64_t>((217706 * exp10 >> 16) + 64 + FloatTraits<FloatType>::kExponentBias - clz); uint128 x = static_cast<uint128>(man) * static_cast<uint128>( kPower10MantissaHighTable[exp10 - kPower10TableMinInclusive]); static constexpr uint64_t high64_mask = FloatTraits<FloatType>::kEiselLemireMask; if (((Uint128High64(x) & high64_mask) == high64_mask) && (man > (std::numeric_limits<uint64_t>::max() - Uint128Low64(x)))) { uint128 y = static_cast<uint128>(man) * static_cast<uint128>( kPower10MantissaLowTable[exp10 - kPower10TableMinInclusive]); x += Uint128High64(y); if (((Uint128High64(x) & high64_mask) == high64_mask) && ((Uint128Low64(x) + 1) == 0) && (man > (std::numeric_limits<uint64_t>::max() - Uint128Low64(y)))) { return false; } } uint64_t msb = Uint128High64(x) >> 63; uint64_t ret_man = Uint128High64(x) >> (msb + FloatTraits<FloatType>::kEiselLemireShift); ret_exp2 -= 1 ^ msb; if ((Uint128Low64(x) == 0) && ((Uint128High64(x) & high64_mask) == 0) && ((ret_man & 3) == 1)) { return false; } ret_man += ret_man & 1; ret_man >>= 1; if ((ret_man >> FloatTraits<FloatType>::kTargetMantissaBits) > 0) { ret_exp2 += 1; } static constexpr uint64_t max_exp2 = (1 << FloatTraits<FloatType>::kTargetExponentBits) - 1; if ((ret_exp2 - 1) >= (max_exp2 - 1)) { return false; } #ifndef ABSL_BIT_PACK_FLOATS if (FloatTraits<FloatType>::kTargetBits == 64) { *value = FloatTraits<FloatType>::Make( (ret_man & 0x000FFFFFFFFFFFFFu) | 0x0010000000000000u, static_cast<int>(ret_exp2) - 1023 - 52, negative); return true; } else if (FloatTraits<FloatType>::kTargetBits == 32) { *value = FloatTraits<FloatType>::Make( (static_cast<uint32_t>(ret_man) & 0x007FFFFFu) | 0x00800000u, static_cast<int>(ret_exp2) - 127 - 23, negative); return true; } #else if (FloatTraits<FloatType>::kTargetBits == 64) { uint64_t ret_bits = (ret_exp2 << 52) | (ret_man & 0x000FFFFFFFFFFFFFu); if (negative) { ret_bits |= 0x8000000000000000u; } *value = absl::bit_cast<double>(ret_bits); return true; } else if (FloatTraits<FloatType>::kTargetBits == 32) { uint32_t ret_bits = (static_cast<uint32_t>(ret_exp2) << 23) | (static_cast<uint32_t>(ret_man) & 0x007FFFFFu); if (negative) { ret_bits |= 0x80000000u; } *value = absl::bit_cast<float>(ret_bits); return true; } #endif return false; } template <typename FloatType> from_chars_result FromCharsImpl(absl::Nonnull<const char*> first, absl::Nonnull<const char*> last, FloatType& value, chars_format fmt_flags) { from_chars_result result; result.ptr = first; result.ec = std::errc(); bool negative = false; if (first != last && *first == '-') { ++first; negative = true; } if ((fmt_flags & chars_format::hex) == chars_format{} && last - first >= 2 && *first == '0' && (first[1] == 'x' || first[1] == 'X')) { const char* hex_first = first + 2; strings_internal::ParsedFloat hex_parse = strings_internal::ParseFloat<16>(hex_first, last, fmt_flags); if (hex_parse.end == nullptr || hex_parse.type != strings_internal::FloatType::kNumber) { if (fmt_flags == chars_format::scientific) { result.ec = std::errc::invalid_argument; } else { result.ptr = first + 1; value = negative ? -0.0 : 0.0; } return result; } result.ptr = hex_parse.end; if (HandleEdgeCase(hex_parse, negative, &value)) { return result; } CalculatedFloat calculated = CalculateFromParsedHexadecimal<FloatType>(hex_parse); EncodeResult(calculated, negative, &result, &value); return result; } if ((fmt_flags & chars_format::hex) == chars_format::hex) { strings_internal::ParsedFloat hex_parse = strings_internal::ParseFloat<16>(first, last, fmt_flags); if (hex_parse.end == nullptr) { result.ec = std::errc::invalid_argument; return result; } result.ptr = hex_parse.end; if (HandleEdgeCase(hex_parse, negative, &value)) { return result; } CalculatedFloat calculated = CalculateFromParsedHexadecimal<FloatType>(hex_parse); EncodeResult(calculated, negative, &result, &value); return result; } else { strings_internal::ParsedFloat decimal_parse = strings_internal::ParseFloat<10>(first, last, fmt_flags); if (decimal_parse.end == nullptr) { result.ec = std::errc::invalid_argument; return result; } result.ptr = decimal_parse.end; if (HandleEdgeCase(decimal_parse, negative, &value)) { return result; } if ((decimal_parse.subrange_begin == nullptr) && EiselLemire<FloatType>(decimal_parse, negative, &value, &result.ec)) { return result; } CalculatedFloat calculated = CalculateFromParsedDecimal<FloatType>(decimal_parse); EncodeResult(calculated, negative, &result, &value); return result; } } } from_chars_result from_chars(absl::Nonnull<const char*> first, absl::Nonnull<const char*> last, double& value, chars_format fmt) { return FromCharsImpl(first, last, value, fmt); } from_chars_result from_chars(absl::Nonnull<const char*> first, absl::Nonnull<const char*> last, float& value, chars_format fmt) { return FromCharsImpl(first, last, value, fmt); } namespace { const uint64_t kPower10MantissaHighTable[] = { 0xeef453d6923bd65aU, 0x9558b4661b6565f8U, 0xbaaee17fa23ebf76U, 0xe95a99df8ace6f53U, 0x91d8a02bb6c10594U, 0xb64ec836a47146f9U, 0xe3e27a444d8d98b7U, 0x8e6d8c6ab0787f72U, 0xb208ef855c969f4fU, 0xde8b2b66b3bc4723U, 0x8b16fb203055ac76U, 0xaddcb9e83c6b1793U, 0xd953e8624b85dd78U, 0x87d4713d6f33aa6bU, 0xa9c98d8ccb009506U, 0xd43bf0effdc0ba48U, 0x84a57695fe98746dU, 0xa5ced43b7e3e9188U, 0xcf42894a5dce35eaU, 0x818995ce7aa0e1b2U, 0xa1ebfb4219491a1fU, 0xca66fa129f9b60a6U, 0xfd00b897478238d0U, 0x9e20735e8cb16382U, 0xc5a890362fddbc62U, 0xf712b443bbd52b7bU, 0x9a6bb0aa55653b2dU, 0xc1069cd4eabe89f8U, 0xf148440a256e2c76U, 0x96cd2a865764dbcaU, 0xbc807527ed3e12bcU, 0xeba09271e88d976bU, 0x93445b8731587ea3U, 0xb8157268fdae9e4cU, 0xe61acf033d1a45dfU, 0x8fd0c16206306babU, 0xb3c4f1ba87bc8696U, 0xe0b62e2929aba83cU, 0x8c71dcd9ba0b4925U, 0xaf8e5410288e1b6fU, 0xdb71e91432b1a24aU, 0x892731ac9faf056eU, 0xab70fe17c79ac6caU, 0xd64d3d9db981787dU, 0x85f0468293f0eb4eU, 0xa76c582338ed2621U, 0xd1476e2c07286faaU, 0x82cca4db847945caU, 0xa37fce126597973cU, 0xcc5fc196fefd7d0cU, 0xff77b1fcbebcdc4fU, 0x9faacf3df73609b1U, 0xc795830d75038c1dU, 0xf97ae3d0d2446f25U, 0x9becce62836ac577U, 0xc2e801fb244576d5U, 0xf3a20279ed56d48aU, 0x9845418c345644d6U, 0xbe5691ef416bd60cU, 0xedec366b11c6cb8fU, 0x94b3a202eb1c3f39U, 0xb9e08a83a5e34f07U, 0xe858ad248f5c22c9U, 0x91376c36d99995beU, 0xb58547448ffffb2dU, 0xe2e69915b3fff9f9U, 0x8dd01fad907ffc3bU, 0xb1442798f49ffb4aU, 0xdd95317f31c7fa1dU, 0x8a7d3eef7f1cfc52U, 0xad1c8eab5ee43b66U, 0xd863b256369d4a40U, 0x873e4f75e2224e68U, 0xa90de3535aaae202U, 0xd3515c2831559a83U, 0x8412d9991ed58091U, 0xa5178fff668ae0b6U, 0xce5d73ff402d98e3U, 0x80fa687f881c7f8eU, 0xa139029f6a239f72U, 0xc987434744ac874eU, 0xfbe9141915d7a922U, 0x9d71ac8fada6c9b5U, 0xc4ce17b399107c22U, 0xf6019da07f549b2bU, 0x99c102844f94e0fbU, 0xc0314325637a1939U, 0xf03d93eebc589f88U, 0x96267c7535b763b5U, 0xbbb01b9283253ca2U, 0xea9c227723ee8bcbU, 0x92a1958a7675175fU, 0xb749faed14125d36U, 0xe51c79a85916f484U, 0x8f31cc0937ae58d2U, 0xb2fe3f0b8599ef07U, 0xdfbdcece67006ac9U, 0x8bd6a141006042bdU, 0xaecc49914078536dU, 0xda7f5bf590966848U, 0x888f99797a5e012dU, 0xaab37fd7d8f58178U, 0xd5605fcdcf32e1d6U, 0x855c3be0a17fcd26U, 0xa6b34ad8c9dfc06fU, 0xd0601d8efc57b08bU, 0x823c12795db6ce57U, 0xa2cb1717b52481edU, 0xcb7ddcdda26da268U, 0xfe5d54150b090b02U, 0x9efa548d26e5a6e1U, 0xc6b8e9b0709f109aU, 0xf867241c8cc6d4c0U, 0x9b407691d7fc44f8U, 0xc21094364dfb5636U, 0xf294b943e17a2bc4U, 0x979cf3ca6cec5b5aU, 0xbd8430bd08277231U, 0xece53cec4a314ebdU, 0x940f4613ae5ed136U, 0xb913179899f68584U, 0xe757dd7ec07426e5U, 0x9096ea6f3848984fU, 0xb4bca50b065abe63U, 0xe1ebce4dc7f16dfbU, 0x8d3360f09cf6e4bdU, 0xb080392cc4349decU, 0xdca04777f541c567U, 0x89e42caaf9491b60U, 0xac5d37d5b79b6239U, 0xd77485cb25823ac7U, 0x86a8d39ef77164bcU, 0xa8530886b54dbdebU, 0xd267caa862a12d66U, 0x8380dea93da4bc60U, 0xa46116538d0deb78U, 0xcd795be870516656U, 0x806bd9714632dff6U, 0xa086cfcd97bf97f3U, 0xc8a883c0fdaf7df0U, 0xfad2a4b13d1b5d6cU, 0x9cc3a6eec6311a63U, 0xc3f490aa77bd60fcU, 0xf4f1b4d515acb93bU, 0x991711052d8bf3c5U, 0xbf5cd54678eef0b6U, 0xef340a98172aace4U, 0x9580869f0e7aac0eU, 0xbae0a846d2195712U, 0xe998d258869facd7U, 0x91ff83775423cc06U, 0xb67f6455292cbf08U, 0xe41f3d6a7377eecaU, 0x8e938662882af53eU, 0xb23867fb2a35b28dU, 0xdec681f9f4c31f31U, 0x8b3c113c38f9f37eU, 0xae0b158b4738705eU, 0xd98ddaee19068c76U, 0x87f8a8d4cfa417c9U, 0xa9f6d30a038d1dbcU, 0xd47487cc8470652bU, 0x84c8d4dfd2c63f3bU, 0xa5fb0a17c777cf09U, 0xcf79cc9db955c2ccU, 0x81ac1fe293d599bfU, 0xa21727db38cb002fU, 0xca9cf1d206fdc03bU, 0xfd442e4688bd304aU, 0x9e4a9cec15763e2eU, 0xc5dd44271ad3cdbaU, 0xf7549530e188c128U, 0x9a94dd3e8cf578b9U, 0xc13a148e3032d6e7U, 0xf18899b1bc3f8ca1U, 0x96f5600f15a7b7e5U, 0xbcb2b812db11a5deU, 0xebdf661791d60f56U, 0x936b9fcebb25c995U, 0xb84687c269ef3bfbU, 0xe65829b3046b0afaU, 0x8ff71a0fe2c2e6dcU, 0xb3f4e093db73a093U, 0xe0f218b8d25088b8U, 0x8c974f7383725573U, 0xafbd2350644eeacfU, 0xdbac6c247d62a583U, 0x894bc396ce5da772U, 0xab9eb47c81f5114fU, 0xd686619ba27255a2U, 0x8613fd0145877585U, 0xa798fc4196e952e7U, 0xd17f3b51fca3a7a0U, 0x82ef85133de648c4U, 0xa3ab66580d5fdaf5U, 0xcc963fee10b7d1b3U, 0xffbbcfe994e5c61fU, 0x9fd561f1fd0f9bd3U, 0xc7caba6e7c5382c8U, 0xf9bd690a1b68637bU, 0x9c1661a651213e2dU, 0xc31bfa0fe5698db8U, 0xf3e2f893dec3f126U, 0x986ddb5c6b3a76b7U, 0xbe89523386091465U, 0xee2ba6c0678b597fU, 0x94db483840b717efU, 0xba121a4650e4ddebU, 0xe896a0d7e51e1566U, 0x915e2486ef32cd60U, 0xb5b5ada8aaff80b8U, 0xe3231912d5bf60e6U, 0x8df5efabc5979c8fU, 0xb1736b96b6fd83b3U, 0xddd0467c64bce4a0U, 0x8aa22c0dbef60ee4U, 0xad4ab7112eb3929dU, 0xd89d64d57a607744U, 0x87625f056c7c4a8bU, 0xa93af6c6c79b5d2dU, 0xd389b47879823479U, 0x843610cb4bf160cbU, 0xa54394fe1eedb8feU, 0xce947a3da6a9273eU, 0x811ccc668829b887U, 0xa163ff802a3426a8U, 0xc9bcff6034c13052U, 0xfc2c3f3841f17c67U, 0x9d9ba7832936edc0U, 0xc5029163f384a931U, 0xf64335bcf065d37dU, 0x99ea0196163fa42eU, 0xc06481fb9bcf8d39U, 0xf07da27a82c37088U, 0x964e858c91ba2655U, 0xbbe226efb628afeaU, 0xeadab0aba3b2dbe5U, 0x92c8ae6b464fc96fU, 0xb77ada0617e3bbcbU, 0xe55990879ddcaabdU, 0x8f57fa54c2a9eab6U, 0xb32df8e9f3546564U, 0xdff9772470297ebdU, 0x8bfbea76c619ef36U, 0xaefae51477a06b03U, 0xdab99e59958885c4U, 0x88b402f7fd75539bU, 0xaae103b5fcd2a881U, 0xd59944a37c0752a2U, 0x857fcae62d8493a5U, 0xa6dfbd9fb8e5b88eU, 0xd097ad07a71f26b2U, 0x825ecc24c873782fU, 0xa2f67f2dfa90563bU, 0xcbb41ef979346bcaU, 0xfea126b7d78186bcU, 0x9f24b832e6b0f436U, 0xc6ede63fa05d3143U, 0xf8a95fcf88747d94U, 0x9b69dbe1b548ce7cU, 0xc24452da229b021bU, 0xf2d56790ab41c2a2U, 0x97c560ba6b0919a5U, 0xbdb6b8e905cb600fU, 0xed246723473e3813U, 0x9436c0760c86e30bU, 0xb94470938fa89bceU, 0xe7958cb87392c2c2U, 0x90bd77f3483bb9b9U, 0xb4ecd5f01a4aa828U, 0xe2280b6c20dd5232U, 0x8d590723948a535fU, 0xb0af48ec79ace837U, 0xdcdb1b2798182244U, 0x8a08f0f8bf0f156bU, 0xac8b2d36eed2dac5U, 0xd7adf884aa879177U, 0x86ccbb52ea94baeaU, 0xa87fea27a539e9a5U, 0xd29fe4b18e88640eU, 0x83a3eeeef9153e89U, 0xa48ceaaab75a8e2bU, 0xcdb02555653131b6U, 0x808e17555f3ebf11U, 0xa0b19d2ab70e6ed6U, 0xc8de047564d20a8bU, 0xfb158592be068d2eU, 0x9ced737bb6c4183dU, 0xc428d05aa4751e4cU, 0xf53304714d9265dfU, 0x993fe2c6d07b7fabU, 0xbf8fdb78849a5f96U, 0xef73d256a5c0f77cU, 0x95a8637627989aadU, 0xbb127c53b17ec159U, 0xe9d71b689dde71afU, 0x9226712162ab070dU, 0xb6b00d69bb55c8d1U, 0xe45c10c42a2b3b05U, 0x8eb98a7a9a5b04e3U, 0xb267ed1940f1c61cU, 0xdf01e85f912e37a3U, 0x8b61313bbabce2c6U, 0xae397d8aa96c1b77U, 0xd9c7dced53c72255U, 0x881cea14545c7575U, 0xaa242499697392d2U, 0xd4ad2dbfc3d07787U, 0x84ec3c97da624ab4U, 0xa6274bbdd0fadd61U, 0xcfb11ead453994baU, 0x81ceb32c4b43fcf4U, 0xa2425ff75e14fc31U, 0xcad2f7f5359a3b3eU, 0xfd87b5f28300ca0dU, 0x9e74d1b791e07e48U, 0xc612062576589ddaU, 0xf79687aed3eec551U, 0x9abe14cd44753b52U, 0xc16d9a0095928a27U, 0xf1c90080baf72cb1U, 0x971da05074da7beeU, 0xbce5086492111aeaU, 0xec1e4a7db69561a5U, 0x9392ee8e921d5d07U, 0xb877aa3236a4b449U, 0xe69594bec44de15bU, 0x901d7cf73ab0acd9U, 0xb424dc35095cd80fU, 0xe12e13424bb40e13U, 0x8cbccc096f5088cbU, 0xafebff0bcb24aafeU, 0xdbe6fecebdedd5beU, 0x89705f4136b4a597U, 0xabcc77118461cefcU, 0xd6bf94d5e57a42bcU, 0x8637bd05af6c69b5U, 0xa7c5ac471b478423U, 0xd1b71758e219652bU, 0x83126e978d4fdf3bU, 0xa3d70a3d70a3d70aU, 0xccccccccccccccccU, 0x8000000000000000U, 0xa000000000000000U, 0xc800000000000000U, 0xfa00000000000000U, 0x9c40000000000000U, 0xc350000000000000U, 0xf424000000000000U, 0x9896800000000000U, 0xbebc200000000000U, 0xee6b280000000000U, 0x9502f90000000000U, 0xba43b74000000000U, 0xe8d4a51000000000U, 0x9184e72a00000000U, 0xb5e620f480000000U, 0xe35fa931a0000000U, 0x8e1bc9bf04000000U, 0xb1a2bc2ec5000000U, 0xde0b6b3a76400000U, 0x8ac7230489e80000U, 0xad78ebc5ac620000U, 0xd8d726b7177a8000U, 0x878678326eac9000U, 0xa968163f0a57b400U, 0xd3c21bcecceda100U, 0x84595161401484a0U, 0xa56fa5b99019a5c8U, 0xcecb8f27f4200f3aU, 0x813f3978f8940984U, 0xa18f07d736b90be5U, 0xc9f2c9cd04674edeU, 0xfc6f7c4045812296U, 0x9dc5ada82b70b59dU, 0xc5371912364ce305U, 0xf684df56c3e01bc6U, 0x9a130b963a6c115cU, 0xc097ce7bc90715b3U, 0xf0bdc21abb48db20U, 0x96769950b50d88f4U, 0xbc143fa4e250eb31U, 0xeb194f8e1ae525fdU, 0x92efd1b8d0cf37beU, 0xb7abc627050305adU, 0xe596b7b0c643c719U, 0x8f7e32ce7bea5c6fU, 0xb35dbf821ae4f38bU, 0xe0352f62a19e306eU, 0x8c213d9da502de45U, 0xaf298d050e4395d6U, 0xdaf3f04651d47b4cU, 0x88d8762bf324cd0fU, 0xab0e93b6efee0053U, 0xd5d238a4abe98068U, 0x85a36366eb71f041U, 0xa70c3c40a64e6c51U, 0xd0cf4b50cfe20765U, 0x82818f1281ed449fU, 0xa321f2d7226895c7U, 0xcbea6f8ceb02bb39U, 0xfee50b7025c36a08U, 0x9f4f2726179a2245U, 0xc722f0ef9d80aad6U, 0xf8ebad2b84e0d58bU, 0x9b934c3b330c8577U, 0xc2781f49ffcfa6d5U, 0xf316271c7fc3908aU, 0x97edd871cfda3a56U, 0xbde94e8e43d0c8ecU, 0xed63a231d4c4fb27U, 0x945e455f24fb1cf8U, 0xb975d6b6ee39e436U, 0xe7d34c64a9c85d44U, 0x90e40fbeea1d3a4aU, 0xb51d13aea4a488ddU, 0xe264589a4dcdab14U, 0x8d7eb76070a08aecU, 0xb0de65388cc8ada8U, 0xdd15fe86affad912U, 0x8a2dbf142dfcc7abU, 0xacb92ed9397bf996U, 0xd7e77a8f87daf7fbU, 0x86f0ac99b4e8dafdU, 0xa8acd7c0222311bcU, 0xd2d80db02aabd62bU, 0x83c7088e1aab65dbU, 0xa4b8cab1a1563f52U, 0xcde6fd5e09abcf26U, 0x80b05e5ac60b6178U, 0xa0dc75f1778e39d6U, 0xc913936dd571c84cU, 0xfb5878494ace3a5fU, 0x9d174b2dcec0e47bU, 0xc45d1df942711d9aU, 0xf5746577930d6500U, 0x9968bf6abbe85f20U, 0xbfc2ef456ae276e8U, 0xefb3ab16c59b14a2U, 0x95d04aee3b80ece5U, 0xbb445da9ca61281fU, 0xea1575143cf97226U, 0x924d692ca61be758U, 0xb6e0c377cfa2e12eU, 0xe498f455c38b997aU, 0x8edf98b59a373fecU, 0xb2977ee300c50fe7U, 0xdf3d5e9bc0f653e1U, 0x8b865b215899f46cU, 0xae67f1e9aec07187U, 0xda01ee641a708de9U, 0x884134fe908658b2U, 0xaa51823e34a7eedeU, 0xd4e5e2cdc1d1ea96U, 0x850fadc09923329eU, 0xa6539930bf6bff45U, 0xcfe87f7cef46ff16U, 0x81f14fae158c5f6eU, 0xa26da3999aef7749U, 0xcb090c8001ab551cU, 0xfdcb4fa002162a63U, 0x9e9f11c4014dda7eU, 0xc646d63501a1511dU, 0xf7d88bc24209a565U, 0x9ae757596946075fU, 0xc1a12d2fc3978937U, 0xf209787bb47d6b84U, 0x9745eb4d50ce6332U, 0xbd176620a501fbffU, 0xec5d3fa8ce427affU, 0x93ba47c980e98cdfU, 0xb8a8d9bbe123f017U, 0xe6d3102ad96cec1dU, 0x9043ea1ac7e41392U, 0xb454e4a179dd1877U, 0xe16a1dc9d8545e94U, 0x8ce2529e2734bb1dU, 0xb01ae745b101e9e4U, 0xdc21a1171d42645dU, 0x899504ae72497ebaU, 0xabfa45da0edbde69U, 0xd6f8d7509292d603U, 0x865b86925b9bc5c2U, 0xa7f26836f282b732U, 0xd1ef0244af2364ffU, 0x8335616aed761f1fU, 0xa402b9c5a8d3a6e7U, 0xcd036837130890a1U, 0x802221226be55a64U, 0xa02aa96b06deb0fdU, 0xc83553c5c8965d3dU, 0xfa42a8b73abbf48cU, 0x9c69a97284b578d7U, 0xc38413cf25e2d70dU, 0xf46518c2ef5b8cd1U, 0x98bf2f79d5993802U, 0xbeeefb584aff8603U, 0xeeaaba2e5dbf6784U, 0x952ab45cfa97a0b2U, 0xba756174393d88dfU, 0xe912b9d1478ceb17U, 0x91abb422ccb812eeU, 0xb616a12b7fe617aaU, 0xe39c49765fdf9d94U, 0x8e41ade9fbebc27dU, 0xb1d219647ae6b31cU, 0xde469fbd99a05fe3U, 0x8aec23d680043beeU, 0xada72ccc20054ae9U, 0xd910f7ff28069da4U, 0x87aa9aff79042286U, 0xa99541bf57452b28U, 0xd3fa922f2d1675f2U, 0x847c9b5d7c2e09b7U, 0xa59bc234db398c25U, 0xcf02b2c21207ef2eU, 0x8161afb94b44f57dU, 0xa1ba1ba79e1632dcU, 0xca28a291859bbf93U, 0xfcb2cb35e702af78U, 0x9defbf01b061adabU, 0xc56baec21c7a1916U, 0xf6c69a72a3989f5bU, 0x9a3c2087a63f6399U, 0xc0cb28a98fcf3c7fU, 0xf0fdf2d3f3c30b9fU, 0x969eb7c47859e743U, 0xbc4665b596706114U, 0xeb57ff22fc0c7959U, 0x9316ff75dd87cbd8U, 0xb7dcbf5354e9beceU, 0xe5d3ef282a242e81U, 0x8fa475791a569d10U, 0xb38d92d760ec4455U, 0xe070f78d3927556aU, 0x8c469ab843b89562U, 0xaf58416654a6babbU, 0xdb2e51bfe9d0696aU, 0x88fcf317f22241e2U, 0xab3c2fddeeaad25aU, 0xd60b3bd56a5586f1U, 0x85c7056562757456U, 0xa738c6bebb12d16cU, 0xd106f86e69d785c7U, 0x82a45b450226b39cU, 0xa34d721642b06084U, 0xcc20ce9bd35c78a5U, 0xff290242c83396ceU, 0x9f79a169bd203e41U, 0xc75809c42c684dd1U, 0xf92e0c3537826145U, 0x9bbcc7a142b17ccbU, 0xc2abf989935ddbfeU, 0xf356f7ebf83552feU, 0x98165af37b2153deU, 0xbe1bf1b059e9a8d6U, 0xeda2ee1c7064130cU, 0x9485d4d1c63e8be7U, 0xb9a74a0637ce2ee1U, 0xe8111c87c5c1ba99U, 0x910ab1d4db9914a0U, 0xb54d5e4a127f59c8U, 0xe2a0b5dc971f303aU, 0x8da471a9de737e24U, 0xb10d8e1456105dadU, 0xdd50f1996b947518U, 0x8a5296ffe33cc92fU, 0xace73cbfdc0bfb7bU, 0xd8210befd30efa5aU, 0x8714a775e3e95c78U, 0xa8d9d1535ce3b396U, 0xd31045a8341ca07cU, 0x83ea2b892091e44dU, 0xa4e4b66b68b65d60U, 0xce1de40642e3f4b9U, 0x80d2ae83e9ce78f3U, 0xa1075a24e4421730U, 0xc94930ae1d529cfcU, 0xfb9b7cd9a4a7443cU, 0x9d412e0806e88aa5U, 0xc491798a08a2ad4eU, 0xf5b5d7ec8acb58a2U, 0x9991a6f3d6bf1765U, 0xbff610b0cc6edd3fU, 0xeff394dcff8a948eU, 0x95f83d0a1fb69cd9U, 0xbb764c4ca7a4440fU, 0xea53df5fd18d5513U, 0x92746b9be2f8552cU, 0xb7118682dbb66a77U, 0xe4d5e82392a40515U, 0x8f05b1163ba6832dU, 0xb2c71d5bca9023f8U, 0xdf78e4b2bd342cf6U, 0x8bab8eefb6409c1aU, 0xae9672aba3d0c320U, 0xda3c0f568cc4f3e8U, 0x8865899617fb1871U, 0xaa7eebfb9df9de8dU, 0xd51ea6fa85785631U, 0x8533285c936b35deU, 0xa67ff273b8460356U, 0xd01fef10a657842cU, 0x8213f56a67f6b29bU, 0xa298f2c501f45f42U, 0xcb3f2f7642717713U, 0xfe0efb53d30dd4d7U, 0x9ec95d1463e8a506U, 0xc67bb4597ce2ce48U, 0xf81aa16fdc1b81daU, 0x9b10a4e5e9913128U, 0xc1d4ce1f63f57d72U, 0xf24a01a73cf2dccfU, 0x976e41088617ca01U, 0xbd49d14aa79dbc82U, 0xec9c459d51852ba2U, 0x93e1ab8252f33b45U, 0xb8da1662e7b00a17U, 0xe7109bfba19c0c9dU, 0x906a617d450187e2U, 0xb484f9dc9641e9daU, 0xe1a63853bbd26451U, 0x8d07e33455637eb2U, 0xb049dc016abc5e5fU, 0xdc5c5301c56b75f7U, 0x89b9b3e11b6329baU, 0xac2820d9623bf429U, 0xd732290fbacaf133U, 0x867f59a9d4bed6c0U, 0xa81f301449ee8c70U, 0xd226fc195c6a2f8cU, 0x83585d8fd9c25db7U, 0xa42e74f3d032f525U, 0xcd3a1230c43fb26fU, 0x80444b5e7aa7cf85U, 0xa0555e361951c366U, 0xc86ab5c39fa63440U, 0xfa856334878fc150U, 0x9c935e00d4b9d8d2U, 0xc3b8358109e84f07U, 0xf4a642e14c6262c8U, 0x98e7e9cccfbd7dbdU, 0xbf21e44003acdd2cU, 0xeeea5d5004981478U, 0x95527a5202df0ccbU, 0xbaa718e68396cffdU, 0xe950df20247c83fdU, 0x91d28b7416cdd27eU, 0xb6472e511c81471dU, 0xe3d8f9e563a198e5U, 0x8e679c2f5e44ff8fU, }; const uint64_t kPower10MantissaLowTable[] = { 0x113faa2906a13b3fU, 0x4ac7ca59a424c507U, 0x5d79bcf00d2df649U, 0xf4d82c2c107973dcU, 0x79071b9b8a4be869U, 0x9748e2826cdee284U, 0xfd1b1b2308169b25U, 0xfe30f0f5e50e20f7U, 0xbdbd2d335e51a935U, 0xad2c788035e61382U, 0x4c3bcb5021afcc31U, 0xdf4abe242a1bbf3dU, 0xd71d6dad34a2af0dU, 0x8672648c40e5ad68U, 0x680efdaf511f18c2U, 0x0212bd1b2566def2U, 0x014bb630f7604b57U, 0x419ea3bd35385e2dU, 0x52064cac828675b9U, 0x7343efebd1940993U, 0x1014ebe6c5f90bf8U, 0xd41a26e077774ef6U, 0x8920b098955522b4U, 0x55b46e5f5d5535b0U, 0xeb2189f734aa831dU, 0xa5e9ec7501d523e4U, 0x47b233c92125366eU, 0x999ec0bb696e840aU, 0xc00670ea43ca250dU, 0x380406926a5e5728U, 0xc605083704f5ecf2U, 0xf7864a44c633682eU, 0x7ab3ee6afbe0211dU, 0x5960ea05bad82964U, 0x6fb92487298e33bdU, 0xa5d3b6d479f8e056U, 0x8f48a4899877186cU, 0x331acdabfe94de87U, 0x9ff0c08b7f1d0b14U, 0x07ecf0ae5ee44dd9U, 0xc9e82cd9f69d6150U, 0xbe311c083a225cd2U, 0x6dbd630a48aaf406U, 0x092cbbccdad5b108U, 0x25bbf56008c58ea5U, 0xaf2af2b80af6f24eU, 0x1af5af660db4aee1U, 0x50d98d9fc890ed4dU, 0xe50ff107bab528a0U, 0x1e53ed49a96272c8U, 0x25e8e89c13bb0f7aU, 0x77b191618c54e9acU, 0xd59df5b9ef6a2417U, 0x4b0573286b44ad1dU, 0x4ee367f9430aec32U, 0x229c41f793cda73fU, 0x6b43527578c1110fU, 0x830a13896b78aaa9U, 0x23cc986bc656d553U, 0x2cbfbe86b7ec8aa8U, 0x7bf7d71432f3d6a9U, 0xdaf5ccd93fb0cc53U, 0xd1b3400f8f9cff68U, 0x23100809b9c21fa1U, 0xabd40a0c2832a78aU, 0x16c90c8f323f516cU, 0xae3da7d97f6792e3U, 0x99cd11cfdf41779cU, 0x40405643d711d583U, 0x482835ea666b2572U, 0xda3243650005eecfU, 0x90bed43e40076a82U, 0x5a7744a6e804a291U, 0x711515d0a205cb36U, 0x0d5a5b44ca873e03U, 0xe858790afe9486c2U, 0x626e974dbe39a872U, 0xfb0a3d212dc8128fU, 0x7ce66634bc9d0b99U, 0x1c1fffc1ebc44e80U, 0xa327ffb266b56220U, 0x4bf1ff9f0062baa8U, 0x6f773fc3603db4a9U, 0xcb550fb4384d21d3U, 0x7e2a53a146606a48U, 0x2eda7444cbfc426dU, 0xfa911155fefb5308U, 0x793555ab7eba27caU, 0x4bc1558b2f3458deU, 0x9eb1aaedfb016f16U, 0x465e15a979c1cadcU, 0x0bfacd89ec191ec9U, 0xcef980ec671f667bU, 0x82b7e12780e7401aU, 0xd1b2ecb8b0908810U, 0x861fa7e6dcb4aa15U, 0x67a791e093e1d49aU, 0xe0c8bb2c5c6d24e0U, 0x58fae9f773886e18U, 0xaf39a475506a899eU, 0x6d8406c952429603U, 0xc8e5087ba6d33b83U, 0xfb1e4a9a90880a64U, 0x5cf2eea09a55067fU, 0xf42faa48c0ea481eU, 0xf13b94daf124da26U, 0x76c53d08d6b70858U, 0x54768c4b0c64ca6eU, 0xa9942f5dcf7dfd09U, 0xd3f93b35435d7c4cU, 0xc47bc5014a1a6dafU, 0x359ab6419ca1091bU, 0xc30163d203c94b62U, 0x79e0de63425dcf1dU, 0x985915fc12f542e4U, 0x3e6f5b7b17b2939dU, 0xa705992ceecf9c42U, 0x50c6ff782a838353U, 0xa4f8bf5635246428U, 0x871b7795e136be99U, 0x28e2557b59846e3fU, 0x331aeada2fe589cfU, 0x3ff0d2c85def7621U, 0x0fed077a756b53a9U, 0xd3e8495912c62894U, 0x64712dd7abbbd95cU, 0xbd8d794d96aacfb3U, 0xecf0d7a0fc5583a0U, 0xf41686c49db57244U, 0x311c2875c522ced5U, 0x7d633293366b828bU, 0xae5dff9c02033197U, 0xd9f57f830283fdfcU, 0xd072df63c324fd7bU, 0x4247cb9e59f71e6dU, 0x52d9be85f074e608U, 0x67902e276c921f8bU, 0x00ba1cd8a3db53b6U, 0x80e8a40eccd228a4U, 0x6122cd128006b2cdU, 0x796b805720085f81U, 0xcbe3303674053bb0U, 0xbedbfc4411068a9cU, 0xee92fb5515482d44U, 0x751bdd152d4d1c4aU, 0xd262d45a78a0635dU, 0x86fb897116c87c34U, 0xd45d35e6ae3d4da0U, 0x8974836059cca109U, 0x2bd1a438703fc94bU, 0x7b6306a34627ddcfU, 0x1a3bc84c17b1d542U, 0x20caba5f1d9e4a93U, 0x547eb47b7282ee9cU, 0xe99e619a4f23aa43U, 0x6405fa00e2ec94d4U, 0xde83bc408dd3dd04U, 0x9624ab50b148d445U, 0x3badd624dd9b0957U, 0xe54ca5d70a80e5d6U, 0x5e9fcf4ccd211f4cU, 0x7647c3200069671fU, 0x29ecd9f40041e073U, 0xf468107100525890U, 0x7182148d4066eeb4U, 0xc6f14cd848405530U, 0xb8ada00e5a506a7cU, 0xa6d90811f0e4851cU, 0x908f4a166d1da663U, 0x9a598e4e043287feU, 0x40eff1e1853f29fdU, 0xd12bee59e68ef47cU, 0x82bb74f8301958ceU, 0xe36a52363c1faf01U, 0xdc44e6c3cb279ac1U, 0x29ab103a5ef8c0b9U, 0x7415d448f6b6f0e7U, 0x111b495b3464ad21U, 0xcab10dd900beec34U, 0x3d5d514f40eea742U, 0x0cb4a5a3112a5112U, 0x47f0e785eaba72abU, 0x59ed216765690f56U, 0x306869c13ec3532cU, 0x1e414218c73a13fbU, 0xe5d1929ef90898faU, 0xdf45f746b74abf39U, 0x6b8bba8c328eb783U, 0x066ea92f3f326564U, 0xc80a537b0efefebdU, 0xbd06742ce95f5f36U, 0x2c48113823b73704U, 0xf75a15862ca504c5U, 0x9a984d73dbe722fbU, 0xc13e60d0d2e0ebbaU, 0x318df905079926a8U, 0xfdf17746497f7052U, 0xfeb6ea8bedefa633U, 0xfe64a52ee96b8fc0U, 0x3dfdce7aa3c673b0U, 0x06bea10ca65c084eU, 0x486e494fcff30a62U, 0x5a89dba3c3efccfaU, 0xf89629465a75e01cU, 0xf6bbb397f1135823U, 0x746aa07ded582e2cU, 0xa8c2a44eb4571cdcU, 0x92f34d62616ce413U, 0x77b020baf9c81d17U, 0x0ace1474dc1d122eU, 0x0d819992132456baU, 0x10e1fff697ed6c69U, 0xca8d3ffa1ef463c1U, 0xbd308ff8a6b17cb2U, 0xac7cb3f6d05ddbdeU, 0x6bcdf07a423aa96bU, 0x86c16c98d2c953c6U, 0xe871c7bf077ba8b7U, 0x11471cd764ad4972U, 0xd598e40d3dd89bcfU, 0x4aff1d108d4ec2c3U, 0xcedf722a585139baU, 0xc2974eb4ee658828U, 0x733d226229feea32U, 0x0806357d5a3f525fU, 0xca07c2dcb0cf26f7U, 0xfc89b393dd02f0b5U, 0xbbac2078d443ace2U, 0xd54b944b84aa4c0dU, 0x0a9e795e65d4df11U, 0x4d4617b5ff4a16d5U, 0x504bced1bf8e4e45U, 0xe45ec2862f71e1d6U, 0x5d767327bb4e5a4cU, 0x3a6a07f8d510f86fU, 0x890489f70a55368bU, 0x2b45ac74ccea842eU, 0x3b0b8bc90012929dU, 0x09ce6ebb40173744U, 0xcc420a6a101d0515U, 0x9fa946824a12232dU, 0x47939822dc96abf9U, 0x59787e2b93bc56f7U, 0x57eb4edb3c55b65aU, 0xede622920b6b23f1U, 0xe95fab368e45ecedU, 0x11dbcb0218ebb414U, 0xd652bdc29f26a119U, 0x4be76d3346f0495fU, 0x6f70a4400c562ddbU, 0xcb4ccd500f6bb952U, 0x7e2000a41346a7a7U, 0x8ed400668c0c28c8U, 0x728900802f0f32faU, 0x4f2b40a03ad2ffb9U, 0xe2f610c84987bfa8U, 0x0dd9ca7d2df4d7c9U, 0x91503d1c79720dbbU, 0x75a44c6397ce912aU, 0xc986afbe3ee11abaU, 0xfbe85badce996168U, 0xfae27299423fb9c3U, 0xdccd879fc967d41aU, 0x5400e987bbc1c920U, 0x290123e9aab23b68U, 0xf9a0b6720aaf6521U, 0xf808e40e8d5b3e69U, 0xb60b1d1230b20e04U, 0xb1c6f22b5e6f48c2U, 0x1e38aeb6360b1af3U, 0x25c6da63c38de1b0U, 0x579c487e5a38ad0eU, 0x2d835a9df0c6d851U, 0xf8e431456cf88e65U, 0x1b8e9ecb641b58ffU, 0xe272467e3d222f3fU, 0x5b0ed81dcc6abb0fU, 0x98e947129fc2b4e9U, 0x3f2398d747b36224U, 0x8eec7f0d19a03aadU, 0x1953cf68300424acU, 0x5fa8c3423c052dd7U, 0x3792f412cb06794dU, 0xe2bbd88bbee40bd0U, 0x5b6aceaeae9d0ec4U, 0xf245825a5a445275U, 0xeed6e2f0f0d56712U, 0x55464dd69685606bU, 0xaa97e14c3c26b886U, 0xd53dd99f4b3066a8U, 0xe546a8038efe4029U, 0xde98520472bdd033U, 0x963e66858f6d4440U, 0xdde7001379a44aa8U, 0x5560c018580d5d52U, 0xaab8f01e6e10b4a6U, 0xcab3961304ca70e8U, 0x3d607b97c5fd0d22U, 0x8cb89a7db77c506aU, 0x77f3608e92adb242U, 0x55f038b237591ed3U, 0x6b6c46dec52f6688U, 0x2323ac4b3b3da015U, 0xabec975e0a0d081aU, 0x96e7bd358c904a21U, 0x7e50d64177da2e54U, 0xdde50bd1d5d0b9e9U, 0x955e4ec64b44e864U, 0xbd5af13bef0b113eU, 0xecb1ad8aeacdd58eU, 0x67de18eda5814af2U, 0x80eacf948770ced7U, 0xa1258379a94d028dU, 0x096ee45813a04330U, 0x8bca9d6e188853fcU, 0x775ea264cf55347dU, 0x95364afe032a819dU, 0x3a83ddbd83f52204U, 0xc4926a9672793542U, 0x75b7053c0f178293U, 0x5324c68b12dd6338U, 0xd3f6fc16ebca5e03U, 0x88f4bb1ca6bcf584U, 0x2b31e9e3d06c32e5U, 0x3aff322e62439fcfU, 0x09befeb9fad487c2U, 0x4c2ebe687989a9b3U, 0x0f9d37014bf60a10U, 0x538484c19ef38c94U, 0x2865a5f206b06fb9U, 0xf93f87b7442e45d3U, 0xf78f69a51539d748U, 0xb573440e5a884d1bU, 0x31680a88f8953030U, 0xfdc20d2b36ba7c3dU, 0x3d32907604691b4cU, 0xa63f9a49c2c1b10fU, 0x0fcf80dc33721d53U, 0xd3c36113404ea4a8U, 0x645a1cac083126e9U, 0x3d70a3d70a3d70a3U, 0xccccccccccccccccU, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x0000000000000000U, 0x4000000000000000U, 0x5000000000000000U, 0xa400000000000000U, 0x4d00000000000000U, 0xf020000000000000U, 0x6c28000000000000U, 0xc732000000000000U, 0x3c7f400000000000U, 0x4b9f100000000000U, 0x1e86d40000000000U, 0x1314448000000000U, 0x17d955a000000000U, 0x5dcfab0800000000U, 0x5aa1cae500000000U, 0xf14a3d9e40000000U, 0x6d9ccd05d0000000U, 0xe4820023a2000000U, 0xdda2802c8a800000U, 0xd50b2037ad200000U, 0x4526f422cc340000U, 0x9670b12b7f410000U, 0x3c0cdd765f114000U, 0xa5880a69fb6ac800U, 0x8eea0d047a457a00U, 0x72a4904598d6d880U, 0x47a6da2b7f864750U, 0x999090b65f67d924U, 0xfff4b4e3f741cf6dU, 0xbff8f10e7a8921a4U, 0xaff72d52192b6a0dU, 0x9bf4f8a69f764490U, 0x02f236d04753d5b4U, 0x01d762422c946590U, 0x424d3ad2b7b97ef5U, 0xd2e0898765a7deb2U, 0x63cc55f49f88eb2fU, 0x3cbf6b71c76b25fbU, 0x8bef464e3945ef7aU, 0x97758bf0e3cbb5acU, 0x3d52eeed1cbea317U, 0x4ca7aaa863ee4bddU, 0x8fe8caa93e74ef6aU, 0xb3e2fd538e122b44U, 0x60dbbca87196b616U, 0xbc8955e946fe31cdU, 0x6babab6398bdbe41U, 0xc696963c7eed2dd1U, 0xfc1e1de5cf543ca2U, 0x3b25a55f43294bcbU, 0x49ef0eb713f39ebeU, 0x6e3569326c784337U, 0x49c2c37f07965404U, 0xdc33745ec97be906U, 0x69a028bb3ded71a3U, 0xc40832ea0d68ce0cU, 0xf50a3fa490c30190U, 0x792667c6da79e0faU, 0x577001b891185938U, 0xed4c0226b55e6f86U, 0x544f8158315b05b4U, 0x696361ae3db1c721U, 0x03bc3a19cd1e38e9U, 0x04ab48a04065c723U, 0x62eb0d64283f9c76U, 0x3ba5d0bd324f8394U, 0xca8f44ec7ee36479U, 0x7e998b13cf4e1ecbU, 0x9e3fedd8c321a67eU, 0xc5cfe94ef3ea101eU, 0xbba1f1d158724a12U, 0x2a8a6e45ae8edc97U, 0xf52d09d71a3293bdU, 0x593c2626705f9c56U, 0x6f8b2fb00c77836cU, 0x0b6dfb9c0f956447U, 0x4724bd4189bd5eacU, 0x58edec91ec2cb657U, 0x2f2967b66737e3edU, 0xbd79e0d20082ee74U, 0xecd8590680a3aa11U, 0xe80e6f4820cc9495U, 0x3109058d147fdcddU, 0xbd4b46f0599fd415U, 0x6c9e18ac7007c91aU, 0x03e2cf6bc604ddb0U, 0x84db8346b786151cU, 0xe612641865679a63U, 0x4fcb7e8f3f60c07eU, 0xe3be5e330f38f09dU, 0x5cadf5bfd3072cc5U, 0x73d9732fc7c8f7f6U, 0x2867e7fddcdd9afaU, 0xb281e1fd541501b8U, 0x1f225a7ca91a4226U, 0x3375788de9b06958U, 0x0052d6b1641c83aeU, 0xc0678c5dbd23a49aU, 0xf840b7ba963646e0U, 0xb650e5a93bc3d898U, 0xa3e51f138ab4cebeU, 0xc66f336c36b10137U, 0xb80b0047445d4184U, 0xa60dc059157491e5U, 0x87c89837ad68db2fU, 0x29babe4598c311fbU, 0xf4296dd6fef3d67aU, 0x1899e4a65f58660cU, 0x5ec05dcff72e7f8fU, 0x76707543f4fa1f73U, 0x6a06494a791c53a8U, 0x0487db9d17636892U, 0x45a9d2845d3c42b6U, 0x0b8a2392ba45a9b2U, 0x8e6cac7768d7141eU, 0x3207d795430cd926U, 0x7f44e6bd49e807b8U, 0x5f16206c9c6209a6U, 0x36dba887c37a8c0fU, 0xc2494954da2c9789U, 0xf2db9baa10b7bd6cU, 0x6f92829494e5acc7U, 0xcb772339ba1f17f9U, 0xff2a760414536efbU, 0xfef5138519684abaU, 0x7eb258665fc25d69U, 0xef2f773ffbd97a61U, 0xaafb550ffacfd8faU, 0x95ba2a53f983cf38U, 0xdd945a747bf26183U, 0x94f971119aeef9e4U, 0x7a37cd5601aab85dU, 0xac62e055c10ab33aU, 0x577b986b314d6009U, 0xed5a7e85fda0b80bU, 0x14588f13be847307U, 0x596eb2d8ae258fc8U, 0x6fca5f8ed9aef3bbU, 0x25de7bb9480d5854U, 0xaf561aa79a10ae6aU, 0x1b2ba1518094da04U, 0x90fb44d2f05d0842U, 0x353a1607ac744a53U, 0x42889b8997915ce8U, 0x69956135febada11U, 0x43fab9837e699095U, 0x94f967e45e03f4bbU, 0x1d1be0eebac278f5U, 0x6462d92a69731732U, 0x7d7b8f7503cfdcfeU, 0x5cda735244c3d43eU, 0x3a0888136afa64a7U, 0x088aaa1845b8fdd0U, 0x8aad549e57273d45U, 0x36ac54e2f678864bU, 0x84576a1bb416a7ddU, 0x656d44a2a11c51d5U, 0x9f644ae5a4b1b325U, 0x873d5d9f0dde1feeU, 0xa90cb506d155a7eaU, 0x09a7f12442d588f2U, 0x0c11ed6d538aeb2fU, 0x8f1668c8a86da5faU, 0xf96e017d694487bcU, 0x37c981dcc395a9acU, 0x85bbe253f47b1417U, 0x93956d7478ccec8eU, 0x387ac8d1970027b2U, 0x06997b05fcc0319eU, 0x441fece3bdf81f03U, 0xd527e81cad7626c3U, 0x8a71e223d8d3b074U, 0xf6872d5667844e49U, 0xb428f8ac016561dbU, 0xe13336d701beba52U, 0xecc0024661173473U, 0x27f002d7f95d0190U, 0x31ec038df7b441f4U, 0x7e67047175a15271U, 0x0f0062c6e984d386U, 0x52c07b78a3e60868U, 0xa7709a56ccdf8a82U, 0x88a66076400bb691U, 0x6acff893d00ea435U, 0x0583f6b8c4124d43U, 0xc3727a337a8b704aU, 0x744f18c0592e4c5cU, 0x1162def06f79df73U, 0x8addcb5645ac2ba8U, 0x6d953e2bd7173692U, 0xc8fa8db6ccdd0437U, 0x1d9c9892400a22a2U, 0x2503beb6d00cab4bU, 0x2e44ae64840fd61dU, 0x5ceaecfed289e5d2U, 0x7425a83e872c5f47U, 0xd12f124e28f77719U, 0x82bd6b70d99aaa6fU, 0x636cc64d1001550bU, 0x3c47f7e05401aa4eU, 0x65acfaec34810a71U, 0x7f1839a741a14d0dU, 0x1ede48111209a050U, 0x934aed0aab460432U, 0xf81da84d5617853fU, 0x36251260ab9d668eU, 0xc1d72b7c6b426019U, 0xb24cf65b8612f81fU, 0xdee033f26797b627U, 0x169840ef017da3b1U, 0x8e1f289560ee864eU, 0xf1a6f2bab92a27e2U, 0xae10af696774b1dbU, 0xacca6da1e0a8ef29U, 0x17fd090a58d32af3U, 0xddfc4b4cef07f5b0U, 0x4abdaf101564f98eU, 0x9d6d1ad41abe37f1U, 0x84c86189216dc5edU, 0x32fd3cf5b4e49bb4U, 0x3fbc8c33221dc2a1U, 0x0fabaf3feaa5334aU, 0x29cb4d87f2a7400eU, 0x743e20e9ef511012U, 0x914da9246b255416U, 0x1ad089b6c2f7548eU, 0xa184ac2473b529b1U, 0xc9e5d72d90a2741eU, 0x7e2fa67c7a658892U, 0xddbb901b98feeab7U, 0x552a74227f3ea565U, 0xd53a88958f87275fU, 0x8a892abaf368f137U, 0x2d2b7569b0432d85U, 0x9c3b29620e29fc73U, 0x8349f3ba91b47b8fU, 0x241c70a936219a73U, 0xed238cd383aa0110U, 0xf4363804324a40aaU, 0xb143c6053edcd0d5U, 0xdd94b7868e94050aU, 0xca7cf2b4191c8326U, 0xfd1c2f611f63a3f0U, 0xbc633b39673c8cecU, 0xd5be0503e085d813U, 0x4b2d8644d8a74e18U, 0xddf8e7d60ed1219eU, 0xcabb90e5c942b503U, 0x3d6a751f3b936243U, 0x0cc512670a783ad4U, 0x27fb2b80668b24c5U, 0xb1f9f660802dedf6U, 0x5e7873f8a0396973U, 0xdb0b487b6423e1e8U, 0x91ce1a9a3d2cda62U, 0x7641a140cc7810fbU, 0xa9e904c87fcb0a9dU, 0x546345fa9fbdcd44U, 0xa97c177947ad4095U, 0x49ed8eabcccc485dU, 0x5c68f256bfff5a74U, 0x73832eec6fff3111U, 0xc831fd53c5ff7eabU, 0xba3e7ca8b77f5e55U, 0x28ce1bd2e55f35ebU, 0x7980d163cf5b81b3U, 0xd7e105bcc332621fU, 0x8dd9472bf3fefaa7U, 0xb14f98f6f0feb951U, 0x6ed1bf9a569f33d3U, 0x0a862f80ec4700c8U, 0xcd27bb612758c0faU, 0x8038d51cb897789cU, 0xe0470a63e6bd56c3U, 0x1858ccfce06cac74U, 0x0f37801e0c43ebc8U, 0xd30560258f54e6baU, 0x47c6b82ef32a2069U, 0x4cdc331d57fa5441U, 0xe0133fe4adf8e952U, 0x58180fddd97723a6U, 0x570f09eaa7ea7648U, }; } ABSL_NAMESPACE_END }
#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<double>(input_gen, expected_gen, -1074, 1023); } TEST(FromChars, HexdecimalFloatLimits) { auto input_gen = [](int index) { return absl::StrCat("0x1.0p", index); }; auto expected_gen = [](int index) { return std::ldexp(1.0f, index); }; TestOverflowAndUnderflow<float>(input_gen, expected_gen, -149, 127); } TEST(FromChars, DecimalDoubleLimits) { auto input_gen = [](int index) { return absl::StrCat("1.0e", index); }; auto expected_gen = [](int index) { return Pow10(index); }; TestOverflowAndUnderflow<double>(input_gen, expected_gen, -323, 308); } TEST(FromChars, DecimalFloatLimits) { auto input_gen = [](int index) { return absl::StrCat("1.0e", index); }; auto expected_gen = [](int index) { return Pow10(index); }; TestOverflowAndUnderflow<float>(input_gen, expected_gen, -45, 38); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/charconv.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/charconv_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ed71d17b-19eb-4298-88f0-ac7a9381d1f5
cpp
abseil/abseil-cpp
str_split
absl/strings/str_split.cc
absl/strings/str_split_test.cc
#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_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER) constexpr size_t kSize = (uint32_t{1} << 26) + 1; #else constexpr size_t kSize = (uint32_t{1} << 31) + 1; #endif if (sizeof(size_t) > 4) { std::string s(kSize, 'x'); s.back() = '-'; std::vector<absl::string_view> v = absl::StrSplit(s, '-'); EXPECT_EQ(2, v.size()); EXPECT_EQ('x', v[0][0]); EXPECT_EQ('x', v[0][1]); EXPECT_EQ('x', v[0][3]); EXPECT_EQ("", v[1]); } } TEST(SplitInternalTest, TypeTraits) { EXPECT_FALSE(absl::strings_internal::HasMappedType<int>::value); EXPECT_TRUE( (absl::strings_internal::HasMappedType<std::map<int, int>>::value)); EXPECT_FALSE(absl::strings_internal::HasValueType<int>::value); EXPECT_TRUE( (absl::strings_internal::HasValueType<std::map<int, int>>::value)); EXPECT_FALSE(absl::strings_internal::HasConstIterator<int>::value); EXPECT_TRUE( (absl::strings_internal::HasConstIterator<std::map<int, int>>::value)); EXPECT_FALSE(absl::strings_internal::IsInitializerList<int>::value); EXPECT_TRUE((absl::strings_internal::IsInitializerList< std::initializer_list<int>>::value)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_split.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_split_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
95881b06-48de-4930-9377-92d811d54452
cpp
abseil/abseil-cpp
substitute
absl/strings/substitute.cc
absl/strings/substitute_test.cc
#include "absl/strings/substitute.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <limits> #include <string> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/nullability.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/internal/resize_uninitialized.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace substitute_internal { void SubstituteAndAppendArray( absl::Nonnull<std::string*> output, absl::string_view format, absl::Nullable<const absl::string_view*> args_array, size_t num_args) { size_t size = 0; for (size_t i = 0; i < format.size(); i++) { if (format[i] == '$') { if (i + 1 >= format.size()) { #ifndef NDEBUG ABSL_RAW_LOG(FATAL, "Invalid absl::Substitute() format string: \"%s\".", absl::CEscape(format).c_str()); #endif return; } else if (absl::ascii_isdigit( static_cast<unsigned char>(format[i + 1]))) { int index = format[i + 1] - '0'; if (static_cast<size_t>(index) >= num_args) { #ifndef NDEBUG ABSL_RAW_LOG( FATAL, "Invalid absl::Substitute() format string: asked for \"$" "%d\", but only %d args were given. Full format string was: " "\"%s\".", index, static_cast<int>(num_args), absl::CEscape(format).c_str()); #endif return; } size += args_array[index].size(); ++i; } else if (format[i + 1] == '$') { ++size; ++i; } else { #ifndef NDEBUG ABSL_RAW_LOG(FATAL, "Invalid absl::Substitute() format string: \"%s\".", absl::CEscape(format).c_str()); #endif return; } } else { ++size; } } if (size == 0) return; size_t original_size = output->size(); ABSL_INTERNAL_CHECK( size <= std::numeric_limits<size_t>::max() - original_size, "size_t overflow"); strings_internal::STLStringResizeUninitializedAmortized(output, original_size + size); char* target = &(*output)[original_size]; for (size_t i = 0; i < format.size(); i++) { if (format[i] == '$') { if (absl::ascii_isdigit(static_cast<unsigned char>(format[i + 1]))) { const absl::string_view src = args_array[format[i + 1] - '0']; target = std::copy(src.begin(), src.end(), target); ++i; } else if (format[i + 1] == '$') { *target++ = '$'; ++i; } } else { *target++ = format[i]; } } assert(target == output->data() + output->size()); } Arg::Arg(absl::Nullable<const void*> value) { static_assert(sizeof(scratch_) >= sizeof(value) * 2 + 2, "fix sizeof(scratch_)"); if (value == nullptr) { piece_ = "NULL"; } else { char* ptr = scratch_ + sizeof(scratch_); uintptr_t num = reinterpret_cast<uintptr_t>(value); do { *--ptr = absl::numbers_internal::kHexChar[num & 0xf]; num >>= 4; } while (num != 0); *--ptr = 'x'; *--ptr = '0'; piece_ = absl::string_view( ptr, static_cast<size_t>(scratch_ + sizeof(scratch_) - ptr)); } } Arg::Arg(Hex hex) { char* const end = &scratch_[numbers_internal::kFastToBufferSize]; char* writer = end; uint64_t value = hex.value; do { *--writer = absl::numbers_internal::kHexChar[value & 0xF]; value >>= 4; } while (value != 0); char* beg; if (end - writer < hex.width) { beg = end - hex.width; std::fill_n(beg, writer - beg, hex.fill); } else { beg = writer; } piece_ = absl::string_view(beg, static_cast<size_t>(end - beg)); } Arg::Arg(Dec dec) { assert(dec.width <= numbers_internal::kFastToBufferSize); char* const end = &scratch_[numbers_internal::kFastToBufferSize]; char* const minfill = end - dec.width; char* writer = end; uint64_t value = dec.value; bool neg = dec.neg; while (value > 9) { *--writer = '0' + (value % 10); value /= 10; } *--writer = '0' + static_cast<char>(value); if (neg) *--writer = '-'; ptrdiff_t fillers = writer - minfill; if (fillers > 0) { bool add_sign_again = false; if (neg && dec.fill == '0') { ++writer; add_sign_again = true; } writer -= fillers; std::fill_n(writer, fillers, dec.fill); if (add_sign_again) *--writer = '-'; } piece_ = absl::string_view(writer, static_cast<size_t>(end - writer)); } } ABSL_NAMESPACE_END }
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/substitute.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/substitute_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
6a99b84b-fcf5-4ca5-8e15-10a72bf74889
cpp
abseil/abseil-cpp
escaping
absl/strings/internal/escaping.cc
absl/strings/escaping_test.cc
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/escaping.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/escaping_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
c8984e03-8b10-44e4-81f8-3b0019417a42
cpp
abseil/abseil-cpp
str_replace
absl/strings/str_replace.cc
absl/strings/str_replace_test.cc
#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"); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_replace.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_replace_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
643b14da-f17b-43cf-9351-78a2030c525c
cpp
abseil/abseil-cpp
cord_rep_crc
absl/strings/internal/cord_rep_crc.cc
absl/strings/internal/cord_rep_crc_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_crc.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_crc_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e01ac670-7a1a-4d0b-8ef1-61fc5f1f5991
cpp
abseil/abseil-cpp
charconv_bigint
absl/strings/internal/charconv_bigint.cc
absl/strings/internal/charconv_bigint_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/charconv_bigint.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/charconv_bigint_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
857b14e6-046b-4b50-97f4-1f1c2b59df7d
cpp
abseil/abseil-cpp
cord_rep_btree_reader
absl/strings/internal/cord_rep_btree_reader.cc
absl/strings/internal/cord_rep_btree_reader_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_btree_reader.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_btree_reader_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
b306449e-1028-4a65-a9cd-5129cd3fe38b
cpp
abseil/abseil-cpp
cordz_info
absl/strings/internal/cordz_info.cc
absl/strings/internal/cordz_info_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_info.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_info_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
545c781b-a6c6-4ce8-b2f2-8f8bc8e219d1
cpp
abseil/abseil-cpp
cordz_sample_token
absl/strings/internal/cordz_sample_token.cc
absl/strings/internal/cordz_sample_token_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_sample_token.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_sample_token_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
b741e8e8-2745-4bf2-ba11-cb07d8f3a0b0
cpp
abseil/abseil-cpp
charconv_parse
absl/strings/internal/charconv_parse.cc
absl/strings/internal/charconv_parse_test.cc
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/charconv_parse.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/charconv_parse_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
c6bacac8-24d4-4a31-850e-7da0d49e71ea
cpp
abseil/abseil-cpp
cordz_handle
absl/strings/internal/cordz_handle.cc
absl/strings/internal/cordz_handle_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_handle.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_handle_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
22062a52-3ab1-495e-b0d6-3265e90401e0
cpp
abseil/abseil-cpp
memutil
absl/strings/internal/memutil.cc
absl/strings/internal/memutil_test.cc
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/memutil.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/memutil_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
681222d2-ea86-4164-a2f2-f032ed5e79c8
cpp
abseil/abseil-cpp
ostringstream
absl/strings/internal/ostringstream.cc
absl/strings/internal/ostringstream_test.cc
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/ostringstream.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/ostringstream_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
65b3e072-6b98-4c67-93c2-83f00a50a655
cpp
abseil/abseil-cpp
pow10_helper
absl/strings/internal/pow10_helper.cc
absl/strings/internal/pow10_helper_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/pow10_helper.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/pow10_helper_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
9a59765c-2c63-495e-b33c-60154ba0061c
cpp
abseil/abseil-cpp
utf8
absl/strings/internal/utf8.cc
absl/strings/internal/utf8_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/utf8.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/utf8_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ebea579e-d2e7-430c-8d2e-95b124dbf235
cpp
abseil/abseil-cpp
damerau_levenshtein_distance
absl/strings/internal/damerau_levenshtein_distance.cc
absl/strings/internal/damerau_levenshtein_distance_test.cc
#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}); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/damerau_levenshtein_distance.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/damerau_levenshtein_distance_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
45c6fd12-caf7-45a0-a1d7-30b319f493de
cpp
abseil/abseil-cpp
cordz_functions
absl/strings/internal/cordz_functions.cc
absl/strings/internal/cordz_functions_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_functions.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_functions_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
afbf6f4d-13ff-4467-a905-6b6f60822eb7
cpp
abseil/abseil-cpp
cord_rep_btree_navigator
absl/strings/internal/cord_rep_btree_navigator.cc
absl/strings/internal/cord_rep_btree_navigator_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_btree_navigator.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_btree_navigator_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ae58849b-b731-44fd-832e-ff17424f19f3
cpp
abseil/abseil-cpp
cord_rep_btree
absl/strings/internal/cord_rep_btree.cc
absl/strings/internal/cord_rep_btree_test.cc
#include "absl/strings/internal/cord_rep_btree.h" #include <atomic> #include <cassert> #include <cstdint> #include <iostream> #include <ostream> #include <string> #include "absl/base/attributes.h" #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_consume.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr size_t CordRepBtree::kMaxCapacity; #endif namespace { using NodeStack = CordRepBtree * [CordRepBtree::kMaxDepth]; using EdgeType = CordRepBtree::EdgeType; using OpResult = CordRepBtree::OpResult; using CopyResult = CordRepBtree::CopyResult; constexpr auto kFront = CordRepBtree::kFront; constexpr auto kBack = CordRepBtree::kBack; ABSL_CONST_INIT std::atomic<bool> cord_btree_exhaustive_validation(false); void DumpAll(const CordRep* rep, bool include_contents, std::ostream& stream, size_t depth = 0) { assert(depth <= CordRepBtree::kMaxDepth + 2); std::string sharing = const_cast<CordRep*>(rep)->refcount.IsOne() ? std::string("Private") : absl::StrCat("Shared(", rep->refcount.Get(), ")"); std::string sptr = absl::StrCat("0x", absl::Hex(rep)); auto maybe_dump_data = [&stream, include_contents](const CordRep* r) { if (include_contents) { constexpr size_t kMaxDataLength = 60; stream << ", data = \"" << EdgeData(r).substr(0, kMaxDataLength) << (r->length > kMaxDataLength ? "\"..." : "\""); } stream << '\n'; }; stream << std::string(depth * 2, ' ') << sharing << " (" << sptr << ") "; if (rep->IsBtree()) { const CordRepBtree* node = rep->btree(); std::string label = node->height() ? absl::StrCat("Node(", node->height(), ")") : "Leaf"; stream << label << ", len = " << node->length << ", begin = " << node->begin() << ", end = " << node->end() << "\n"; for (CordRep* edge : node->Edges()) { DumpAll(edge, include_contents, stream, depth + 1); } } else if (rep->tag == SUBSTRING) { const CordRepSubstring* substring = rep->substring(); stream << "Substring, len = " << rep->length << ", start = " << substring->start; maybe_dump_data(rep); DumpAll(substring->child, include_contents, stream, depth + 1); } else if (rep->tag >= FLAT) { stream << "Flat, len = " << rep->length << ", cap = " << rep->flat()->Capacity(); maybe_dump_data(rep); } else if (rep->tag == EXTERNAL) { stream << "Extn, len = " << rep->length; maybe_dump_data(rep); } } CordRepSubstring* CreateSubstring(CordRep* rep, size_t offset, size_t n) { assert(n != 0); assert(offset + n <= rep->length); assert(offset != 0 || n != rep->length); if (rep->tag == SUBSTRING) { CordRepSubstring* substring = rep->substring(); offset += substring->start; rep = CordRep::Ref(substring->child); CordRep::Unref(substring); } assert(rep->IsExternal() || rep->IsFlat()); CordRepSubstring* substring = new CordRepSubstring(); substring->length = n; substring->tag = SUBSTRING; substring->start = offset; substring->child = rep; return substring; } inline CordRep* MakeSubstring(CordRep* rep, size_t offset, size_t n) { if (n == rep->length) return rep; if (n == 0) return CordRep::Unref(rep), nullptr; return CreateSubstring(rep, offset, n); } inline CordRep* MakeSubstring(CordRep* rep, size_t offset) { if (offset == 0) return rep; return CreateSubstring(rep, offset, rep->length - offset); } CordRep* ResizeEdge(CordRep* edge, size_t length, bool is_mutable) { assert(length > 0); assert(length <= edge->length); assert(IsDataEdge(edge)); if (length >= edge->length) return edge; if (is_mutable && (edge->tag >= FLAT || edge->tag == SUBSTRING)) { edge->length = length; return edge; } return CreateSubstring(edge, 0, length); } template <EdgeType edge_type> inline absl::string_view Consume(absl::string_view s, size_t n) { return edge_type == kBack ? s.substr(n) : s.substr(0, s.size() - n); } template <EdgeType edge_type> inline absl::string_view Consume(char* dst, absl::string_view s, size_t n) { if (edge_type == kBack) { memcpy(dst, s.data(), n); return s.substr(n); } else { const size_t offset = s.size() - n; memcpy(dst, s.data() + offset, n); return s.substr(0, offset); } } template <typename R, typename Fn> inline void FastUnref(R* r, Fn&& fn) { if (r->refcount.IsOne()) { fn(r); } else if (!r->refcount.DecrementExpectHighRefcount()) { fn(r); } } void DeleteSubstring(CordRepSubstring* substring) { CordRep* rep = substring->child; if (!rep->refcount.Decrement()) { if (rep->tag >= FLAT) { CordRepFlat::Delete(rep->flat()); } else { assert(rep->tag == EXTERNAL); CordRepExternal::Delete(rep->external()); } } delete substring; } void DeleteLeafEdge(CordRep* rep) { assert(IsDataEdge(rep)); if (rep->tag >= FLAT) { CordRepFlat::Delete(rep->flat()); } else if (rep->tag == EXTERNAL) { CordRepExternal::Delete(rep->external()); } else { DeleteSubstring(rep->substring()); } } template <EdgeType edge_type> struct StackOperations { inline bool owned(int depth) const { return depth < share_depth; } inline CordRepBtree* node(int depth) const { return stack[depth]; } inline CordRepBtree* BuildStack(CordRepBtree* tree, int depth) { assert(depth <= tree->height()); int current_depth = 0; while (current_depth < depth && tree->refcount.IsOne()) { stack[current_depth++] = tree; tree = tree->Edge(edge_type)->btree(); } share_depth = current_depth + (tree->refcount.IsOne() ? 1 : 0); while (current_depth < depth) { stack[current_depth++] = tree; tree = tree->Edge(edge_type)->btree(); } return tree; } inline void BuildOwnedStack(CordRepBtree* tree, int height) { assert(height <= CordRepBtree::kMaxHeight); int depth = 0; while (depth < height) { assert(tree->refcount.IsOne()); stack[depth++] = tree; tree = tree->Edge(edge_type)->btree(); } assert(tree->refcount.IsOne()); share_depth = depth + 1; } static inline CordRepBtree* Finalize(CordRepBtree* tree, OpResult result) { switch (result.action) { case CordRepBtree::kPopped: tree = edge_type == kBack ? CordRepBtree::New(tree, result.tree) : CordRepBtree::New(result.tree, tree); if (ABSL_PREDICT_FALSE(tree->height() > CordRepBtree::kMaxHeight)) { tree = CordRepBtree::Rebuild(tree); ABSL_RAW_CHECK(tree->height() <= CordRepBtree::kMaxHeight, "Max height exceeded"); } return tree; case CordRepBtree::kCopied: CordRep::Unref(tree); ABSL_FALLTHROUGH_INTENDED; case CordRepBtree::kSelf: return result.tree; } ABSL_UNREACHABLE(); return result.tree; } template <bool propagate = false> inline CordRepBtree* Unwind(CordRepBtree* tree, int depth, size_t length, OpResult result) { if (depth != 0) { do { CordRepBtree* node = stack[--depth]; const bool owned = depth < share_depth; switch (result.action) { case CordRepBtree::kPopped: assert(!propagate); result = node->AddEdge<edge_type>(owned, result.tree, length); break; case CordRepBtree::kCopied: result = node->SetEdge<edge_type>(owned, result.tree, length); if (propagate) stack[depth] = result.tree; break; case CordRepBtree::kSelf: node->length += length; while (depth > 0) { node = stack[--depth]; node->length += length; } return node; } } while (depth > 0); } return Finalize(tree, result); } inline CordRepBtree* Propagate(CordRepBtree* tree, int depth, size_t length, OpResult result) { return Unwind<true>(tree, depth, length, result); } int share_depth; NodeStack stack; }; } void SetCordBtreeExhaustiveValidation(bool do_exaustive_validation) { cord_btree_exhaustive_validation.store(do_exaustive_validation, std::memory_order_relaxed); } bool IsCordBtreeExhaustiveValidationEnabled() { return cord_btree_exhaustive_validation.load(std::memory_order_relaxed); } void CordRepBtree::Dump(const CordRep* rep, absl::string_view label, bool include_contents, std::ostream& stream) { stream << "===================================\n"; if (!label.empty()) { stream << label << '\n'; stream << "-----------------------------------\n"; } if (rep) { DumpAll(rep, include_contents, stream); } else { stream << "NULL\n"; } } void CordRepBtree::Dump(const CordRep* rep, absl::string_view label, std::ostream& stream) { Dump(rep, label, false, stream); } void CordRepBtree::Dump(const CordRep* rep, std::ostream& stream) { Dump(rep, absl::string_view(), false, stream); } template <size_t size> static void DestroyTree(CordRepBtree* tree) { for (CordRep* node : tree->Edges()) { if (node->refcount.Decrement()) continue; for (CordRep* edge : node->btree()->Edges()) { if (edge->refcount.Decrement()) continue; if (size == 1) { DeleteLeafEdge(edge); } else { CordRepBtree::Destroy(edge->btree()); } } CordRepBtree::Delete(node->btree()); } CordRepBtree::Delete(tree); } void CordRepBtree::Destroy(CordRepBtree* tree) { switch (tree->height()) { case 0: for (CordRep* edge : tree->Edges()) { if (!edge->refcount.Decrement()) { DeleteLeafEdge(edge); } } return CordRepBtree::Delete(tree); case 1: return DestroyTree<1>(tree); default: return DestroyTree<2>(tree); } } bool CordRepBtree::IsValid(const CordRepBtree* tree, bool shallow) { #define NODE_CHECK_VALID(x) \ if (!(x)) { \ ABSL_RAW_LOG(ERROR, "CordRepBtree::CheckValid() FAILED: %s", #x); \ return false; \ } #define NODE_CHECK_EQ(x, y) \ if ((x) != (y)) { \ ABSL_RAW_LOG(ERROR, \ "CordRepBtree::CheckValid() FAILED: %s != %s (%s vs %s)", #x, \ #y, absl::StrCat(x).c_str(), absl::StrCat(y).c_str()); \ return false; \ } NODE_CHECK_VALID(tree != nullptr); NODE_CHECK_VALID(tree->IsBtree()); NODE_CHECK_VALID(tree->height() <= kMaxHeight); NODE_CHECK_VALID(tree->begin() < tree->capacity()); NODE_CHECK_VALID(tree->end() <= tree->capacity()); NODE_CHECK_VALID(tree->begin() <= tree->end()); size_t child_length = 0; for (CordRep* edge : tree->Edges()) { NODE_CHECK_VALID(edge != nullptr); if (tree->height() > 0) { NODE_CHECK_VALID(edge->IsBtree()); NODE_CHECK_VALID(edge->btree()->height() == tree->height() - 1); } else { NODE_CHECK_VALID(IsDataEdge(edge)); } child_length += edge->length; } NODE_CHECK_EQ(child_length, tree->length); if ((!shallow || IsCordBtreeExhaustiveValidationEnabled()) && tree->height() > 0) { for (CordRep* edge : tree->Edges()) { if (!IsValid(edge->btree(), shallow)) return false; } } return true; #undef NODE_CHECK_VALID #undef NODE_CHECK_EQ } #ifndef NDEBUG CordRepBtree* CordRepBtree::AssertValid(CordRepBtree* tree, bool shallow) { if (!IsValid(tree, shallow)) { Dump(tree, "CordRepBtree validation failed:", false, std::cout); ABSL_RAW_LOG(FATAL, "CordRepBtree::CheckValid() FAILED"); } return tree; } const CordRepBtree* CordRepBtree::AssertValid(const CordRepBtree* tree, bool shallow) { if (!IsValid(tree, shallow)) { Dump(tree, "CordRepBtree validation failed:", false, std::cout); ABSL_RAW_LOG(FATAL, "CordRepBtree::CheckValid() FAILED"); } return tree; } #endif template <EdgeType edge_type> inline OpResult CordRepBtree::AddEdge(bool owned, CordRep* edge, size_t delta) { if (size() >= kMaxCapacity) return {New(edge), kPopped}; OpResult result = ToOpResult(owned); result.tree->Add<edge_type>(edge); result.tree->length += delta; return result; } template <EdgeType edge_type> OpResult CordRepBtree::SetEdge(bool owned, CordRep* edge, size_t delta) { OpResult result; const size_t idx = index(edge_type); if (owned) { result = {this, kSelf}; CordRep::Unref(edges_[idx]); } else { result = {CopyRaw(length), kCopied}; constexpr int shift = edge_type == kFront ? 1 : 0; for (CordRep* r : Edges(begin() + shift, back() + shift)) { CordRep::Ref(r); } } result.tree->edges_[idx] = edge; result.tree->length += delta; return result; } template <EdgeType edge_type> CordRepBtree* CordRepBtree::AddCordRep(CordRepBtree* tree, CordRep* rep) { const int depth = tree->height(); const size_t length = rep->length; StackOperations<edge_type> ops; CordRepBtree* leaf = ops.BuildStack(tree, depth); const OpResult result = leaf->AddEdge<edge_type>(ops.owned(depth), rep, length); return ops.Unwind(tree, depth, length, result); } template <> CordRepBtree* CordRepBtree::NewLeaf<kBack>(absl::string_view data, size_t extra) { CordRepBtree* leaf = CordRepBtree::New(0); size_t length = 0; size_t end = 0; const size_t cap = leaf->capacity(); while (!data.empty() && end != cap) { auto* flat = CordRepFlat::New(data.length() + extra); flat->length = (std::min)(data.length(), flat->Capacity()); length += flat->length; leaf->edges_[end++] = flat; data = Consume<kBack>(flat->Data(), data, flat->length); } leaf->length = length; leaf->set_end(end); return leaf; } template <> CordRepBtree* CordRepBtree::NewLeaf<kFront>(absl::string_view data, size_t extra) { CordRepBtree* leaf = CordRepBtree::New(0); size_t length = 0; size_t begin = leaf->capacity(); leaf->set_end(leaf->capacity()); while (!data.empty() && begin != 0) { auto* flat = CordRepFlat::New(data.length() + extra); flat->length = (std::min)(data.length(), flat->Capacity()); length += flat->length; leaf->edges_[--begin] = flat; data = Consume<kFront>(flat->Data(), data, flat->length); } leaf->length = length; leaf->set_begin(begin); return leaf; } template <> absl::string_view CordRepBtree::AddData<kBack>(absl::string_view data, size_t extra) { assert(!data.empty()); assert(size() < capacity()); AlignBegin(); const size_t cap = capacity(); do { CordRepFlat* flat = CordRepFlat::New(data.length() + extra); const size_t n = (std::min)(data.length(), flat->Capacity()); flat->length = n; edges_[fetch_add_end(1)] = flat; data = Consume<kBack>(flat->Data(), data, n); } while (!data.empty() && end() != cap); return data; } template <> absl::string_view CordRepBtree::AddData<kFront>(absl::string_view data, size_t extra) { assert(!data.empty()); assert(size() < capacity()); AlignEnd(); do { CordRepFlat* flat = CordRepFlat::New(data.length() + extra); const size_t n = (std::min)(data.length(), flat->Capacity()); flat->length = n; edges_[sub_fetch_begin(1)] = flat; data = Consume<kFront>(flat->Data(), data, n); } while (!data.empty() && begin() != 0); return data; } template <EdgeType edge_type> CordRepBtree* CordRepBtree::AddData(CordRepBtree* tree, absl::string_view data, size_t extra) { if (ABSL_PREDICT_FALSE(data.empty())) return tree; const size_t original_data_size = data.size(); int depth = tree->height(); StackOperations<edge_type> ops; CordRepBtree* leaf = ops.BuildStack(tree, depth); if (leaf->size() < leaf->capacity()) { OpResult result = leaf->ToOpResult(ops.owned(depth)); data = result.tree->AddData<edge_type>(data, extra); if (data.empty()) { result.tree->length += original_data_size; return ops.Unwind(tree, depth, original_data_size, result); } size_t delta = original_data_size - data.size(); assert(delta > 0); result.tree->length += delta; tree = ops.Propagate(tree, depth, delta, result); ops.share_depth = depth + 1; } for (;;) { OpResult result = {CordRepBtree::NewLeaf<edge_type>(data, extra), kPopped}; if (result.tree->length == data.size()) { return ops.Unwind(tree, depth, result.tree->length, result); } data = Consume<edge_type>(data, result.tree->length); tree = ops.Unwind(tree, depth, result.tree->length, result); depth = tree->height(); ops.BuildOwnedStack(tree, depth); } } template <EdgeType edge_type> CordRepBtree* CordRepBtree::Merge(CordRepBtree* dst, CordRepBtree* src) { assert(dst->height() >= src->height()); const size_t length = src->length; const int depth = dst->height() - src->height(); StackOperations<edge_type> ops; CordRepBtree* merge_node = ops.BuildStack(dst, depth); OpResult result; if (merge_node->size() + src->size() <= kMaxCapacity) { result = merge_node->ToOpResult(ops.owned(depth)); result.tree->Add<edge_type>(src->Edges()); result.tree->length += src->length; if (src->refcount.IsOne()) { Delete(src); } else { for (CordRep* edge : src->Edges()) CordRep::Ref(edge); CordRepBtree::Unref(src); } } else { result = {src, kPopped}; } if (depth) { return ops.Unwind(dst, depth, length, result); } return ops.Finalize(dst, result); } CopyResult CordRepBtree::CopySuffix(size_t offset) { assert(offset < this->length); int height = this->height(); CordRepBtree* node = this; size_t len = node->length - offset; CordRep* back = node->Edge(kBack); while (back->length >= len) { offset = back->length - len; if (--height < 0) { return {MakeSubstring(CordRep::Ref(back), offset), height}; } node = back->btree(); back = node->Edge(kBack); } if (offset == 0) return {CordRep::Ref(node), height}; Position pos = node->IndexBeyond(offset); CordRepBtree* sub = node->CopyToEndFrom(pos.index, len); const CopyResult result = {sub, height}; while (pos.n != 0) { assert(pos.index >= 1); const size_t begin = pos.index - 1; sub->set_begin(begin); CordRep* const edge = node->Edge(begin); len = pos.n; offset = edge->length - len; if (--height < 0) { sub->edges_[begin] = MakeSubstring(CordRep::Ref(edge), offset, len); return result; } node = edge->btree(); pos = node->IndexBeyond(offset); CordRepBtree* nsub = node->CopyToEndFrom(pos.index, len); sub->edges_[begin] = nsub; sub = nsub; } sub->set_begin(pos.index); return result; } CopyResult CordRepBtree::CopyPrefix(size_t n, bool allow_folding) { assert(n > 0); assert(n <= this->length); int height = this->height(); CordRepBtree* node = this; CordRep* front = node->Edge(kFront); if (allow_folding) { while (front->length >= n) { if (--height < 0) return {MakeSubstring(CordRep::Ref(front), 0, n), -1}; node = front->btree(); front = node->Edge(kFront); } } if (node->length == n) return {CordRep::Ref(node), height}; Position pos = node->IndexOf(n); CordRepBtree* sub = node->CopyBeginTo(pos.index, n); const CopyResult result = {sub, height}; while (pos.n != 0) { size_t end = pos.index; n = pos.n; CordRep* edge = node->Edge(pos.index); if (--height < 0) { sub->edges_[end++] = MakeSubstring(CordRep::Ref(edge), 0, n); sub->set_end(end); AssertValid(result.edge->btree()); return result; } node = edge->btree(); pos = node->IndexOf(n); CordRepBtree* nsub = node->CopyBeginTo(pos.index, n); sub->edges_[end++] = nsub; sub->set_end(end); sub = nsub; } sub->set_end(pos.index); AssertValid(result.edge->btree()); return result; } CordRep* CordRepBtree::ExtractFront(CordRepBtree* tree) { CordRep* front = tree->Edge(tree->begin()); if (tree->refcount.IsOne()) { Unref(tree->Edges(tree->begin() + 1, tree->end())); CordRepBtree::Delete(tree); } else { CordRep::Ref(front); CordRep::Unref(tree); } return front; } CordRepBtree* CordRepBtree::ConsumeBeginTo(CordRepBtree* tree, size_t end, size_t new_length) { assert(end <= tree->end()); if (tree->refcount.IsOne()) { Unref(tree->Edges(end, tree->end())); tree->set_end(end); tree->length = new_length; } else { CordRepBtree* old = tree; tree = tree->CopyBeginTo(end, new_length); CordRep::Unref(old); } return tree; } CordRep* CordRepBtree::RemoveSuffix(CordRepBtree* tree, size_t n) { assert(tree != nullptr); assert(n <= tree->length); const size_t len = tree->length; if (ABSL_PREDICT_FALSE(n == 0)) { return tree; } if (ABSL_PREDICT_FALSE(n >= len)) { CordRepBtree::Unref(tree); return nullptr; } size_t length = len - n; int height = tree->height(); bool is_mutable = tree->refcount.IsOne(); Position pos = tree->IndexOfLength(length); while (pos.index == tree->begin()) { CordRep* edge = ExtractFront(tree); is_mutable &= edge->refcount.IsOne(); if (height-- == 0) return ResizeEdge(edge, length, is_mutable); tree = edge->btree(); pos = tree->IndexOfLength(length); } CordRepBtree* top = tree = ConsumeBeginTo(tree, pos.index + 1, length); CordRep* edge = tree->Edge(pos.index); length = pos.n; while (length != edge->length) { assert(tree->refcount.IsOne()); const bool edge_is_mutable = edge->refcount.IsOne(); if (height-- == 0) { tree->edges_[pos.index] = ResizeEdge(edge, length, edge_is_mutable); return AssertValid(top); } if (!edge_is_mutable) { tree->edges_[pos.index] = edge->btree()->CopyPrefix(length, false).edge; CordRep::Unref(edge); return AssertValid(top); } tree = edge->btree(); pos = tree->IndexOfLength(length); tree = ConsumeBeginTo(edge->btree(), pos.index + 1, length); edge = tree->Edge(pos.index); length = pos.n; } return AssertValid(top); } CordRep* CordRepBtree::SubTree(size_t offset, size_t n) { assert(n <= this->length); assert(offset <= this->length - n); if (ABSL_PREDICT_FALSE(n == 0)) return nullptr; CordRepBtree* node = this; int height = node->height(); Position front = node->IndexOf(offset); CordRep* left = node->edges_[front.index]; while (front.n + n <= left->length) { if (--height < 0) return MakeSubstring(CordRep::Ref(left), front.n, n); node = left->btree(); front = node->IndexOf(front.n); left = node->edges_[front.index]; } const Position back = node->IndexBefore(front, n); CordRep* const right = node->edges_[back.index]; assert(back.index > front.index); CopyResult prefix; CopyResult suffix; if (height > 0) { prefix = left->btree()->CopySuffix(front.n); suffix = right->btree()->CopyPrefix(back.n); if (front.index + 1 == back.index) { height = (std::max)(prefix.height, suffix.height) + 1; } for (int h = prefix.height + 1; h < height; ++h) { prefix.edge = CordRepBtree::New(prefix.edge); } for (int h = suffix.height + 1; h < height; ++h) { suffix.edge = CordRepBtree::New(suffix.edge); } } else { prefix = CopyResult{MakeSubstring(CordRep::Ref(left), front.n), -1}; suffix = CopyResult{MakeSubstring(CordRep::Ref(right), 0, back.n), -1}; } CordRepBtree* sub = CordRepBtree::New(height); size_t end = 0; sub->edges_[end++] = prefix.edge; for (CordRep* r : node->Edges(front.index + 1, back.index)) { sub->edges_[end++] = CordRep::Ref(r); } sub->edges_[end++] = suffix.edge; sub->set_end(end); sub->length = n; return AssertValid(sub); } CordRepBtree* CordRepBtree::MergeTrees(CordRepBtree* left, CordRepBtree* right) { return left->height() >= right->height() ? Merge<kBack>(left, right) : Merge<kFront>(right, left); } bool CordRepBtree::IsFlat(absl::string_view* fragment) const { if (height() == 0 && size() == 1) { if (fragment) *fragment = Data(begin()); return true; } return false; } bool CordRepBtree::IsFlat(size_t offset, const size_t n, absl::string_view* fragment) const { assert(n <= this->length); assert(offset <= this->length - n); if (ABSL_PREDICT_FALSE(n == 0)) return false; int height = this->height(); const CordRepBtree* node = this; for (;;) { const Position front = node->IndexOf(offset); const CordRep* edge = node->Edge(front.index); if (edge->length < front.n + n) return false; if (--height < 0) { if (fragment) *fragment = EdgeData(edge).substr(front.n, n); return true; } offset = front.n; node = node->Edge(front.index)->btree(); } } char CordRepBtree::GetCharacter(size_t offset) const { assert(offset < length); const CordRepBtree* node = this; int height = node->height(); for (;;) { Position front = node->IndexOf(offset); if (--height < 0) return node->Data(front.index)[front.n]; offset = front.n; node = node->Edge(front.index)->btree(); } } Span<char> CordRepBtree::GetAppendBufferSlow(size_t size) { assert(height() >= 4); assert(refcount.IsOne()); const int depth = height(); CordRepBtree* node = this; CordRepBtree* stack[kMaxDepth]; for (int i = 0; i < depth; ++i) { node = node->Edge(kBack)->btree(); if (!node->refcount.IsOne()) return {}; stack[i] = node; } CordRep* const edge = node->Edge(kBack); if (!edge->refcount.IsOne() || edge->tag < FLAT) return {}; const size_t avail = edge->flat()->Capacity() - edge->length; if (avail == 0) return {}; size_t delta = (std::min)(size, avail); Span<char> span = {edge->flat()->Data() + edge->length, delta}; edge->length += delta; this->length += delta; for (int i = 0; i < depth; ++i) { stack[i]->length += delta; } return span; } CordRepBtree* CordRepBtree::CreateSlow(CordRep* rep) { if (rep->IsBtree()) return rep->btree(); CordRepBtree* node = nullptr; auto consume = [&node](CordRep* r, size_t offset, size_t length) { r = MakeSubstring(r, offset, length); if (node == nullptr) { node = New(r); } else { node = CordRepBtree::AddCordRep<kBack>(node, r); } }; Consume(rep, consume); return node; } CordRepBtree* CordRepBtree::AppendSlow(CordRepBtree* tree, CordRep* rep) { if (ABSL_PREDICT_TRUE(rep->IsBtree())) { return MergeTrees(tree, rep->btree()); } auto consume = [&tree](CordRep* r, size_t offset, size_t length) { r = MakeSubstring(r, offset, length); tree = CordRepBtree::AddCordRep<kBack>(tree, r); }; Consume(rep, consume); return tree; } CordRepBtree* CordRepBtree::PrependSlow(CordRepBtree* tree, CordRep* rep) { if (ABSL_PREDICT_TRUE(rep->IsBtree())) { return MergeTrees(rep->btree(), tree); } auto consume = [&tree](CordRep* r, size_t offset, size_t length) { r = MakeSubstring(r, offset, length); tree = CordRepBtree::AddCordRep<kFront>(tree, r); }; ReverseConsume(rep, consume); return tree; } CordRepBtree* CordRepBtree::Append(CordRepBtree* tree, absl::string_view data, size_t extra) { return CordRepBtree::AddData<kBack>(tree, data, extra); } CordRepBtree* CordRepBtree::Prepend(CordRepBtree* tree, absl::string_view data, size_t extra) { return CordRepBtree::AddData<kFront>(tree, data, extra); } template CordRepBtree* CordRepBtree::AddCordRep<kFront>(CordRepBtree* tree, CordRep* rep); template CordRepBtree* CordRepBtree::AddCordRep<kBack>(CordRepBtree* tree, CordRep* rep); template CordRepBtree* CordRepBtree::AddData<kFront>(CordRepBtree* tree, absl::string_view data, size_t extra); template CordRepBtree* CordRepBtree::AddData<kBack>(CordRepBtree* tree, absl::string_view data, size_t extra); void CordRepBtree::Rebuild(CordRepBtree** stack, CordRepBtree* tree, bool consume) { bool owned = consume && tree->refcount.IsOne(); if (tree->height() == 0) { for (CordRep* edge : tree->Edges()) { if (!owned) edge = CordRep::Ref(edge); size_t height = 0; size_t length = edge->length; CordRepBtree* node = stack[0]; OpResult result = node->AddEdge<kBack>(true, edge, length); while (result.action == CordRepBtree::kPopped) { stack[height] = result.tree; if (stack[++height] == nullptr) { result.action = CordRepBtree::kSelf; stack[height] = CordRepBtree::New(node, result.tree); } else { node = stack[height]; result = node->AddEdge<kBack>(true, result.tree, length); } } while (stack[++height] != nullptr) { stack[height]->length += length; } } } else { for (CordRep* rep : tree->Edges()) { Rebuild(stack, rep->btree(), owned); } } if (consume) { if (owned) { CordRepBtree::Delete(tree); } else { CordRepBtree::Unref(tree); } } } CordRepBtree* CordRepBtree::Rebuild(CordRepBtree* tree) { CordRepBtree* node = CordRepBtree::New(); CordRepBtree* stack[CordRepBtree::kMaxDepth + 1] = {node}; Rebuild(stack, tree, true); for (CordRepBtree* parent : stack) { if (parent == nullptr) return node; node = parent; } assert(false); return nullptr; } CordRepBtree::ExtractResult CordRepBtree::ExtractAppendBuffer( CordRepBtree* tree, size_t extra_capacity) { int depth = 0; NodeStack stack; ExtractResult result; result.tree = tree; result.extracted = nullptr; while (tree->height() > 0) { if (!tree->refcount.IsOne()) return result; stack[depth++] = tree; tree = tree->Edge(kBack)->btree(); } if (!tree->refcount.IsOne()) return result; CordRep* rep = tree->Edge(kBack); if (!(rep->IsFlat() && rep->refcount.IsOne())) return result; CordRepFlat* flat = rep->flat(); const size_t length = flat->length; const size_t avail = flat->Capacity() - flat->length; if (extra_capacity > avail) return result; result.extracted = flat; while (tree->size() == 1) { CordRepBtree::Delete(tree); if (--depth < 0) { result.tree = nullptr; return result; } rep = tree; tree = stack[depth]; } tree->set_end(tree->end() - 1); tree->length -= length; while (depth > 0) { tree = stack[--depth]; tree->length -= length; } while (tree->size() == 1) { int height = tree->height(); rep = tree->Edge(kBack); Delete(tree); if (height == 0) { result.tree = rep; return result; } tree = rep->btree(); } result.tree = tree; return result; } } ABSL_NAMESPACE_END }
#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(), ElementsAre(Conditional(shared(), Ne(leaf0), Eq(leaf0)), leaf1)); EXPECT_THAT(CordToString(result), Eq("123456789" + data)); CordRep::Unref(result); } TEST_P(CordRepBtreeTest, AddDataToTreeThreeLevelsDeep) { constexpr size_t max_cap = CordRepBtree::kMaxCapacity; const size_t n = max_cap * max_cap * max_cap; const std::string data = CreateRandomString(n * 3); for (bool append : {true, false}) { AutoUnref refs; DataConsumer consumer(data, append); SCOPED_TRACE(append ? "Append" : "Prepend"); CordRepBtree* tree = CordRepBtree::Create(MakeFlat(consumer.Next(3))); for (size_t i = 1; i < max_cap; ++i) { tree = BtreeAdd(tree, append, consumer.Next(3)); } ASSERT_THAT(CordToString(tree), Eq(consumer.Consumed())); refs.RefIf(shared(), tree); CordRepBtree* result = BtreeAdd(tree, append, consumer.Next(3)); ASSERT_THAT(result, IsNode(1)); ASSERT_THAT(result, Ne(tree)); ASSERT_THAT(CordToString(result), Eq(consumer.Consumed())); tree = result; for (size_t i = max_cap + 1; i < max_cap * max_cap; ++i) { refs.RefIf(shared(), tree); result = BtreeAdd(tree, append, consumer.Next(3)); ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); ASSERT_THAT(CordToString(result), Eq(consumer.Consumed())); tree = result; } refs.RefIf(shared(), tree); result = BtreeAdd(tree, append, consumer.Next(3)); ASSERT_THAT(result, IsNode(2)); ASSERT_THAT(result, Ne(tree)); ASSERT_THAT(CordToString(result), Eq(consumer.Consumed())); tree = result; for (size_t i = max_cap * max_cap + 1; i < max_cap * max_cap * max_cap; ++i) { refs.RefIf(shared(), tree); result = BtreeAdd(tree, append, consumer.Next(3)); ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree))); ASSERT_THAT(CordToString(result), Eq(consumer.Consumed())); tree = result; } CordRep::Unref(tree); } } TEST_P(CordRepBtreeTest, AddLargeDataToLeaf) { const size_t max_cap = CordRepBtree::kMaxCapacity; const size_t n = max_cap * max_cap * max_cap * 3 + 2; const std::string data = CreateRandomString(n * kMaxFlatLength); for (bool append : {true, false}) { AutoUnref refs; SCOPED_TRACE(append ? "Append" : "Prepend"); CordRepBtree* leaf = CordRepBtree::Create(MakeFlat("abc")); refs.RefIf(shared(), leaf); CordRepBtree* result = BtreeAdd(leaf, append, data); EXPECT_THAT(CordToString(result), Eq(append ? "abc" + data : data + "abc")); CordRep::Unref(result); } } TEST_P(CordRepBtreeTest, CreateFromTreeReturnsTree) { AutoUnref refs; CordRepBtree* leaf = CordRepBtree::Create(MakeFlat("Hello world")); refs.RefIf(shared(), leaf); CordRepBtree* result = CordRepBtree::Create(leaf); EXPECT_THAT(result, Eq(leaf)); CordRep::Unref(result); } TEST(CordRepBtreeTest, GetCharacter) { size_t n = CordRepBtree::kMaxCapacity * CordRepBtree::kMaxCapacity + 2; std::string data = CreateRandomString(n * 3); CordRepBtree* tree = CreateTree(data, 3); tree = tree->Append(tree, MakeSubstring(4, 5, MakeFlat("abcdefghijklm"))); data += "efghi"; for (size_t i = 0; i < data.length(); ++i) { ASSERT_THAT(tree->GetCharacter(i), Eq(data[i])); } CordRep::Unref(tree); } TEST_P(CordRepBtreeTest, IsFlatSingleFlat) { CordRepBtree* leaf = CordRepBtree::Create(MakeFlat("Hello world")); absl::string_view fragment; EXPECT_TRUE(leaf->IsFlat(nullptr)); EXPECT_TRUE(leaf->IsFlat(&fragment)); EXPECT_THAT(fragment, Eq("Hello world")); fragment = ""; EXPECT_TRUE(leaf->IsFlat(0, 11, nullptr)); EXPECT_TRUE(leaf->IsFlat(0, 11, &fragment)); EXPECT_THAT(fragment, Eq("Hello world")); EXPECT_TRUE(leaf->IsFlat(1, 4, &fragment)); EXPECT_THAT(fragment, Eq("ello")); EXPECT_TRUE(leaf->IsFlat(6, 5, &fragment)); EXPECT_THAT(fragment, Eq("world")); CordRep::Unref(leaf); } TEST(CordRepBtreeTest, IsFlatMultiFlat) { size_t n = CordRepBtree::kMaxCapacity * CordRepBtree::kMaxCapacity + 2; std::string data = CreateRandomString(n * 3); CordRepBtree* tree = CreateTree(data, 3); tree = tree->Append(tree, MakeSubstring(4, 3, MakeFlat("abcdefghijklm"))); tree = tree->Append(tree, MakeSubstring(8, 3, MakeFlat("abcdefghijklm"))); data += "efgijk"; EXPECT_FALSE(tree->IsFlat(nullptr)); absl::string_view fragment = "Can't touch this"; EXPECT_FALSE(tree->IsFlat(&fragment)); EXPECT_THAT(fragment, Eq("Can't touch this")); for (size_t offset = 0; offset < data.size(); offset += 3) { EXPECT_TRUE(tree->IsFlat(offset, 3, nullptr)); EXPECT_TRUE(tree->IsFlat(offset, 3, &fragment)); EXPECT_THAT(fragment, Eq(data.substr(offset, 3))); fragment = "Can't touch this"; if (offset > 0) { EXPECT_FALSE(tree->IsFlat(offset - 1, 4, nullptr)); EXPECT_FALSE(tree->IsFlat(offset - 1, 4, &fragment)); EXPECT_THAT(fragment, Eq("Can't touch this")); } if (offset < data.size() - 4) { EXPECT_FALSE(tree->IsFlat(offset, 4, nullptr)); EXPECT_FALSE(tree->IsFlat(offset, 4, &fragment)); EXPECT_THAT(fragment, Eq("Can't touch this")); } } CordRep::Unref(tree); } #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) TEST_P(CordRepBtreeHeightTest, GetAppendBufferNotPrivate) { CordRepBtree* tree = CordRepBtree::Create(MakeExternal("Foo")); CordRepBtree::Ref(tree); EXPECT_DEATH(tree->GetAppendBuffer(1), ".*"); CordRepBtree::Unref(tree); CordRepBtree::Unref(tree); } #endif TEST_P(CordRepBtreeHeightTest, GetAppendBufferNotFlat) { CordRepBtree* tree = CordRepBtree::Create(MakeExternal("Foo")); for (int i = 1; i <= height(); ++i) { tree = CordRepBtree::New(tree); } EXPECT_THAT(tree->GetAppendBuffer(1), SizeIs(0u)); CordRepBtree::Unref(tree); } TEST_P(CordRepBtreeHeightTest, GetAppendBufferFlatNotPrivate) { CordRepFlat* flat = MakeFlat("abc"); CordRepBtree* tree = CordRepBtree::Create(CordRep::Ref(flat)); for (int i = 1; i <= height(); ++i) { tree = CordRepBtree::New(tree); } EXPECT_THAT(tree->GetAppendBuffer(1), SizeIs(0u)); CordRepBtree::Unref(tree); CordRep::Unref(flat); } TEST_P(CordRepBtreeHeightTest, GetAppendBufferTreeNotPrivate) { if (height() == 0) return; AutoUnref refs; CordRepFlat* flat = MakeFlat("abc"); CordRepBtree* tree = CordRepBtree::Create(CordRep::Ref(flat)); for (int i = 1; i <= height(); ++i) { if (i == (height() + 1) / 2) refs.Ref(tree); tree = CordRepBtree::New(tree); } EXPECT_THAT(tree->GetAppendBuffer(1), SizeIs(0u)); CordRepBtree::Unref(tree); CordRep::Unref(flat); } TEST_P(CordRepBtreeHeightTest, GetAppendBufferFlatNoCapacity) { CordRepFlat* flat = MakeFlat("abc"); flat->length = flat->Capacity(); CordRepBtree* tree = CordRepBtree::Create(flat); for (int i = 1; i <= height(); ++i) { tree = CordRepBtree::New(tree); } EXPECT_THAT(tree->GetAppendBuffer(1), SizeIs(0u)); CordRepBtree::Unref(tree); } TEST_P(CordRepBtreeHeightTest, GetAppendBufferFlatWithCapacity) { CordRepFlat* flat = MakeFlat("abc"); CordRepBtree* tree = CordRepBtree::Create(flat); for (int i = 1; i <= height(); ++i) { tree = CordRepBtree::New(tree); } absl::Span<char> span = tree->GetAppendBuffer(2); EXPECT_THAT(span, SizeIs(2u)); EXPECT_THAT(span.data(), TypedEq<void*>(flat->Data() + 3)); EXPECT_THAT(tree->length, Eq(5u)); size_t avail = flat->Capacity() - 5; span = tree->GetAppendBuffer(avail + 100); EXPECT_THAT(span, SizeIs(avail)); EXPECT_THAT(span.data(), TypedEq<void*>(flat->Data() + 5)); EXPECT_THAT(tree->length, Eq(5 + avail)); CordRepBtree::Unref(tree); } TEST(CordRepBtreeTest, Dump) { std::stringstream ss; CordRepBtree::Dump(nullptr, ss); CordRepBtree::Dump(nullptr, "Once upon a label", ss); CordRepBtree::Dump(nullptr, "Once upon a label", false, ss); CordRepBtree::Dump(nullptr, "Once upon a label", true, ss); CordRepFlat* flat = MakeFlat("Hello world"); CordRepExternal* external = MakeExternal("Hello external"); CordRep* substr_flat = MakeSubstring(1, 6, CordRep::Ref(flat)); CordRep* substr_external = MakeSubstring(2, 7, CordRep::Ref(external)); CordRepBtree* tree = CordRepBtree::Create(flat); tree = CordRepBtree::Append(tree, external); tree = CordRepBtree::Append(tree, substr_flat); tree = CordRepBtree::Append(tree, substr_external); while (tree->height() == 0) { tree = CordRepBtree::Append(tree, CordRep::Ref(flat)); tree = CordRepBtree::Append(tree, CordRep::Ref(external)); tree = CordRepBtree::Append(tree, CordRep::Ref(substr_flat)); tree = CordRepBtree::Append(tree, CordRep::Ref(substr_external)); } for (int api = 0; api <= 3; ++api) { absl::string_view api_scope; std::stringstream ss; switch (api) { case 0: api_scope = "Bare"; CordRepBtree::Dump(tree, ss); break; case 1: api_scope = "Label only"; CordRepBtree::Dump(tree, "Once upon a label", ss); break; case 2: api_scope = "Label no content"; CordRepBtree::Dump(tree, "Once upon a label", false, ss); break; default: api_scope = "Label and content"; CordRepBtree::Dump(tree, "Once upon a label", true, ss); break; } SCOPED_TRACE(api_scope); std::string str = ss.str(); EXPECT_THAT(str, AllOf(HasSubstr("Node(1)"), HasSubstr("Leaf"), HasSubstr("Private"), HasSubstr("Shared"))); EXPECT_THAT(str, AllOf(HasSubstr("len = 11"), HasSubstr("len = 14"), HasSubstr("len = 6"), HasSubstr("len = 7"), HasSubstr("start = 1"), HasSubstr("start = 2"))); EXPECT_THAT( str, AllOf(HasSubstr(absl::StrCat("0x", absl::Hex(flat))), HasSubstr(absl::StrCat("0x", absl::Hex(external))), HasSubstr(absl::StrCat("0x", absl::Hex(substr_flat))), HasSubstr(absl::StrCat("0x", absl::Hex(substr_external))))); if (api != 0) { EXPECT_THAT(str, HasSubstr("Once upon a label")); } if (api != 3) { EXPECT_THAT(str, Not(AnyOf((HasSubstr("data = \"Hello world\""), HasSubstr("data = \"Hello external\""), HasSubstr("data = \"ello w\""), HasSubstr("data = \"llo ext\""))))); } else { EXPECT_THAT(str, AllOf((HasSubstr("data = \"Hello world\""), HasSubstr("data = \"Hello external\""), HasSubstr("data = \"ello w\""), HasSubstr("data = \"llo ext\"")))); } } CordRep::Unref(tree); } TEST(CordRepBtreeTest, IsValid) { EXPECT_FALSE(CordRepBtree::IsValid(nullptr)); CordRepBtree* empty = CordRepBtree::New(0); EXPECT_TRUE(CordRepBtree::IsValid(empty)); CordRep::Unref(empty); for (bool as_tree : {false, true}) { CordRepBtree* leaf = CordRepBtree::Create(MakeFlat("abc")); CordRepBtree* tree = as_tree ? CordRepBtree::New(leaf) : nullptr; CordRepBtree* check = as_tree ? tree : leaf; ASSERT_TRUE(CordRepBtree::IsValid(check)); leaf->length--; EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->length++; ASSERT_TRUE(CordRepBtree::IsValid(check)); leaf->tag--; EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->tag++; ASSERT_TRUE(CordRepBtree::IsValid(check)); leaf->storage[0] = static_cast<uint8_t>(CordRepBtree::kMaxHeight + 1); EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->storage[0] = 1; EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->storage[0] = 0; ASSERT_TRUE(CordRepBtree::IsValid(check)); const uint8_t begin = leaf->storage[1]; leaf->storage[1] = static_cast<uint8_t>(CordRepBtree::kMaxCapacity); EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->storage[1] = 2; EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->storage[1] = begin; ASSERT_TRUE(CordRepBtree::IsValid(check)); const uint8_t end = leaf->storage[2]; leaf->storage[2] = static_cast<uint8_t>(CordRepBtree::kMaxCapacity + 1); EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->storage[2] = end; ASSERT_TRUE(CordRepBtree::IsValid(check)); CordRep* const edge = leaf->Edges()[0]; const uint8_t tag = edge->tag; CordRepBtreeTestPeer::SetEdge(leaf, begin, nullptr); EXPECT_FALSE(CordRepBtree::IsValid(check)); CordRepBtreeTestPeer::SetEdge(leaf, begin, edge); edge->tag = BTREE; EXPECT_FALSE(CordRepBtree::IsValid(check)); edge->tag = tag; if (as_tree) { ASSERT_TRUE(CordRepBtree::IsValid(check)); leaf->length--; EXPECT_FALSE(CordRepBtree::IsValid(check)); leaf->length++; ASSERT_TRUE(CordRepBtree::IsValid(check)); tree->storage[0] = static_cast<uint8_t>(2); EXPECT_FALSE(CordRepBtree::IsValid(check)); tree->storage[0] = 1; ASSERT_TRUE(CordRepBtree::IsValid(check)); CordRep* const edge = tree->Edges()[0]; const uint8_t tag = edge->tag; edge->tag = FLAT; EXPECT_FALSE(CordRepBtree::IsValid(check)); edge->tag = tag; } ASSERT_TRUE(CordRepBtree::IsValid(check)); CordRep::Unref(check); } } TEST(CordRepBtreeTest, AssertValid) { CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc")); const CordRepBtree* ctree = tree; EXPECT_THAT(CordRepBtree::AssertValid(tree), Eq(tree)); EXPECT_THAT(CordRepBtree::AssertValid(ctree), Eq(ctree)); #if defined(GTEST_HAS_DEATH_TEST) CordRepBtree* nulltree = nullptr; const CordRepBtree* cnulltree = nullptr; EXPECT_DEBUG_DEATH( EXPECT_THAT(CordRepBtree::AssertValid(nulltree), Eq(nulltree)), ".*"); EXPECT_DEBUG_DEATH( EXPECT_THAT(CordRepBtree::AssertValid(cnulltree), Eq(cnulltree)), ".*"); tree->length--; EXPECT_DEBUG_DEATH(EXPECT_THAT(CordRepBtree::AssertValid(tree), Eq(tree)), ".*"); EXPECT_DEBUG_DEATH(EXPECT_THAT(CordRepBtree::AssertValid(ctree), Eq(ctree)), ".*"); tree->length++; #endif CordRep::Unref(tree); } TEST(CordRepBtreeTest, CheckAssertValidShallowVsDeep) { const bool exhaustive_validation = IsCordBtreeExhaustiveValidationEnabled(); auto cleanup = absl::MakeCleanup([exhaustive_validation] { SetCordBtreeExhaustiveValidation(exhaustive_validation); }); CordRep* flat = MakeFlat("abc"); CordRepBtree* tree = CordRepBtree::Create(flat); constexpr size_t max_cap = CordRepBtree::kMaxCapacity; const size_t n = max_cap * max_cap * 2; for (size_t i = 0; i < n; ++i) { tree = CordRepBtree::Append(tree, MakeFlat("Hello world")); } flat->length = 100; SetCordBtreeExhaustiveValidation(false); EXPECT_FALSE(CordRepBtree::IsValid(tree)); EXPECT_TRUE(CordRepBtree::IsValid(tree, true)); EXPECT_FALSE(CordRepBtree::IsValid(tree, false)); CordRepBtree::AssertValid(tree); CordRepBtree::AssertValid(tree, true); #if defined(GTEST_HAS_DEATH_TEST) EXPECT_DEBUG_DEATH(CordRepBtree::AssertValid(tree, false), ".*"); #endif SetCordBtreeExhaustiveValidation(true); EXPECT_FALSE(CordRepBtree::IsValid(tree)); EXPECT_FALSE(CordRepBtree::IsValid(tree, true)); EXPECT_FALSE(CordRepBtree::IsValid(tree, false)); #if defined(GTEST_HAS_DEATH_TEST) EXPECT_DEBUG_DEATH(CordRepBtree::AssertValid(tree), ".*"); EXPECT_DEBUG_DEATH(CordRepBtree::AssertValid(tree, true), ".*"); #endif flat->length = 3; CordRep::Unref(tree); } TEST_P(CordRepBtreeTest, Rebuild) { for (size_t size : {3u, 8u, 100u, 10000u, 1000000u}) { SCOPED_TRACE(absl::StrCat("Rebuild @", size)); std::vector<CordRepFlat*> flats; for (size_t i = 0; i < size; ++i) { flats.push_back(CordRepFlat::New(2)); flats.back()->Data()[0] = 'x'; flats.back()->length = 1; } size_t split_count = 0; size_t split_limit = 3; auto it = flats.begin(); CordRepBtree* left = nullptr; CordRepBtree* right = CordRepBtree::New(*it); while (++it != flats.end()) { if (++split_count >= split_limit) { split_limit += split_limit / 16; left = left ? CordRepBtree::Append(left, right) : right; right = CordRepBtree::New(*it); } else { right = CordRepBtree::Append(right, *it); } } left = left ? CordRepBtree::Append(left, right) : right; AutoUnref ref; left = ref.Add(CordRepBtree::Rebuild(ref.RefIf(shared(), left))); ASSERT_TRUE(CordRepBtree::IsValid(left)); bool ok = true; it = flats.begin(); CordVisitReps(left, [&](CordRep* edge) { if (edge->tag < FLAT) return; ok = ok && (it != flats.end() && *it++ == edge); }); EXPECT_TRUE(ok && it == flats.end()) << "Rebuild edges mismatch"; } } CordRepBtree::ExtractResult ExtractLast(CordRepBtree* input, size_t cap = 1) { return CordRepBtree::ExtractAppendBuffer(input, cap); } TEST(CordRepBtreeTest, ExtractAppendBufferLeafSingleFlat) { CordRep* flat = MakeFlat("Abc"); CordRepBtree* leaf = CordRepBtree::Create(flat); EXPECT_THAT(ExtractLast(leaf), EqExtractResult(nullptr, flat)); CordRep::Unref(flat); } TEST(CordRepBtreeTest, ExtractAppendBufferNodeSingleFlat) { CordRep* flat = MakeFlat("Abc"); CordRepBtree* leaf = CordRepBtree::Create(flat); CordRepBtree* node = CordRepBtree::New(leaf); EXPECT_THAT(ExtractLast(node), EqExtractResult(nullptr, flat)); CordRep::Unref(flat); } TEST(CordRepBtreeTest, ExtractAppendBufferLeafTwoFlats) { std::vector<CordRep*> flats = CreateFlatsFromString("abcdef", 3); CordRepBtree* leaf = CreateTree(flats); EXPECT_THAT(ExtractLast(leaf), EqExtractResult(flats[0], flats[1])); CordRep::Unref(flats[0]); CordRep::Unref(flats[1]); } TEST(CordRepBtreeTest, ExtractAppendBufferNodeTwoFlats) { std::vector<CordRep*> flats = CreateFlatsFromString("abcdef", 3); CordRepBtree* leaf = CreateTree(flats); CordRepBtree* node = CordRepBtree::New(leaf); EXPECT_THAT(ExtractLast(node), EqExtractResult(flats[0], flats[1])); CordRep::Unref(flats[0]); CordRep::Unref(flats[1]); } TEST(CordRepBtreeTest, ExtractAppendBufferNodeTwoFlatsInTwoLeafs) { std::vector<CordRep*> flats = CreateFlatsFromString("abcdef", 3); CordRepBtree* leaf1 = CordRepBtree::Create(flats[0]); CordRepBtree* leaf2 = CordRepBtree::Create(flats[1]); CordRepBtree* node = CordRepBtree::New(leaf1, leaf2); EXPECT_THAT(ExtractLast(node), EqExtractResult(flats[0], flats[1])); CordRep::Unref(flats[0]); CordRep::Unref(flats[1]); } TEST(CordRepBtreeTest, ExtractAppendBufferLeafThreeFlats) { std::vector<CordRep*> flats = CreateFlatsFromString("abcdefghi", 3); CordRepBtree* leaf = CreateTree(flats); EXPECT_THAT(ExtractLast(leaf), EqExtractResult(leaf, flats[2])); CordRep::Unref(flats[2]); CordRep::Unref(leaf); } TEST(CordRepBtreeTest, ExtractAppendBufferNodeThreeFlatsRightNoFolding) { CordRep* flat = MakeFlat("Abc"); std::vector<CordRep*> flats = CreateFlatsFromString("defghi", 3); CordRepBtree* leaf1 = CordRepBtree::Create(flat); CordRepBtree* leaf2 = CreateTree(flats); CordRepBtree* node = CordRepBtree::New(leaf1, leaf2); EXPECT_THAT(ExtractLast(node), EqExtractResult(node, flats[1])); EXPECT_THAT(node->Edges(), ElementsAre(leaf1, leaf2)); EXPECT_THAT(leaf1->Edges(), ElementsAre(flat)); EXPECT_THAT(leaf2->Edges(), ElementsAre(flats[0])); CordRep::Unref(node); CordRep::Unref(flats[1]); } TEST(CordRepBtreeTest, ExtractAppendBufferNodeThreeFlatsRightLeafFolding) { CordRep* flat = MakeFlat("Abc"); std::vector<CordRep*> flats = CreateFlatsFromString("defghi", 3); CordRepBtree* leaf1 = CreateTree(flats); CordRepBtree* leaf2 = CordRepBtree::Create(flat); CordRepBtree* node = CordRepBtree::New(leaf1, leaf2); EXPECT_THAT(ExtractLast(node), EqExtractResult(leaf1, flat)); EXPECT_THAT(leaf1->Edges(), ElementsAreArray(flats)); CordRep::Unref(leaf1); CordRep::Unref(flat); } TEST(CordRepBtreeTest, ExtractAppendBufferNoCapacity) { std::vector<CordRep*> flats = CreateFlatsFromString("abcdef", 3); CordRepBtree* leaf = CreateTree(flats); size_t avail = flats[1]->flat()->Capacity() - flats[1]->length; EXPECT_THAT(ExtractLast(leaf, avail + 1), EqExtractResult(leaf, nullptr)); EXPECT_THAT(ExtractLast(leaf, avail), EqExtractResult(flats[0], flats[1])); CordRep::Unref(flats[0]); CordRep::Unref(flats[1]); } TEST(CordRepBtreeTest, ExtractAppendBufferNotFlat) { std::vector<CordRep*> flats = CreateFlatsFromString("abcdef", 3); auto substr = MakeSubstring(1, 2, flats[1]); CordRepBtree* leaf = CreateTree({flats[0], substr}); EXPECT_THAT(ExtractLast(leaf), EqExtractResult(leaf, nullptr)); CordRep::Unref(leaf); } TEST(CordRepBtreeTest, ExtractAppendBufferShared) { std::vector<CordRep*> flats = CreateFlatsFromString("abcdef", 3); CordRepBtree* leaf = CreateTree(flats); CordRep::Ref(flats[1]); EXPECT_THAT(ExtractLast(leaf), EqExtractResult(leaf, nullptr)); CordRep::Unref(flats[1]); CordRep::Ref(leaf); EXPECT_THAT(ExtractLast(leaf), EqExtractResult(leaf, nullptr)); CordRep::Unref(leaf); CordRepBtree* node = CordRepBtree::New(leaf); CordRep::Ref(node); EXPECT_THAT(ExtractLast(node), EqExtractResult(node, nullptr)); CordRep::Unref(node); CordRep::Unref(node); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_btree.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_rep_btree_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
4f1cde24-9bd1-4c35-b0a6-b5d8de9285af
cpp
abseil/abseil-cpp
arg
absl/strings/internal/str_format/arg.cc
absl/strings/internal/str_format/arg_test.cc
#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(storage_) - p); } string_view with_neg_and_zero() const { return {start_, size_}; } string_view without_neg_or_zero() const { static_assert('-' < '0', "The check below verifies both."); size_t advance = start_[0] <= '0' ? 1 : 0; return {start_ + advance, size_ - advance}; } bool is_negative() const { return start_[0] == '-'; } private: const char *start_; size_t size_; char storage_[128 / 3 + 1 + 1]; }; string_view BaseIndicator(const IntDigits &as_digits, const FormatConversionSpecImpl conv) { bool alt = conv.has_alt_flag() || conv.conversion_char() == FormatConversionCharInternal::p; bool hex = (conv.conversion_char() == FormatConversionCharInternal::x || conv.conversion_char() == FormatConversionCharInternal::X || conv.conversion_char() == FormatConversionCharInternal::p); if (alt && hex && !as_digits.without_neg_or_zero().empty()) { return conv.conversion_char() == FormatConversionCharInternal::X ? "0X" : "0x"; } return {}; } string_view SignColumn(bool neg, const FormatConversionSpecImpl conv) { if (conv.conversion_char() == FormatConversionCharInternal::d || conv.conversion_char() == FormatConversionCharInternal::i) { if (neg) return "-"; if (conv.has_show_pos_flag()) return "+"; if (conv.has_sign_col_flag()) return " "; } return {}; } bool ConvertCharImpl(char v, const FormatConversionSpecImpl conv, FormatSinkImpl* sink) { size_t fill = 0; if (conv.width() >= 0) fill = static_cast<size_t>(conv.width()); ReducePadding(1, &fill); if (!conv.has_left_flag()) sink->Append(fill, ' '); sink->Append(1, v); if (conv.has_left_flag()) sink->Append(fill, ' '); return true; } bool ConvertIntImplInnerSlow(const IntDigits &as_digits, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { size_t fill = 0; if (conv.width() >= 0) fill = static_cast<size_t>(conv.width()); string_view formatted = as_digits.without_neg_or_zero(); ReducePadding(formatted, &fill); string_view sign = SignColumn(as_digits.is_negative(), conv); ReducePadding(sign, &fill); string_view base_indicator = BaseIndicator(as_digits, conv); ReducePadding(base_indicator, &fill); bool precision_specified = conv.precision() >= 0; size_t precision = precision_specified ? static_cast<size_t>(conv.precision()) : size_t{1}; if (conv.has_alt_flag() && conv.conversion_char() == FormatConversionCharInternal::o) { if (formatted.empty() || *formatted.begin() != '0') { size_t needed = formatted.size() + 1; precision = std::max(precision, needed); } } size_t num_zeroes = Excess(formatted.size(), precision); ReducePadding(num_zeroes, &fill); size_t num_left_spaces = !conv.has_left_flag() ? fill : 0; size_t num_right_spaces = conv.has_left_flag() ? fill : 0; if (!precision_specified && conv.has_zero_flag()) { num_zeroes += num_left_spaces; num_left_spaces = 0; } sink->Append(num_left_spaces, ' '); sink->Append(sign); sink->Append(base_indicator); sink->Append(num_zeroes, '0'); sink->Append(formatted); sink->Append(num_right_spaces, ' '); return true; } template <typename T> bool ConvertFloatArg(T v, FormatConversionSpecImpl conv, FormatSinkImpl *sink) { if (conv.conversion_char() == FormatConversionCharInternal::v) { conv.set_conversion_char(FormatConversionCharInternal::g); } return FormatConversionCharIsFloat(conv.conversion_char()) && ConvertFloatImpl(v, conv, sink); } inline bool ConvertStringArg(string_view v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { if (conv.is_basic()) { sink->Append(v); return true; } return sink->PutPaddedString(v, conv.width(), conv.precision(), conv.has_left_flag()); } struct ShiftState { bool saw_high_surrogate = false; uint8_t bits = 0; }; inline size_t WideToUtf8(wchar_t wc, char *buf, ShiftState &s) { const auto v = static_cast<uint32_t>(wc); if (v < 0x80) { *buf = static_cast<char>(v); return 1; } else if (v < 0x800) { *buf++ = static_cast<char>(0xc0 | (v >> 6)); *buf = static_cast<char>(0x80 | (v & 0x3f)); return 2; } else if (v < 0xd800 || (v - 0xe000) < 0x2000) { *buf++ = static_cast<char>(0xe0 | (v >> 12)); *buf++ = static_cast<char>(0x80 | ((v >> 6) & 0x3f)); *buf = static_cast<char>(0x80 | (v & 0x3f)); return 3; } else if ((v - 0x10000) < 0x100000) { *buf++ = static_cast<char>(0xf0 | (v >> 18)); *buf++ = static_cast<char>(0x80 | ((v >> 12) & 0x3f)); *buf++ = static_cast<char>(0x80 | ((v >> 6) & 0x3f)); *buf = static_cast<char>(0x80 | (v & 0x3f)); return 4; } else if (v < 0xdc00) { s.saw_high_surrogate = true; s.bits = static_cast<uint8_t>(v & 0x3); const uint8_t high_bits = ((v >> 6) & 0xf) + 1; *buf++ = static_cast<char>(0xf0 | (high_bits >> 2)); *buf = static_cast<char>(0x80 | static_cast<uint8_t>((high_bits & 0x3) << 4) | static_cast<uint8_t>((v >> 2) & 0xf)); return 2; } else if (v < 0xe000 && s.saw_high_surrogate) { *buf++ = static_cast<char>(0x80 | static_cast<uint8_t>(s.bits << 4) | static_cast<uint8_t>((v >> 6) & 0xf)); *buf = static_cast<char>(0x80 | (v & 0x3f)); s.saw_high_surrogate = false; s.bits = 0; return 2; } else { return static_cast<size_t>(-1); } } inline bool ConvertStringArg(const wchar_t *v, size_t len, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { FixedArray<char> mb(len * 4); ShiftState s; size_t chars_written = 0; for (size_t i = 0; i < len; ++i) { const size_t chars = WideToUtf8(v[i], &mb[chars_written], s); if (chars == static_cast<size_t>(-1)) { return false; } chars_written += chars; } return ConvertStringArg(string_view(mb.data(), chars_written), conv, sink); } bool ConvertWCharTImpl(wchar_t v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { char mb[4]; ShiftState s; const size_t chars_written = WideToUtf8(v, mb, s); return chars_written != static_cast<size_t>(-1) && !s.saw_high_surrogate && ConvertStringArg(string_view(mb, chars_written), conv, sink); } } bool ConvertBoolArg(bool v, FormatSinkImpl *sink) { if (v) { sink->Append("true"); } else { sink->Append("false"); } return true; } template <typename T> bool ConvertIntArg(T v, FormatConversionSpecImpl conv, FormatSinkImpl *sink) { using U = typename MakeUnsigned<T>::type; IntDigits as_digits; switch (static_cast<uint8_t>(conv.conversion_char())) { case static_cast<uint8_t>(FormatConversionCharInternal::c): return (std::is_same<T, wchar_t>::value || (conv.length_mod() == LengthMod::l)) ? ConvertWCharTImpl(static_cast<wchar_t>(v), conv, sink) : ConvertCharImpl(static_cast<char>(v), conv, sink); case static_cast<uint8_t>(FormatConversionCharInternal::o): as_digits.PrintAsOct(static_cast<U>(v)); break; case static_cast<uint8_t>(FormatConversionCharInternal::x): as_digits.PrintAsHexLower(static_cast<U>(v)); break; case static_cast<uint8_t>(FormatConversionCharInternal::X): as_digits.PrintAsHexUpper(static_cast<U>(v)); break; case static_cast<uint8_t>(FormatConversionCharInternal::u): as_digits.PrintAsDec(static_cast<U>(v)); break; case static_cast<uint8_t>(FormatConversionCharInternal::d): case static_cast<uint8_t>(FormatConversionCharInternal::i): case static_cast<uint8_t>(FormatConversionCharInternal::v): as_digits.PrintAsDec(v); break; case static_cast<uint8_t>(FormatConversionCharInternal::a): case static_cast<uint8_t>(FormatConversionCharInternal::e): case static_cast<uint8_t>(FormatConversionCharInternal::f): case static_cast<uint8_t>(FormatConversionCharInternal::g): case static_cast<uint8_t>(FormatConversionCharInternal::A): case static_cast<uint8_t>(FormatConversionCharInternal::E): case static_cast<uint8_t>(FormatConversionCharInternal::F): case static_cast<uint8_t>(FormatConversionCharInternal::G): return ConvertFloatImpl(static_cast<double>(v), conv, sink); default: ABSL_ASSUME(false); } if (conv.is_basic()) { sink->Append(as_digits.with_neg_and_zero()); return true; } return ConvertIntImplInnerSlow(as_digits, conv, sink); } template bool ConvertIntArg<char>(char v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<signed char>(signed char v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<unsigned char>(unsigned char v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<wchar_t>(wchar_t v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<short>(short v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<unsigned short>(unsigned short v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<int>(int v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<unsigned int>(unsigned int v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<long>(long v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<unsigned long>(unsigned long v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<long long>(long long v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); template bool ConvertIntArg<unsigned long long>(unsigned long long v, FormatConversionSpecImpl conv, FormatSinkImpl *sink); StringConvertResult FormatConvertImpl(const std::string &v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertStringArg(v, conv, sink)}; } StringConvertResult FormatConvertImpl(const std::wstring &v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertStringArg(v.data(), v.size(), conv, sink)}; } StringConvertResult FormatConvertImpl(string_view v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertStringArg(v, conv, sink)}; } #if defined(ABSL_HAVE_STD_STRING_VIEW) StringConvertResult FormatConvertImpl(std::wstring_view v, const FormatConversionSpecImpl conv, FormatSinkImpl* sink) { return {ConvertStringArg(v.data(), v.size(), conv, sink)}; } #endif StringPtrConvertResult FormatConvertImpl(const char* v, const FormatConversionSpecImpl conv, FormatSinkImpl* sink) { if (conv.conversion_char() == FormatConversionCharInternal::p) return {FormatConvertImpl(VoidPtr(v), conv, sink).value}; size_t len; if (v == nullptr) { len = 0; } else if (conv.precision() < 0) { len = std::strlen(v); } else { len = static_cast<size_t>(std::find(v, v + conv.precision(), '\0') - v); } return {ConvertStringArg(string_view(v, len), conv, sink)}; } StringPtrConvertResult FormatConvertImpl(const wchar_t* v, const FormatConversionSpecImpl conv, FormatSinkImpl* sink) { if (conv.conversion_char() == FormatConversionCharInternal::p) { return {FormatConvertImpl(VoidPtr(v), conv, sink).value}; } size_t len; if (v == nullptr) { len = 0; } else if (conv.precision() < 0) { len = std::wcslen(v); } else { len = static_cast<size_t>(std::find(v, v + conv.precision(), L'\0') - v); } return {ConvertStringArg(v, len, conv, sink)}; } StringPtrConvertResult FormatConvertImpl(std::nullptr_t, const FormatConversionSpecImpl conv, FormatSinkImpl* sink) { return FormatConvertImpl(static_cast<const char*>(nullptr), conv, sink); } ArgConvertResult<FormatConversionCharSetInternal::p> FormatConvertImpl( VoidPtr v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { if (!v.value) { sink->Append("(nil)"); return {true}; } IntDigits as_digits; as_digits.PrintAsHexLower(v.value); return {ConvertIntImplInnerSlow(as_digits, conv, sink)}; } FloatingConvertResult FormatConvertImpl(float v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertFloatArg(v, conv, sink)}; } FloatingConvertResult FormatConvertImpl(double v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertFloatArg(v, conv, sink)}; } FloatingConvertResult FormatConvertImpl(long double v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertFloatArg(v, conv, sink)}; } CharConvertResult FormatConvertImpl(char v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } CharConvertResult FormatConvertImpl(wchar_t v, const FormatConversionSpecImpl conv, FormatSinkImpl* sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(signed char v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(unsigned char v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(short v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(unsigned short v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(int v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(unsigned v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(long v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(unsigned long v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(long long v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(unsigned long long v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(absl::int128 v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } IntegralConvertResult FormatConvertImpl(absl::uint128 v, const FormatConversionSpecImpl conv, FormatSinkImpl *sink) { return {ConvertIntArg(v, conv, sink)}; } ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_(); } ABSL_NAMESPACE_END }
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/arg.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/arg_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
61865ce6-0174-448b-a44e-f550f1411f73
cpp
abseil/abseil-cpp
output
absl/strings/internal/str_format/output.cc
absl/strings/internal/str_format/output_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/output.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/output_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
a6800de3-849c-48b0-9041-0987170573d6
cpp
abseil/abseil-cpp
bind
absl/strings/internal/str_format/bind.cc
absl/strings/internal/str_format/bind_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/bind.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/bind_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
9f3814bc-04c6-4fb0-bea8-19533f866030
cpp
abseil/abseil-cpp
parser
absl/strings/internal/str_format/parser.cc
absl/strings/internal/str_format/parser_test.cc
#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 }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/parser.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/parser_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
99e0ea1b-a681-4414-8060-f0272fd44c2a
cpp
abseil/abseil-cpp
extension
absl/strings/internal/str_format/extension.cc
absl/strings/internal/str_format/extension_test.cc
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/extension.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/extension_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
9722a3da-f201-47f3-8264-7d91231aa0cb
cpp
abseil/abseil-cpp
parse
absl/flags/parse.cc
absl/flags/parse_test.cc
#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 = input_args.back().FrontIndex(); arg_index < static_cast<size_t>(argc); ++arg_index) { positional_args.push_back(argv[arg_index]); } } specified_flags->shrink_to_fit(); std::sort(specified_flags->begin(), specified_flags->end(), flags_internal::SpecifiedFlagsCompare{}); std::vector<UnrecognizedFlag> filtered; filtered.reserve(unrecognized_flags.size()); for (const auto& unrecognized : unrecognized_flags) { if (flags_internal::CanIgnoreUndefinedFlag(unrecognized.flag_name)) continue; filtered.push_back(unrecognized); } std::swap(unrecognized_flags, filtered); if (!success) { #if ABSL_FLAGS_STRIP_NAMES flags_internal::ReportUsageError( "NOTE: command line flags are disabled in this build", true); #else flags_internal::HandleUsageFlags(std::cerr, ProgramUsageMessage()); #endif return HelpMode::kFull; } return usage_flag_action == UsageFlagsAction::kHandleUsage ? flags_internal::HandleUsageFlags(std::cout, ProgramUsageMessage()) : HelpMode::kNone; } } void ParseAbseilFlagsOnly(int argc, char* argv[], std::vector<char*>& positional_args, std::vector<UnrecognizedFlag>& unrecognized_flags) { auto help_mode = flags_internal::ParseAbseilFlagsOnlyImpl( argc, argv, positional_args, unrecognized_flags, flags_internal::UsageFlagsAction::kHandleUsage); flags_internal::MaybeExit(help_mode); } void ReportUnrecognizedFlags( const std::vector<UnrecognizedFlag>& unrecognized_flags) { flags_internal::ReportUnrecognizedFlags(unrecognized_flags, true); } std::vector<char*> ParseCommandLine(int argc, char* argv[]) { return flags_internal::ParseCommandLineImpl( argc, argv, flags_internal::UsageFlagsAction::kHandleUsage, flags_internal::OnUndefinedFlag::kAbortIfUndefined); } ABSL_NAMESPACE_END }
#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"))); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/parse.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/parse_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
3ec14302-5a69-4a3f-b8cd-f1cb4b4633c8
cpp
abseil/abseil-cpp
usage
absl/flags/internal/usage.cc
absl/flags/internal/usage_test.cc
#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(); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/usage.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/usage_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
2dbc3bb9-9f0d-4727-be03-8810e34b02b3
cpp
abseil/abseil-cpp
reflection
absl/flags/reflection.cc
absl/flags/reflection_test.cc
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/reflection.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/reflection_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
124ce3af-8573-40e2-9097-e788f3cff240
cpp
abseil/abseil-cpp
usage_config
absl/flags/usage_config.cc
absl/flags/usage_config_test.cc
#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("\\\\"), ""); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/usage_config.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/usage_config_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
921b0b79-ebce-45ca-b982-602abe0d6c51
cpp
abseil/abseil-cpp
marshalling
absl/flags/marshalling.cc
absl/flags/marshalling_test.cc
#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_EQ(absl::UnparseFlag(value), "123456789"); value = -987654321L; EXPECT_EQ(absl::UnparseFlag(value), "-987654321"); value = 0x7FFFFFFFFFFFFFFF; EXPECT_EQ(absl::UnparseFlag(value), "9223372036854775807"); } TEST(MarshallingTest, TestUint128Unparsing) { absl::uint128 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 = absl::MakeUint128(0, 0xFFFFFFFFFFFFFFFF); EXPECT_EQ(absl::UnparseFlag(value), "18446744073709551615"); } TEST(MarshallingTest, TestFloatUnparsing) { float value; value = 1.1f; EXPECT_EQ(absl::UnparseFlag(value), "1.1"); value = 0.01f; EXPECT_EQ(absl::UnparseFlag(value), "0.01"); value = 1.23e-2f; EXPECT_EQ(absl::UnparseFlag(value), "0.0123"); value = -0.71f; EXPECT_EQ(absl::UnparseFlag(value), "-0.71"); } TEST(MarshallingTest, TestDoubleUnparsing) { double value; value = 1.1; EXPECT_EQ(absl::UnparseFlag(value), "1.1"); value = 0.01; EXPECT_EQ(absl::UnparseFlag(value), "0.01"); value = 1.23e-2; EXPECT_EQ(absl::UnparseFlag(value), "0.0123"); value = -0.71; EXPECT_EQ(absl::UnparseFlag(value), "-0.71"); value = -0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = std::nan(""); EXPECT_EQ(absl::UnparseFlag(value), "nan"); value = std::numeric_limits<double>::infinity(); EXPECT_EQ(absl::UnparseFlag(value), "inf"); } TEST(MarshallingTest, TestStringUnparsing) { EXPECT_EQ(absl::UnparseFlag(""), ""); EXPECT_EQ(absl::UnparseFlag(" "), " "); EXPECT_EQ(absl::UnparseFlag("qwerty"), "qwerty"); EXPECT_EQ(absl::UnparseFlag("ASDFGH"), "ASDFGH"); EXPECT_EQ(absl::UnparseFlag("\n\t "), "\n\t "); } TEST(MarshallingTest, TestOptionalBoolUnparsing) { absl::optional<bool> value; EXPECT_EQ(absl::UnparseFlag(value), ""); value = true; EXPECT_EQ(absl::UnparseFlag(value), "true"); value = false; EXPECT_EQ(absl::UnparseFlag(value), "false"); value = absl::nullopt; EXPECT_EQ(absl::UnparseFlag(value), ""); } TEST(MarshallingTest, TestOptionalIntUnparsing) { absl::optional<int> value; EXPECT_EQ(absl::UnparseFlag(value), ""); value = 0; EXPECT_EQ(absl::UnparseFlag(value), "0"); value = -12; EXPECT_EQ(absl::UnparseFlag(value), "-12"); value = absl::nullopt; EXPECT_EQ(absl::UnparseFlag(value), ""); } TEST(MarshallingTest, TestOptionalDoubleUnparsing) { absl::optional<double> value; EXPECT_EQ(absl::UnparseFlag(value), ""); value = 1.; EXPECT_EQ(absl::UnparseFlag(value), "1"); value = -1.23; EXPECT_EQ(absl::UnparseFlag(value), "-1.23"); value = absl::nullopt; EXPECT_EQ(absl::UnparseFlag(value), ""); } TEST(MarshallingTest, TestOptionalStringUnparsing) { absl::optional<std::string> strvalue; EXPECT_EQ(absl::UnparseFlag(strvalue), ""); strvalue = "asdfg"; EXPECT_EQ(absl::UnparseFlag(strvalue), "asdfg"); strvalue = " "; EXPECT_EQ(absl::UnparseFlag(strvalue), " "); strvalue = ""; EXPECT_EQ(absl::UnparseFlag(strvalue), ""); } #if defined(ABSL_HAVE_STD_OPTIONAL) && !defined(ABSL_USES_STD_OPTIONAL) TEST(MarshallingTest, TestStdOptionalUnparsing) { std::optional<std::string> strvalue; EXPECT_EQ(absl::UnparseFlag(strvalue), ""); strvalue = "asdfg"; EXPECT_EQ(absl::UnparseFlag(strvalue), "asdfg"); strvalue = " "; EXPECT_EQ(absl::UnparseFlag(strvalue), " "); strvalue = ""; EXPECT_EQ(absl::UnparseFlag(strvalue), ""); std::optional<int> intvalue; EXPECT_EQ(absl::UnparseFlag(intvalue), ""); intvalue = 10; EXPECT_EQ(absl::UnparseFlag(intvalue), "10"); } #endif template <typename T> void TestRoundtrip(T v) { T new_v; std::string err; EXPECT_TRUE(absl::ParseFlag(absl::UnparseFlag(v), &new_v, &err)); EXPECT_EQ(new_v, v); } TEST(MarshallingTest, TestFloatRoundTrip) { TestRoundtrip(0.1f); TestRoundtrip(0.12f); TestRoundtrip(0.123f); TestRoundtrip(0.1234f); TestRoundtrip(0.12345f); TestRoundtrip(0.123456f); TestRoundtrip(0.1234567f); TestRoundtrip(0.12345678f); TestRoundtrip(0.1e20f); TestRoundtrip(0.12e20f); TestRoundtrip(0.123e20f); TestRoundtrip(0.1234e20f); TestRoundtrip(0.12345e20f); TestRoundtrip(0.123456e20f); TestRoundtrip(0.1234567e20f); TestRoundtrip(0.12345678e20f); TestRoundtrip(0.1e-20f); TestRoundtrip(0.12e-20f); TestRoundtrip(0.123e-20f); TestRoundtrip(0.1234e-20f); TestRoundtrip(0.12345e-20f); TestRoundtrip(0.123456e-20f); TestRoundtrip(0.1234567e-20f); TestRoundtrip(0.12345678e-20f); } TEST(MarshallingTest, TestDoubleRoundTrip) { TestRoundtrip(0.1); TestRoundtrip(0.12); TestRoundtrip(0.123); TestRoundtrip(0.1234); TestRoundtrip(0.12345); TestRoundtrip(0.123456); TestRoundtrip(0.1234567); TestRoundtrip(0.12345678); TestRoundtrip(0.123456789); TestRoundtrip(0.1234567891); TestRoundtrip(0.12345678912); TestRoundtrip(0.123456789123); TestRoundtrip(0.1234567891234); TestRoundtrip(0.12345678912345); TestRoundtrip(0.123456789123456); TestRoundtrip(0.1234567891234567); TestRoundtrip(0.12345678912345678); TestRoundtrip(0.1e50); TestRoundtrip(0.12e50); TestRoundtrip(0.123e50); TestRoundtrip(0.1234e50); TestRoundtrip(0.12345e50); TestRoundtrip(0.123456e50); TestRoundtrip(0.1234567e50); TestRoundtrip(0.12345678e50); TestRoundtrip(0.123456789e50); TestRoundtrip(0.1234567891e50); TestRoundtrip(0.12345678912e50); TestRoundtrip(0.123456789123e50); TestRoundtrip(0.1234567891234e50); TestRoundtrip(0.12345678912345e50); TestRoundtrip(0.123456789123456e50); TestRoundtrip(0.1234567891234567e50); TestRoundtrip(0.12345678912345678e50); TestRoundtrip(0.1e-50); TestRoundtrip(0.12e-50); TestRoundtrip(0.123e-50); TestRoundtrip(0.1234e-50); TestRoundtrip(0.12345e-50); TestRoundtrip(0.123456e-50); TestRoundtrip(0.1234567e-50); TestRoundtrip(0.12345678e-50); TestRoundtrip(0.123456789e-50); TestRoundtrip(0.1234567891e-50); TestRoundtrip(0.12345678912e-50); TestRoundtrip(0.123456789123e-50); TestRoundtrip(0.1234567891234e-50); TestRoundtrip(0.12345678912345e-50); TestRoundtrip(0.123456789123456e-50); TestRoundtrip(0.1234567891234567e-50); TestRoundtrip(0.12345678912345678e-50); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/marshalling.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/marshalling_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
1fc6fda9-8140-4f7a-9e71-44fa235ca800
cpp
abseil/abseil-cpp
commandlineflag
absl/flags/internal/commandlineflag.cc
absl/flags/commandlineflag_test.cc
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/commandlineflag.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/commandlineflag_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5945563f-208f-42bb-a922-d6e8a9c97005
cpp
abseil/abseil-cpp
program_name
absl/flags/internal/program_name.cc
absl/flags/internal/program_name_test.cc
#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"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/program_name.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/program_name_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
17c1c1cb-7043-484e-958b-7e161aa5da2d
cpp
abseil/abseil-cpp
flag
absl/flags/internal/flag.cc
absl/time/flag_test.cc
#include "absl/flags/internal/flag.h" #include <assert.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <array> #include <atomic> #include <cstring> #include <memory> #include <string> #include <typeinfo> #include <vector> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/const_init.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_; }; ABSL_CONST_INIT absl::Mutex s_freelist_guard(absl::kConstInit); ABSL_CONST_INIT std::vector<void*>* s_freelist = nullptr; void AddToFreelist(void* p) { absl::MutexLock l(&s_freelist_guard); if (!s_freelist) { s_freelist = new std::vector<void*>; } s_freelist->push_back(p); } } uint64_t NumLeakedFlagValues() { absl::MutexLock l(&s_freelist_guard); return s_freelist == nullptr ? 0u : s_freelist->size(); } 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::kHeapAllocated && 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_; }; DynValueDeleter::DynValueDeleter(FlagOpFn op_arg) : op(op_arg) {} void DynValueDeleter::operator()(void* ptr) const { if (op == nullptr) return; Delete(op, ptr); } MaskedPointer::MaskedPointer(ptr_t rhs, bool is_candidate) : ptr_(rhs) { if (is_candidate) { ApplyMask(kUnprotectedReadCandidate); } } bool MaskedPointer::IsUnprotectedReadCandidate() const { return CheckMask(kUnprotectedReadCandidate); } bool MaskedPointer::HasBeenRead() const { return CheckMask(kHasBeenRead); } void MaskedPointer::Set(FlagOpFn op, const void* src, bool is_candidate) { flags_internal::Copy(op, src, Ptr()); if (is_candidate) { ApplyMask(kUnprotectedReadCandidate); } } void MaskedPointer::MarkAsRead() { ApplyMask(kHasBeenRead); } void MaskedPointer::ApplyMask(mask_t mask) { ptr_ = reinterpret_cast<ptr_t>(reinterpret_cast<mask_t>(ptr_) | mask); } bool MaskedPointer::CheckMask(mask_t mask) const { return (reinterpret_cast<mask_t>(ptr_) & mask) != 0; } void FlagImpl::Init() { new (&data_guard_) absl::Mutex; auto def_kind = static_cast<FlagDefaultKind>(def_kind_); switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: { alignas(int64_t) std::array<char, sizeof(int64_t)> buf{}; if (def_kind == FlagDefaultKind::kGenFunc) { (*default_value_.gen_func)(buf.data()); } else { assert(def_kind != FlagDefaultKind::kDynamicValue); std::memcpy(buf.data(), &default_value_, Sizeof(op_)); } if (ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit) { uint8_t initialized = 1; std::memcpy(buf.data() + Sizeof(op_), &initialized, sizeof(initialized)); } ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(buf.data(), buf.size()); OneWordValue().store(absl::bit_cast<int64_t>(buf), std::memory_order_release); break; } case FlagValueStorageKind::kSequenceLocked: { assert(def_kind == FlagDefaultKind::kGenFunc); (*default_value_.gen_func)(AtomicBufferValue()); break; } case FlagValueStorageKind::kHeapAllocated: assert(def_kind == FlagDefaultKind::kGenFunc); MaskedPointer ptr_value = PtrStorage().load(std::memory_order_acquire); (*default_value_.gen_func)(ptr_value.Ptr()); PtrStorage().store(MaskedPointer(ptr_value.Ptr(), true), std::memory_order_release); break; } seq_lock_.MarkInitialized(); } absl::Mutex* FlagImpl::DataGuard() const { absl::call_once(const_cast<FlagImpl*>(this)->init_control_, &FlagImpl::Init, const_cast<FlagImpl*>(this)); return reinterpret_cast<absl::Mutex*>(&data_guard_); } void FlagImpl::AssertValidType(FlagFastTypeId rhs_type_id, const std::type_info* (*gen_rtti)()) const { FlagFastTypeId lhs_type_id = flags_internal::FastTypeId(op_); if (ABSL_PREDICT_TRUE(lhs_type_id == rhs_type_id)) return; const std::type_info* lhs_runtime_type_id = flags_internal::RuntimeTypeId(op_); const std::type_info* rhs_runtime_type_id = (*gen_rtti)(); if (lhs_runtime_type_id == rhs_runtime_type_id) return; #ifdef ABSL_INTERNAL_HAS_RTTI if (*lhs_runtime_type_id == *rhs_runtime_type_id) return; #endif ABSL_INTERNAL_LOG( FATAL, absl::StrCat("Flag '", Name(), "' is defined as one type and declared as another")); } std::unique_ptr<void, DynValueDeleter> FlagImpl::MakeInitValue() const { void* res = nullptr; switch (DefaultKind()) { case FlagDefaultKind::kDynamicValue: res = flags_internal::Clone(op_, default_value_.dynamic_value); break; case FlagDefaultKind::kGenFunc: res = flags_internal::Alloc(op_); (*default_value_.gen_func)(res); break; default: res = flags_internal::Clone(op_, &default_value_); break; } return {res, DynValueDeleter{op_}}; } void FlagImpl::StoreValue(const void* src, ValueSource source) { switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: { int64_t one_word_val = OneWordValue().load(std::memory_order_acquire); std::memcpy(&one_word_val, src, Sizeof(op_)); OneWordValue().store(one_word_val, std::memory_order_release); seq_lock_.IncrementModificationCount(); break; } case FlagValueStorageKind::kSequenceLocked: { seq_lock_.Write(AtomicBufferValue(), src, Sizeof(op_)); break; } case FlagValueStorageKind::kHeapAllocated: MaskedPointer ptr_value = PtrStorage().load(std::memory_order_acquire); if (ptr_value.IsUnprotectedReadCandidate() && ptr_value.HasBeenRead()) { AddToFreelist(ptr_value.Ptr()); ptr_value = MaskedPointer(Clone(op_, src), source == kCommandLine); } else { ptr_value.Set(op_, src, source == kCommandLine); } PtrStorage().store(ptr_value, std::memory_order_release); seq_lock_.IncrementModificationCount(); break; } modified_ = true; InvokeCallback(); } absl::string_view FlagImpl::Name() const { return name_; } std::string FlagImpl::Filename() const { return flags_internal::GetUsageConfig().normalize_filename(filename_); } std::string FlagImpl::Help() const { return HelpSourceKind() == FlagHelpKind::kLiteral ? help_.literal : help_.gen_func(); } FlagFastTypeId FlagImpl::TypeId() const { return flags_internal::FastTypeId(op_); } int64_t FlagImpl::ModificationCount() const { return seq_lock_.ModificationCount(); } bool FlagImpl::IsSpecifiedOnCommandLine() const { absl::MutexLock l(DataGuard()); return on_command_line_; } std::string FlagImpl::DefaultValue() const { absl::MutexLock l(DataGuard()); auto obj = MakeInitValue(); return flags_internal::Unparse(op_, obj.get()); } std::string FlagImpl::CurrentValue() const { auto* guard = DataGuard(); switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: { const auto one_word_val = absl::bit_cast<std::array<char, sizeof(int64_t)>>( OneWordValue().load(std::memory_order_acquire)); return flags_internal::Unparse(op_, one_word_val.data()); } case FlagValueStorageKind::kSequenceLocked: { std::unique_ptr<void, DynValueDeleter> cloned(flags_internal::Alloc(op_), DynValueDeleter{op_}); ReadSequenceLockedData(cloned.get()); return flags_internal::Unparse(op_, cloned.get()); } case FlagValueStorageKind::kHeapAllocated: { absl::MutexLock l(guard); return flags_internal::Unparse( op_, PtrStorage().load(std::memory_order_acquire).Ptr()); } } return ""; } void FlagImpl::SetCallback(const FlagCallbackFunc mutation_callback) { absl::MutexLock l(DataGuard()); if (callback_ == nullptr) { callback_ = new FlagCallback; } callback_->func = mutation_callback; InvokeCallback(); } void FlagImpl::InvokeCallback() const { if (!callback_) return; FlagCallbackFunc cb = callback_->func; MutexRelock relock(*DataGuard()); absl::MutexLock lock(&callback_->guard); cb(); } std::unique_ptr<FlagStateInterface> FlagImpl::SaveState() { absl::MutexLock l(DataGuard()); bool modified = modified_; bool on_command_line = on_command_line_; switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: { return absl::make_unique<FlagState>( *this, OneWordValue().load(std::memory_order_acquire), modified, on_command_line, ModificationCount()); } case FlagValueStorageKind::kSequenceLocked: { void* cloned = flags_internal::Alloc(op_); bool success = seq_lock_.TryRead(cloned, AtomicBufferValue(), Sizeof(op_)); assert(success); static_cast<void>(success); return absl::make_unique<FlagState>(*this, cloned, modified, on_command_line, ModificationCount()); } case FlagValueStorageKind::kHeapAllocated: { return absl::make_unique<FlagState>( *this, flags_internal::Clone( op_, PtrStorage().load(std::memory_order_acquire).Ptr()), modified, on_command_line, ModificationCount()); } } return nullptr; } bool FlagImpl::RestoreState(const FlagState& flag_state) { absl::MutexLock l(DataGuard()); if (flag_state.counter_ == ModificationCount()) { return false; } switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: StoreValue(&flag_state.value_.one_word, kProgrammaticChange); break; case FlagValueStorageKind::kSequenceLocked: case FlagValueStorageKind::kHeapAllocated: StoreValue(flag_state.value_.heap_allocated, kProgrammaticChange); break; } modified_ = flag_state.modified_; on_command_line_ = flag_state.on_command_line_; return true; } template <typename StorageT> StorageT* FlagImpl::OffsetValue() const { char* p = reinterpret_cast<char*>(const_cast<FlagImpl*>(this)); ptrdiff_t offset = flags_internal::ValueOffset(op_); return reinterpret_cast<StorageT*>(p + offset); } std::atomic<uint64_t>* FlagImpl::AtomicBufferValue() const { assert(ValueStorageKind() == FlagValueStorageKind::kSequenceLocked); return OffsetValue<std::atomic<uint64_t>>(); } std::atomic<int64_t>& FlagImpl::OneWordValue() const { assert(ValueStorageKind() == FlagValueStorageKind::kOneWordAtomic || ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit); return OffsetValue<FlagOneWordValue>()->value; } std::atomic<MaskedPointer>& FlagImpl::PtrStorage() const { assert(ValueStorageKind() == FlagValueStorageKind::kHeapAllocated); return OffsetValue<FlagMaskedPointerValue>()->value; } std::unique_ptr<void, DynValueDeleter> FlagImpl::TryParse( absl::string_view value, std::string& err) const { std::unique_ptr<void, DynValueDeleter> tentative_value = MakeInitValue(); std::string parse_err; if (!flags_internal::Parse(op_, value, tentative_value.get(), &parse_err)) { absl::string_view err_sep = parse_err.empty() ? "" : "; "; err = absl::StrCat("Illegal value '", value, "' specified for flag '", Name(), "'", err_sep, parse_err); return nullptr; } return tentative_value; } void FlagImpl::Read(void* dst) const { auto* guard = DataGuard(); switch (ValueStorageKind()) { case FlagValueStorageKind::kValueAndInitBit: case FlagValueStorageKind::kOneWordAtomic: { const int64_t one_word_val = OneWordValue().load(std::memory_order_acquire); std::memcpy(dst, &one_word_val, Sizeof(op_)); break; } case FlagValueStorageKind::kSequenceLocked: { ReadSequenceLockedData(dst); break; } case FlagValueStorageKind::kHeapAllocated: { absl::MutexLock l(guard); MaskedPointer ptr_value = PtrStorage().load(std::memory_order_acquire); flags_internal::CopyConstruct(op_, ptr_value.Ptr(), dst); if (ptr_value.IsUnprotectedReadCandidate() && !ptr_value.HasBeenRead()) { ptr_value.MarkAsRead(); PtrStorage().store(ptr_value, std::memory_order_release); } break; } } } int64_t FlagImpl::ReadOneWord() const { assert(ValueStorageKind() == FlagValueStorageKind::kOneWordAtomic || ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit); auto* guard = DataGuard(); (void)guard; return OneWordValue().load(std::memory_order_acquire); } bool FlagImpl::ReadOneBool() const { assert(ValueStorageKind() == FlagValueStorageKind::kValueAndInitBit); auto* guard = DataGuard(); (void)guard; return absl::bit_cast<FlagValueAndInitBit<bool>>( OneWordValue().load(std::memory_order_acquire)) .value; } void FlagImpl::ReadSequenceLockedData(void* dst) const { size_t size = Sizeof(op_); if (ABSL_PREDICT_TRUE(seq_lock_.TryRead(dst, AtomicBufferValue(), size))) { return; } absl::ReaderMutexLock l(DataGuard()); bool success = seq_lock_.TryRead(dst, AtomicBufferValue(), size); assert(success); static_cast<void>(success); } void FlagImpl::Write(const void* src) { absl::MutexLock l(DataGuard()); if (ShouldValidateFlagValue(flags_internal::FastTypeId(op_))) { std::unique_ptr<void, DynValueDeleter> obj{flags_internal::Clone(op_, src), DynValueDeleter{op_}}; std::string ignored_error; std::string src_as_str = flags_internal::Unparse(op_, src); if (!flags_internal::Parse(op_, src_as_str, obj.get(), &ignored_error)) { ABSL_INTERNAL_LOG(ERROR, absl::StrCat("Attempt to set flag '", Name(), "' to invalid value ", src_as_str)); } } StoreValue(src, kProgrammaticChange); } bool FlagImpl::ParseFrom(absl::string_view value, FlagSettingMode set_mode, ValueSource source, std::string& err) { absl::MutexLock l(DataGuard()); switch (set_mode) { case SET_FLAGS_VALUE: { auto tentative_value = TryParse(value, err); if (!tentative_value) return false; StoreValue(tentative_value.get(), source); if (source == kCommandLine) { on_command_line_ = true; } break; } case SET_FLAG_IF_DEFAULT: { if (modified_) { return true; } auto tentative_value = TryParse(value, err); if (!tentative_value) return false; StoreValue(tentative_value.get(), source); break; } case SET_FLAGS_DEFAULT: { auto tentative_value = TryParse(value, err); if (!tentative_value) return false; if (DefaultKind() == FlagDefaultKind::kDynamicValue) { void* old_value = default_value_.dynamic_value; default_value_.dynamic_value = tentative_value.release(); tentative_value.reset(old_value); } else { default_value_.dynamic_value = tentative_value.release(); def_kind_ = static_cast<uint8_t>(FlagDefaultKind::kDynamicValue); } if (!modified_) { StoreValue(default_value_.dynamic_value, source); modified_ = false; } break; } } return true; } void FlagImpl::CheckDefaultValueParsingRoundtrip() const { std::string v = DefaultValue(); absl::MutexLock lock(DataGuard()); auto dst = MakeInitValue(); std::string error; if (!flags_internal::Parse(op_, v, dst.get(), &error)) { ABSL_INTERNAL_LOG( FATAL, absl::StrCat("Flag ", Name(), " (from ", Filename(), "): string form of default value '", v, "' could not be parsed; error=", error)); } } bool FlagImpl::ValidateInputValue(absl::string_view value) const { absl::MutexLock l(DataGuard()); auto obj = MakeInitValue(); std::string ignored_error; return flags_internal::Parse(op_, value, obj.get(), &ignored_error); } } ABSL_NAMESPACE_END }
#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); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/flag.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/flag_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
389afdcb-70bf-4bef-a959-45ba901616f2
cpp
abseil/abseil-cpp
blocking_counter
absl/synchronization/blocking_counter.cc
absl/synchronization/blocking_counter_test.cc
#include "absl/synchronization/blocking_counter.h" #include <atomic> #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/tracing.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) { base_internal::TraceSignal(this, TraceObjectKind()); MutexLock l(&lock_); done_ = true; return true; } return false; } void BlockingCounter::Wait() { base_internal::TraceWait(this, TraceObjectKind()); { MutexLock l(&this->lock_); ABSL_RAW_CHECK(num_waiting_ == 0, "multiple threads called Wait()"); num_waiting_++; this->lock_.Await(Condition(IsDone, &this->done_)); } base_internal::TraceContinue(this, TraceObjectKind()); } ABSL_NAMESPACE_END }
#include "absl/synchronization/blocking_counter.h" #include <thread> #include <tuple> #include <vector> #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/tracing.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 } #if ABSL_HAVE_ATTRIBUTE_WEAK namespace base_internal { namespace { using TraceRecord = std::tuple<const void*, ObjectKind>; thread_local TraceRecord tls_signal; thread_local TraceRecord tls_wait; thread_local TraceRecord tls_continue; } extern "C" { void ABSL_INTERNAL_C_SYMBOL(AbslInternalTraceWait)(const void* object, ObjectKind kind) { tls_wait = {object, kind}; } void ABSL_INTERNAL_C_SYMBOL(AbslInternalTraceContinue)(const void* object, ObjectKind kind) { tls_continue = {object, kind}; } void ABSL_INTERNAL_C_SYMBOL(AbslInternalTraceSignal)(const void* object, ObjectKind kind) { tls_signal = {object, kind}; } } TEST(BlockingCounterTest, TracesSignal) { BlockingCounter counter(2); tls_signal = {}; counter.DecrementCount(); EXPECT_EQ(tls_signal, TraceRecord(nullptr, ObjectKind::kUnknown)); tls_signal = {}; counter.DecrementCount(); EXPECT_EQ(tls_signal, TraceRecord(&counter, ObjectKind::kBlockingCounter)); } TEST(BlockingCounterTest, TracesWaitContinue) { BlockingCounter counter(1); counter.DecrementCount(); tls_wait = {}; tls_continue = {}; counter.Wait(); EXPECT_EQ(tls_wait, TraceRecord(&counter, ObjectKind::kBlockingCounter)); EXPECT_EQ(tls_continue, TraceRecord(&counter, ObjectKind::kBlockingCounter)); } } #endif ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/blocking_counter.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/blocking_counter_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
77bb6f69-f3ad-456a-9ead-66283c2d0924
cpp
abseil/abseil-cpp
mutex
absl/synchronization/mutex.cc
absl/synchronization/mutex_test.cc
#include "absl/synchronization/mutex.h" #ifdef _WIN32 #include <windows.h> #ifdef ERROR #undef ERROR #endif #else #include <fcntl.h> #include <pthread.h> #include <sched.h> #include <sys/time.h> #endif #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <algorithm> #include <atomic> #include <cstddef> #include <cstdlib> #include <cstring> #include <thread> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/base/config.h" #include "absl/base/dynamic_annotations.h" #include "absl/base/internal/atomic_hook.h" #include "absl/base/internal/cycleclock.h" #include "absl/base/internal/hide_ptr.h" #include "absl/base/internal/low_level_alloc.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/spinlock.h" #include "absl/base/internal/sysinfo.h" #include "absl/base/internal/thread_identity.h" #include "absl/base/internal/tsan_mutex_interface.h" #include "absl/base/optimization.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/synchronization/internal/graphcycles.h" #include "absl/synchronization/internal/per_thread_sem.h" #include "absl/time/time.h" using absl::base_internal::CurrentThreadIdentityIfPresent; using absl::base_internal::CycleClock; using absl::base_internal::PerThreadSynch; using absl::base_internal::SchedulingGuard; using absl::base_internal::ThreadIdentity; using absl::synchronization_internal::GetOrCreateCurrentThreadIdentity; using absl::synchronization_internal::GraphCycles; using absl::synchronization_internal::GraphId; using absl::synchronization_internal::InvalidGraphId; using absl::synchronization_internal::KernelTimeout; using absl::synchronization_internal::PerThreadSem; extern "C" { ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)() { std::this_thread::yield(); } } namespace absl { ABSL_NAMESPACE_BEGIN namespace { #if defined(ABSL_HAVE_THREAD_SANITIZER) constexpr OnDeadlockCycle kDeadlockDetectionDefault = OnDeadlockCycle::kIgnore; #else constexpr OnDeadlockCycle kDeadlockDetectionDefault = OnDeadlockCycle::kAbort; #endif ABSL_CONST_INIT std::atomic<OnDeadlockCycle> synch_deadlock_detection( kDeadlockDetectionDefault); ABSL_CONST_INIT std::atomic<bool> synch_check_invariants(false); ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<void (*)(int64_t wait_cycles)> submit_profile_data; ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<void (*)( const char* msg, const void* obj, int64_t wait_cycles)> mutex_tracer; ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<void (*)(const char* msg, const void* cv)> cond_var_tracer; } static inline bool EvalConditionAnnotated(const Condition* cond, Mutex* mu, bool locking, bool trylock, bool read_lock); void RegisterMutexProfiler(void (*fn)(int64_t wait_cycles)) { submit_profile_data.Store(fn); } void RegisterMutexTracer(void (*fn)(const char* msg, const void* obj, int64_t wait_cycles)) { mutex_tracer.Store(fn); } void RegisterCondVarTracer(void (*fn)(const char* msg, const void* cv)) { cond_var_tracer.Store(fn); } namespace { enum DelayMode { AGGRESSIVE, GENTLE }; struct ABSL_CACHELINE_ALIGNED MutexGlobals { absl::once_flag once; std::atomic<int> spinloop_iterations{0}; int32_t mutex_sleep_spins[2] = {}; absl::Duration mutex_sleep_time; }; ABSL_CONST_INIT static MutexGlobals globals; absl::Duration MeasureTimeToYield() { absl::Time before = absl::Now(); ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)(); return absl::Now() - before; } const MutexGlobals& GetMutexGlobals() { absl::base_internal::LowLevelCallOnce(&globals.once, [&]() { if (absl::base_internal::NumCPUs() > 1) { globals.mutex_sleep_spins[AGGRESSIVE] = 5000; globals.mutex_sleep_spins[GENTLE] = 250; globals.mutex_sleep_time = absl::Microseconds(10); } else { globals.mutex_sleep_spins[AGGRESSIVE] = 0; globals.mutex_sleep_spins[GENTLE] = 0; globals.mutex_sleep_time = MeasureTimeToYield() * 5; globals.mutex_sleep_time = std::min(globals.mutex_sleep_time, absl::Milliseconds(1)); globals.mutex_sleep_time = std::max(globals.mutex_sleep_time, absl::Microseconds(10)); } }); return globals; } } namespace synchronization_internal { int MutexDelay(int32_t c, int mode) { const int32_t limit = GetMutexGlobals().mutex_sleep_spins[mode]; const absl::Duration sleep_time = GetMutexGlobals().mutex_sleep_time; if (c < limit) { c++; } else { SchedulingGuard::ScopedEnable enable_rescheduling; ABSL_TSAN_MUTEX_PRE_DIVERT(nullptr, 0); if (c == limit) { ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)(); c++; } else { absl::SleepFor(sleep_time); c = 0; } ABSL_TSAN_MUTEX_POST_DIVERT(nullptr, 0); } return c; } } static bool AtomicSetBits(std::atomic<intptr_t>* pv, intptr_t bits, intptr_t wait_until_clear) { for (;;) { intptr_t v = pv->load(std::memory_order_relaxed); if ((v & bits) == bits) { return false; } if ((v & wait_until_clear) != 0) { continue; } if (pv->compare_exchange_weak(v, v | bits, std::memory_order_release, std::memory_order_relaxed)) { return true; } } } ABSL_CONST_INIT static absl::base_internal::SpinLock deadlock_graph_mu( absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY); ABSL_CONST_INIT static GraphCycles* deadlock_graph ABSL_GUARDED_BY(deadlock_graph_mu) ABSL_PT_GUARDED_BY(deadlock_graph_mu); namespace { enum { SYNCH_EV_TRYLOCK_SUCCESS, SYNCH_EV_TRYLOCK_FAILED, SYNCH_EV_READERTRYLOCK_SUCCESS, SYNCH_EV_READERTRYLOCK_FAILED, SYNCH_EV_LOCK, SYNCH_EV_LOCK_RETURNING, SYNCH_EV_READERLOCK, SYNCH_EV_READERLOCK_RETURNING, SYNCH_EV_UNLOCK, SYNCH_EV_READERUNLOCK, SYNCH_EV_WAIT, SYNCH_EV_WAIT_RETURNING, SYNCH_EV_SIGNAL, SYNCH_EV_SIGNALALL, }; enum { SYNCH_F_R = 0x01, SYNCH_F_LCK = 0x02, SYNCH_F_TRY = 0x04, SYNCH_F_UNLOCK = 0x08, SYNCH_F_LCK_W = SYNCH_F_LCK, SYNCH_F_LCK_R = SYNCH_F_LCK | SYNCH_F_R, }; } static const struct { int flags; const char* msg; } event_properties[] = { {SYNCH_F_LCK_W | SYNCH_F_TRY, "TryLock succeeded "}, {0, "TryLock failed "}, {SYNCH_F_LCK_R | SYNCH_F_TRY, "ReaderTryLock succeeded "}, {0, "ReaderTryLock failed "}, {0, "Lock blocking "}, {SYNCH_F_LCK_W, "Lock returning "}, {0, "ReaderLock blocking "}, {SYNCH_F_LCK_R, "ReaderLock returning "}, {SYNCH_F_LCK_W | SYNCH_F_UNLOCK, "Unlock "}, {SYNCH_F_LCK_R | SYNCH_F_UNLOCK, "ReaderUnlock "}, {0, "Wait on "}, {0, "Wait unblocked "}, {0, "Signal on "}, {0, "SignalAll on "}, }; ABSL_CONST_INIT static absl::base_internal::SpinLock synch_event_mu( absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY); static constexpr uint32_t kNSynchEvent = 1031; static struct SynchEvent { int refcount ABSL_GUARDED_BY(synch_event_mu); SynchEvent* next ABSL_GUARDED_BY(synch_event_mu); uintptr_t masked_addr; void (*invariant)(void* arg); void* arg; bool log; char name[1]; }* synch_event[kNSynchEvent] ABSL_GUARDED_BY(synch_event_mu); static SynchEvent* EnsureSynchEvent(std::atomic<intptr_t>* addr, const char* name, intptr_t bits, intptr_t lockbit) { uint32_t h = reinterpret_cast<uintptr_t>(addr) % kNSynchEvent; synch_event_mu.Lock(); constexpr size_t kMaxSynchEventCount = 100 << 10; static size_t synch_event_count ABSL_GUARDED_BY(synch_event_mu); if (++synch_event_count > kMaxSynchEventCount) { synch_event_count = 0; ABSL_RAW_LOG(ERROR, "Accumulated %zu Mutex debug objects. If you see this" " in production, it may mean that the production code" " accidentally calls " "Mutex/CondVar::EnableDebugLog/EnableInvariantDebugging.", kMaxSynchEventCount); for (auto*& head : synch_event) { for (auto* e = head; e != nullptr;) { SynchEvent* next = e->next; if (--(e->refcount) == 0) { base_internal::LowLevelAlloc::Free(e); } e = next; } head = nullptr; } } SynchEvent* e = nullptr; if (!AtomicSetBits(addr, bits, lockbit)) { for (e = synch_event[h]; e != nullptr && e->masked_addr != base_internal::HidePtr(addr); e = e->next) { } } if (e == nullptr) { if (name == nullptr) { name = ""; } size_t l = strlen(name); e = reinterpret_cast<SynchEvent*>( base_internal::LowLevelAlloc::Alloc(sizeof(*e) + l)); e->refcount = 2; e->masked_addr = base_internal::HidePtr(addr); e->invariant = nullptr; e->arg = nullptr; e->log = false; strcpy(e->name, name); e->next = synch_event[h]; synch_event[h] = e; } else { e->refcount++; } synch_event_mu.Unlock(); return e; } static void UnrefSynchEvent(SynchEvent* e) { if (e != nullptr) { synch_event_mu.Lock(); bool del = (--(e->refcount) == 0); synch_event_mu.Unlock(); if (del) { base_internal::LowLevelAlloc::Free(e); } } } static SynchEvent* GetSynchEvent(const void* addr) { uint32_t h = reinterpret_cast<uintptr_t>(addr) % kNSynchEvent; SynchEvent* e; synch_event_mu.Lock(); for (e = synch_event[h]; e != nullptr && e->masked_addr != base_internal::HidePtr(addr); e = e->next) { } if (e != nullptr) { e->refcount++; } synch_event_mu.Unlock(); return e; } static void PostSynchEvent(void* obj, int ev) { SynchEvent* e = GetSynchEvent(obj); if (e == nullptr || e->log) { void* pcs[40]; int n = absl::GetStackTrace(pcs, ABSL_ARRAYSIZE(pcs), 1); char buffer[ABSL_ARRAYSIZE(pcs) * 24]; int pos = snprintf(buffer, sizeof(buffer), " @"); for (int i = 0; i != n; i++) { int b = snprintf(&buffer[pos], sizeof(buffer) - static_cast<size_t>(pos), " %p", pcs[i]); if (b < 0 || static_cast<size_t>(b) >= sizeof(buffer) - static_cast<size_t>(pos)) { break; } pos += b; } ABSL_RAW_LOG(INFO, "%s%p %s %s", event_properties[ev].msg, obj, (e == nullptr ? "" : e->name), buffer); } const int flags = event_properties[ev].flags; if ((flags & SYNCH_F_LCK) != 0 && e != nullptr && e->invariant != nullptr) { struct local { static bool pred(SynchEvent* ev) { (*ev->invariant)(ev->arg); return false; } }; Condition cond(&local::pred, e); Mutex* mu = static_cast<Mutex*>(obj); const bool locking = (flags & SYNCH_F_UNLOCK) == 0; const bool trylock = (flags & SYNCH_F_TRY) != 0; const bool read_lock = (flags & SYNCH_F_R) != 0; EvalConditionAnnotated(&cond, mu, locking, trylock, read_lock); } UnrefSynchEvent(e); } struct SynchWaitParams { SynchWaitParams(Mutex::MuHow how_arg, const Condition* cond_arg, KernelTimeout timeout_arg, Mutex* cvmu_arg, PerThreadSynch* thread_arg, std::atomic<intptr_t>* cv_word_arg) : how(how_arg), cond(cond_arg), timeout(timeout_arg), cvmu(cvmu_arg), thread(thread_arg), cv_word(cv_word_arg), contention_start_cycles(CycleClock::Now()), should_submit_contention_data(false) {} const Mutex::MuHow how; const Condition* cond; KernelTimeout timeout; Mutex* const cvmu; PerThreadSynch* const thread; std::atomic<intptr_t>* cv_word; int64_t contention_start_cycles; bool should_submit_contention_data; }; struct SynchLocksHeld { int n; bool overflow; struct { Mutex* mu; int32_t count; GraphId id; } locks[40]; }; static PerThreadSynch* const kPerThreadSynchNull = reinterpret_cast<PerThreadSynch*>(1); static SynchLocksHeld* LocksHeldAlloc() { SynchLocksHeld* ret = reinterpret_cast<SynchLocksHeld*>( base_internal::LowLevelAlloc::Alloc(sizeof(SynchLocksHeld))); ret->n = 0; ret->overflow = false; return ret; } static PerThreadSynch* Synch_GetPerThread() { ThreadIdentity* identity = GetOrCreateCurrentThreadIdentity(); return &identity->per_thread_synch; } static PerThreadSynch* Synch_GetPerThreadAnnotated(Mutex* mu) { if (mu) { ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0); } PerThreadSynch* w = Synch_GetPerThread(); if (mu) { ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0); } return w; } static SynchLocksHeld* Synch_GetAllLocks() { PerThreadSynch* s = Synch_GetPerThread(); if (s->all_locks == nullptr) { s->all_locks = LocksHeldAlloc(); } return s->all_locks; } void Mutex::IncrementSynchSem(Mutex* mu, PerThreadSynch* w) { static_cast<void>(mu); ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0); ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN(); PerThreadSem::Post(w->thread_identity()); ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_END(); ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0); } bool Mutex::DecrementSynchSem(Mutex* mu, PerThreadSynch* w, KernelTimeout t) { static_cast<void>(mu); ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0); assert(w == Synch_GetPerThread()); static_cast<void>(w); bool res = PerThreadSem::Wait(t); ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0); return res; } void Mutex::InternalAttemptToUseMutexInFatalSignalHandler() { ThreadIdentity* identity = CurrentThreadIdentityIfPresent(); if (identity != nullptr) { identity->per_thread_synch.suppress_fatal_errors = true; } synch_deadlock_detection.store(OnDeadlockCycle::kIgnore, std::memory_order_release); } static const intptr_t kMuReader = 0x0001L; static const intptr_t kMuDesig = 0x0002L; static const intptr_t kMuWait = 0x0004L; static const intptr_t kMuWriter = 0x0008L; static const intptr_t kMuEvent = 0x0010L; static const intptr_t kMuWrWait = 0x0020L; static const intptr_t kMuSpin = 0x0040L; static const intptr_t kMuLow = 0x00ffL; static const intptr_t kMuHigh = ~kMuLow; static_assert((0xab & (kMuWriter | kMuReader)) == (kMuWriter | kMuReader), "The debug allocator's uninitialized pattern (0xab) must be an " "invalid mutex state"); static_assert((0xcd & (kMuWriter | kMuReader)) == (kMuWriter | kMuReader), "The debug allocator's freed pattern (0xcd) must be an invalid " "mutex state"); enum { kGdbMuSpin = kMuSpin, kGdbMuEvent = kMuEvent, kGdbMuWait = kMuWait, kGdbMuWriter = kMuWriter, kGdbMuDesig = kMuDesig, kGdbMuWrWait = kMuWrWait, kGdbMuReader = kMuReader, kGdbMuLow = kMuLow, }; static const intptr_t kMuOne = 0x0100; static const int kMuHasBlocked = 0x01; static const int kMuIsCond = 0x02; static const int kMuIsFer = 0x04; static_assert(PerThreadSynch::kAlignment > kMuLow, "PerThreadSynch::kAlignment must be greater than kMuLow"); struct MuHowS { intptr_t fast_need_zero; intptr_t fast_or; intptr_t fast_add; intptr_t slow_need_zero; intptr_t slow_inc_need_zero; }; static const MuHowS kSharedS = { kMuWriter | kMuWait | kMuEvent, kMuReader, kMuOne, kMuWriter | kMuWait, kMuSpin | kMuWriter | kMuWrWait, }; static const MuHowS kExclusiveS = { kMuWriter | kMuReader | kMuEvent, kMuWriter, 0, kMuWriter | kMuReader, ~static_cast<intptr_t>(0), }; static const Mutex::MuHow kShared = &kSharedS; static const Mutex::MuHow kExclusive = &kExclusiveS; #ifdef NDEBUG static constexpr bool kDebugMode = false; #else static constexpr bool kDebugMode = true; #endif #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE static unsigned TsanFlags(Mutex::MuHow how) { return how == kShared ? __tsan_mutex_read_lock : 0; } #endif #if defined(__APPLE__) || defined(ABSL_BUILD_DLL) Mutex::~Mutex() { Dtor(); } #endif #if !defined(NDEBUG) || defined(ABSL_HAVE_THREAD_SANITIZER) void Mutex::Dtor() { if (kDebugMode) { this->ForgetDeadlockInfo(); } ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); } #endif void Mutex::EnableDebugLog(const char* name) { ABSL_ANNOTATE_IGNORE_WRITES_BEGIN(); SynchEvent* e = EnsureSynchEvent(&this->mu_, name, kMuEvent, kMuSpin); e->log = true; UnrefSynchEvent(e); ABSL_ATTRIBUTE_UNUSED volatile auto dtor = &Mutex::Dtor; ABSL_ANNOTATE_IGNORE_WRITES_END(); } void EnableMutexInvariantDebugging(bool enabled) { synch_check_invariants.store(enabled, std::memory_order_release); } void Mutex::EnableInvariantDebugging(void (*invariant)(void*), void* arg) { ABSL_ANNOTATE_IGNORE_WRITES_BEGIN(); if (synch_check_invariants.load(std::memory_order_acquire) && invariant != nullptr) { SynchEvent* e = EnsureSynchEvent(&this->mu_, nullptr, kMuEvent, kMuSpin); e->invariant = invariant; e->arg = arg; UnrefSynchEvent(e); } ABSL_ANNOTATE_IGNORE_WRITES_END(); } void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode) { synch_deadlock_detection.store(mode, std::memory_order_release); } static bool MuEquivalentWaiter(PerThreadSynch* x, PerThreadSynch* y) { return x->waitp->how == y->waitp->how && x->priority == y->priority && Condition::GuaranteedEqual(x->waitp->cond, y->waitp->cond); } static inline PerThreadSynch* GetPerThreadSynch(intptr_t v) { return reinterpret_cast<PerThreadSynch*>(v & kMuHigh); } static PerThreadSynch* Skip(PerThreadSynch* x) { PerThreadSynch* x0 = nullptr; PerThreadSynch* x1 = x; PerThreadSynch* x2 = x->skip; if (x2 != nullptr) { while ((x0 = x1, x1 = x2, x2 = x2->skip) != nullptr) { x0->skip = x2; } x->skip = x1; } return x1; } static void FixSkip(PerThreadSynch* ancestor, PerThreadSynch* to_be_removed) { if (ancestor->skip == to_be_removed) { if (to_be_removed->skip != nullptr) { ancestor->skip = to_be_removed->skip; } else if (ancestor->next != to_be_removed) { ancestor->skip = ancestor->next; } else { ancestor->skip = nullptr; } } } static void CondVarEnqueue(SynchWaitParams* waitp); static PerThreadSynch* Enqueue(PerThreadSynch* head, SynchWaitParams* waitp, intptr_t mu, int flags) { if (waitp->cv_word != nullptr) { CondVarEnqueue(waitp); return head; } PerThreadSynch* s = waitp->thread; ABSL_RAW_CHECK( s->waitp == nullptr || s->waitp == waitp || s->suppress_fatal_errors, "detected illegal recursion into Mutex code"); s->waitp = waitp; s->skip = nullptr; s->may_skip = true; s->wake = false; s->cond_waiter = ((flags & kMuIsCond) != 0); #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM if ((flags & kMuIsFer) == 0) { assert(s == Synch_GetPerThread()); int64_t now_cycles = CycleClock::Now(); if (s->next_priority_read_cycles < now_cycles) { int policy; struct sched_param param; const int err = pthread_getschedparam(pthread_self(), &policy, &param); if (err != 0) { ABSL_RAW_LOG(ERROR, "pthread_getschedparam failed: %d", err); } else { s->priority = param.sched_priority; s->next_priority_read_cycles = now_cycles + static_cast<int64_t>(CycleClock::Frequency()); } } } #endif if (head == nullptr) { s->next = s; s->readers = mu; s->maybe_unlocking = false; head = s; } else { PerThreadSynch* enqueue_after = nullptr; #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM if (s->priority > head->priority) { if (!head->maybe_unlocking) { PerThreadSynch* advance_to = head; do { enqueue_after = advance_to; advance_to = Skip(enqueue_after->next); } while (s->priority <= advance_to->priority); } else if (waitp->how == kExclusive && waitp->cond == nullptr) { enqueue_after = head; } } #endif if (enqueue_after != nullptr) { s->next = enqueue_after->next; enqueue_after->next = s; ABSL_RAW_CHECK(enqueue_after->skip == nullptr || MuEquivalentWaiter(enqueue_after, s), "Mutex Enqueue failure"); if (enqueue_after != head && enqueue_after->may_skip && MuEquivalentWaiter(enqueue_after, enqueue_after->next)) { enqueue_after->skip = enqueue_after->next; } if (MuEquivalentWaiter(s, s->next)) { s->skip = s->next; } } else if ((flags & kMuHasBlocked) && (s->priority >= head->next->priority) && (!head->maybe_unlocking || (waitp->how == kExclusive && Condition::GuaranteedEqual(waitp->cond, nullptr)))) { s->next = head->next; head->next = s; if (MuEquivalentWaiter(s, s->next)) { s->skip = s->next; } } else { s->next = head->next; head->next = s; s->readers = head->readers; s->maybe_unlocking = head->maybe_unlocking; if (head->may_skip && MuEquivalentWaiter(head, s)) { head->skip = s; } head = s; } } s->state.store(PerThreadSynch::kQueued, std::memory_order_relaxed); return head; } static PerThreadSynch* Dequeue(PerThreadSynch* head, PerThreadSynch* pw) { PerThreadSynch* w = pw->next; pw->next = w->next; if (head == w) { head = (pw == w) ? nullptr : pw; } else if (pw != head && MuEquivalentWaiter(pw, pw->next)) { if (pw->next->skip != nullptr) { pw->skip = pw->next->skip; } else { pw->skip = pw->next; } } return head; } static PerThreadSynch* DequeueAllWakeable(PerThreadSynch* head, PerThreadSynch* pw, PerThreadSynch** wake_tail) { PerThreadSynch* orig_h = head; PerThreadSynch* w = pw->next; bool skipped = false; do { if (w->wake) { ABSL_RAW_CHECK(pw->skip == nullptr, "bad skip in DequeueAllWakeable"); head = Dequeue(head, pw); w->next = *wake_tail; *wake_tail = w; wake_tail = &w->next; if (w->waitp->how == kExclusive) { break; } } else { pw = Skip(w); skipped = true; } w = pw->next; } while (orig_h == head && (pw != head || !skipped)); return head; } void Mutex::TryRemove(PerThreadSynch* s) { SchedulingGuard::ScopedDisable disable_rescheduling; intptr_t v = mu_.load(std::memory_order_relaxed); if ((v & (kMuWait | kMuSpin | kMuWriter | kMuReader)) == kMuWait && mu_.compare_exchange_strong(v, v | kMuSpin | kMuWriter, std::memory_order_acquire, std::memory_order_relaxed)) { PerThreadSynch* h = GetPerThreadSynch(v); if (h != nullptr) { PerThreadSynch* pw = h; PerThreadSynch* w; if ((w = pw->next) != s) { do { if (!MuEquivalentWaiter(s, w)) { pw = Skip(w); } else { FixSkip(w, s); pw = w; } } while ((w = pw->next) != s && pw != h); } if (w == s) { h = Dequeue(h, pw); s->next = nullptr; s->state.store(PerThreadSynch::kAvailable, std::memory_order_release); } } intptr_t nv; do { v = mu_.load(std::memory_order_relaxed); nv = v & (kMuDesig | kMuEvent); if (h != nullptr) { nv |= kMuWait | reinterpret_cast<intptr_t>(h); h->readers = 0; h->maybe_unlocking = false; } } while (!mu_.compare_exchange_weak(v, nv, std::memory_order_release, std::memory_order_relaxed)); } } void Mutex::Block(PerThreadSynch* s) { while (s->state.load(std::memory_order_acquire) == PerThreadSynch::kQueued) { if (!DecrementSynchSem(this, s, s->waitp->timeout)) { this->TryRemove(s); int c = 0; while (s->next != nullptr) { c = synchronization_internal::MutexDelay(c, GENTLE); this->TryRemove(s); } if (kDebugMode) { this->TryRemove(s); } s->waitp->timeout = KernelTimeout::Never(); s->waitp->cond = nullptr; } } ABSL_RAW_CHECK(s->waitp != nullptr || s->suppress_fatal_errors, "detected illegal recursion in Mutex code"); s->waitp = nullptr; } PerThreadSynch* Mutex::Wakeup(PerThreadSynch* w) { PerThreadSynch* next = w->next; w->next = nullptr; w->state.store(PerThreadSynch::kAvailable, std::memory_order_release); IncrementSynchSem(this, w); return next; } static GraphId GetGraphIdLocked(Mutex* mu) ABSL_EXCLUSIVE_LOCKS_REQUIRED(deadlock_graph_mu) { if (!deadlock_graph) { deadlock_graph = new (base_internal::LowLevelAlloc::Alloc(sizeof(*deadlock_graph))) GraphCycles; } return deadlock_graph->GetId(mu); } static GraphId GetGraphId(Mutex* mu) ABSL_LOCKS_EXCLUDED(deadlock_graph_mu) { deadlock_graph_mu.Lock(); GraphId id = GetGraphIdLocked(mu); deadlock_graph_mu.Unlock(); return id; } static void LockEnter(Mutex* mu, GraphId id, SynchLocksHeld* held_locks) { int n = held_locks->n; int i = 0; while (i != n && held_locks->locks[i].id != id) { i++; } if (i == n) { if (n == ABSL_ARRAYSIZE(held_locks->locks)) { held_locks->overflow = true; } else { held_locks->locks[i].mu = mu; held_locks->locks[i].count = 1; held_locks->locks[i].id = id; held_locks->n = n + 1; } } else { held_locks->locks[i].count++; } } static void LockLeave(Mutex* mu, GraphId id, SynchLocksHeld* held_locks) { int n = held_locks->n; int i = 0; while (i != n && held_locks->locks[i].id != id) { i++; } if (i == n) { if (!held_locks->overflow) { i = 0; while (i != n && held_locks->locks[i].mu != mu) { i++; } if (i == n) { SynchEvent* mu_events = GetSynchEvent(mu); ABSL_RAW_LOG(FATAL, "thread releasing lock it does not hold: %p %s; " , static_cast<void*>(mu), mu_events == nullptr ? "" : mu_events->name); } } } else if (held_locks->locks[i].count == 1) { held_locks->n = n - 1; held_locks->locks[i] = held_locks->locks[n - 1]; held_locks->locks[n - 1].id = InvalidGraphId(); held_locks->locks[n - 1].mu = nullptr; } else { assert(held_locks->locks[i].count > 0); held_locks->locks[i].count--; } } static inline void DebugOnlyLockEnter(Mutex* mu) { if (kDebugMode) { if (synch_deadlock_detection.load(std::memory_order_acquire) != OnDeadlockCycle::kIgnore) { LockEnter(mu, GetGraphId(mu), Synch_GetAllLocks()); } } } static inline void DebugOnlyLockEnter(Mutex* mu, GraphId id) { if (kDebugMode) { if (synch_deadlock_detection.load(std::memory_order_acquire) != OnDeadlockCycle::kIgnore) { LockEnter(mu, id, Synch_GetAllLocks()); } } } static inline void DebugOnlyLockLeave(Mutex* mu) { if (kDebugMode) { if (synch_deadlock_detection.load(std::memory_order_acquire) != OnDeadlockCycle::kIgnore) { LockLeave(mu, GetGraphId(mu), Synch_GetAllLocks()); } } } static char* StackString(void** pcs, int n, char* buf, int maxlen, bool symbolize) { static constexpr int kSymLen = 200; char sym[kSymLen]; int len = 0; for (int i = 0; i != n; i++) { if (len >= maxlen) return buf; size_t count = static_cast<size_t>(maxlen - len); if (symbolize) { if (!absl::Symbolize(pcs[i], sym, kSymLen)) { sym[0] = '\0'; } snprintf(buf + len, count, "%s\t@ %p %s\n", (i == 0 ? "\n" : ""), pcs[i], sym); } else { snprintf(buf + len, count, " %p", pcs[i]); } len += strlen(&buf[len]); } return buf; } static char* CurrentStackString(char* buf, int maxlen, bool symbolize) { void* pcs[40]; return StackString(pcs, absl::GetStackTrace(pcs, ABSL_ARRAYSIZE(pcs), 2), buf, maxlen, symbolize); } namespace { enum { kMaxDeadlockPathLen = 10 }; struct DeadlockReportBuffers { char buf[6100]; GraphId path[kMaxDeadlockPathLen]; }; struct ScopedDeadlockReportBuffers { ScopedDeadlockReportBuffers() { b = reinterpret_cast<DeadlockReportBuffers*>( base_internal::LowLevelAlloc::Alloc(sizeof(*b))); } ~ScopedDeadlockReportBuffers() { base_internal::LowLevelAlloc::Free(b); } DeadlockReportBuffers* b; }; int GetStack(void** stack, int max_depth) { return absl::GetStackTrace(stack, max_depth, 3); } } static GraphId DeadlockCheck(Mutex* mu) { if (synch_deadlock_detection.load(std::memory_order_acquire) == OnDeadlockCycle::kIgnore) { return InvalidGraphId(); } SynchLocksHeld* all_locks = Synch_GetAllLocks(); absl::base_internal::SpinLockHolder lock(&deadlock_graph_mu); const GraphId mu_id = GetGraphIdLocked(mu); if (all_locks->n == 0) { return mu_id; } deadlock_graph->UpdateStackTrace(mu_id, all_locks->n + 1, GetStack); for (int i = 0; i != all_locks->n; i++) { const GraphId other_node_id = all_locks->locks[i].id; const Mutex* other = static_cast<const Mutex*>(deadlock_graph->Ptr(other_node_id)); if (other == nullptr) { continue; } if (!deadlock_graph->InsertEdge(other_node_id, mu_id)) { ScopedDeadlockReportBuffers scoped_buffers; DeadlockReportBuffers* b = scoped_buffers.b; static int number_of_reported_deadlocks = 0; number_of_reported_deadlocks++; bool symbolize = number_of_reported_deadlocks <= 2; ABSL_RAW_LOG(ERROR, "Potential Mutex deadlock: %s", CurrentStackString(b->buf, sizeof (b->buf), symbolize)); size_t len = 0; for (int j = 0; j != all_locks->n; j++) { void* pr = deadlock_graph->Ptr(all_locks->locks[j].id); if (pr != nullptr) { snprintf(b->buf + len, sizeof(b->buf) - len, " %p", pr); len += strlen(&b->buf[len]); } } ABSL_RAW_LOG(ERROR, "Acquiring absl::Mutex %p while holding %s; a cycle in the " "historical lock ordering graph has been observed", static_cast<void*>(mu), b->buf); ABSL_RAW_LOG(ERROR, "Cycle: "); int path_len = deadlock_graph->FindPath(mu_id, other_node_id, ABSL_ARRAYSIZE(b->path), b->path); for (int j = 0; j != path_len && j != ABSL_ARRAYSIZE(b->path); j++) { GraphId id = b->path[j]; Mutex* path_mu = static_cast<Mutex*>(deadlock_graph->Ptr(id)); if (path_mu == nullptr) continue; void** stack; int depth = deadlock_graph->GetStackTrace(id, &stack); snprintf(b->buf, sizeof(b->buf), "mutex@%p stack: ", static_cast<void*>(path_mu)); StackString(stack, depth, b->buf + strlen(b->buf), static_cast<int>(sizeof(b->buf) - strlen(b->buf)), symbolize); ABSL_RAW_LOG(ERROR, "%s", b->buf); } if (path_len > static_cast<int>(ABSL_ARRAYSIZE(b->path))) { ABSL_RAW_LOG(ERROR, "(long cycle; list truncated)"); } if (synch_deadlock_detection.load(std::memory_order_acquire) == OnDeadlockCycle::kAbort) { deadlock_graph_mu.Unlock(); ABSL_RAW_LOG(FATAL, "dying due to potential deadlock"); return mu_id; } break; } } return mu_id; } static inline GraphId DebugOnlyDeadlockCheck(Mutex* mu) { if (kDebugMode && synch_deadlock_detection.load(std::memory_order_acquire) != OnDeadlockCycle::kIgnore) { return DeadlockCheck(mu); } else { return InvalidGraphId(); } } void Mutex::ForgetDeadlockInfo() { if (kDebugMode && synch_deadlock_detection.load(std::memory_order_acquire) != OnDeadlockCycle::kIgnore) { deadlock_graph_mu.Lock(); if (deadlock_graph != nullptr) { deadlock_graph->RemoveNode(this); } deadlock_graph_mu.Unlock(); } } void Mutex::AssertNotHeld() const { if (kDebugMode && (mu_.load(std::memory_order_relaxed) & (kMuWriter | kMuReader)) != 0 && synch_deadlock_detection.load(std::memory_order_acquire) != OnDeadlockCycle::kIgnore) { GraphId id = GetGraphId(const_cast<Mutex*>(this)); SynchLocksHeld* locks = Synch_GetAllLocks(); for (int i = 0; i != locks->n; i++) { if (locks->locks[i].id == id) { SynchEvent* mu_events = GetSynchEvent(this); ABSL_RAW_LOG(FATAL, "thread should not hold mutex %p %s", static_cast<const void*>(this), (mu_events == nullptr ? "" : mu_events->name)); } } } } static bool TryAcquireWithSpinning(std::atomic<intptr_t>* mu) { int c = globals.spinloop_iterations.load(std::memory_order_relaxed); do { intptr_t v = mu->load(std::memory_order_relaxed); if ((v & (kMuReader | kMuEvent)) != 0) { return false; } else if (((v & kMuWriter) == 0) && mu->compare_exchange_strong(v, kMuWriter | v, std::memory_order_acquire, std::memory_order_relaxed)) { return true; } } while (--c > 0); return false; } void Mutex::Lock() { ABSL_TSAN_MUTEX_PRE_LOCK(this, 0); GraphId id = DebugOnlyDeadlockCheck(this); intptr_t v = mu_.load(std::memory_order_relaxed); if (ABSL_PREDICT_FALSE((v & (kMuWriter | kMuReader | kMuEvent)) != 0) || ABSL_PREDICT_FALSE(!mu_.compare_exchange_strong( v, kMuWriter | v, std::memory_order_acquire, std::memory_order_relaxed))) { if (ABSL_PREDICT_FALSE(!TryAcquireWithSpinning(&this->mu_))) { this->LockSlow(kExclusive, nullptr, 0); } } DebugOnlyLockEnter(this, id); ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0); } void Mutex::ReaderLock() { ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_read_lock); GraphId id = DebugOnlyDeadlockCheck(this); intptr_t v = mu_.load(std::memory_order_relaxed); for (;;) { if (ABSL_PREDICT_FALSE(v & (kMuWriter | kMuWait | kMuEvent)) != 0) { this->LockSlow(kShared, nullptr, 0); break; } if (ABSL_PREDICT_TRUE(mu_.compare_exchange_weak( v, (kMuReader | v) + kMuOne, std::memory_order_acquire, std::memory_order_relaxed))) { break; } } DebugOnlyLockEnter(this, id); ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_read_lock, 0); } bool Mutex::LockWhenCommon(const Condition& cond, synchronization_internal::KernelTimeout t, bool write) { MuHow how = write ? kExclusive : kShared; ABSL_TSAN_MUTEX_PRE_LOCK(this, TsanFlags(how)); GraphId id = DebugOnlyDeadlockCheck(this); bool res = LockSlowWithDeadline(how, &cond, t, 0); DebugOnlyLockEnter(this, id); ABSL_TSAN_MUTEX_POST_LOCK(this, TsanFlags(how), 0); return res; } bool Mutex::AwaitCommon(const Condition& cond, KernelTimeout t) { if (kDebugMode) { this->AssertReaderHeld(); } if (cond.Eval()) { return true; } MuHow how = (mu_.load(std::memory_order_relaxed) & kMuWriter) ? kExclusive : kShared; ABSL_TSAN_MUTEX_PRE_UNLOCK(this, TsanFlags(how)); SynchWaitParams waitp(how, &cond, t, nullptr , Synch_GetPerThreadAnnotated(this), nullptr ); this->UnlockSlow(&waitp); this->Block(waitp.thread); ABSL_TSAN_MUTEX_POST_UNLOCK(this, TsanFlags(how)); ABSL_TSAN_MUTEX_PRE_LOCK(this, TsanFlags(how)); this->LockSlowLoop(&waitp, kMuHasBlocked | kMuIsCond); bool res = waitp.cond != nullptr || EvalConditionAnnotated(&cond, this, true, false, how == kShared); ABSL_TSAN_MUTEX_POST_LOCK(this, TsanFlags(how), 0); ABSL_RAW_CHECK(res || t.has_timeout(), "condition untrue on return from Await"); return res; } bool Mutex::TryLock() { ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock); intptr_t v = mu_.load(std::memory_order_relaxed); if (ABSL_PREDICT_TRUE((v & (kMuWriter | kMuReader | kMuEvent)) == 0)) { if (ABSL_PREDICT_TRUE(mu_.compare_exchange_strong( v, kMuWriter | v, std::memory_order_acquire, std::memory_order_relaxed))) { DebugOnlyLockEnter(this); ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_try_lock, 0); return true; } } else if (ABSL_PREDICT_FALSE((v & kMuEvent) != 0)) { return TryLockSlow(); } ABSL_TSAN_MUTEX_POST_LOCK( this, __tsan_mutex_try_lock | __tsan_mutex_try_lock_failed, 0); return false; } ABSL_ATTRIBUTE_NOINLINE bool Mutex::TryLockSlow() { intptr_t v = mu_.load(std::memory_order_relaxed); if ((v & kExclusive->slow_need_zero) == 0 && mu_.compare_exchange_strong( v, (kExclusive->fast_or | v) + kExclusive->fast_add, std::memory_order_acquire, std::memory_order_relaxed)) { DebugOnlyLockEnter(this); PostSynchEvent(this, SYNCH_EV_TRYLOCK_SUCCESS); ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_try_lock, 0); return true; } PostSynchEvent(this, SYNCH_EV_TRYLOCK_FAILED); ABSL_TSAN_MUTEX_POST_LOCK( this, __tsan_mutex_try_lock | __tsan_mutex_try_lock_failed, 0); return false; } bool Mutex::ReaderTryLock() { ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_read_lock | __tsan_mutex_try_lock); intptr_t v = mu_.load(std::memory_order_relaxed); #if defined(__clang__) #pragma nounroll #endif for (int loop_limit = 5; loop_limit != 0; loop_limit--) { if (ABSL_PREDICT_FALSE((v & (kMuWriter | kMuWait | kMuEvent)) != 0)) { break; } if (ABSL_PREDICT_TRUE(mu_.compare_exchange_strong( v, (kMuReader | v) + kMuOne, std::memory_order_acquire, std::memory_order_relaxed))) { DebugOnlyLockEnter(this); ABSL_TSAN_MUTEX_POST_LOCK( this, __tsan_mutex_read_lock | __tsan_mutex_try_lock, 0); return true; } } if (ABSL_PREDICT_TRUE((v & kMuEvent) == 0)) { ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_read_lock | __tsan_mutex_try_lock | __tsan_mutex_try_lock_failed, 0); return false; } return ReaderTryLockSlow(); } ABSL_ATTRIBUTE_NOINLINE bool Mutex::ReaderTryLockSlow() { intptr_t v = mu_.load(std::memory_order_relaxed); #if defined(__clang__) #pragma nounroll #endif for (int loop_limit = 5; loop_limit != 0; loop_limit--) { if ((v & kShared->slow_need_zero) == 0 && mu_.compare_exchange_strong(v, (kMuReader | v) + kMuOne, std::memory_order_acquire, std::memory_order_relaxed)) { DebugOnlyLockEnter(this); PostSynchEvent(this, SYNCH_EV_READERTRYLOCK_SUCCESS); ABSL_TSAN_MUTEX_POST_LOCK( this, __tsan_mutex_read_lock | __tsan_mutex_try_lock, 0); return true; } } PostSynchEvent(this, SYNCH_EV_READERTRYLOCK_FAILED); ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_read_lock | __tsan_mutex_try_lock | __tsan_mutex_try_lock_failed, 0); return false; } void Mutex::Unlock() { ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0); DebugOnlyLockLeave(this); intptr_t v = mu_.load(std::memory_order_relaxed); if (kDebugMode && ((v & (kMuWriter | kMuReader)) != kMuWriter)) { ABSL_RAW_LOG(FATAL, "Mutex unlocked when destroyed or not locked: v=0x%x", static_cast<unsigned>(v)); } bool should_try_cas = ((v & (kMuEvent | kMuWriter)) == kMuWriter && (v & (kMuWait | kMuDesig)) != kMuWait); static_assert(kMuEvent > kMuWait, "Needed for should_try_cas_fast"); static_assert(kMuEvent > kMuDesig, "Needed for should_try_cas_fast"); static_assert(kMuWriter > kMuWait, "Needed for should_try_cas_fast"); static_assert(kMuWriter > kMuDesig, "Needed for should_try_cas_fast"); bool should_try_cas_fast = ((v ^ (kMuWriter | kMuDesig)) & (kMuEvent | kMuWriter | kMuWait | kMuDesig)) < (kMuWait | kMuDesig); if (kDebugMode && should_try_cas != should_try_cas_fast) { ABSL_RAW_LOG(FATAL, "internal logic error %llx %llx %llx\n", static_cast<long long>(v), static_cast<long long>(should_try_cas), static_cast<long long>(should_try_cas_fast)); } if (should_try_cas_fast && mu_.compare_exchange_strong(v, v & ~(kMuWrWait | kMuWriter), std::memory_order_release, std::memory_order_relaxed)) { } else { this->UnlockSlow(nullptr ); } ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0); } static bool ExactlyOneReader(intptr_t v) { assert((v & (kMuWriter | kMuReader)) == kMuReader); assert((v & kMuHigh) != 0); constexpr intptr_t kMuMultipleWaitersMask = kMuHigh ^ kMuOne; return (v & kMuMultipleWaitersMask) == 0; } void Mutex::ReaderUnlock() { ABSL_TSAN_MUTEX_PRE_UNLOCK(this, __tsan_mutex_read_lock); DebugOnlyLockLeave(this); intptr_t v = mu_.load(std::memory_order_relaxed); assert((v & (kMuWriter | kMuReader)) == kMuReader); for (;;) { if (ABSL_PREDICT_FALSE((v & (kMuReader | kMuWait | kMuEvent)) != kMuReader)) { this->UnlockSlow(nullptr ); break; } intptr_t clear = ExactlyOneReader(v) ? kMuReader | kMuOne : kMuOne; if (ABSL_PREDICT_TRUE( mu_.compare_exchange_strong(v, v - clear, std::memory_order_release, std::memory_order_relaxed))) { break; } } ABSL_TSAN_MUTEX_POST_UNLOCK(this, __tsan_mutex_read_lock); } static intptr_t ClearDesignatedWakerMask(int flag) { assert(flag >= 0); assert(flag <= 1); switch (flag) { case 0: return ~static_cast<intptr_t>(0); case 1: return ~static_cast<intptr_t>(kMuDesig); } ABSL_UNREACHABLE(); } static intptr_t IgnoreWaitingWritersMask(int flag) { assert(flag >= 0); assert(flag <= 1); switch (flag) { case 0: return ~static_cast<intptr_t>(0); case 1: return ~static_cast<intptr_t>(kMuWrWait); } ABSL_UNREACHABLE(); } ABSL_ATTRIBUTE_NOINLINE void Mutex::LockSlow(MuHow how, const Condition* cond, int flags) { if (ABSL_PREDICT_FALSE( globals.spinloop_iterations.load(std::memory_order_relaxed) == 0)) { if (absl::base_internal::NumCPUs() > 1) { globals.spinloop_iterations.store(1500, std::memory_order_relaxed); } else { globals.spinloop_iterations.store(-1, std::memory_order_relaxed); } } ABSL_RAW_CHECK( this->LockSlowWithDeadline(how, cond, KernelTimeout::Never(), flags), "condition untrue on return from LockSlow"); } static inline bool EvalConditionAnnotated(const Condition* cond, Mutex* mu, bool locking, bool trylock, bool read_lock) { bool res = false; #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE const uint32_t flags = read_lock ? __tsan_mutex_read_lock : 0; const uint32_t tryflags = flags | (trylock ? __tsan_mutex_try_lock : 0); #endif if (locking) { ABSL_TSAN_MUTEX_POST_LOCK(mu, tryflags, 0); res = cond->Eval(); ABSL_TSAN_MUTEX_PRE_UNLOCK(mu, flags); ABSL_TSAN_MUTEX_POST_UNLOCK(mu, flags); ABSL_TSAN_MUTEX_PRE_LOCK(mu, tryflags); } else { ABSL_TSAN_MUTEX_POST_UNLOCK(mu, flags); ABSL_TSAN_MUTEX_PRE_LOCK(mu, flags); ABSL_TSAN_MUTEX_POST_LOCK(mu, flags, 0); res = cond->Eval(); ABSL_TSAN_MUTEX_PRE_UNLOCK(mu, flags); } static_cast<void>(mu); static_cast<void>(trylock); static_cast<void>(read_lock); return res; } static inline bool EvalConditionIgnored(Mutex* mu, const Condition* cond) { ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0); ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN(); bool res = cond->Eval(); ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_END(); ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0); static_cast<void>(mu); return res; } bool Mutex::LockSlowWithDeadline(MuHow how, const Condition* cond, KernelTimeout t, int flags) { intptr_t v = mu_.load(std::memory_order_relaxed); bool unlock = false; if ((v & how->fast_need_zero) == 0 && mu_.compare_exchange_strong( v, (how->fast_or | (v & ClearDesignatedWakerMask(flags & kMuHasBlocked))) + how->fast_add, std::memory_order_acquire, std::memory_order_relaxed)) { if (cond == nullptr || EvalConditionAnnotated(cond, this, true, false, how == kShared)) { return true; } unlock = true; } SynchWaitParams waitp(how, cond, t, nullptr , Synch_GetPerThreadAnnotated(this), nullptr ); if (cond != nullptr) { flags |= kMuIsCond; } if (unlock) { this->UnlockSlow(&waitp); this->Block(waitp.thread); flags |= kMuHasBlocked; } this->LockSlowLoop(&waitp, flags); return waitp.cond != nullptr || cond == nullptr || EvalConditionAnnotated(cond, this, true, false, how == kShared); } #define RAW_CHECK_FMT(cond, ...) \ do { \ if (ABSL_PREDICT_FALSE(!(cond))) { \ ABSL_RAW_LOG(FATAL, "Check " #cond " failed: " __VA_ARGS__); \ } \ } while (0) static void CheckForMutexCorruption(intptr_t v, const char* label) { const uintptr_t w = static_cast<uintptr_t>(v ^ kMuWait); static_assert(kMuReader << 3 == kMuWriter, "must match"); static_assert(kMuWait << 3 == kMuWrWait, "must match"); if (ABSL_PREDICT_TRUE((w & (w << 3) & (kMuWriter | kMuWrWait)) == 0)) return; RAW_CHECK_FMT((v & (kMuWriter | kMuReader)) != (kMuWriter | kMuReader), "%s: Mutex corrupt: both reader and writer lock held: %p", label, reinterpret_cast<void*>(v)); RAW_CHECK_FMT((v & (kMuWait | kMuWrWait)) != kMuWrWait, "%s: Mutex corrupt: waiting writer with no waiters: %p", label, reinterpret_cast<void*>(v)); assert(false); } void Mutex::LockSlowLoop(SynchWaitParams* waitp, int flags) { SchedulingGuard::ScopedDisable disable_rescheduling; int c = 0; intptr_t v = mu_.load(std::memory_order_relaxed); if ((v & kMuEvent) != 0) { PostSynchEvent( this, waitp->how == kExclusive ? SYNCH_EV_LOCK : SYNCH_EV_READERLOCK); } ABSL_RAW_CHECK( waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors, "detected illegal recursion into Mutex code"); for (;;) { v = mu_.load(std::memory_order_relaxed); CheckForMutexCorruption(v, "Lock"); if ((v & waitp->how->slow_need_zero) == 0) { if (mu_.compare_exchange_strong( v, (waitp->how->fast_or | (v & ClearDesignatedWakerMask(flags & kMuHasBlocked))) + waitp->how->fast_add, std::memory_order_acquire, std::memory_order_relaxed)) { if (waitp->cond == nullptr || EvalConditionAnnotated(waitp->cond, this, true, false, waitp->how == kShared)) { break; } this->UnlockSlow(waitp); this->Block(waitp->thread); flags |= kMuHasBlocked; c = 0; } } else { bool dowait = false; if ((v & (kMuSpin | kMuWait)) == 0) { PerThreadSynch* new_h = Enqueue(nullptr, waitp, v, flags); intptr_t nv = (v & ClearDesignatedWakerMask(flags & kMuHasBlocked) & kMuLow) | kMuWait; ABSL_RAW_CHECK(new_h != nullptr, "Enqueue to empty list failed"); if (waitp->how == kExclusive && (v & kMuReader) != 0) { nv |= kMuWrWait; } if (mu_.compare_exchange_strong( v, reinterpret_cast<intptr_t>(new_h) | nv, std::memory_order_release, std::memory_order_relaxed)) { dowait = true; } else { waitp->thread->waitp = nullptr; } } else if ((v & waitp->how->slow_inc_need_zero & IgnoreWaitingWritersMask(flags & kMuHasBlocked)) == 0) { if (mu_.compare_exchange_strong( v, (v & ClearDesignatedWakerMask(flags & kMuHasBlocked)) | kMuSpin | kMuReader, std::memory_order_acquire, std::memory_order_relaxed)) { PerThreadSynch* h = GetPerThreadSynch(v); h->readers += kMuOne; do { v = mu_.load(std::memory_order_relaxed); } while (!mu_.compare_exchange_weak(v, (v & ~kMuSpin) | kMuReader, std::memory_order_release, std::memory_order_relaxed)); if (waitp->cond == nullptr || EvalConditionAnnotated(waitp->cond, this, true, false, waitp->how == kShared)) { break; } this->UnlockSlow(waitp); this->Block(waitp->thread); flags |= kMuHasBlocked; c = 0; } } else if ((v & kMuSpin) == 0 && mu_.compare_exchange_strong( v, (v & ClearDesignatedWakerMask(flags & kMuHasBlocked)) | kMuSpin | kMuWait, std::memory_order_acquire, std::memory_order_relaxed)) { PerThreadSynch* h = GetPerThreadSynch(v); PerThreadSynch* new_h = Enqueue(h, waitp, v, flags); intptr_t wr_wait = 0; ABSL_RAW_CHECK(new_h != nullptr, "Enqueue to list failed"); if (waitp->how == kExclusive && (v & kMuReader) != 0) { wr_wait = kMuWrWait; } do { v = mu_.load(std::memory_order_relaxed); } while (!mu_.compare_exchange_weak( v, (v & (kMuLow & ~kMuSpin)) | kMuWait | wr_wait | reinterpret_cast<intptr_t>(new_h), std::memory_order_release, std::memory_order_relaxed)); dowait = true; } if (dowait) { this->Block(waitp->thread); flags |= kMuHasBlocked; c = 0; } } ABSL_RAW_CHECK( waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors, "detected illegal recursion into Mutex code"); c = synchronization_internal::MutexDelay(c, GENTLE); } ABSL_RAW_CHECK( waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors, "detected illegal recursion into Mutex code"); if ((v & kMuEvent) != 0) { PostSynchEvent(this, waitp->how == kExclusive ? SYNCH_EV_LOCK_RETURNING : SYNCH_EV_READERLOCK_RETURNING); } } ABSL_ATTRIBUTE_NOINLINE void Mutex::UnlockSlow(SynchWaitParams* waitp) { SchedulingGuard::ScopedDisable disable_rescheduling; intptr_t v = mu_.load(std::memory_order_relaxed); this->AssertReaderHeld(); CheckForMutexCorruption(v, "Unlock"); if ((v & kMuEvent) != 0) { PostSynchEvent( this, (v & kMuWriter) != 0 ? SYNCH_EV_UNLOCK : SYNCH_EV_READERUNLOCK); } int c = 0; PerThreadSynch* w = nullptr; PerThreadSynch* pw = nullptr; PerThreadSynch* old_h = nullptr; PerThreadSynch* wake_list = kPerThreadSynchNull; intptr_t wr_wait = 0; ABSL_RAW_CHECK(waitp == nullptr || waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors, "detected illegal recursion into Mutex code"); for (;;) { v = mu_.load(std::memory_order_relaxed); if ((v & kMuWriter) != 0 && (v & (kMuWait | kMuDesig)) != kMuWait && waitp == nullptr) { if (mu_.compare_exchange_strong(v, v & ~(kMuWrWait | kMuWriter), std::memory_order_release, std::memory_order_relaxed)) { return; } } else if ((v & (kMuReader | kMuWait)) == kMuReader && waitp == nullptr) { intptr_t clear = ExactlyOneReader(v) ? kMuReader | kMuOne : kMuOne; if (mu_.compare_exchange_strong(v, v - clear, std::memory_order_release, std::memory_order_relaxed)) { return; } } else if ((v & kMuSpin) == 0 && mu_.compare_exchange_strong(v, v | kMuSpin, std::memory_order_acquire, std::memory_order_relaxed)) { if ((v & kMuWait) == 0) { intptr_t nv; bool do_enqueue = true; ABSL_RAW_CHECK(waitp != nullptr, "UnlockSlow is confused"); do { v = mu_.load(std::memory_order_relaxed); intptr_t new_readers = (v >= kMuOne) ? v - kMuOne : v; PerThreadSynch* new_h = nullptr; if (do_enqueue) { do_enqueue = (waitp->cv_word == nullptr); new_h = Enqueue(nullptr, waitp, new_readers, kMuIsCond); } intptr_t clear = kMuWrWait | kMuWriter; if ((v & kMuWriter) == 0 && ExactlyOneReader(v)) { clear = kMuWrWait | kMuReader; } nv = (v & kMuLow & ~clear & ~kMuSpin); if (new_h != nullptr) { nv |= kMuWait | reinterpret_cast<intptr_t>(new_h); } else { nv |= new_readers & kMuHigh; } } while (!mu_.compare_exchange_weak(v, nv, std::memory_order_release, std::memory_order_relaxed)); break; } PerThreadSynch* h = GetPerThreadSynch(v); if ((v & kMuReader) != 0 && (h->readers & kMuHigh) > kMuOne) { h->readers -= kMuOne; intptr_t nv = v; if (waitp != nullptr) { PerThreadSynch* new_h = Enqueue(h, waitp, v, kMuIsCond); ABSL_RAW_CHECK(new_h != nullptr, "waiters disappeared during Enqueue()!"); nv &= kMuLow; nv |= kMuWait | reinterpret_cast<intptr_t>(new_h); } mu_.store(nv, std::memory_order_release); break; } ABSL_RAW_CHECK(old_h == nullptr || h->maybe_unlocking, "Mutex queue changed beneath us"); if (old_h != nullptr && !old_h->may_skip) { old_h->may_skip = true; ABSL_RAW_CHECK(old_h->skip == nullptr, "illegal skip from head"); if (h != old_h && MuEquivalentWaiter(old_h, old_h->next)) { old_h->skip = old_h->next; } } if (h->next->waitp->how == kExclusive && h->next->waitp->cond == nullptr) { pw = h; w = h->next; w->wake = true; wr_wait = kMuWrWait; } else if (w != nullptr && (w->waitp->how == kExclusive || h == old_h)) { if (pw == nullptr) { pw = h; } } else { if (old_h == h) { intptr_t nv = (v & ~(kMuReader | kMuWriter | kMuWrWait)); h->readers = 0; h->maybe_unlocking = false; if (waitp != nullptr) { PerThreadSynch* new_h = Enqueue(h, waitp, v, kMuIsCond); nv &= kMuLow; if (new_h != nullptr) { nv |= kMuWait | reinterpret_cast<intptr_t>(new_h); } } mu_.store(nv, std::memory_order_release); break; } PerThreadSynch* w_walk; PerThreadSynch* pw_walk; if (old_h != nullptr) { pw_walk = old_h; w_walk = old_h->next; } else { pw_walk = nullptr; w_walk = h->next; } h->may_skip = false; ABSL_RAW_CHECK(h->skip == nullptr, "illegal skip from head"); h->maybe_unlocking = true; mu_.store(v, std::memory_order_release); old_h = h; while (pw_walk != h) { w_walk->wake = false; if (w_walk->waitp->cond == nullptr || EvalConditionIgnored(this, w_walk->waitp->cond)) { if (w == nullptr) { w_walk->wake = true; w = w_walk; pw = pw_walk; if (w_walk->waitp->how == kExclusive) { wr_wait = kMuWrWait; break; } } else if (w_walk->waitp->how == kShared) { w_walk->wake = true; } else { wr_wait = kMuWrWait; } } if (w_walk->wake) { pw_walk = w_walk; } else { pw_walk = Skip(w_walk); } if (pw_walk != h) { w_walk = pw_walk->next; } } continue; } ABSL_RAW_CHECK(pw->next == w, "pw not w's predecessor"); h = DequeueAllWakeable(h, pw, &wake_list); intptr_t nv = (v & kMuEvent) | kMuDesig; if (waitp != nullptr) { h = Enqueue(h, waitp, v, kMuIsCond); } ABSL_RAW_CHECK(wake_list != kPerThreadSynchNull, "unexpected empty wake list"); if (h != nullptr) { h->readers = 0; h->maybe_unlocking = false; nv |= wr_wait | kMuWait | reinterpret_cast<intptr_t>(h); } mu_.store(nv, std::memory_order_release); break; } c = synchronization_internal::MutexDelay(c, AGGRESSIVE); } if (wake_list != kPerThreadSynchNull) { int64_t total_wait_cycles = 0; int64_t max_wait_cycles = 0; int64_t now = CycleClock::Now(); do { if (!wake_list->cond_waiter) { int64_t cycles_waited = (now - wake_list->waitp->contention_start_cycles); total_wait_cycles += cycles_waited; if (max_wait_cycles == 0) max_wait_cycles = cycles_waited; wake_list->waitp->contention_start_cycles = now; wake_list->waitp->should_submit_contention_data = true; } wake_list = Wakeup(wake_list); } while (wake_list != kPerThreadSynchNull); if (total_wait_cycles > 0) { mutex_tracer("slow release", this, total_wait_cycles); ABSL_TSAN_MUTEX_PRE_DIVERT(this, 0); submit_profile_data(total_wait_cycles); ABSL_TSAN_MUTEX_POST_DIVERT(this, 0); } } } void Mutex::Trans(MuHow how) { this->LockSlow(how, nullptr, kMuHasBlocked | kMuIsCond); } void Mutex::Fer(PerThreadSynch* w) { SchedulingGuard::ScopedDisable disable_rescheduling; int c = 0; ABSL_RAW_CHECK(w->waitp->cond == nullptr, "Mutex::Fer while waiting on Condition"); ABSL_RAW_CHECK(w->waitp->cv_word == nullptr, "Mutex::Fer with pending CondVar queueing"); w->waitp->timeout = {}; for (;;) { intptr_t v = mu_.load(std::memory_order_relaxed); const intptr_t conflicting = kMuWriter | (w->waitp->how == kShared ? 0 : kMuReader); if ((v & conflicting) == 0) { w->next = nullptr; w->state.store(PerThreadSynch::kAvailable, std::memory_order_release); IncrementSynchSem(this, w); return; } else { if ((v & (kMuSpin | kMuWait)) == 0) { PerThreadSynch* new_h = Enqueue(nullptr, w->waitp, v, kMuIsCond | kMuIsFer); ABSL_RAW_CHECK(new_h != nullptr, "Enqueue failed"); if (mu_.compare_exchange_strong( v, reinterpret_cast<intptr_t>(new_h) | (v & kMuLow) | kMuWait, std::memory_order_release, std::memory_order_relaxed)) { return; } } else if ((v & kMuSpin) == 0 && mu_.compare_exchange_strong(v, v | kMuSpin | kMuWait)) { PerThreadSynch* h = GetPerThreadSynch(v); PerThreadSynch* new_h = Enqueue(h, w->waitp, v, kMuIsCond | kMuIsFer); ABSL_RAW_CHECK(new_h != nullptr, "Enqueue failed"); do { v = mu_.load(std::memory_order_relaxed); } while (!mu_.compare_exchange_weak( v, (v & kMuLow & ~kMuSpin) | kMuWait | reinterpret_cast<intptr_t>(new_h), std::memory_order_release, std::memory_order_relaxed)); return; } } c = synchronization_internal::MutexDelay(c, GENTLE); } } void Mutex::AssertHeld() const { if ((mu_.load(std::memory_order_relaxed) & kMuWriter) == 0) { SynchEvent* e = GetSynchEvent(this); ABSL_RAW_LOG(FATAL, "thread should hold write lock on Mutex %p %s", static_cast<const void*>(this), (e == nullptr ? "" : e->name)); } } void Mutex::AssertReaderHeld() const { if ((mu_.load(std::memory_order_relaxed) & (kMuReader | kMuWriter)) == 0) { SynchEvent* e = GetSynchEvent(this); ABSL_RAW_LOG(FATAL, "thread should hold at least a read lock on Mutex %p %s", static_cast<const void*>(this), (e == nullptr ? "" : e->name)); } } static const intptr_t kCvSpin = 0x0001L; static const intptr_t kCvEvent = 0x0002L; static const intptr_t kCvLow = 0x0003L; enum { kGdbCvSpin = kCvSpin, kGdbCvEvent = kCvEvent, kGdbCvLow = kCvLow, }; static_assert(PerThreadSynch::kAlignment > kCvLow, "PerThreadSynch::kAlignment must be greater than kCvLow"); void CondVar::EnableDebugLog(const char* name) { SynchEvent* e = EnsureSynchEvent(&this->cv_, name, kCvEvent, kCvSpin); e->log = true; UnrefSynchEvent(e); } void CondVar::Remove(PerThreadSynch* s) { SchedulingGuard::ScopedDisable disable_rescheduling; intptr_t v; int c = 0; for (v = cv_.load(std::memory_order_relaxed);; v = cv_.load(std::memory_order_relaxed)) { if ((v & kCvSpin) == 0 && cv_.compare_exchange_strong(v, v | kCvSpin, std::memory_order_acquire, std::memory_order_relaxed)) { PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow); if (h != nullptr) { PerThreadSynch* w = h; while (w->next != s && w->next != h) { w = w->next; } if (w->next == s) { w->next = s->next; if (h == s) { h = (w == s) ? nullptr : w; } s->next = nullptr; s->state.store(PerThreadSynch::kAvailable, std::memory_order_release); } } cv_.store((v & kCvEvent) | reinterpret_cast<intptr_t>(h), std::memory_order_release); return; } else { c = synchronization_internal::MutexDelay(c, GENTLE); } } } static void CondVarEnqueue(SynchWaitParams* waitp) { std::atomic<intptr_t>* cv_word = waitp->cv_word; waitp->cv_word = nullptr; intptr_t v = cv_word->load(std::memory_order_relaxed); int c = 0; while ((v & kCvSpin) != 0 || !cv_word->compare_exchange_weak(v, v | kCvSpin, std::memory_order_acquire, std::memory_order_relaxed)) { c = synchronization_internal::MutexDelay(c, GENTLE); v = cv_word->load(std::memory_order_relaxed); } ABSL_RAW_CHECK(waitp->thread->waitp == nullptr, "waiting when shouldn't be"); waitp->thread->waitp = waitp; PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow); if (h == nullptr) { waitp->thread->next = waitp->thread; } else { waitp->thread->next = h->next; h->next = waitp->thread; } waitp->thread->state.store(PerThreadSynch::kQueued, std::memory_order_relaxed); cv_word->store((v & kCvEvent) | reinterpret_cast<intptr_t>(waitp->thread), std::memory_order_release); } bool CondVar::WaitCommon(Mutex* mutex, KernelTimeout t) { bool rc = false; intptr_t mutex_v = mutex->mu_.load(std::memory_order_relaxed); Mutex::MuHow mutex_how = ((mutex_v & kMuWriter) != 0) ? kExclusive : kShared; ABSL_TSAN_MUTEX_PRE_UNLOCK(mutex, TsanFlags(mutex_how)); intptr_t v = cv_.load(std::memory_order_relaxed); cond_var_tracer("Wait", this); if ((v & kCvEvent) != 0) { PostSynchEvent(this, SYNCH_EV_WAIT); } SynchWaitParams waitp(mutex_how, nullptr, t, mutex, Synch_GetPerThreadAnnotated(mutex), &cv_); mutex->UnlockSlow(&waitp); while (waitp.thread->state.load(std::memory_order_acquire) == PerThreadSynch::kQueued) { if (!Mutex::DecrementSynchSem(mutex, waitp.thread, t)) { t = KernelTimeout::Never(); this->Remove(waitp.thread); rc = true; } } ABSL_RAW_CHECK(waitp.thread->waitp != nullptr, "not waiting when should be"); waitp.thread->waitp = nullptr; cond_var_tracer("Unwait", this); if ((v & kCvEvent) != 0) { PostSynchEvent(this, SYNCH_EV_WAIT_RETURNING); } ABSL_TSAN_MUTEX_POST_UNLOCK(mutex, TsanFlags(mutex_how)); ABSL_TSAN_MUTEX_PRE_LOCK(mutex, TsanFlags(mutex_how)); mutex->Trans(mutex_how); ABSL_TSAN_MUTEX_POST_LOCK(mutex, TsanFlags(mutex_how), 0); return rc; } void CondVar::Signal() { SchedulingGuard::ScopedDisable disable_rescheduling; ABSL_TSAN_MUTEX_PRE_SIGNAL(nullptr, 0); intptr_t v; int c = 0; for (v = cv_.load(std::memory_order_relaxed); v != 0; v = cv_.load(std::memory_order_relaxed)) { if ((v & kCvSpin) == 0 && cv_.compare_exchange_strong(v, v | kCvSpin, std::memory_order_acquire, std::memory_order_relaxed)) { PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow); PerThreadSynch* w = nullptr; if (h != nullptr) { w = h->next; if (w == h) { h = nullptr; } else { h->next = w->next; } } cv_.store((v & kCvEvent) | reinterpret_cast<intptr_t>(h), std::memory_order_release); if (w != nullptr) { w->waitp->cvmu->Fer(w); cond_var_tracer("Signal wakeup", this); } if ((v & kCvEvent) != 0) { PostSynchEvent(this, SYNCH_EV_SIGNAL); } ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0); return; } else { c = synchronization_internal::MutexDelay(c, GENTLE); } } ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0); } void CondVar::SignalAll() { ABSL_TSAN_MUTEX_PRE_SIGNAL(nullptr, 0); intptr_t v; int c = 0; for (v = cv_.load(std::memory_order_relaxed); v != 0; v = cv_.load(std::memory_order_relaxed)) { if ((v & kCvSpin) == 0 && cv_.compare_exchange_strong(v, v & kCvEvent, std::memory_order_acquire, std::memory_order_relaxed)) { PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow); if (h != nullptr) { PerThreadSynch* w; PerThreadSynch* n = h->next; do { w = n; n = n->next; w->waitp->cvmu->Fer(w); } while (w != h); cond_var_tracer("SignalAll wakeup", this); } if ((v & kCvEvent) != 0) { PostSynchEvent(this, SYNCH_EV_SIGNALALL); } ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0); return; } else { c = synchronization_internal::MutexDelay(c, GENTLE); } } ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0); } void ReleasableMutexLock::Release() { ABSL_RAW_CHECK(this->mu_ != nullptr, "ReleasableMutexLock::Release may only be called once"); this->mu_->Unlock(); this->mu_ = nullptr; } #ifdef ABSL_HAVE_THREAD_SANITIZER extern "C" void __tsan_read1(void* addr); #else #define __tsan_read1(addr) #endif static bool Dereference(void* arg) { __tsan_read1(arg); return *(static_cast<bool*>(arg)); } ABSL_CONST_INIT const Condition Condition::kTrue; Condition::Condition(bool (*func)(void*), void* arg) : eval_(&CallVoidPtrFunction), arg_(arg) { static_assert(sizeof(&func) <= sizeof(callback_), "An overlarge function pointer passed to Condition."); StoreCallback(func); } bool Condition::CallVoidPtrFunction(const Condition* c) { using FunctionPointer = bool (*)(void*); FunctionPointer function_pointer; std::memcpy(&function_pointer, c->callback_, sizeof(function_pointer)); return (*function_pointer)(c->arg_); } Condition::Condition(const bool* cond) : eval_(CallVoidPtrFunction), arg_(const_cast<bool*>(cond)) { using FunctionPointer = bool (*)(void*); const FunctionPointer dereference = Dereference; StoreCallback(dereference); } bool Condition::Eval() const { return (*this->eval_)(this); } bool Condition::GuaranteedEqual(const Condition* a, const Condition* b) { if (a == nullptr || b == nullptr) { return a == b; } return a->eval_ == b->eval_ && a->arg_ == b->arg_ && !memcmp(a->callback_, b->callback_, sizeof(a->callback_)); } ABSL_NAMESPACE_END }
#include "absl/synchronization/mutex.h" #ifdef _WIN32 #include <windows.h> #endif #include <algorithm> #include <atomic> #include <cstdlib> #include <functional> #include <memory> #include <random> #include <string> #include <thread> #include <type_traits> #include <vector> #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/sysinfo.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/synchronization/internal/create_thread_identity.h" #include "absl/synchronization/internal/thread_pool.h" #include "absl/time/clock.h" #include "absl/time/time.h" #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM #include <pthread.h> #include <string.h> #endif namespace { static constexpr bool kExtendedTest = false; std::unique_ptr<absl::synchronization_internal::ThreadPool> CreatePool( int threads) { return absl::make_unique<absl::synchronization_internal::ThreadPool>(threads); } std::unique_ptr<absl::synchronization_internal::ThreadPool> CreateDefaultPool() { return CreatePool(kExtendedTest ? 32 : 10); } static void ScheduleAfter(absl::synchronization_internal::ThreadPool *tp, absl::Duration after, const std::function<void()> &func) { tp->Schedule([func, after] { absl::SleepFor(after); func(); }); } struct ScopedInvariantDebugging { ScopedInvariantDebugging() { absl::EnableMutexInvariantDebugging(true); } ~ScopedInvariantDebugging() { absl::EnableMutexInvariantDebugging(false); } }; struct TestContext { int iterations; int threads; int g0; int g1; absl::Mutex mu; absl::CondVar cv; }; static std::atomic<bool> invariant_checked; static bool GetInvariantChecked() { return invariant_checked.load(std::memory_order_relaxed); } static void SetInvariantChecked(bool new_value) { invariant_checked.store(new_value, std::memory_order_relaxed); } static void CheckSumG0G1(void *v) { TestContext *cxt = static_cast<TestContext *>(v); CHECK_EQ(cxt->g0, -cxt->g1) << "Error in CheckSumG0G1"; SetInvariantChecked(true); } static void TestMu(TestContext *cxt, int c) { for (int i = 0; i != cxt->iterations; i++) { absl::MutexLock l(&cxt->mu); int a = cxt->g0 + 1; cxt->g0 = a; cxt->g1--; } } static void TestTry(TestContext *cxt, int c) { for (int i = 0; i != cxt->iterations; i++) { do { std::this_thread::yield(); } while (!cxt->mu.TryLock()); int a = cxt->g0 + 1; cxt->g0 = a; cxt->g1--; cxt->mu.Unlock(); } } static void TestR20ms(TestContext *cxt, int c) { for (int i = 0; i != cxt->iterations; i++) { absl::ReaderMutexLock l(&cxt->mu); absl::SleepFor(absl::Milliseconds(20)); cxt->mu.AssertReaderHeld(); } } static void TestRW(TestContext *cxt, int c) { if ((c & 1) == 0) { for (int i = 0; i != cxt->iterations; i++) { absl::WriterMutexLock l(&cxt->mu); cxt->g0++; cxt->g1--; cxt->mu.AssertHeld(); cxt->mu.AssertReaderHeld(); } } else { for (int i = 0; i != cxt->iterations; i++) { absl::ReaderMutexLock l(&cxt->mu); CHECK_EQ(cxt->g0, -cxt->g1) << "Error in TestRW"; cxt->mu.AssertReaderHeld(); } } } struct MyContext { int target; TestContext *cxt; bool MyTurn(); }; bool MyContext::MyTurn() { TestContext *cxt = this->cxt; return cxt->g0 == this->target || cxt->g0 == cxt->iterations; } static void TestAwait(TestContext *cxt, int c) { MyContext mc; mc.target = c; mc.cxt = cxt; absl::MutexLock l(&cxt->mu); cxt->mu.AssertHeld(); while (cxt->g0 < cxt->iterations) { cxt->mu.Await(absl::Condition(&mc, &MyContext::MyTurn)); CHECK(mc.MyTurn()) << "Error in TestAwait"; cxt->mu.AssertHeld(); if (cxt->g0 < cxt->iterations) { int a = cxt->g0 + 1; cxt->g0 = a; mc.target += cxt->threads; } } } static void TestSignalAll(TestContext *cxt, int c) { int target = c; absl::MutexLock l(&cxt->mu); cxt->mu.AssertHeld(); while (cxt->g0 < cxt->iterations) { while (cxt->g0 != target && cxt->g0 != cxt->iterations) { cxt->cv.Wait(&cxt->mu); } if (cxt->g0 < cxt->iterations) { int a = cxt->g0 + 1; cxt->g0 = a; cxt->cv.SignalAll(); target += cxt->threads; } } } static void TestSignal(TestContext *cxt, int c) { CHECK_EQ(cxt->threads, 2) << "TestSignal should use 2 threads"; int target = c; absl::MutexLock l(&cxt->mu); cxt->mu.AssertHeld(); while (cxt->g0 < cxt->iterations) { while (cxt->g0 != target && cxt->g0 != cxt->iterations) { cxt->cv.Wait(&cxt->mu); } if (cxt->g0 < cxt->iterations) { int a = cxt->g0 + 1; cxt->g0 = a; cxt->cv.Signal(); target += cxt->threads; } } } static void TestCVTimeout(TestContext *cxt, int c) { int target = c; absl::MutexLock l(&cxt->mu); cxt->mu.AssertHeld(); while (cxt->g0 < cxt->iterations) { while (cxt->g0 != target && cxt->g0 != cxt->iterations) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(100)); } if (cxt->g0 < cxt->iterations) { int a = cxt->g0 + 1; cxt->g0 = a; cxt->cv.SignalAll(); target += cxt->threads; } } } static bool G0GE2(TestContext *cxt) { return cxt->g0 >= 2; } static void TestTime(TestContext *cxt, int c, bool use_cv) { CHECK_EQ(cxt->iterations, 1) << "TestTime should only use 1 iteration"; CHECK_GT(cxt->threads, 2) << "TestTime should use more than 2 threads"; const bool kFalse = false; absl::Condition false_cond(&kFalse); absl::Condition g0ge2(G0GE2, cxt); if (c == 0) { absl::MutexLock l(&cxt->mu); absl::Time start = absl::Now(); if (use_cv) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1)); } else { CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1))) << "TestTime failed"; } absl::Duration elapsed = absl::Now() - start; CHECK(absl::Seconds(0.9) <= elapsed && elapsed <= absl::Seconds(2.0)) << "TestTime failed"; CHECK_EQ(cxt->g0, 1) << "TestTime failed"; start = absl::Now(); if (use_cv) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1)); } else { CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1))) << "TestTime failed"; } elapsed = absl::Now() - start; CHECK(absl::Seconds(0.9) <= elapsed && elapsed <= absl::Seconds(2.0)) << "TestTime failed"; cxt->g0++; if (use_cv) { cxt->cv.Signal(); } start = absl::Now(); if (use_cv) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(4)); } else { CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(4))) << "TestTime failed"; } elapsed = absl::Now() - start; CHECK(absl::Seconds(3.9) <= elapsed && elapsed <= absl::Seconds(6.0)) << "TestTime failed"; CHECK_GE(cxt->g0, 3) << "TestTime failed"; start = absl::Now(); if (use_cv) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1)); } else { CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1))) << "TestTime failed"; } elapsed = absl::Now() - start; CHECK(absl::Seconds(0.9) <= elapsed && elapsed <= absl::Seconds(2.0)) << "TestTime failed"; if (use_cv) { cxt->cv.SignalAll(); } start = absl::Now(); if (use_cv) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(1)); } else { CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Seconds(1))) << "TestTime failed"; } elapsed = absl::Now() - start; CHECK(absl::Seconds(0.9) <= elapsed && elapsed <= absl::Seconds(2.0)) << "TestTime failed"; CHECK_EQ(cxt->g0, cxt->threads) << "TestTime failed"; } else if (c == 1) { absl::MutexLock l(&cxt->mu); const absl::Time start = absl::Now(); if (use_cv) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Milliseconds(500)); } else { CHECK(!cxt->mu.AwaitWithTimeout(false_cond, absl::Milliseconds(500))) << "TestTime failed"; } const absl::Duration elapsed = absl::Now() - start; CHECK(absl::Seconds(0.4) <= elapsed && elapsed <= absl::Seconds(0.9)) << "TestTime failed"; cxt->g0++; } else if (c == 2) { absl::MutexLock l(&cxt->mu); if (use_cv) { while (cxt->g0 < 2) { cxt->cv.WaitWithTimeout(&cxt->mu, absl::Seconds(100)); } } else { CHECK(cxt->mu.AwaitWithTimeout(g0ge2, absl::Seconds(100))) << "TestTime failed"; } cxt->g0++; } else { absl::MutexLock l(&cxt->mu); if (use_cv) { while (cxt->g0 < 2) { cxt->cv.Wait(&cxt->mu); } } else { cxt->mu.Await(g0ge2); } cxt->g0++; } } static void TestMuTime(TestContext *cxt, int c) { TestTime(cxt, c, false); } static void TestCVTime(TestContext *cxt, int c) { TestTime(cxt, c, true); } static void EndTest(int *c0, int *c1, absl::Mutex *mu, absl::CondVar *cv, const std::function<void(int)> &cb) { mu->Lock(); int c = (*c0)++; mu->Unlock(); cb(c); absl::MutexLock l(mu); (*c1)++; cv->Signal(); } static int RunTestCommon(TestContext *cxt, void (*test)(TestContext *cxt, int), int threads, int iterations, int operations) { absl::Mutex mu2; absl::CondVar cv2; int c0 = 0; int c1 = 0; cxt->g0 = 0; cxt->g1 = 0; cxt->iterations = iterations; cxt->threads = threads; absl::synchronization_internal::ThreadPool tp(threads); for (int i = 0; i != threads; i++) { tp.Schedule(std::bind( &EndTest, &c0, &c1, &mu2, &cv2, std::function<void(int)>(std::bind(test, cxt, std::placeholders::_1)))); } mu2.Lock(); while (c1 != threads) { cv2.Wait(&mu2); } mu2.Unlock(); return cxt->g0; } static int RunTest(void (*test)(TestContext *cxt, int), int threads, int iterations, int operations) { TestContext cxt; return RunTestCommon(&cxt, test, threads, iterations, operations); } #if !defined(ABSL_MUTEX_ENABLE_INVARIANT_DEBUGGING_NOT_IMPLEMENTED) static int RunTestWithInvariantDebugging(void (*test)(TestContext *cxt, int), int threads, int iterations, int operations, void (*invariant)(void *)) { ScopedInvariantDebugging scoped_debugging; SetInvariantChecked(false); TestContext cxt; cxt.mu.EnableInvariantDebugging(invariant, &cxt); int ret = RunTestCommon(&cxt, test, threads, iterations, operations); CHECK(GetInvariantChecked()) << "Invariant not checked"; return ret; } #endif struct TimeoutBugStruct { absl::Mutex mu; bool a; int a_waiter_count; }; static void WaitForA(TimeoutBugStruct *x) { x->mu.LockWhen(absl::Condition(&x->a)); x->a_waiter_count--; x->mu.Unlock(); } static bool NoAWaiters(TimeoutBugStruct *x) { return x->a_waiter_count == 0; } TEST(Mutex, CondVarWaitSignalsAwait) { struct { absl::Mutex barrier_mu; bool barrier ABSL_GUARDED_BY(barrier_mu) = false; absl::Mutex release_mu; bool release ABSL_GUARDED_BY(release_mu) = false; absl::CondVar released_cv; } state; auto pool = CreateDefaultPool(); pool->Schedule([&state] { state.release_mu.Lock(); state.barrier_mu.Lock(); state.barrier = true; state.barrier_mu.Unlock(); state.release_mu.Await(absl::Condition(&state.release)); state.released_cv.Signal(); state.release_mu.Unlock(); }); state.barrier_mu.LockWhen(absl::Condition(&state.barrier)); state.barrier_mu.Unlock(); state.release_mu.Lock(); state.release = true; state.released_cv.Wait(&state.release_mu); state.release_mu.Unlock(); } TEST(Mutex, CondVarWaitWithTimeoutSignalsAwait) { struct { absl::Mutex barrier_mu; bool barrier ABSL_GUARDED_BY(barrier_mu) = false; absl::Mutex release_mu; bool release ABSL_GUARDED_BY(release_mu) = false; absl::CondVar released_cv; } state; auto pool = CreateDefaultPool(); pool->Schedule([&state] { state.release_mu.Lock(); state.barrier_mu.Lock(); state.barrier = true; state.barrier_mu.Unlock(); state.release_mu.Await(absl::Condition(&state.release)); state.released_cv.Signal(); state.release_mu.Unlock(); }); state.barrier_mu.LockWhen(absl::Condition(&state.barrier)); state.barrier_mu.Unlock(); state.release_mu.Lock(); state.release = true; EXPECT_TRUE( !state.released_cv.WaitWithTimeout(&state.release_mu, absl::Seconds(10))) << "; Unrecoverable test failure: CondVar::WaitWithTimeout did not " "unblock the absl::Mutex::Await call in another thread."; state.release_mu.Unlock(); } TEST(Mutex, MutexTimeoutBug) { auto tp = CreateDefaultPool(); TimeoutBugStruct x; x.a = false; x.a_waiter_count = 2; tp->Schedule(std::bind(&WaitForA, &x)); tp->Schedule(std::bind(&WaitForA, &x)); absl::SleepFor(absl::Seconds(1)); bool always_false = false; x.mu.LockWhenWithTimeout(absl::Condition(&always_false), absl::Milliseconds(500)); x.a = true; x.mu.Await(absl::Condition(&NoAWaiters, &x)); x.mu.Unlock(); } struct CondVarWaitDeadlock : testing::TestWithParam<int> { absl::Mutex mu; absl::CondVar cv; bool cond1 = false; bool cond2 = false; bool read_lock1; bool read_lock2; bool signal_unlocked; CondVarWaitDeadlock() { read_lock1 = GetParam() & (1 << 0); read_lock2 = GetParam() & (1 << 1); signal_unlocked = GetParam() & (1 << 2); } void Waiter1() { if (read_lock1) { mu.ReaderLock(); while (!cond1) { cv.Wait(&mu); } mu.ReaderUnlock(); } else { mu.Lock(); while (!cond1) { cv.Wait(&mu); } mu.Unlock(); } } void Waiter2() { if (read_lock2) { mu.ReaderLockWhen(absl::Condition(&cond2)); mu.ReaderUnlock(); } else { mu.LockWhen(absl::Condition(&cond2)); mu.Unlock(); } } }; TEST_P(CondVarWaitDeadlock, Test) { auto waiter1 = CreatePool(1); auto waiter2 = CreatePool(1); waiter1->Schedule([this] { this->Waiter1(); }); waiter2->Schedule([this] { this->Waiter2(); }); absl::SleepFor(absl::Milliseconds(100)); mu.Lock(); cond1 = true; if (signal_unlocked) { mu.Unlock(); cv.Signal(); } else { cv.Signal(); mu.Unlock(); } waiter1.reset(); mu.Lock(); cond2 = true; mu.Unlock(); waiter2.reset(); } INSTANTIATE_TEST_SUITE_P(CondVarWaitDeadlockTest, CondVarWaitDeadlock, ::testing::Range(0, 8), ::testing::PrintToStringParamName()); struct DequeueAllWakeableBugStruct { absl::Mutex mu; absl::Mutex mu2; int unfinished_count; bool done1; int finished_count; bool done2; }; static void AcquireAsReader(DequeueAllWakeableBugStruct *x) { x->mu.ReaderLock(); x->mu2.Lock(); x->unfinished_count--; x->done1 = (x->unfinished_count == 0); x->mu2.Unlock(); absl::SleepFor(absl::Seconds(2)); x->mu.ReaderUnlock(); x->mu2.Lock(); x->finished_count--; x->done2 = (x->finished_count == 0); x->mu2.Unlock(); } TEST(Mutex, MutexReaderWakeupBug) { auto tp = CreateDefaultPool(); DequeueAllWakeableBugStruct x; x.unfinished_count = 2; x.done1 = false; x.finished_count = 2; x.done2 = false; x.mu.Lock(); tp->Schedule(std::bind(&AcquireAsReader, &x)); tp->Schedule(std::bind(&AcquireAsReader, &x)); absl::SleepFor(absl::Seconds(1)); x.mu.Unlock(); EXPECT_TRUE( x.mu2.LockWhenWithTimeout(absl::Condition(&x.done1), absl::Seconds(10))); x.mu2.Unlock(); EXPECT_TRUE( x.mu2.LockWhenWithTimeout(absl::Condition(&x.done2), absl::Seconds(10))); x.mu2.Unlock(); } struct LockWhenTestStruct { absl::Mutex mu1; bool cond = false; absl::Mutex mu2; bool waiting = false; }; static bool LockWhenTestIsCond(LockWhenTestStruct *s) { s->mu2.Lock(); s->waiting = true; s->mu2.Unlock(); return s->cond; } static void LockWhenTestWaitForIsCond(LockWhenTestStruct *s) { s->mu1.LockWhen(absl::Condition(&LockWhenTestIsCond, s)); s->mu1.Unlock(); } TEST(Mutex, LockWhen) { LockWhenTestStruct s; std::thread t(LockWhenTestWaitForIsCond, &s); s.mu2.LockWhen(absl::Condition(&s.waiting)); s.mu2.Unlock(); s.mu1.Lock(); s.cond = true; s.mu1.Unlock(); t.join(); } TEST(Mutex, LockWhenGuard) { absl::Mutex mu; int n = 30; bool done = false; bool (*cond_eq_10)(int *) = [](int *p) { return *p == 10; }; bool (*cond_lt_10)(int *) = [](int *p) { return *p < 10; }; std::thread t1([&mu, &n, &done, cond_eq_10]() { absl::ReaderMutexLock lock(&mu, absl::Condition(cond_eq_10, &n)); done = true; }); std::thread t2[10]; for (std::thread &t : t2) { t = std::thread([&mu, &n, cond_lt_10]() { absl::WriterMutexLock lock(&mu, absl::Condition(cond_lt_10, &n)); ++n; }); } { absl::MutexLock lock(&mu); n = 0; } for (std::thread &t : t2) t.join(); t1.join(); EXPECT_TRUE(done); EXPECT_EQ(n, 10); } #if !defined(ABSL_MUTEX_READER_LOCK_IS_EXCLUSIVE) struct ReaderDecrementBugStruct { bool cond; int done; absl::Mutex mu; bool waiting_on_cond; bool have_reader_lock; bool complete; absl::Mutex mu2; }; static bool IsCond(void *v) { ReaderDecrementBugStruct *x = reinterpret_cast<ReaderDecrementBugStruct *>(v); x->mu2.Lock(); x->waiting_on_cond = true; x->mu2.Unlock(); return x->cond; } static bool AllDone(void *v) { ReaderDecrementBugStruct *x = reinterpret_cast<ReaderDecrementBugStruct *>(v); return x->done == 0; } static void WaitForCond(ReaderDecrementBugStruct *x) { absl::Mutex dummy; absl::MutexLock l(&dummy); x->mu.LockWhen(absl::Condition(&IsCond, x)); x->done--; x->mu.Unlock(); } static void GetReadLock(ReaderDecrementBugStruct *x) { x->mu.ReaderLock(); x->mu2.Lock(); x->have_reader_lock = true; x->mu2.Await(absl::Condition(&x->complete)); x->mu2.Unlock(); x->mu.ReaderUnlock(); x->mu.Lock(); x->done--; x->mu.Unlock(); } TEST(Mutex, MutexReaderDecrementBug) ABSL_NO_THREAD_SAFETY_ANALYSIS { ReaderDecrementBugStruct x; x.cond = false; x.waiting_on_cond = false; x.have_reader_lock = false; x.complete = false; x.done = 2; std::thread thread1(WaitForCond, &x); x.mu2.LockWhen(absl::Condition(&x.waiting_on_cond)); x.mu2.Unlock(); std::thread thread2(GetReadLock, &x); x.mu2.LockWhen(absl::Condition(&x.have_reader_lock)); x.mu2.Unlock(); x.mu.ReaderLock(); x.mu.ReaderUnlock(); x.mu.AssertReaderHeld(); x.mu2.Lock(); x.complete = true; x.mu2.Unlock(); x.mu.Lock(); x.cond = true; x.mu.Await(absl::Condition(&AllDone, &x)); x.mu.Unlock(); thread1.join(); thread2.join(); } #endif #ifdef ABSL_HAVE_THREAD_SANITIZER TEST(Mutex, DISABLED_LockedMutexDestructionBug) ABSL_NO_THREAD_SAFETY_ANALYSIS { #else TEST(Mutex, LockedMutexDestructionBug) ABSL_NO_THREAD_SAFETY_ANALYSIS { #endif for (int i = 0; i != 10; i++) { const int kNumLocks = 10; auto mu = absl::make_unique<absl::Mutex[]>(kNumLocks); for (int j = 0; j != kNumLocks; j++) { if ((j % 2) == 0) { mu[j].WriterLock(); } else { mu[j].ReaderLock(); } } } } bool Equals42(int *p) { return *p == 42; } bool Equals43(int *p) { return *p == 43; } bool ConstEquals42(const int *p) { return *p == 42; } bool ConstEquals43(const int *p) { return *p == 43; } template <typename T> bool TemplateEquals42(T *p) { return *p == 42; } template <typename T> bool TemplateEquals43(T *p) { return *p == 43; } TEST(Mutex, FunctionPointerCondition) { int x = 42; const int const_x = 42; EXPECT_TRUE(absl::Condition(Equals42, &x).Eval()); EXPECT_FALSE(absl::Condition(Equals43, &x).Eval()); EXPECT_TRUE(absl::Condition(ConstEquals42, &x).Eval()); EXPECT_FALSE(absl::Condition(ConstEquals43, &x).Eval()); EXPECT_TRUE(absl::Condition(ConstEquals42, &const_x).Eval()); EXPECT_FALSE(absl::Condition(ConstEquals43, &const_x).Eval()); EXPECT_TRUE(absl::Condition(TemplateEquals42, &x).Eval()); EXPECT_FALSE(absl::Condition(TemplateEquals43, &x).Eval()); EXPECT_TRUE(absl::Condition(TemplateEquals42, &const_x).Eval()); EXPECT_FALSE(absl::Condition(TemplateEquals43, &const_x).Eval()); EXPECT_FALSE((std::is_constructible<absl::Condition, decltype(Equals42), decltype(&const_x)>::value)); EXPECT_TRUE((std::is_constructible<absl::Condition, decltype(ConstEquals42), decltype(&const_x)>::value)); } struct Base { explicit Base(int v) : value(v) {} int value; }; struct Derived : Base { explicit Derived(int v) : Base(v) {} }; bool BaseEquals42(Base *p) { return p->value == 42; } bool BaseEquals43(Base *p) { return p->value == 43; } bool ConstBaseEquals42(const Base *p) { return p->value == 42; } bool ConstBaseEquals43(const Base *p) { return p->value == 43; } TEST(Mutex, FunctionPointerConditionWithDerivedToBaseConversion) { Derived derived(42); const Derived const_derived(42); EXPECT_TRUE(absl::Condition(BaseEquals42, &derived).Eval()); EXPECT_FALSE(absl::Condition(BaseEquals43, &derived).Eval()); EXPECT_TRUE(absl::Condition(ConstBaseEquals42, &derived).Eval()); EXPECT_FALSE(absl::Condition(ConstBaseEquals43, &derived).Eval()); EXPECT_TRUE(absl::Condition(ConstBaseEquals42, &const_derived).Eval()); EXPECT_FALSE(absl::Condition(ConstBaseEquals43, &const_derived).Eval()); EXPECT_TRUE(absl::Condition(ConstBaseEquals42, &const_derived).Eval()); EXPECT_FALSE(absl::Condition(ConstBaseEquals43, &const_derived).Eval()); bool (*derived_pred)(const Derived *) = [](const Derived *) { return true; }; EXPECT_FALSE((std::is_constructible<absl::Condition, decltype(derived_pred), Base *>::value)); EXPECT_FALSE((std::is_constructible<absl::Condition, decltype(derived_pred), const Base *>::value)); EXPECT_TRUE((std::is_constructible<absl::Condition, decltype(derived_pred), Derived *>::value)); EXPECT_TRUE((std::is_constructible<absl::Condition, decltype(derived_pred), const Derived *>::value)); } struct Constable { bool WotsAllThisThen() const { return true; } }; TEST(Mutex, FunctionPointerConditionWithConstMethod) { const Constable chapman; EXPECT_TRUE(absl::Condition(&chapman, &Constable::WotsAllThisThen).Eval()); } struct True { template <class... Args> bool operator()(Args...) const { return true; } }; struct DerivedTrue : True {}; TEST(Mutex, FunctorCondition) { { True f; EXPECT_TRUE(absl::Condition(&f).Eval()); } { DerivedTrue g; EXPECT_TRUE(absl::Condition(&g).Eval()); } { int value = 3; auto is_zero = [&value] { return value == 0; }; absl::Condition c(&is_zero); EXPECT_FALSE(c.Eval()); value = 0; EXPECT_TRUE(c.Eval()); } { int value = 0; auto is_positive = std::bind(std::less<int>(), 0, std::cref(value)); absl::Condition c(&is_positive); EXPECT_FALSE(c.Eval()); value = 1; EXPECT_TRUE(c.Eval()); } { int value = 3; std::function<bool()> is_zero = [&value] { return value == 0; }; absl::Condition c(&is_zero); EXPECT_FALSE(c.Eval()); value = 0; EXPECT_TRUE(c.Eval()); } } TEST(Mutex, ConditionSwap) { bool b1 = true; absl::Condition c1(&b1); bool b2 = false; absl::Condition c2(&b2); EXPECT_TRUE(c1.Eval()); EXPECT_FALSE(c2.Eval()); std::swap(c1, c2); EXPECT_FALSE(c1.Eval()); EXPECT_TRUE(c2.Eval()); } static void ReaderForReaderOnCondVar(absl::Mutex *mu, absl::CondVar *cv, int *running) { std::random_device dev; std::mt19937 gen(dev()); std::uniform_int_distribution<int> random_millis(0, 15); mu->ReaderLock(); while (*running == 3) { absl::SleepFor(absl::Milliseconds(random_millis(gen))); cv->WaitWithTimeout(mu, absl::Milliseconds(random_millis(gen))); } mu->ReaderUnlock(); mu->Lock(); (*running)--; mu->Unlock(); } static bool IntIsZero(int *x) { return *x == 0; } TEST(Mutex, TestReaderOnCondVar) { auto tp = CreateDefaultPool(); absl::Mutex mu; absl::CondVar cv; int running = 3; tp->Schedule(std::bind(&ReaderForReaderOnCondVar, &mu, &cv, &running)); tp->Schedule(std::bind(&ReaderForReaderOnCondVar, &mu, &cv, &running)); absl::SleepFor(absl::Seconds(2)); mu.Lock(); running--; mu.Await(absl::Condition(&IntIsZero, &running)); mu.Unlock(); } struct AcquireFromConditionStruct { absl::Mutex mu0; int value; bool done; absl::Mutex mu1; absl::CondVar cv; }; static bool ConditionWithAcquire(AcquireFromConditionStruct *x) { x->value++; if (x->value == 2 || x->value == 3) { bool always_false = false; x->mu1.LockWhenWithTimeout(absl::Condition(&always_false), absl::Milliseconds(100)); x->mu1.Unlock(); } CHECK_LT(x->value, 4) << "should not be invoked a fourth time"; return x->value == 2 || x->value == 3; } static void WaitForCond2(AcquireFromConditionStruct *x) { x->mu0.LockWhen(absl::Condition(&ConditionWithAcquire, x)); x->done = true; x->mu0.Unlock(); } TEST(Mutex, AcquireFromCondition) { auto tp = CreateDefaultPool(); AcquireFromConditionStruct x; x.value = 0; x.done = false; tp->Schedule( std::bind(&WaitForCond2, &x)); absl::SleepFor(absl::Milliseconds(500)); x.mu0.Lock(); x.cv.WaitWithTimeout(&x.mu0, absl::Milliseconds(500)); x.mu0.Unlock(); x.mu0.LockWhen(absl::Condition(&x.done)); x.mu0.Unlock(); } TEST(Mutex, DeadlockDetector) { absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); absl::Mutex m1; absl::Mutex m2; absl::Mutex m3; absl::Mutex m4; m1.Lock(); m2.Lock(); m3.Lock(); m3.Unlock(); m2.Unlock(); m1.ForgetDeadlockInfo(); m2.Lock(); m3.Lock(); m4.Lock(); m3.Unlock(); m2.Unlock(); m4.Unlock(); m1.Unlock(); } class ScopedDisableBazelTestWarnings { public: ScopedDisableBazelTestWarnings() { #ifdef _WIN32 char file[MAX_PATH]; if (GetEnvironmentVariableA(kVarName, file, sizeof(file)) < sizeof(file)) { warnings_output_file_ = file; SetEnvironmentVariableA(kVarName, nullptr); } #else const char *file = getenv(kVarName); if (file != nullptr) { warnings_output_file_ = file; unsetenv(kVarName); } #endif } ~ScopedDisableBazelTestWarnings() { if (!warnings_output_file_.empty()) { #ifdef _WIN32 SetEnvironmentVariableA(kVarName, warnings_output_file_.c_str()); #else setenv(kVarName, warnings_output_file_.c_str(), 0); #endif } } private: static const char kVarName[]; std::string warnings_output_file_; }; const char ScopedDisableBazelTestWarnings::kVarName[] = "TEST_WARNINGS_OUTPUT_FILE"; #ifdef ABSL_HAVE_THREAD_SANITIZER TEST(Mutex, DISABLED_DeadlockDetectorBazelWarning) { #else TEST(Mutex, DeadlockDetectorBazelWarning) { #endif absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kReport); ScopedDisableBazelTestWarnings disable_bazel_test_warnings; absl::Mutex mu0; absl::Mutex mu1; bool got_mu0 = mu0.TryLock(); mu1.Lock(); if (got_mu0) { mu0.Unlock(); } if (mu0.TryLock()) { mu0.Unlock(); } mu0.Lock(); mu0.Unlock(); mu1.Unlock(); absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); } TEST(Mutex, DeadlockDetectorLongCycle) { absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kReport); ScopedDisableBazelTestWarnings disable_bazel_test_warnings; std::vector<absl::Mutex> mutex(100); for (size_t i = 0; i != mutex.size(); i++) { mutex[i].Lock(); mutex[(i + 1) % mutex.size()].Lock(); mutex[i].Unlock(); mutex[(i + 1) % mutex.size()].Unlock(); } absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); } TEST(Mutex, DeadlockDetectorStressTest) ABSL_NO_THREAD_SAFETY_ANALYSIS { const int n_locks = 1 << 17; auto array_of_locks = absl::make_unique<absl::Mutex[]>(n_locks); for (int i = 0; i < n_locks; i++) { int end = std::min(n_locks, i + 5); for (int j = i; j < end; j++) { array_of_locks[j].Lock(); } for (int j = i; j < end; j++) { array_of_locks[j].Unlock(); } } } #ifdef ABSL_HAVE_THREAD_SANITIZER TEST(Mutex, DISABLED_DeadlockIdBug) ABSL_NO_THREAD_SAFETY_ANALYSIS { #else TEST(Mutex, DeadlockIdBug) ABSL_NO_THREAD_SAFETY_ANALYSIS { #endif absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); absl::Mutex *a = new absl::Mutex; absl::Mutex b, c; a->Lock(); b.Lock(); b.Unlock(); absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kIgnore); delete a; absl::SetMutexDeadlockDetectionMode(absl::OnDeadlockCycle::kAbort); c.Lock(); c.Unlock(); } static absl::Duration TimeoutTestAllowedSchedulingDelay() { return absl::Milliseconds(150); } ABSL_MUST_USE_RESULT static bool DelayIsWithinBounds(absl::Duration expected_delay, absl::Duration actual_delay) { bool pass = true; if (actual_delay < expected_delay) { LOG(WARNING) << "Actual delay " << actual_delay << " was too short, expected " << expected_delay << " (difference " << actual_delay - expected_delay << ")"; pass = false; } absl::Duration tolerance = expected_delay <= absl::ZeroDuration() ? absl::Milliseconds(10) : TimeoutTestAllowedSchedulingDelay(); if (actual_delay > expected_delay + tolerance) { LOG(WARNING) << "Actual delay " << actual_delay << " was too long, expected " << expected_delay << " (difference " << actual_delay - expected_delay << ")"; pass = false; } return pass; } struct TimeoutTestParam { const char *from_file; int from_line; bool use_absolute_deadline; absl::Duration wait_timeout; absl::Duration satisfy_condition_delay; bool expected_result; absl::Duration expected_delay; }; std::ostream &operator<<(std::ostream &os, const TimeoutTestParam &param) { return os << "from: " << param.from_file << ":" << param.from_line << " use_absolute_deadline: " << (param.use_absolute_deadline ? "true" : "false") << " wait_timeout: " << param.wait_timeout << " satisfy_condition_delay: " << param.satisfy_condition_delay << " expected_result: " << (param.expected_result ? "true" : "false") << " expected_delay: " << param.expected_delay; } static void RunAfterDelay(absl::Duration delay, absl::synchronization_internal::ThreadPool *pool, const std::function<void()> &callback) { if (delay <= absl::ZeroDuration()) { callback(); } else if (delay != absl::InfiniteDuration()) { ScheduleAfter(pool, delay, callback); } } class TimeoutTest : public ::testing::Test, public ::testing::WithParamInterface<TimeoutTestParam> {}; std::vector<TimeoutTestParam> MakeTimeoutTestParamValues() { const absl::Duration finite = 3 * TimeoutTestAllowedSchedulingDelay(); const absl::Duration never = absl::InfiniteDuration(); const absl::Duration negative = -absl::InfiniteDuration(); const absl::Duration immediate = absl::ZeroDuration(); std::vector<TimeoutTestParam> values; for (bool use_absolute_deadline : {false, true}) { values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, negative, immediate, true, immediate, }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, negative, finite, false, immediate }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, negative, never, false, immediate }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, never, immediate, true, immediate }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, never, finite, true, finite, }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, never, immediate, true, immediate }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, finite * 2, finite, true, finite }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, finite, finite * 2, false, finite }); values.push_back(TimeoutTestParam{ __FILE__, __LINE__, use_absolute_deadline, finite, never, false, finite }); } return values; } INSTANTIATE_TEST_SUITE_P(All, TimeoutTest, testing::ValuesIn(MakeTimeoutTestParamValues())); TEST_P(TimeoutTest, Await) { const TimeoutTestParam params = GetParam(); LOG(INFO) << "Params: " << params; for (int attempt = 1;; ++attempt) { LOG(INFO) << "Attempt " << attempt; absl::Mutex mu; bool value = false; std::unique_ptr<absl::synchronization_internal::ThreadPool> pool = CreateDefaultPool(); RunAfterDelay(params.satisfy_condition_delay, pool.get(), [&] { absl::MutexLock l(&mu); value = true; }); absl::MutexLock lock(&mu); absl::Time start_time = absl::Now(); absl::Condition cond(&value); bool result = params.use_absolute_deadline ? mu.AwaitWithDeadline(cond, start_time + params.wait_timeout) : mu.AwaitWithTimeout(cond, params.wait_timeout); if (DelayIsWithinBounds(params.expected_delay, absl::Now() - start_time)) { EXPECT_EQ(params.expected_result, result); break; } } } TEST_P(TimeoutTest, LockWhen) { const TimeoutTestParam params = GetParam(); LOG(INFO) << "Params: " << params; for (int attempt = 1;; ++attempt) { LOG(INFO) << "Attempt " << attempt; absl::Mutex mu; bool value = false; std::unique_ptr<absl::synchronization_internal::ThreadPool> pool = CreateDefaultPool(); RunAfterDelay(params.satisfy_condition_delay, pool.get(), [&] { absl::MutexLock l(&mu); value = true; }); absl::Time start_time = absl::Now(); absl::Condition cond(&value); bool result = params.use_absolute_deadline ? mu.LockWhenWithDeadline(cond, start_time + params.wait_timeout) : mu.LockWhenWithTimeout(cond, params.wait_timeout); mu.Unlock(); if (DelayIsWithinBounds(params.expected_delay, absl::Now() - start_time)) { EXPECT_EQ(params.expected_result, result); break; } } } TEST_P(TimeoutTest, ReaderLockWhen) { const TimeoutTestParam params = GetParam(); LOG(INFO) << "Params: " << params; for (int attempt = 0;; ++attempt) { LOG(INFO) << "Attempt " << attempt; absl::Mutex mu; bool value = false; std::unique_ptr<absl::synchronization_internal::ThreadPool> pool = CreateDefaultPool(); RunAfterDelay(params.satisfy_condition_delay, pool.get(), [&] { absl::MutexLock l(&mu); value = true; }); absl::Time start_time = absl::Now(); bool result = params.use_absolute_deadline ? mu.ReaderLockWhenWithDeadline(absl::Condition(&value), start_time + params.wait_timeout) : mu.ReaderLockWhenWithTimeout(absl::Condition(&value), params.wait_timeout); mu.ReaderUnlock(); if (DelayIsWithinBounds(params.expected_delay, absl::Now() - start_time)) { EXPECT_EQ(params.expected_result, result); break; } } } TEST_P(TimeoutTest, Wait) { const TimeoutTestParam params = GetParam(); LOG(INFO) << "Params: " << params; for (int attempt = 0;; ++attempt) { LOG(INFO) << "Attempt " << attempt; absl::Mutex mu; bool value = false; absl::CondVar cv; std::unique_ptr<absl::synchronization_internal::ThreadPool> pool = CreateDefaultPool(); RunAfterDelay(params.satisfy_condition_delay, pool.get(), [&] { absl::MutexLock l(&mu); value = true; cv.Signal(); }); absl::MutexLock lock(&mu); absl::Time start_time = absl::Now(); absl::Duration timeout = params.wait_timeout; absl::Time deadline = start_time + timeout; while (!value) { if (params.use_absolute_deadline ? cv.WaitWithDeadline(&mu, deadline) : cv.WaitWithTimeout(&mu, timeout)) { break; } timeout = deadline - absl::Now(); } bool result = value; if (DelayIsWithinBounds(params.expected_delay, absl::Now() - start_time)) { EXPECT_EQ(params.expected_result, result); break; } } } TEST(Mutex, Logging) { absl::Mutex logged_mutex; logged_mutex.EnableDebugLog("fido_mutex"); absl::CondVar logged_cv; logged_cv.EnableDebugLog("rover_cv"); logged_mutex.Lock(); logged_cv.WaitWithTimeout(&logged_mutex, absl::Milliseconds(20)); logged_mutex.Unlock(); logged_mutex.ReaderLock(); logged_mutex.ReaderUnlock(); logged_mutex.Lock(); logged_mutex.Unlock(); logged_cv.Signal(); logged_cv.SignalAll(); } TEST(Mutex, LoggingAddressReuse) { ScopedInvariantDebugging scoped_debugging; alignas(absl::Mutex) char storage[sizeof(absl::Mutex)]; auto invariant = +[](void *alive) { EXPECT_TRUE(*static_cast<bool *>(alive)); }; constexpr size_t kIters = 10; bool alive[kIters] = {}; for (size_t i = 0; i < kIters; ++i) { absl::Mutex *mu = new (storage) absl::Mutex; alive[i] = true; mu->EnableDebugLog("Mutex"); mu->EnableInvariantDebugging(invariant, &alive[i]); mu->Lock(); mu->Unlock(); mu->~Mutex(); alive[i] = false; } } TEST(Mutex, LoggingBankrupcy) { ScopedInvariantDebugging scoped_debugging; std::vector<absl::Mutex> mus(1 << 20); for (auto &mu : mus) { mu.EnableDebugLog("Mutex"); } } TEST(Mutex, SynchEventRace) { ScopedInvariantDebugging scoped_debugging; std::vector<std::thread> threads; for (size_t i = 0; i < 5; i++) { threads.emplace_back([&] { for (size_t j = 0; j < (1 << 17); j++) { { absl::Mutex mu; mu.EnableInvariantDebugging([](void *) {}, nullptr); mu.Lock(); mu.Unlock(); } { absl::Mutex mu; mu.EnableDebugLog("Mutex"); } } }); } for (auto &thread : threads) { thread.join(); } } static std::vector<int> AllThreadCountValues() { if (kExtendedTest) { return {2, 4, 8, 10, 16, 20, 24, 30, 32}; } return {2, 4, 10}; } class MutexVariableThreadCountTest : public ::testing::TestWithParam<int> {}; INSTANTIATE_TEST_SUITE_P(ThreadCounts, MutexVariableThreadCountTest, ::testing::ValuesIn(AllThreadCountValues()), ::testing::PrintToStringParamName()); static int ScaleIterations(int x) { #if defined(ABSL_MUTEX_READER_LOCK_IS_EXCLUSIVE) return x / 10; #else return x; #endif } TEST_P(MutexVariableThreadCountTest, Mutex) { int threads = GetParam(); int iterations = ScaleIterations(10000000) / threads; int operations = threads * iterations; EXPECT_EQ(RunTest(&TestMu, threads, iterations, operations), operations); #if !defined(ABSL_MUTEX_ENABLE_INVARIANT_DEBUGGING_NOT_IMPLEMENTED) iterations = std::min(iterations, 10); operations = threads * iterations; EXPECT_EQ(RunTestWithInvariantDebugging(&TestMu, threads, iterations, operations, CheckSumG0G1), operations); #endif } TEST_P(MutexVariableThreadCountTest, Try) { int threads = GetParam(); int iterations = 1000000 / threads; int operations = iterations * threads; EXPECT_EQ(RunTest(&TestTry, threads, iterations, operations), operations); #if !defined(ABSL_MUTEX_ENABLE_INVARIANT_DEBUGGING_NOT_IMPLEMENTED) iterations = std::min(iterations, 10); operations = threads * iterations; EXPECT_EQ(RunTestWithInvariantDebugging(&TestTry, threads, iterations, operations, CheckSumG0G1), operations); #endif } TEST_P(MutexVariableThreadCountTest, R20ms) { int threads = GetParam(); int iterations = 100; int operations = iterations * threads; EXPECT_EQ(RunTest(&TestR20ms, threads, iterations, operations), 0); } TEST_P(MutexVariableThreadCountTest, RW) { int threads = GetParam(); int iterations = ScaleIterations(20000000) / threads; int operations = iterations * threads; EXPECT_EQ(RunTest(&TestRW, threads, iterations, operations), operations / 2); #if !defined(ABSL_MUTEX_ENABLE_INVARIANT_DEBUGGING_NOT_IMPLEMENTED) iterations = std::min(iterations, 10); operations = threads * iterations; EXPECT_EQ(RunTestWithInvariantDebugging(&TestRW, threads, iterations, operations, CheckSumG0G1), operations / 2); #endif } TEST_P(MutexVariableThreadCountTest, Await) { int threads = GetParam(); int iterations = ScaleIterations(500000); int operations = iterations; EXPECT_EQ(RunTest(&TestAwait, threads, iterations, operations), operations); } TEST_P(MutexVariableThreadCountTest, SignalAll) { int threads = GetParam(); int iterations = 200000 / threads; int operations = iterations; EXPECT_EQ(RunTest(&TestSignalAll, threads, iterations, operations), operations); } TEST(Mutex, Signal) { int threads = 2; int iterations = 200000; int operations = iterations; EXPECT_EQ(RunTest(&TestSignal, threads, iterations, operations), operations); } TEST(Mutex, Timed) { int threads = 10; int iterations = 1000; int operations = iterations; EXPECT_EQ(RunTest(&TestCVTimeout, threads, iterations, operations), operations); } TEST(Mutex, CVTime) { int threads = 10; int iterations = 1; EXPECT_EQ(RunTest(&TestCVTime, threads, iterations, 1), threads * iterations); } TEST(Mutex, MuTime) { int threads = 10; int iterations = 1; EXPECT_EQ(RunTest(&TestMuTime, threads, iterations, 1), threads * iterations); } TEST(Mutex, SignalExitedThread) { #if defined(__wasm__) || defined(__asmjs__) constexpr int kThreads = 1; #else constexpr int kThreads = 100; #endif std::vector<std::thread> top; for (unsigned i = 0; i < 2 * std::thread::hardware_concurrency(); i++) { top.emplace_back([&]() { for (int i = 0; i < kThreads; i++) { absl::Mutex mu; std::thread t([&]() { mu.Lock(); mu.Unlock(); }); mu.Lock(); mu.Unlock(); t.join(); } }); } for (auto &th : top) th.join(); } TEST(Mutex, WriterPriority) { absl::Mutex mu; bool wrote = false; std::atomic<bool> saw_wrote{false}; auto readfunc = [&]() { for (size_t i = 0; i < 10; ++i) { absl::ReaderMutexLock lock(&mu); if (wrote) { saw_wrote = true; break; } absl::SleepFor(absl::Seconds(1)); } }; std::thread t1(readfunc); absl::SleepFor(absl::Milliseconds(500)); std::thread t2(readfunc); std::thread t3([&]() { absl::MutexLock lock(&mu); wrote = true; }); t1.join(); t2.join(); t3.join(); EXPECT_TRUE(saw_wrote.load()); } #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM TEST(Mutex, CondVarPriority) { int err = 0; sched_param param; param.sched_priority = 7; std::thread test([&]() { err = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param); }); test.join(); if (err) { GTEST_SKIP() << "failed to set priority: " << strerror(err); } absl::Mutex mu; absl::CondVar cv; bool locked = false; bool notified = false; bool waiting = false; bool morph = false; std::thread th([&]() { EXPECT_EQ(0, pthread_setschedparam(pthread_self(), SCHED_FIFO, &param)); mu.Lock(); locked = true; mu.Await(absl::Condition(&notified)); mu.Unlock(); EXPECT_EQ(absl::synchronization_internal::GetOrCreateCurrentThreadIdentity() ->per_thread_synch.priority, param.sched_priority); mu.Lock(); mu.Await(absl::Condition(&waiting)); morph = true; absl::SleepFor(absl::Seconds(1)); cv.Signal(); mu.Unlock(); }); mu.Lock(); mu.Await(absl::Condition(&locked)); notified = true; mu.Unlock(); mu.Lock(); waiting = true; while (!morph) { cv.Wait(&mu); } mu.Unlock(); th.join(); EXPECT_NE(absl::synchronization_internal::GetOrCreateCurrentThreadIdentity() ->per_thread_synch.priority, param.sched_priority); } #endif TEST(Mutex, LockWhenWithTimeoutResult) { absl::Mutex mu; const bool kAlwaysTrue = true, kAlwaysFalse = false; const absl::Condition kTrueCond(&kAlwaysTrue), kFalseCond(&kAlwaysFalse); EXPECT_TRUE(mu.LockWhenWithTimeout(kTrueCond, absl::Milliseconds(1))); mu.Unlock(); EXPECT_FALSE(mu.LockWhenWithTimeout(kFalseCond, absl::Milliseconds(1))); EXPECT_TRUE(mu.AwaitWithTimeout(kTrueCond, absl::Milliseconds(1))); EXPECT_FALSE(mu.AwaitWithTimeout(kFalseCond, absl::Milliseconds(1))); std::thread th1([&]() { EXPECT_TRUE(mu.LockWhenWithTimeout(kTrueCond, absl::Milliseconds(1))); mu.Unlock(); }); std::thread th2([&]() { EXPECT_FALSE(mu.LockWhenWithTimeout(kFalseCond, absl::Milliseconds(1))); mu.Unlock(); }); absl::SleepFor(absl::Milliseconds(100)); mu.Unlock(); th1.join(); th2.join(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/mutex.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/mutex_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
4590b1c7-332b-4543-a56c-801e115dd511
cpp
abseil/abseil-cpp
barrier
absl/synchronization/barrier.cc
absl/synchronization/barrier_test.cc
#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); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/barrier.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/barrier_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
6a6114bb-5dc2-413d-b16f-9cc25ad67de1
cpp
abseil/abseil-cpp
notification
absl/synchronization/notification.cc
absl/synchronization/notification_test.cc
#include "absl/synchronization/notification.h" #include <atomic> #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/tracing.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN void Notification::Notify() { base_internal::TraceSignal(this, TraceObjectKind()); MutexLock l(&this->mutex_); #ifndef NDEBUG if (ABSL_PREDICT_FALSE(notified_yet_.load(std::memory_order_relaxed))) { ABSL_RAW_LOG( FATAL, "Notify() method called more than once for Notification object %p", static_cast<void *>(this)); } #endif notified_yet_.store(true, std::memory_order_release); } Notification::~Notification() { MutexLock l(&this->mutex_); } void Notification::WaitForNotification() const { base_internal::TraceWait(this, TraceObjectKind()); if (!HasBeenNotifiedInternal(&this->notified_yet_)) { this->mutex_.LockWhen( Condition(&HasBeenNotifiedInternal, &this->notified_yet_)); this->mutex_.Unlock(); } base_internal::TraceContinue(this, TraceObjectKind()); } bool Notification::WaitForNotificationWithTimeout( absl::Duration timeout) const { base_internal::TraceWait(this, TraceObjectKind()); bool notified = HasBeenNotifiedInternal(&this->notified_yet_); if (!notified) { notified = this->mutex_.LockWhenWithTimeout( Condition(&HasBeenNotifiedInternal, &this->notified_yet_), timeout); this->mutex_.Unlock(); } base_internal::TraceContinue(notified ? this : nullptr, TraceObjectKind()); return notified; } bool Notification::WaitForNotificationWithDeadline(absl::Time deadline) const { base_internal::TraceWait(this, TraceObjectKind()); bool notified = HasBeenNotifiedInternal(&this->notified_yet_); if (!notified) { notified = this->mutex_.LockWhenWithDeadline( Condition(&HasBeenNotifiedInternal, &this->notified_yet_), deadline); this->mutex_.Unlock(); } base_internal::TraceContinue(notified ? this : nullptr, TraceObjectKind()); return notified; } ABSL_NAMESPACE_END }
#include "absl/synchronization/notification.h" #include <thread> #include <tuple> #include <vector> #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/tracing.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN class ThreadSafeCounter { public: ThreadSafeCounter() : count_(0) {} void Increment() { MutexLock lock(&mutex_); ++count_; } int Get() const { MutexLock lock(&mutex_); return count_; } void WaitUntilGreaterOrEqual(int n) { MutexLock lock(&mutex_); auto cond = [this, n]() { return count_ >= n; }; mutex_.Await(Condition(&cond)); } private: mutable Mutex mutex_; int count_; }; static void RunWorker(int i, ThreadSafeCounter* ready_counter, Notification* notification, ThreadSafeCounter* done_counter) { ready_counter->Increment(); notification->WaitForNotification(); done_counter->Increment(); } static void BasicTests(bool notify_before_waiting, Notification* notification) { EXPECT_FALSE(notification->HasBeenNotified()); EXPECT_FALSE( notification->WaitForNotificationWithTimeout(absl::Milliseconds(0))); EXPECT_FALSE(notification->WaitForNotificationWithDeadline(absl::Now())); const absl::Duration delay = absl::Milliseconds(50); const absl::Time start = absl::Now(); EXPECT_FALSE(notification->WaitForNotificationWithTimeout(delay)); const absl::Duration elapsed = absl::Now() - start; const absl::Duration slop = absl::Milliseconds(5); EXPECT_LE(delay - slop, elapsed) << "WaitForNotificationWithTimeout returned " << delay - elapsed << " early (with " << slop << " slop), start time was " << start; ThreadSafeCounter ready_counter; ThreadSafeCounter done_counter; if (notify_before_waiting) { notification->Notify(); } const int kNumThreads = 10; std::vector<std::thread> workers; for (int i = 0; i < kNumThreads; ++i) { workers.push_back(std::thread(&RunWorker, i, &ready_counter, notification, &done_counter)); } if (!notify_before_waiting) { ready_counter.WaitUntilGreaterOrEqual(kNumThreads); EXPECT_EQ(0, done_counter.Get()); notification->Notify(); } notification->WaitForNotification(); EXPECT_TRUE(notification->HasBeenNotified()); EXPECT_TRUE(notification->WaitForNotificationWithTimeout(absl::Seconds(0))); EXPECT_TRUE(notification->WaitForNotificationWithDeadline(absl::Now())); for (std::thread& worker : workers) { worker.join(); } EXPECT_EQ(kNumThreads, ready_counter.Get()); EXPECT_EQ(kNumThreads, done_counter.Get()); } TEST(NotificationTest, SanityTest) { Notification local_notification1, local_notification2; BasicTests(false, &local_notification1); BasicTests(true, &local_notification2); } #if ABSL_HAVE_ATTRIBUTE_WEAK namespace base_internal { namespace { using TraceRecord = std::tuple<const void*, ObjectKind>; thread_local TraceRecord tls_signal; thread_local TraceRecord tls_wait; thread_local TraceRecord tls_continue; thread_local TraceRecord tls_observed; } extern "C" { void ABSL_INTERNAL_C_SYMBOL(AbslInternalTraceWait)(const void* object, ObjectKind kind) { tls_wait = {object, kind}; } void ABSL_INTERNAL_C_SYMBOL(AbslInternalTraceContinue)(const void* object, ObjectKind kind) { tls_continue = {object, kind}; } void ABSL_INTERNAL_C_SYMBOL(AbslInternalTraceSignal)(const void* object, ObjectKind kind) { tls_signal = {object, kind}; } void ABSL_INTERNAL_C_SYMBOL(AbslInternalTraceObserved)(const void* object, ObjectKind kind) { tls_observed = {object, kind}; } } TEST(NotificationTest, TracesNotify) { Notification n; tls_signal = {}; n.Notify(); EXPECT_EQ(tls_signal, TraceRecord(&n, ObjectKind::kNotification)); } TEST(NotificationTest, TracesWaitForNotification) { Notification n; n.Notify(); tls_wait = tls_continue = {}; n.WaitForNotification(); EXPECT_EQ(tls_wait, TraceRecord(&n, ObjectKind::kNotification)); EXPECT_EQ(tls_continue, TraceRecord(&n, ObjectKind::kNotification)); } TEST(NotificationTest, TracesWaitForNotificationWithTimeout) { Notification n; tls_wait = tls_continue = {}; n.WaitForNotificationWithTimeout(absl::Milliseconds(1)); EXPECT_EQ(tls_wait, TraceRecord(&n, ObjectKind::kNotification)); EXPECT_EQ(tls_continue, TraceRecord(nullptr, ObjectKind::kNotification)); n.Notify(); tls_wait = tls_continue = {}; n.WaitForNotificationWithTimeout(absl::Milliseconds(1)); EXPECT_EQ(tls_wait, TraceRecord(&n, ObjectKind::kNotification)); EXPECT_EQ(tls_continue, TraceRecord(&n, ObjectKind::kNotification)); } TEST(NotificationTest, TracesHasBeenNotified) { Notification n; tls_observed = {}; ASSERT_FALSE(n.HasBeenNotified()); EXPECT_EQ(tls_observed, TraceRecord(nullptr, ObjectKind::kUnknown)); n.Notify(); tls_observed = {}; ASSERT_TRUE(n.HasBeenNotified()); EXPECT_EQ(tls_observed, TraceRecord(&n, ObjectKind::kNotification)); } } #endif ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/notification.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/notification_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
b06d8b0c-17ce-447c-92e5-73775c5dc0a2
cpp
abseil/abseil-cpp
per_thread_sem
absl/synchronization/internal/per_thread_sem.cc
absl/synchronization/internal/per_thread_sem_test.cc
#include "absl/base/internal/low_level_alloc.h" #ifndef ABSL_LOW_LEVEL_ALLOC_MISSING #include "absl/synchronization/internal/per_thread_sem.h" #include <atomic> #include "absl/base/attributes.h" #include "absl/base/internal/thread_identity.h" #include "absl/synchronization/internal/waiter.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace synchronization_internal { void PerThreadSem::SetThreadBlockedCounter(std::atomic<int> *counter) { base_internal::ThreadIdentity *identity; identity = GetOrCreateCurrentThreadIdentity(); identity->blocked_count_ptr = counter; } std::atomic<int> *PerThreadSem::GetThreadBlockedCounter() { base_internal::ThreadIdentity *identity; identity = GetOrCreateCurrentThreadIdentity(); return identity->blocked_count_ptr; } void PerThreadSem::Tick(base_internal::ThreadIdentity *identity) { const int ticker = identity->ticker.fetch_add(1, std::memory_order_relaxed) + 1; const int wait_start = identity->wait_start.load(std::memory_order_relaxed); const bool is_idle = identity->is_idle.load(std::memory_order_relaxed); if (wait_start && (ticker - wait_start > Waiter::kIdlePeriods) && !is_idle) { ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemPoke)(identity); } } } ABSL_NAMESPACE_END } extern "C" { ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemInit)( absl::base_internal::ThreadIdentity *identity) { new (absl::synchronization_internal::Waiter::GetWaiter(identity)) absl::synchronization_internal::Waiter(); } ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemPost)( absl::base_internal::ThreadIdentity *identity) { absl::synchronization_internal::Waiter::GetWaiter(identity)->Post(); } ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemPoke)( absl::base_internal::ThreadIdentity *identity) { absl::synchronization_internal::Waiter::GetWaiter(identity)->Poke(); } ABSL_ATTRIBUTE_WEAK bool ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemWait)( absl::synchronization_internal::KernelTimeout t) { bool timeout = false; absl::base_internal::ThreadIdentity *identity; identity = absl::synchronization_internal::GetOrCreateCurrentThreadIdentity(); int ticker = identity->ticker.load(std::memory_order_relaxed); identity->wait_start.store(ticker ? ticker : 1, std::memory_order_relaxed); identity->is_idle.store(false, std::memory_order_relaxed); if (identity->blocked_count_ptr != nullptr) { identity->blocked_count_ptr->fetch_add(1, std::memory_order_relaxed); } timeout = !absl::synchronization_internal::Waiter::GetWaiter(identity)->Wait(t); if (identity->blocked_count_ptr != nullptr) { identity->blocked_count_ptr->fetch_sub(1, std::memory_order_relaxed); } identity->is_idle.store(false, std::memory_order_relaxed); identity->wait_start.store(0, std::memory_order_relaxed); return !timeout; } } #endif
#include "absl/synchronization/internal/per_thread_sem.h" #include <atomic> #include <condition_variable> #include <functional> #include <limits> #include <mutex> #include <string> #include <thread> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/internal/cycleclock.h" #include "absl/base/internal/thread_identity.h" #include "absl/strings/str_cat.h" #include "absl/time/clock.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace synchronization_internal { class SimpleSemaphore { public: SimpleSemaphore() : count_(0) {} void Wait() { std::unique_lock<std::mutex> lock(mu_); cv_.wait(lock, [this]() { return count_ > 0; }); --count_; cv_.notify_one(); } void Post() { std::lock_guard<std::mutex> lock(mu_); ++count_; cv_.notify_one(); } private: std::mutex mu_; std::condition_variable cv_; int count_; }; struct ThreadData { int num_iterations; SimpleSemaphore identity2_written; base_internal::ThreadIdentity *identity1; base_internal::ThreadIdentity *identity2; KernelTimeout timeout; }; class PerThreadSemTest : public testing::Test { public: static void TimingThread(ThreadData* t) { t->identity2 = GetOrCreateCurrentThreadIdentity(); t->identity2_written.Post(); while (t->num_iterations--) { Wait(t->timeout); Post(t->identity1); } } void TestTiming(const char *msg, bool timeout) { static const int kNumIterations = 100; ThreadData t; t.num_iterations = kNumIterations; t.timeout = timeout ? KernelTimeout(absl::Now() + absl::Seconds(10000)) : KernelTimeout::Never(); t.identity1 = GetOrCreateCurrentThreadIdentity(); std::thread partner_thread(std::bind(TimingThread, &t)); t.identity2_written.Wait(); int64_t min_cycles = std::numeric_limits<int64_t>::max(); int64_t total_cycles = 0; for (int i = 0; i < kNumIterations; ++i) { absl::SleepFor(absl::Milliseconds(20)); int64_t cycles = base_internal::CycleClock::Now(); Post(t.identity2); Wait(t.timeout); cycles = base_internal::CycleClock::Now() - cycles; min_cycles = std::min(min_cycles, cycles); total_cycles += cycles; } std::string out = StrCat( msg, "min cycle count=", min_cycles, " avg cycle count=", absl::SixDigits(static_cast<double>(total_cycles) / kNumIterations)); printf("%s\n", out.c_str()); partner_thread.join(); } protected: static void Post(base_internal::ThreadIdentity *id) { PerThreadSem::Post(id); } static bool Wait(KernelTimeout t) { return PerThreadSem::Wait(t); } static bool Wait(absl::Time t) { return Wait(KernelTimeout(t)); } static void Tick(base_internal::ThreadIdentity *identity) { PerThreadSem::Tick(identity); } }; namespace { TEST_F(PerThreadSemTest, WithoutTimeout) { PerThreadSemTest::TestTiming("Without timeout: ", false); } TEST_F(PerThreadSemTest, WithTimeout) { PerThreadSemTest::TestTiming("With timeout: ", true); } TEST_F(PerThreadSemTest, Timeouts) { const absl::Duration delay = absl::Milliseconds(50); const absl::Time start = absl::Now(); EXPECT_FALSE(Wait(start + delay)); const absl::Duration elapsed = absl::Now() - start; absl::Duration slop = absl::Milliseconds(1); #ifdef _MSC_VER slop = absl::Milliseconds(16); #endif EXPECT_LE(delay - slop, elapsed) << "Wait returned " << delay - elapsed << " early (with " << slop << " slop), start time was " << start; absl::Time negative_timeout = absl::UnixEpoch() - absl::Milliseconds(100); EXPECT_FALSE(Wait(negative_timeout)); EXPECT_LE(negative_timeout, absl::Now() + slop); Post(GetOrCreateCurrentThreadIdentity()); EXPECT_TRUE(Wait(negative_timeout)); } TEST_F(PerThreadSemTest, ThreadIdentityReuse) { for (int i = 0; i < 10000; i++) { std::thread t([]() { GetOrCreateCurrentThreadIdentity(); }); t.join(); } } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/per_thread_sem.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/per_thread_sem_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
cc39785c-7b2f-476e-a2fa-adde7d1d292a
cpp
abseil/abseil-cpp
kernel_timeout
absl/synchronization/internal/kernel_timeout.cc
absl/synchronization/internal/kernel_timeout_test.cc
#include "absl/synchronization/internal/kernel_timeout.h" #ifndef _WIN32 #include <sys/types.h> #endif #include <algorithm> #include <chrono> #include <cstdint> #include <cstdlib> #include <cstring> #include <ctime> #include <limits> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/base/config.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace synchronization_internal { #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr uint64_t KernelTimeout::kNoTimeout; constexpr int64_t KernelTimeout::kMaxNanos; #endif int64_t KernelTimeout::SteadyClockNow() { if (!SupportsSteadyClock()) { return absl::GetCurrentTimeNanos(); } return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::steady_clock::now().time_since_epoch()) .count(); } KernelTimeout::KernelTimeout(absl::Time t) { if (t == absl::InfiniteFuture()) { rep_ = kNoTimeout; return; } int64_t unix_nanos = absl::ToUnixNanos(t); if (unix_nanos < 0) { unix_nanos = 0; } if (unix_nanos >= kMaxNanos) { rep_ = kNoTimeout; return; } rep_ = static_cast<uint64_t>(unix_nanos) << 1; } KernelTimeout::KernelTimeout(absl::Duration d) { if (d == absl::InfiniteDuration()) { rep_ = kNoTimeout; return; } int64_t nanos = absl::ToInt64Nanoseconds(d); if (nanos < 0) { nanos = 0; } int64_t now = SteadyClockNow(); if (nanos > kMaxNanos - now) { rep_ = kNoTimeout; return; } nanos += now; rep_ = (static_cast<uint64_t>(nanos) << 1) | uint64_t{1}; } int64_t KernelTimeout::MakeAbsNanos() const { if (!has_timeout()) { return kMaxNanos; } int64_t nanos = RawAbsNanos(); if (is_relative_timeout()) { nanos = std::max<int64_t>(nanos - SteadyClockNow(), 0); int64_t now = absl::GetCurrentTimeNanos(); if (nanos > kMaxNanos - now) { nanos = kMaxNanos; } else { nanos += now; } } else if (nanos == 0) { nanos = 1; } return nanos; } int64_t KernelTimeout::InNanosecondsFromNow() const { if (!has_timeout()) { return kMaxNanos; } int64_t nanos = RawAbsNanos(); if (is_absolute_timeout()) { return std::max<int64_t>(nanos - absl::GetCurrentTimeNanos(), 0); } return std::max<int64_t>(nanos - SteadyClockNow(), 0); } struct timespec KernelTimeout::MakeAbsTimespec() const { return absl::ToTimespec(absl::Nanoseconds(MakeAbsNanos())); } struct timespec KernelTimeout::MakeRelativeTimespec() const { return absl::ToTimespec(absl::Nanoseconds(InNanosecondsFromNow())); } #ifndef _WIN32 struct timespec KernelTimeout::MakeClockAbsoluteTimespec(clockid_t c) const { if (!has_timeout()) { return absl::ToTimespec(absl::Nanoseconds(kMaxNanos)); } int64_t nanos = RawAbsNanos(); if (is_absolute_timeout()) { nanos -= absl::GetCurrentTimeNanos(); } else { nanos -= SteadyClockNow(); } struct timespec now; ABSL_RAW_CHECK(clock_gettime(c, &now) == 0, "clock_gettime() failed"); absl::Duration from_clock_epoch = absl::DurationFromTimespec(now) + absl::Nanoseconds(nanos); if (from_clock_epoch <= absl::ZeroDuration()) { return absl::ToTimespec(absl::Nanoseconds(1)); } return absl::ToTimespec(from_clock_epoch); } #endif KernelTimeout::DWord KernelTimeout::InMillisecondsFromNow() const { constexpr DWord kInfinite = std::numeric_limits<DWord>::max(); if (!has_timeout()) { return kInfinite; } constexpr uint64_t kNanosInMillis = uint64_t{1'000'000}; constexpr uint64_t kMaxValueNanos = std::numeric_limits<int64_t>::max() - kNanosInMillis + 1; uint64_t ns_from_now = static_cast<uint64_t>(InNanosecondsFromNow()); if (ns_from_now >= kMaxValueNanos) { return kInfinite; } uint64_t ms_from_now = (ns_from_now + kNanosInMillis - 1) / kNanosInMillis; if (ms_from_now > kInfinite) { return kInfinite; } return static_cast<DWord>(ms_from_now); } std::chrono::time_point<std::chrono::system_clock> KernelTimeout::ToChronoTimePoint() const { if (!has_timeout()) { return std::chrono::time_point<std::chrono::system_clock>::max(); } auto micros = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::nanoseconds(MakeAbsNanos())); return std::chrono::system_clock::from_time_t(0) + micros; } std::chrono::nanoseconds KernelTimeout::ToChronoDuration() const { if (!has_timeout()) { return std::chrono::nanoseconds::max(); } return std::chrono::nanoseconds(InNanosecondsFromNow()); } } ABSL_NAMESPACE_END }
#include "absl/synchronization/internal/kernel_timeout.h" #include <ctime> #include <chrono> #include <limits> #include "absl/base/config.h" #include "absl/random/random.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "gtest/gtest.h" #if defined(__GOOGLE_GRTE_VERSION__) && \ !defined(ABSL_HAVE_ADDRESS_SANITIZER) && \ !defined(ABSL_HAVE_MEMORY_SANITIZER) && \ !defined(ABSL_HAVE_THREAD_SANITIZER) extern "C" int __clock_gettime(clockid_t c, struct timespec* ts); extern "C" int clock_gettime(clockid_t c, struct timespec* ts) { if (c == CLOCK_MONOTONIC && !absl::synchronization_internal::KernelTimeout::SupportsSteadyClock()) { thread_local absl::BitGen gen; ts->tv_sec = absl::Uniform(gen, 0, 1'000'000'000); ts->tv_nsec = absl::Uniform(gen, 0, 1'000'000'000); return 0; } return __clock_gettime(c, ts); } #endif namespace { #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_MEMORY_SANITIZER) || \ defined(ABSL_HAVE_THREAD_SANITIZER) || defined(__ANDROID__) || \ defined(__APPLE__) || defined(_WIN32) || defined(_WIN64) constexpr absl::Duration kTimingBound = absl::Milliseconds(5); #else constexpr absl::Duration kTimingBound = absl::Microseconds(250); #endif using absl::synchronization_internal::KernelTimeout; TEST(KernelTimeout, DISABLED_FiniteTimes) { constexpr absl::Duration kDurationsToTest[] = { absl::ZeroDuration(), absl::Nanoseconds(1), absl::Microseconds(1), absl::Milliseconds(1), absl::Seconds(1), absl::Minutes(1), absl::Hours(1), absl::Hours(1000), -absl::Nanoseconds(1), -absl::Microseconds(1), -absl::Milliseconds(1), -absl::Seconds(1), -absl::Minutes(1), -absl::Hours(1), -absl::Hours(1000), }; for (auto duration : kDurationsToTest) { const absl::Time now = absl::Now(); const absl::Time when = now + duration; SCOPED_TRACE(duration); KernelTimeout t(when); EXPECT_TRUE(t.has_timeout()); EXPECT_TRUE(t.is_absolute_timeout()); EXPECT_FALSE(t.is_relative_timeout()); EXPECT_EQ(absl::TimeFromTimespec(t.MakeAbsTimespec()), when); #ifndef _WIN32 EXPECT_LE( absl::AbsDuration(absl::Now() + duration - absl::TimeFromTimespec( t.MakeClockAbsoluteTimespec(CLOCK_REALTIME))), absl::Milliseconds(10)); #endif EXPECT_LE( absl::AbsDuration(absl::DurationFromTimespec(t.MakeRelativeTimespec()) - std::max(duration, absl::ZeroDuration())), kTimingBound); EXPECT_EQ(absl::FromUnixNanos(t.MakeAbsNanos()), when); EXPECT_LE(absl::AbsDuration(absl::Milliseconds(t.InMillisecondsFromNow()) - std::max(duration, absl::ZeroDuration())), absl::Milliseconds(5)); EXPECT_LE(absl::AbsDuration(absl::FromChrono(t.ToChronoTimePoint()) - when), absl::Microseconds(1)); EXPECT_LE(absl::AbsDuration(absl::FromChrono(t.ToChronoDuration()) - std::max(duration, absl::ZeroDuration())), kTimingBound); } } TEST(KernelTimeout, InfiniteFuture) { KernelTimeout t(absl::InfiniteFuture()); EXPECT_FALSE(t.has_timeout()); EXPECT_GT(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::Now() + absl::Hours(100000)); #ifndef _WIN32 EXPECT_GT(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::Now() + absl::Hours(100000)); #endif EXPECT_GT(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::Hours(100000)); EXPECT_GT(absl::FromUnixNanos(t.MakeAbsNanos()), absl::Now() + absl::Hours(100000)); EXPECT_EQ(t.InMillisecondsFromNow(), std::numeric_limits<KernelTimeout::DWord>::max()); EXPECT_EQ(t.ToChronoTimePoint(), std::chrono::time_point<std::chrono::system_clock>::max()); EXPECT_GE(t.ToChronoDuration(), std::chrono::nanoseconds::max()); } TEST(KernelTimeout, DefaultConstructor) { KernelTimeout t; EXPECT_FALSE(t.has_timeout()); EXPECT_GT(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::Now() + absl::Hours(100000)); #ifndef _WIN32 EXPECT_GT(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::Now() + absl::Hours(100000)); #endif EXPECT_GT(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::Hours(100000)); EXPECT_GT(absl::FromUnixNanos(t.MakeAbsNanos()), absl::Now() + absl::Hours(100000)); EXPECT_EQ(t.InMillisecondsFromNow(), std::numeric_limits<KernelTimeout::DWord>::max()); EXPECT_EQ(t.ToChronoTimePoint(), std::chrono::time_point<std::chrono::system_clock>::max()); EXPECT_GE(t.ToChronoDuration(), std::chrono::nanoseconds::max()); } TEST(KernelTimeout, TimeMaxNanos) { KernelTimeout t(absl::FromUnixNanos(std::numeric_limits<int64_t>::max())); EXPECT_FALSE(t.has_timeout()); EXPECT_GT(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::Now() + absl::Hours(100000)); #ifndef _WIN32 EXPECT_GT(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::Now() + absl::Hours(100000)); #endif EXPECT_GT(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::Hours(100000)); EXPECT_GT(absl::FromUnixNanos(t.MakeAbsNanos()), absl::Now() + absl::Hours(100000)); EXPECT_EQ(t.InMillisecondsFromNow(), std::numeric_limits<KernelTimeout::DWord>::max()); EXPECT_EQ(t.ToChronoTimePoint(), std::chrono::time_point<std::chrono::system_clock>::max()); EXPECT_GE(t.ToChronoDuration(), std::chrono::nanoseconds::max()); } TEST(KernelTimeout, Never) { KernelTimeout t = KernelTimeout::Never(); EXPECT_FALSE(t.has_timeout()); EXPECT_GT(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::Now() + absl::Hours(100000)); #ifndef _WIN32 EXPECT_GT(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::Now() + absl::Hours(100000)); #endif EXPECT_GT(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::Hours(100000)); EXPECT_GT(absl::FromUnixNanos(t.MakeAbsNanos()), absl::Now() + absl::Hours(100000)); EXPECT_EQ(t.InMillisecondsFromNow(), std::numeric_limits<KernelTimeout::DWord>::max()); EXPECT_EQ(t.ToChronoTimePoint(), std::chrono::time_point<std::chrono::system_clock>::max()); EXPECT_GE(t.ToChronoDuration(), std::chrono::nanoseconds::max()); } TEST(KernelTimeout, InfinitePast) { KernelTimeout t(absl::InfinitePast()); EXPECT_TRUE(t.has_timeout()); EXPECT_TRUE(t.is_absolute_timeout()); EXPECT_FALSE(t.is_relative_timeout()); EXPECT_LE(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::FromUnixNanos(1)); #ifndef _WIN32 EXPECT_LE(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::FromUnixSeconds(1)); #endif EXPECT_EQ(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::ZeroDuration()); EXPECT_LE(absl::FromUnixNanos(t.MakeAbsNanos()), absl::FromUnixNanos(1)); EXPECT_EQ(t.InMillisecondsFromNow(), KernelTimeout::DWord{0}); EXPECT_LT(t.ToChronoTimePoint(), std::chrono::system_clock::from_time_t(0) + std::chrono::seconds(1)); EXPECT_EQ(t.ToChronoDuration(), std::chrono::nanoseconds(0)); } TEST(KernelTimeout, DISABLED_FiniteDurations) { constexpr absl::Duration kDurationsToTest[] = { absl::ZeroDuration(), absl::Nanoseconds(1), absl::Microseconds(1), absl::Milliseconds(1), absl::Seconds(1), absl::Minutes(1), absl::Hours(1), absl::Hours(1000), }; for (auto duration : kDurationsToTest) { SCOPED_TRACE(duration); KernelTimeout t(duration); EXPECT_TRUE(t.has_timeout()); EXPECT_FALSE(t.is_absolute_timeout()); EXPECT_TRUE(t.is_relative_timeout()); EXPECT_LE(absl::AbsDuration(absl::Now() + duration - absl::TimeFromTimespec(t.MakeAbsTimespec())), absl::Milliseconds(5)); #ifndef _WIN32 EXPECT_LE( absl::AbsDuration(absl::Now() + duration - absl::TimeFromTimespec( t.MakeClockAbsoluteTimespec(CLOCK_REALTIME))), absl::Milliseconds(5)); #endif EXPECT_LE( absl::AbsDuration(absl::DurationFromTimespec(t.MakeRelativeTimespec()) - duration), kTimingBound); EXPECT_LE(absl::AbsDuration(absl::Now() + duration - absl::FromUnixNanos(t.MakeAbsNanos())), absl::Milliseconds(5)); EXPECT_LE(absl::Milliseconds(t.InMillisecondsFromNow()) - duration, absl::Milliseconds(5)); EXPECT_LE(absl::AbsDuration(absl::Now() + duration - absl::FromChrono(t.ToChronoTimePoint())), kTimingBound); EXPECT_LE( absl::AbsDuration(absl::FromChrono(t.ToChronoDuration()) - duration), kTimingBound); } } TEST(KernelTimeout, DISABLED_NegativeDurations) { constexpr absl::Duration kDurationsToTest[] = { -absl::ZeroDuration(), -absl::Nanoseconds(1), -absl::Microseconds(1), -absl::Milliseconds(1), -absl::Seconds(1), -absl::Minutes(1), -absl::Hours(1), -absl::Hours(1000), -absl::InfiniteDuration(), }; for (auto duration : kDurationsToTest) { SCOPED_TRACE(duration); KernelTimeout t(duration); EXPECT_TRUE(t.has_timeout()); EXPECT_FALSE(t.is_absolute_timeout()); EXPECT_TRUE(t.is_relative_timeout()); EXPECT_LE(absl::AbsDuration(absl::Now() - absl::TimeFromTimespec(t.MakeAbsTimespec())), absl::Milliseconds(5)); #ifndef _WIN32 EXPECT_LE(absl::AbsDuration(absl::Now() - absl::TimeFromTimespec( t.MakeClockAbsoluteTimespec( CLOCK_REALTIME))), absl::Milliseconds(5)); #endif EXPECT_EQ(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::ZeroDuration()); EXPECT_LE( absl::AbsDuration(absl::Now() - absl::FromUnixNanos(t.MakeAbsNanos())), absl::Milliseconds(5)); EXPECT_EQ(t.InMillisecondsFromNow(), KernelTimeout::DWord{0}); EXPECT_LE(absl::AbsDuration(absl::Now() - absl::FromChrono(t.ToChronoTimePoint())), absl::Milliseconds(5)); EXPECT_EQ(t.ToChronoDuration(), std::chrono::nanoseconds(0)); } } TEST(KernelTimeout, InfiniteDuration) { KernelTimeout t(absl::InfiniteDuration()); EXPECT_FALSE(t.has_timeout()); EXPECT_GT(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::Now() + absl::Hours(100000)); #ifndef _WIN32 EXPECT_GT(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::Now() + absl::Hours(100000)); #endif EXPECT_GT(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::Hours(100000)); EXPECT_GT(absl::FromUnixNanos(t.MakeAbsNanos()), absl::Now() + absl::Hours(100000)); EXPECT_EQ(t.InMillisecondsFromNow(), std::numeric_limits<KernelTimeout::DWord>::max()); EXPECT_EQ(t.ToChronoTimePoint(), std::chrono::time_point<std::chrono::system_clock>::max()); EXPECT_GE(t.ToChronoDuration(), std::chrono::nanoseconds::max()); } TEST(KernelTimeout, DurationMaxNanos) { KernelTimeout t(absl::Nanoseconds(std::numeric_limits<int64_t>::max())); EXPECT_FALSE(t.has_timeout()); EXPECT_GT(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::Now() + absl::Hours(100000)); #ifndef _WIN32 EXPECT_GT(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::Now() + absl::Hours(100000)); #endif EXPECT_GT(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::Hours(100000)); EXPECT_GT(absl::FromUnixNanos(t.MakeAbsNanos()), absl::Now() + absl::Hours(100000)); EXPECT_EQ(t.InMillisecondsFromNow(), std::numeric_limits<KernelTimeout::DWord>::max()); EXPECT_EQ(t.ToChronoTimePoint(), std::chrono::time_point<std::chrono::system_clock>::max()); EXPECT_GE(t.ToChronoDuration(), std::chrono::nanoseconds::max()); } TEST(KernelTimeout, OverflowNanos) { int64_t now_nanos = absl::ToUnixNanos(absl::Now()); int64_t limit = std::numeric_limits<int64_t>::max() - now_nanos; absl::Duration duration = absl::Nanoseconds(limit) + absl::Seconds(1); KernelTimeout t(duration); EXPECT_GT(absl::TimeFromTimespec(t.MakeAbsTimespec()), absl::Now() + absl::Hours(100000)); #ifndef _WIN32 EXPECT_GT(absl::TimeFromTimespec(t.MakeClockAbsoluteTimespec(CLOCK_REALTIME)), absl::Now() + absl::Hours(100000)); #endif EXPECT_GT(absl::DurationFromTimespec(t.MakeRelativeTimespec()), absl::Hours(100000)); EXPECT_GT(absl::FromUnixNanos(t.MakeAbsNanos()), absl::Now() + absl::Hours(100000)); EXPECT_LE(absl::Milliseconds(t.InMillisecondsFromNow()) - duration, absl::Milliseconds(5)); EXPECT_GT(t.ToChronoTimePoint(), std::chrono::system_clock::now() + std::chrono::hours(100000)); EXPECT_GT(t.ToChronoDuration(), std::chrono::hours(100000)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/kernel_timeout.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/kernel_timeout_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
6a47b4ce-2bbe-45dc-a620-bf3980bd6292
cpp
abseil/abseil-cpp
graphcycles
absl/synchronization/internal/graphcycles.cc
absl/synchronization/internal/graphcycles_test.cc
#include "absl/base/attributes.h" #include "absl/base/internal/low_level_alloc.h" #ifndef ABSL_LOW_LEVEL_ALLOC_MISSING #include "absl/synchronization/internal/graphcycles.h" #include <algorithm> #include <array> #include <cinttypes> #include <limits> #include "absl/base/internal/hide_ptr.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/spinlock.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace synchronization_internal { namespace { ABSL_CONST_INIT static absl::base_internal::SpinLock arena_mu( absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY); ABSL_CONST_INIT static base_internal::LowLevelAlloc::Arena* arena; static void InitArenaIfNecessary() { arena_mu.Lock(); if (arena == nullptr) { arena = base_internal::LowLevelAlloc::NewArena(0); } arena_mu.Unlock(); } static const uint32_t kInline = 8; template <typename T> class Vec { public: Vec() { Init(); } ~Vec() { Discard(); } void clear() { Discard(); Init(); } bool empty() const { return size_ == 0; } uint32_t size() const { return size_; } T* begin() { return ptr_; } T* end() { return ptr_ + size_; } const T& operator[](uint32_t i) const { return ptr_[i]; } T& operator[](uint32_t i) { return ptr_[i]; } const T& back() const { return ptr_[size_-1]; } void pop_back() { size_--; } void push_back(const T& v) { if (size_ == capacity_) Grow(size_ + 1); ptr_[size_] = v; size_++; } void resize(uint32_t n) { if (n > capacity_) Grow(n); size_ = n; } void fill(const T& val) { for (uint32_t i = 0; i < size(); i++) { ptr_[i] = val; } } void MoveFrom(Vec<T>* src) { if (src->ptr_ == src->space_) { resize(src->size_); std::copy_n(src->ptr_, src->size_, ptr_); src->size_ = 0; } else { Discard(); ptr_ = src->ptr_; size_ = src->size_; capacity_ = src->capacity_; src->Init(); } } private: T* ptr_; T space_[kInline]; uint32_t size_; uint32_t capacity_; void Init() { ptr_ = space_; size_ = 0; capacity_ = kInline; } void Discard() { if (ptr_ != space_) base_internal::LowLevelAlloc::Free(ptr_); } void Grow(uint32_t n) { while (capacity_ < n) { capacity_ *= 2; } size_t request = static_cast<size_t>(capacity_) * sizeof(T); T* copy = static_cast<T*>( base_internal::LowLevelAlloc::AllocWithArena(request, arena)); std::copy_n(ptr_, size_, copy); Discard(); ptr_ = copy; } Vec(const Vec&) = delete; Vec& operator=(const Vec&) = delete; }; class NodeSet { public: NodeSet() { Init(); } void clear() { Init(); } bool contains(int32_t v) const { return table_[FindIndex(v)] == v; } bool insert(int32_t v) { uint32_t i = FindIndex(v); if (table_[i] == v) { return false; } if (table_[i] == kEmpty) { occupied_++; } table_[i] = v; if (occupied_ >= table_.size() - table_.size()/4) Grow(); return true; } void erase(int32_t v) { uint32_t i = FindIndex(v); if (table_[i] == v) { table_[i] = kDel; } } #define HASH_FOR_EACH(elem, eset) \ for (int32_t elem, _cursor = 0; (eset).Next(&_cursor, &elem); ) bool Next(int32_t* cursor, int32_t* elem) { while (static_cast<uint32_t>(*cursor) < table_.size()) { int32_t v = table_[static_cast<uint32_t>(*cursor)]; (*cursor)++; if (v >= 0) { *elem = v; return true; } } return false; } private: enum : int32_t { kEmpty = -1, kDel = -2 }; Vec<int32_t> table_; uint32_t occupied_; static uint32_t Hash(int32_t a) { return static_cast<uint32_t>(a) * 41; } uint32_t FindIndex(int32_t v) const { const uint32_t mask = table_.size() - 1; uint32_t i = Hash(v) & mask; uint32_t deleted_index = 0; bool seen_deleted_element = false; while (true) { int32_t e = table_[i]; if (v == e) { return i; } else if (e == kEmpty) { return seen_deleted_element ? deleted_index : i; } else if (e == kDel && !seen_deleted_element) { deleted_index = i; seen_deleted_element = true; } i = (i + 1) & mask; } } void Init() { table_.clear(); table_.resize(kInline); table_.fill(kEmpty); occupied_ = 0; } void Grow() { Vec<int32_t> copy; copy.MoveFrom(&table_); occupied_ = 0; table_.resize(copy.size() * 2); table_.fill(kEmpty); for (const auto& e : copy) { if (e >= 0) insert(e); } } NodeSet(const NodeSet&) = delete; NodeSet& operator=(const NodeSet&) = delete; }; inline GraphId MakeId(int32_t index, uint32_t version) { GraphId g; g.handle = (static_cast<uint64_t>(version) << 32) | static_cast<uint32_t>(index); return g; } inline int32_t NodeIndex(GraphId id) { return static_cast<int32_t>(id.handle); } inline uint32_t NodeVersion(GraphId id) { return static_cast<uint32_t>(id.handle >> 32); } struct Node { int32_t rank; uint32_t version; int32_t next_hash; bool visited; uintptr_t masked_ptr; NodeSet in; NodeSet out; int priority; int nstack; void* stack[40]; }; class PointerMap { public: explicit PointerMap(const Vec<Node*>* nodes) : nodes_(nodes) { table_.fill(-1); } int32_t Find(void* ptr) { auto masked = base_internal::HidePtr(ptr); for (int32_t i = table_[Hash(ptr)]; i != -1;) { Node* n = (*nodes_)[static_cast<uint32_t>(i)]; if (n->masked_ptr == masked) return i; i = n->next_hash; } return -1; } void Add(void* ptr, int32_t i) { int32_t* head = &table_[Hash(ptr)]; (*nodes_)[static_cast<uint32_t>(i)]->next_hash = *head; *head = i; } int32_t Remove(void* ptr) { auto masked = base_internal::HidePtr(ptr); for (int32_t* slot = &table_[Hash(ptr)]; *slot != -1; ) { int32_t index = *slot; Node* n = (*nodes_)[static_cast<uint32_t>(index)]; if (n->masked_ptr == masked) { *slot = n->next_hash; n->next_hash = -1; return index; } slot = &n->next_hash; } return -1; } private: static constexpr uint32_t kHashTableSize = 262139; const Vec<Node*>* nodes_; std::array<int32_t, kHashTableSize> table_; static uint32_t Hash(void* ptr) { return reinterpret_cast<uintptr_t>(ptr) % kHashTableSize; } }; } struct GraphCycles::Rep { Vec<Node*> nodes_; Vec<int32_t> free_nodes_; PointerMap ptrmap_; Vec<int32_t> deltaf_; Vec<int32_t> deltab_; Vec<int32_t> list_; Vec<int32_t> merged_; Vec<int32_t> stack_; Rep() : ptrmap_(&nodes_) {} }; static Node* FindNode(GraphCycles::Rep* rep, GraphId id) { Node* n = rep->nodes_[static_cast<uint32_t>(NodeIndex(id))]; return (n->version == NodeVersion(id)) ? n : nullptr; } void GraphCycles::TestOnlyAddNodes(uint32_t n) { uint32_t old_size = rep_->nodes_.size(); rep_->nodes_.resize(n); for (auto i = old_size; i < n; ++i) { rep_->nodes_[i] = nullptr; } } GraphCycles::GraphCycles() { InitArenaIfNecessary(); rep_ = new (base_internal::LowLevelAlloc::AllocWithArena(sizeof(Rep), arena)) Rep; } GraphCycles::~GraphCycles() { for (auto* node : rep_->nodes_) { if (node == nullptr) { continue; } node->Node::~Node(); base_internal::LowLevelAlloc::Free(node); } rep_->Rep::~Rep(); base_internal::LowLevelAlloc::Free(rep_); } bool GraphCycles::CheckInvariants() const { Rep* r = rep_; NodeSet ranks; for (uint32_t x = 0; x < r->nodes_.size(); x++) { Node* nx = r->nodes_[x]; void* ptr = base_internal::UnhidePtr<void>(nx->masked_ptr); if (ptr != nullptr && static_cast<uint32_t>(r->ptrmap_.Find(ptr)) != x) { ABSL_RAW_LOG(FATAL, "Did not find live node in hash table %" PRIu32 " %p", x, ptr); } if (nx->visited) { ABSL_RAW_LOG(FATAL, "Did not clear visited marker on node %" PRIu32, x); } if (!ranks.insert(nx->rank)) { ABSL_RAW_LOG(FATAL, "Duplicate occurrence of rank %" PRId32, nx->rank); } HASH_FOR_EACH(y, nx->out) { Node* ny = r->nodes_[static_cast<uint32_t>(y)]; if (nx->rank >= ny->rank) { ABSL_RAW_LOG(FATAL, "Edge %" PRIu32 " ->%" PRId32 " has bad rank assignment %" PRId32 "->%" PRId32, x, y, nx->rank, ny->rank); } } } return true; } GraphId GraphCycles::GetId(void* ptr) { int32_t i = rep_->ptrmap_.Find(ptr); if (i != -1) { return MakeId(i, rep_->nodes_[static_cast<uint32_t>(i)]->version); } else if (rep_->free_nodes_.empty()) { Node* n = new (base_internal::LowLevelAlloc::AllocWithArena(sizeof(Node), arena)) Node; n->version = 1; n->visited = false; n->rank = static_cast<int32_t>(rep_->nodes_.size()); n->masked_ptr = base_internal::HidePtr(ptr); n->nstack = 0; n->priority = 0; rep_->nodes_.push_back(n); rep_->ptrmap_.Add(ptr, n->rank); return MakeId(n->rank, n->version); } else { int32_t r = rep_->free_nodes_.back(); rep_->free_nodes_.pop_back(); Node* n = rep_->nodes_[static_cast<uint32_t>(r)]; n->masked_ptr = base_internal::HidePtr(ptr); n->nstack = 0; n->priority = 0; rep_->ptrmap_.Add(ptr, r); return MakeId(r, n->version); } } void GraphCycles::RemoveNode(void* ptr) { int32_t i = rep_->ptrmap_.Remove(ptr); if (i == -1) { return; } Node* x = rep_->nodes_[static_cast<uint32_t>(i)]; HASH_FOR_EACH(y, x->out) { rep_->nodes_[static_cast<uint32_t>(y)]->in.erase(i); } HASH_FOR_EACH(y, x->in) { rep_->nodes_[static_cast<uint32_t>(y)]->out.erase(i); } x->in.clear(); x->out.clear(); x->masked_ptr = base_internal::HidePtr<void>(nullptr); if (x->version == std::numeric_limits<uint32_t>::max()) { } else { x->version++; rep_->free_nodes_.push_back(i); } } void* GraphCycles::Ptr(GraphId id) { Node* n = FindNode(rep_, id); return n == nullptr ? nullptr : base_internal::UnhidePtr<void>(n->masked_ptr); } bool GraphCycles::HasNode(GraphId node) { return FindNode(rep_, node) != nullptr; } bool GraphCycles::HasEdge(GraphId x, GraphId y) const { Node* xn = FindNode(rep_, x); return xn && FindNode(rep_, y) && xn->out.contains(NodeIndex(y)); } void GraphCycles::RemoveEdge(GraphId x, GraphId y) { Node* xn = FindNode(rep_, x); Node* yn = FindNode(rep_, y); if (xn && yn) { xn->out.erase(NodeIndex(y)); yn->in.erase(NodeIndex(x)); } } static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound); static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound); static void Reorder(GraphCycles::Rep* r); static void Sort(const Vec<Node*>&, Vec<int32_t>* delta); static void MoveToList( GraphCycles::Rep* r, Vec<int32_t>* src, Vec<int32_t>* dst); bool GraphCycles::InsertEdge(GraphId idx, GraphId idy) { Rep* r = rep_; const int32_t x = NodeIndex(idx); const int32_t y = NodeIndex(idy); Node* nx = FindNode(r, idx); Node* ny = FindNode(r, idy); if (nx == nullptr || ny == nullptr) return true; if (nx == ny) return false; if (!nx->out.insert(y)) { return true; } ny->in.insert(x); if (nx->rank <= ny->rank) { return true; } if (!ForwardDFS(r, y, nx->rank)) { nx->out.erase(y); ny->in.erase(x); for (const auto& d : r->deltaf_) { r->nodes_[static_cast<uint32_t>(d)]->visited = false; } return false; } BackwardDFS(r, x, ny->rank); Reorder(r); return true; } static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound) { r->deltaf_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = r->nodes_[static_cast<uint32_t>(n)]; if (nn->visited) continue; nn->visited = true; r->deltaf_.push_back(n); HASH_FOR_EACH(w, nn->out) { Node* nw = r->nodes_[static_cast<uint32_t>(w)]; if (nw->rank == upper_bound) { return false; } if (!nw->visited && nw->rank < upper_bound) { r->stack_.push_back(w); } } } return true; } static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound) { r->deltab_.clear(); r->stack_.clear(); r->stack_.push_back(n); while (!r->stack_.empty()) { n = r->stack_.back(); r->stack_.pop_back(); Node* nn = r->nodes_[static_cast<uint32_t>(n)]; if (nn->visited) continue; nn->visited = true; r->deltab_.push_back(n); HASH_FOR_EACH(w, nn->in) { Node* nw = r->nodes_[static_cast<uint32_t>(w)]; if (!nw->visited && lower_bound < nw->rank) { r->stack_.push_back(w); } } } } static void Reorder(GraphCycles::Rep* r) { Sort(r->nodes_, &r->deltab_); Sort(r->nodes_, &r->deltaf_); r->list_.clear(); MoveToList(r, &r->deltab_, &r->list_); MoveToList(r, &r->deltaf_, &r->list_); r->merged_.resize(r->deltab_.size() + r->deltaf_.size()); std::merge(r->deltab_.begin(), r->deltab_.end(), r->deltaf_.begin(), r->deltaf_.end(), r->merged_.begin()); for (uint32_t i = 0; i < r->list_.size(); i++) { r->nodes_[static_cast<uint32_t>(r->list_[i])]->rank = r->merged_[i]; } } static void Sort(const Vec<Node*>& nodes, Vec<int32_t>* delta) { struct ByRank { const Vec<Node*>* nodes; bool operator()(int32_t a, int32_t b) const { return (*nodes)[static_cast<uint32_t>(a)]->rank < (*nodes)[static_cast<uint32_t>(b)]->rank; } }; ByRank cmp; cmp.nodes = &nodes; std::sort(delta->begin(), delta->end(), cmp); } static void MoveToList( GraphCycles::Rep* r, Vec<int32_t>* src, Vec<int32_t>* dst) { for (auto& v : *src) { int32_t w = v; v = r->nodes_[static_cast<uint32_t>(w)]->rank; r->nodes_[static_cast<uint32_t>(w)]->visited = false; dst->push_back(w); } } int GraphCycles::FindPath(GraphId idx, GraphId idy, int max_path_len, GraphId path[]) const { Rep* r = rep_; if (FindNode(r, idx) == nullptr || FindNode(r, idy) == nullptr) return 0; const int32_t x = NodeIndex(idx); const int32_t y = NodeIndex(idy); int path_len = 0; NodeSet seen; r->stack_.clear(); r->stack_.push_back(x); while (!r->stack_.empty()) { int32_t n = r->stack_.back(); r->stack_.pop_back(); if (n < 0) { path_len--; continue; } if (path_len < max_path_len) { path[path_len] = MakeId(n, rep_->nodes_[static_cast<uint32_t>(n)]->version); } path_len++; r->stack_.push_back(-1); if (n == y) { return path_len; } HASH_FOR_EACH(w, r->nodes_[static_cast<uint32_t>(n)]->out) { if (seen.insert(w)) { r->stack_.push_back(w); } } } return 0; } bool GraphCycles::IsReachable(GraphId x, GraphId y) const { return FindPath(x, y, 0, nullptr) > 0; } void GraphCycles::UpdateStackTrace(GraphId id, int priority, int (*get_stack_trace)(void** stack, int)) { Node* n = FindNode(rep_, id); if (n == nullptr || n->priority >= priority) { return; } n->nstack = (*get_stack_trace)(n->stack, ABSL_ARRAYSIZE(n->stack)); n->priority = priority; } int GraphCycles::GetStackTrace(GraphId id, void*** ptr) { Node* n = FindNode(rep_, id); if (n == nullptr) { *ptr = nullptr; return 0; } else { *ptr = n->stack; return n->nstack; } } } ABSL_NAMESPACE_END } #endif
#include "absl/synchronization/internal/graphcycles.h" #include <climits> #include <map> #include <random> #include <unordered_set> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/log/check.h" #include "absl/log/log.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace synchronization_internal { using Nodes = std::vector<int>; struct Edge { int from; int to; }; using Edges = std::vector<Edge>; using RandomEngine = std::mt19937_64; typedef std::map<int, GraphId> IdMap; static GraphId Get(const IdMap& id, int num) { auto iter = id.find(num); return (iter == id.end()) ? InvalidGraphId() : iter->second; } static bool IsReachable(Edges *edges, int from, int to, std::unordered_set<int> *seen) { seen->insert(from); if (from == to) return true; for (const auto &edge : *edges) { if (edge.from == from) { if (edge.to == to) { return true; } else if (seen->find(edge.to) == seen->end() && IsReachable(edges, edge.to, to, seen)) { return true; } } } return false; } static void PrintEdges(Edges *edges) { LOG(INFO) << "EDGES (" << edges->size() << ")"; for (const auto &edge : *edges) { int a = edge.from; int b = edge.to; LOG(INFO) << a << " " << b; } LOG(INFO) << "---"; } static void PrintGCEdges(Nodes *nodes, const IdMap &id, GraphCycles *gc) { LOG(INFO) << "GC EDGES"; for (int a : *nodes) { for (int b : *nodes) { if (gc->HasEdge(Get(id, a), Get(id, b))) { LOG(INFO) << a << " " << b; } } } LOG(INFO) << "---"; } static void PrintTransitiveClosure(Nodes *nodes, Edges *edges) { LOG(INFO) << "Transitive closure"; for (int a : *nodes) { for (int b : *nodes) { std::unordered_set<int> seen; if (IsReachable(edges, a, b, &seen)) { LOG(INFO) << a << " " << b; } } } LOG(INFO) << "---"; } static void PrintGCTransitiveClosure(Nodes *nodes, const IdMap &id, GraphCycles *gc) { LOG(INFO) << "GC Transitive closure"; for (int a : *nodes) { for (int b : *nodes) { if (gc->IsReachable(Get(id, a), Get(id, b))) { LOG(INFO) << a << " " << b; } } } LOG(INFO) << "---"; } static void CheckTransitiveClosure(Nodes *nodes, Edges *edges, const IdMap &id, GraphCycles *gc) { std::unordered_set<int> seen; for (const auto &a : *nodes) { for (const auto &b : *nodes) { seen.clear(); bool gc_reachable = gc->IsReachable(Get(id, a), Get(id, b)); bool reachable = IsReachable(edges, a, b, &seen); if (gc_reachable != reachable) { PrintEdges(edges); PrintGCEdges(nodes, id, gc); PrintTransitiveClosure(nodes, edges); PrintGCTransitiveClosure(nodes, id, gc); LOG(FATAL) << "gc_reachable " << gc_reachable << " reachable " << reachable << " a " << a << " b " << b; } } } } static void CheckEdges(Nodes *nodes, Edges *edges, const IdMap &id, GraphCycles *gc) { int count = 0; for (const auto &edge : *edges) { int a = edge.from; int b = edge.to; if (!gc->HasEdge(Get(id, a), Get(id, b))) { PrintEdges(edges); PrintGCEdges(nodes, id, gc); LOG(FATAL) << "!gc->HasEdge(" << a << ", " << b << ")"; } } for (const auto &a : *nodes) { for (const auto &b : *nodes) { if (gc->HasEdge(Get(id, a), Get(id, b))) { count++; } } } if (count != edges->size()) { PrintEdges(edges); PrintGCEdges(nodes, id, gc); LOG(FATAL) << "edges->size() " << edges->size() << " count " << count; } } static void CheckInvariants(const GraphCycles &gc) { CHECK(gc.CheckInvariants()) << "CheckInvariants"; } static int RandomNode(RandomEngine* rng, Nodes *nodes) { std::uniform_int_distribution<int> uniform(0, nodes->size()-1); return uniform(*rng); } static int RandomEdge(RandomEngine* rng, Edges *edges) { std::uniform_int_distribution<int> uniform(0, edges->size()-1); return uniform(*rng); } static int EdgeIndex(Edges *edges, int from, int to) { int i = 0; while (i != edges->size() && ((*edges)[i].from != from || (*edges)[i].to != to)) { i++; } return i == edges->size()? -1 : i; } TEST(GraphCycles, RandomizedTest) { int next_node = 0; Nodes nodes; Edges edges; IdMap id; GraphCycles graph_cycles; static const int kMaxNodes = 7; static const int kDataOffset = 17; int n = 100000; int op = 0; RandomEngine rng(testing::UnitTest::GetInstance()->random_seed()); std::uniform_int_distribution<int> uniform(0, 5); auto ptr = [](intptr_t i) { return reinterpret_cast<void*>(i + kDataOffset); }; for (int iter = 0; iter != n; iter++) { for (const auto &node : nodes) { ASSERT_EQ(graph_cycles.Ptr(Get(id, node)), ptr(node)) << " node " << node; } CheckEdges(&nodes, &edges, id, &graph_cycles); CheckTransitiveClosure(&nodes, &edges, id, &graph_cycles); op = uniform(rng); switch (op) { case 0: if (nodes.size() < kMaxNodes) { int new_node = next_node++; GraphId new_gnode = graph_cycles.GetId(ptr(new_node)); ASSERT_NE(new_gnode, InvalidGraphId()); id[new_node] = new_gnode; ASSERT_EQ(ptr(new_node), graph_cycles.Ptr(new_gnode)); nodes.push_back(new_node); } break; case 1: if (nodes.size() > 0) { int node_index = RandomNode(&rng, &nodes); int node = nodes[node_index]; nodes[node_index] = nodes.back(); nodes.pop_back(); graph_cycles.RemoveNode(ptr(node)); ASSERT_EQ(graph_cycles.Ptr(Get(id, node)), nullptr); id.erase(node); int i = 0; while (i != edges.size()) { if (edges[i].from == node || edges[i].to == node) { edges[i] = edges.back(); edges.pop_back(); } else { i++; } } } break; case 2: if (nodes.size() > 0) { int from = RandomNode(&rng, &nodes); int to = RandomNode(&rng, &nodes); if (EdgeIndex(&edges, nodes[from], nodes[to]) == -1) { if (graph_cycles.InsertEdge(id[nodes[from]], id[nodes[to]])) { Edge new_edge; new_edge.from = nodes[from]; new_edge.to = nodes[to]; edges.push_back(new_edge); } else { std::unordered_set<int> seen; ASSERT_TRUE(IsReachable(&edges, nodes[to], nodes[from], &seen)) << "Edge " << nodes[to] << "->" << nodes[from]; } } } break; case 3: if (edges.size() > 0) { int i = RandomEdge(&rng, &edges); int from = edges[i].from; int to = edges[i].to; ASSERT_EQ(i, EdgeIndex(&edges, from, to)); edges[i] = edges.back(); edges.pop_back(); ASSERT_EQ(-1, EdgeIndex(&edges, from, to)); graph_cycles.RemoveEdge(id[from], id[to]); } break; case 4: if (nodes.size() > 0) { int from = RandomNode(&rng, &nodes); int to = RandomNode(&rng, &nodes); GraphId path[2*kMaxNodes]; int path_len = graph_cycles.FindPath(id[nodes[from]], id[nodes[to]], ABSL_ARRAYSIZE(path), path); std::unordered_set<int> seen; bool reachable = IsReachable(&edges, nodes[from], nodes[to], &seen); bool gc_reachable = graph_cycles.IsReachable(Get(id, nodes[from]), Get(id, nodes[to])); ASSERT_EQ(path_len != 0, reachable); ASSERT_EQ(path_len != 0, gc_reachable); ASSERT_LE(path_len, kMaxNodes + 1); if (path_len != 0) { ASSERT_EQ(id[nodes[from]], path[0]); ASSERT_EQ(id[nodes[to]], path[path_len-1]); for (int i = 1; i < path_len; i++) { ASSERT_TRUE(graph_cycles.HasEdge(path[i-1], path[i])); } } } break; case 5: CheckInvariants(graph_cycles); break; default: LOG(FATAL) << "op " << op; } std::bernoulli_distribution one_in_1024(1.0 / 1024); if (one_in_1024(rng)) { CheckEdges(&nodes, &edges, id, &graph_cycles); CheckTransitiveClosure(&nodes, &edges, id, &graph_cycles); for (int i = 0; i != 256; i++) { int new_node = next_node++; GraphId new_gnode = graph_cycles.GetId(ptr(new_node)); ASSERT_NE(InvalidGraphId(), new_gnode); id[new_node] = new_gnode; ASSERT_EQ(ptr(new_node), graph_cycles.Ptr(new_gnode)); for (const auto &node : nodes) { ASSERT_NE(node, new_node); } nodes.push_back(new_node); } for (int i = 0; i != 256; i++) { ASSERT_GT(nodes.size(), 0); int node_index = RandomNode(&rng, &nodes); int node = nodes[node_index]; nodes[node_index] = nodes.back(); nodes.pop_back(); graph_cycles.RemoveNode(ptr(node)); id.erase(node); int j = 0; while (j != edges.size()) { if (edges[j].from == node || edges[j].to == node) { edges[j] = edges.back(); edges.pop_back(); } else { j++; } } } CheckInvariants(graph_cycles); } } } class GraphCyclesTest : public ::testing::Test { public: IdMap id_; GraphCycles g_; static void* Ptr(int i) { return reinterpret_cast<void*>(static_cast<uintptr_t>(i)); } static int Num(void* ptr) { return static_cast<int>(reinterpret_cast<uintptr_t>(ptr)); } GraphCyclesTest() { for (int i = 0; i < 100; i++) { id_[i] = g_.GetId(Ptr(i)); } CheckInvariants(g_); } bool AddEdge(int x, int y) { return g_.InsertEdge(Get(id_, x), Get(id_, y)); } void AddMultiples() { for (int x = 1; x < 25; x++) { EXPECT_TRUE(AddEdge(x, 2*x)) << x; EXPECT_TRUE(AddEdge(x, 3*x)) << x; } CheckInvariants(g_); } std::string Path(int x, int y) { GraphId path[5]; int np = g_.FindPath(Get(id_, x), Get(id_, y), ABSL_ARRAYSIZE(path), path); std::string result; for (int i = 0; i < np; i++) { if (i >= ABSL_ARRAYSIZE(path)) { result += " ..."; break; } if (!result.empty()) result.push_back(' '); char buf[20]; snprintf(buf, sizeof(buf), "%d", Num(g_.Ptr(path[i]))); result += buf; } return result; } }; TEST_F(GraphCyclesTest, NoCycle) { AddMultiples(); CheckInvariants(g_); } TEST_F(GraphCyclesTest, SimpleCycle) { AddMultiples(); EXPECT_FALSE(AddEdge(8, 4)); EXPECT_EQ("4 8", Path(4, 8)); CheckInvariants(g_); } TEST_F(GraphCyclesTest, IndirectCycle) { AddMultiples(); EXPECT_TRUE(AddEdge(16, 9)); CheckInvariants(g_); EXPECT_FALSE(AddEdge(9, 2)); EXPECT_EQ("2 4 8 16 9", Path(2, 9)); CheckInvariants(g_); } TEST_F(GraphCyclesTest, LongPath) { ASSERT_TRUE(AddEdge(2, 4)); ASSERT_TRUE(AddEdge(4, 6)); ASSERT_TRUE(AddEdge(6, 8)); ASSERT_TRUE(AddEdge(8, 10)); ASSERT_TRUE(AddEdge(10, 12)); ASSERT_FALSE(AddEdge(12, 2)); EXPECT_EQ("2 4 6 8 10 ...", Path(2, 12)); CheckInvariants(g_); } TEST_F(GraphCyclesTest, RemoveNode) { ASSERT_TRUE(AddEdge(1, 2)); ASSERT_TRUE(AddEdge(2, 3)); ASSERT_TRUE(AddEdge(3, 4)); ASSERT_TRUE(AddEdge(4, 5)); g_.RemoveNode(g_.Ptr(id_[3])); id_.erase(3); ASSERT_TRUE(AddEdge(5, 1)); } TEST_F(GraphCyclesTest, ManyEdges) { const int N = 50; for (int i = 0; i < N; i++) { for (int j = 1; j < N; j++) { ASSERT_TRUE(AddEdge(i, i+j)); } } CheckInvariants(g_); ASSERT_TRUE(AddEdge(2*N-1, 0)); CheckInvariants(g_); ASSERT_FALSE(AddEdge(10, 9)); CheckInvariants(g_); } TEST(GraphCycles, IntegerOverflow) { GraphCycles graph_cycles; char *buf = (char *)nullptr; GraphId prev_id = graph_cycles.GetId(buf); buf += 1; GraphId id = graph_cycles.GetId(buf); ASSERT_TRUE(graph_cycles.InsertEdge(prev_id, id)); graph_cycles.TestOnlyAddNodes(INT_MAX / 40); buf += 1; GraphId newid = graph_cycles.GetId(buf); graph_cycles.HasEdge(prev_id, newid); graph_cycles.RemoveNode(buf); } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/graphcycles.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/graphcycles_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4