ID
int64 0
2.65k
| Language
stringclasses 1
value | Repository Name
stringclasses 14
values | File Name
stringlengths 2
48
| File Path in Repository
stringlengths 11
111
⌀ | File Path for Unit Test
stringlengths 16
116
⌀ | Code
stringlengths 411
31.4k
| Unit Test - (Ground Truth)
stringlengths 40
32.1k
|
---|---|---|---|---|---|---|---|
2,500 | cpp | abseil/abseil-cpp | leak_check | absl/debugging/leak_check.cc | absl/debugging/leak_check_test.cc | #ifndef ABSL_DEBUGGING_LEAK_CHECK_H_
#define ABSL_DEBUGGING_LEAK_CHECK_H_
#include <cstddef>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
bool HaveLeakSanitizer();
bool LeakCheckerIsActive();
void DoIgnoreLeak(const void* ptr);
template <typename T>
T* IgnoreLeak(T* ptr) {
DoIgnoreLeak(ptr);
return ptr;
}
bool FindAndReportLeaks();
class LeakCheckDisabler {
public:
LeakCheckDisabler();
LeakCheckDisabler(const LeakCheckDisabler&) = delete;
LeakCheckDisabler& operator=(const LeakCheckDisabler&) = delete;
~LeakCheckDisabler();
};
void RegisterLivePointers(const void* ptr, size_t size);
void UnRegisterLivePointers(const void* ptr, size_t size);
ABSL_NAMESPACE_END
}
#endif
#include "absl/debugging/leak_check.h"
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#if defined(ABSL_HAVE_LEAK_SANITIZER)
#include <sanitizer/lsan_interface.h>
#if ABSL_HAVE_ATTRIBUTE_WEAK
extern "C" ABSL_ATTRIBUTE_WEAK int __lsan_is_turned_off();
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
bool HaveLeakSanitizer() { return true; }
#if ABSL_HAVE_ATTRIBUTE_WEAK
bool LeakCheckerIsActive() {
return !(&__lsan_is_turned_off && __lsan_is_turned_off());
}
#else
bool LeakCheckerIsActive() { return true; }
#endif
bool FindAndReportLeaks() { return __lsan_do_recoverable_leak_check(); }
void DoIgnoreLeak(const void* ptr) { __lsan_ignore_object(ptr); }
void RegisterLivePointers(const void* ptr, size_t size) {
__lsan_register_root_region(ptr, size);
}
void UnRegisterLivePointers(const void* ptr, size_t size) {
__lsan_unregister_root_region(ptr, size);
}
LeakCheckDisabler::LeakCheckDisabler() { __lsan_disable(); }
LeakCheckDisabler::~LeakCheckDisabler() { __lsan_enable(); }
ABSL_NAMESPACE_END
}
#else
namespace absl {
ABSL_NAMESPACE_BEGIN
bool HaveLeakSanitizer() { return false; }
bool LeakCheckerIsActive() { return false; }
void DoIgnoreLeak(const void*) { }
void RegisterLivePointers(const void*, size_t) { }
void UnRegisterLivePointers(const void*, size_t) { }
LeakCheckDisabler::LeakCheckDisabler() = default;
LeakCheckDisabler::~LeakCheckDisabler() = default;
ABSL_NAMESPACE_END
}
#endif | #include <string>
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/debugging/leak_check.h"
#include "absl/log/log.h"
namespace {
TEST(LeakCheckTest, IgnoreLeakSuppressesLeakedMemoryErrors) {
if (!absl::LeakCheckerIsActive()) {
GTEST_SKIP() << "LeakChecker is not active";
}
auto foo = absl::IgnoreLeak(new std::string("some ignored leaked string"));
LOG(INFO) << "Ignoring leaked string " << foo;
}
TEST(LeakCheckTest, LeakCheckDisablerIgnoresLeak) {
if (!absl::LeakCheckerIsActive()) {
GTEST_SKIP() << "LeakChecker is not active";
}
absl::LeakCheckDisabler disabler;
auto foo = new std::string("some string leaked while checks are disabled");
LOG(INFO) << "Ignoring leaked string " << foo;
}
} |
2,501 | cpp | abseil/abseil-cpp | symbolize | absl/debugging/symbolize.cc | absl/debugging/symbolize_test.cc | #ifndef ABSL_DEBUGGING_INTERNAL_SYMBOLIZE_H_
#define ABSL_DEBUGGING_INTERNAL_SYMBOLIZE_H_
#ifdef __cplusplus
#include <cstddef>
#include <cstdint>
#include "absl/base/config.h"
#include "absl/strings/string_view.h"
#ifdef ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE
#error ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE cannot be directly set
#elif defined(__ELF__) && defined(__GLIBC__) && !defined(__native_client__) \
&& !defined(__asmjs__) && !defined(__wasm__)
#define ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE 1
#include <elf.h>
#include <link.h>
#include <functional>
#include <string>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
bool ForEachSection(int fd,
const std::function<bool(absl::string_view name,
const ElfW(Shdr) &)>& callback);
bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
ElfW(Shdr) *out);
}
ABSL_NAMESPACE_END
}
#endif
#ifdef ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE
#error ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE cannot be directly set
#elif defined(__APPLE__)
#define ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE 1
#endif
#ifdef ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE
#error ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE cannot be directly set
#elif defined(__EMSCRIPTEN__)
#define ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE 1
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
struct SymbolDecoratorArgs {
const void *pc;
ptrdiff_t relocation;
int fd;
char *const symbol_buf;
size_t symbol_buf_size;
char *const tmp_buf;
size_t tmp_buf_size;
void* arg;
};
using SymbolDecorator = void (*)(const SymbolDecoratorArgs *);
int InstallSymbolDecorator(SymbolDecorator decorator, void* arg);
bool RemoveSymbolDecorator(int ticket);
bool RemoveAllSymbolDecorators();
bool RegisterFileMappingHint(const void* start, const void* end,
uint64_t offset, const char* filename);
bool GetFileMappingHint(const void** start, const void** end, uint64_t* offset,
const char** filename);
}
ABSL_NAMESPACE_END
}
#endif
#include <stdbool.h>
#ifdef __cplusplus
extern "C"
#endif
bool
AbslInternalGetFileMappingHint(const void** start, const void** end,
uint64_t* offset, const char** filename);
#endif
#include "absl/debugging/symbolize.h"
#ifdef _WIN32
#include <winapifamily.h>
#if !(WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)) || \
WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#define ABSL_INTERNAL_HAVE_SYMBOLIZE_WIN32
#endif
#endif
#if defined(__EMSCRIPTEN__) && !defined(STANDALONE_WASM)
#define ABSL_INTERNAL_HAVE_SYMBOLIZE_WASM
#endif
#if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE)
#include "absl/debugging/symbolize_elf.inc"
#elif defined(ABSL_INTERNAL_HAVE_SYMBOLIZE_WIN32)
#include "absl/debugging/symbolize_win32.inc"
#elif defined(__APPLE__)
#include "absl/debugging/symbolize_darwin.inc"
#elif defined(ABSL_INTERNAL_HAVE_SYMBOLIZE_WASM)
#include "absl/debugging/symbolize_emscripten.inc"
#else
#include "absl/debugging/symbolize_unimplemented.inc"
#endif | #include "absl/debugging/symbolize.h"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#ifndef _WIN32
#include <fcntl.h>
#include <sys/mman.h>
#endif
#include <cstring>
#include <iostream>
#include <memory>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/casts.h"
#include "absl/base/config.h"
#include "absl/base/internal/per_thread_tls.h"
#include "absl/base/optimization.h"
#include "absl/debugging/internal/stack_consumption.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
#define MAP_ANONYMOUS MAP_ANON
#endif
using testing::Contains;
#ifdef _WIN32
#define ABSL_SYMBOLIZE_TEST_NOINLINE __declspec(noinline)
#else
#define ABSL_SYMBOLIZE_TEST_NOINLINE ABSL_ATTRIBUTE_NOINLINE
#endif
extern "C" {
ABSL_SYMBOLIZE_TEST_NOINLINE void nonstatic_func() {
volatile int x = __LINE__;
static_cast<void>(x);
ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
}
ABSL_SYMBOLIZE_TEST_NOINLINE static void static_func() {
volatile int x = __LINE__;
static_cast<void>(x);
ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
}
}
struct Foo {
static void func(int x);
};
ABSL_SYMBOLIZE_TEST_NOINLINE void Foo::func(int) {
volatile int x = __LINE__;
static_cast<void>(x);
ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
}
int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.unlikely) unlikely_func() {
return 0;
}
int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.hot) hot_func() { return 0; }
int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.startup) startup_func() { return 0; }
int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.exit) exit_func() { return 0; }
int regular_func() { return 0; }
#if ABSL_PER_THREAD_TLS
static ABSL_PER_THREAD_TLS_KEYWORD char symbolize_test_thread_small[1];
static ABSL_PER_THREAD_TLS_KEYWORD char
symbolize_test_thread_big[2 * 1024 * 1024];
#endif
#if !defined(__EMSCRIPTEN__)
static void *GetPCFromFnPtr(void *ptr) { return ptr; }
static volatile bool volatile_bool = false;
static constexpr size_t kHpageSize = 1 << 21;
const char kHpageTextPadding[kHpageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(
.text) = "";
#else
static void *GetPCFromFnPtr(void *ptr) {
return EM_ASM_PTR(
{ return wasmOffsetConverter.convert(wasmTable.get($0).name, 0); }, ptr);
}
#endif
static char try_symbolize_buffer[4096];
static const char *TrySymbolizeWithLimit(void *pc, int limit) {
CHECK_LE(limit, sizeof(try_symbolize_buffer))
<< "try_symbolize_buffer is too small";
auto heap_buffer = absl::make_unique<char[]>(sizeof(try_symbolize_buffer));
bool found = absl::Symbolize(pc, heap_buffer.get(), limit);
if (found) {
CHECK_LT(static_cast<int>(
strnlen(heap_buffer.get(), static_cast<size_t>(limit))),
limit)
<< "absl::Symbolize() did not properly terminate the string";
strncpy(try_symbolize_buffer, heap_buffer.get(),
sizeof(try_symbolize_buffer) - 1);
try_symbolize_buffer[sizeof(try_symbolize_buffer) - 1] = '\0';
}
return found ? try_symbolize_buffer : nullptr;
}
static const char *TrySymbolize(void *pc) {
return TrySymbolizeWithLimit(pc, sizeof(try_symbolize_buffer));
}
#if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE) || \
defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE) || \
defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE)
void ABSL_ATTRIBUTE_NOINLINE TestWithReturnAddress() {
#if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE)
void *return_address = __builtin_return_address(0);
const char *symbol = TrySymbolize(return_address);
CHECK_NE(symbol, nullptr) << "TestWithReturnAddress failed";
CHECK_STREQ(symbol, "main") << "TestWithReturnAddress failed";
std::cout << "TestWithReturnAddress passed" << std::endl;
#endif
}
TEST(Symbolize, Cached) {
EXPECT_STREQ("nonstatic_func",
TrySymbolize(GetPCFromFnPtr((void *)(&nonstatic_func))));
const char *static_func_symbol =
TrySymbolize(GetPCFromFnPtr((void *)(&static_func)));
EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 ||
strcmp("static_func()", static_func_symbol) == 0);
EXPECT_TRUE(nullptr == TrySymbolize(nullptr));
}
TEST(Symbolize, Truncation) {
constexpr char kNonStaticFunc[] = "nonstatic_func";
EXPECT_STREQ("nonstatic_func",
TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)),
strlen(kNonStaticFunc) + 1));
EXPECT_STREQ("nonstatic_...",
TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)),
strlen(kNonStaticFunc) + 0));
EXPECT_STREQ("nonstatic...",
TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)),
strlen(kNonStaticFunc) - 1));
EXPECT_STREQ("n...", TrySymbolizeWithLimit(
GetPCFromFnPtr((void *)(&nonstatic_func)), 5));
EXPECT_STREQ("...", TrySymbolizeWithLimit(
GetPCFromFnPtr((void *)(&nonstatic_func)), 4));
EXPECT_STREQ("..", TrySymbolizeWithLimit(
GetPCFromFnPtr((void *)(&nonstatic_func)), 3));
EXPECT_STREQ(
".", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), 2));
EXPECT_STREQ(
"", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), 1));
EXPECT_EQ(nullptr, TrySymbolizeWithLimit(
GetPCFromFnPtr((void *)(&nonstatic_func)), 0));
}
TEST(Symbolize, SymbolizeWithDemangling) {
Foo::func(100);
#ifdef __EMSCRIPTEN__
EXPECT_STREQ("Foo::func(int)",
TrySymbolize(GetPCFromFnPtr((void *)(&Foo::func))));
#else
EXPECT_STREQ("Foo::func()",
TrySymbolize(GetPCFromFnPtr((void *)(&Foo::func))));
#endif
}
TEST(Symbolize, SymbolizeSplitTextSections) {
EXPECT_STREQ("unlikely_func()",
TrySymbolize(GetPCFromFnPtr((void *)(&unlikely_func))));
EXPECT_STREQ("hot_func()", TrySymbolize(GetPCFromFnPtr((void *)(&hot_func))));
EXPECT_STREQ("startup_func()",
TrySymbolize(GetPCFromFnPtr((void *)(&startup_func))));
EXPECT_STREQ("exit_func()",
TrySymbolize(GetPCFromFnPtr((void *)(&exit_func))));
EXPECT_STREQ("regular_func()",
TrySymbolize(GetPCFromFnPtr((void *)(®ular_func))));
}
#ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
static void *g_pc_to_symbolize;
static char g_symbolize_buffer[4096];
static char *g_symbolize_result;
static void SymbolizeSignalHandler(int signo) {
if (absl::Symbolize(g_pc_to_symbolize, g_symbolize_buffer,
sizeof(g_symbolize_buffer))) {
g_symbolize_result = g_symbolize_buffer;
} else {
g_symbolize_result = nullptr;
}
}
static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) {
g_pc_to_symbolize = pc;
*stack_consumed = absl::debugging_internal::GetSignalHandlerStackConsumption(
SymbolizeSignalHandler);
return g_symbolize_result;
}
static int GetStackConsumptionUpperLimit() {
int stack_consumption_upper_limit = 2048;
#if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
defined(ABSL_HAVE_MEMORY_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER)
stack_consumption_upper_limit *= 5;
#endif
return stack_consumption_upper_limit;
}
TEST(Symbolize, SymbolizeStackConsumption) {
int stack_consumed = 0;
const char *symbol =
SymbolizeStackConsumption((void *)(&nonstatic_func), &stack_consumed);
EXPECT_STREQ("nonstatic_func", symbol);
EXPECT_GT(stack_consumed, 0);
EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit());
symbol = SymbolizeStackConsumption((void *)(&static_func), &stack_consumed);
EXPECT_TRUE(strcmp("static_func", symbol) == 0 ||
strcmp("static_func()", symbol) == 0);
EXPECT_GT(stack_consumed, 0);
EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit());
}
TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) {
Foo::func(100);
int stack_consumed = 0;
const char *symbol =
SymbolizeStackConsumption((void *)(&Foo::func), &stack_consumed);
EXPECT_STREQ("Foo::func()", symbol);
EXPECT_GT(stack_consumed, 0);
EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit());
}
#endif
#if !defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE) && \
!defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE)
const size_t kPageSize = 64 << 10;
const char kPadding0[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = "";
const char kPadding1[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = "";
static int FilterElfHeader(struct dl_phdr_info *info, size_t size, void *data) {
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD &&
info->dlpi_phdr[i].p_flags == (PF_R | PF_X)) {
const void *const vaddr =
absl::bit_cast<void *>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
const auto segsize = info->dlpi_phdr[i].p_memsz;
const char *self_exe;
if (info->dlpi_name != nullptr && info->dlpi_name[0] != '\0') {
self_exe = info->dlpi_name;
} else {
self_exe = "/proc/self/exe";
}
absl::debugging_internal::RegisterFileMappingHint(
vaddr, reinterpret_cast<const char *>(vaddr) + segsize,
info->dlpi_phdr[i].p_offset, self_exe);
return 1;
}
}
return 1;
}
TEST(Symbolize, SymbolizeWithMultipleMaps) {
if (volatile_bool) {
LOG(INFO) << kPadding0;
LOG(INFO) << kPadding1;
}
char buf[512];
memset(buf, 0, sizeof(buf));
absl::Symbolize(kPadding0, buf, sizeof(buf));
EXPECT_STREQ("kPadding0", buf);
memset(buf, 0, sizeof(buf));
absl::Symbolize(kPadding1, buf, sizeof(buf));
EXPECT_STREQ("kPadding1", buf);
dl_iterate_phdr(FilterElfHeader, nullptr);
const char *ptrs[] = {kPadding0, kPadding1};
for (const char *ptr : ptrs) {
const int kMapFlags = MAP_ANONYMOUS | MAP_PRIVATE;
void *addr = mmap(nullptr, kPageSize, PROT_READ, kMapFlags, 0, 0);
ASSERT_NE(addr, MAP_FAILED);
void *remapped = reinterpret_cast<void *>(
reinterpret_cast<uintptr_t>(ptr + kPageSize) & ~(kPageSize - 1ULL));
const int kMremapFlags = (MREMAP_MAYMOVE | MREMAP_FIXED);
void *ret = mremap(addr, kPageSize, kPageSize, kMremapFlags, remapped);
ASSERT_NE(ret, MAP_FAILED);
}
absl::Symbolize(nullptr, buf, sizeof(buf));
const char *expected[] = {"kPadding0", "kPadding1"};
const size_t offsets[] = {0, kPageSize, 2 * kPageSize, 3 * kPageSize};
for (int i = 0; i < 2; i++) {
for (size_t offset : offsets) {
memset(buf, 0, sizeof(buf));
absl::Symbolize(ptrs[i] + offset, buf, sizeof(buf));
EXPECT_STREQ(expected[i], buf);
}
}
}
static void DummySymbolDecorator(
const absl::debugging_internal::SymbolDecoratorArgs *args) {
std::string *message = static_cast<std::string *>(args->arg);
strncat(args->symbol_buf, message->c_str(),
args->symbol_buf_size - strlen(args->symbol_buf) - 1);
}
TEST(Symbolize, InstallAndRemoveSymbolDecorators) {
int ticket_a;
std::string a_message("a");
EXPECT_GE(ticket_a = absl::debugging_internal::InstallSymbolDecorator(
DummySymbolDecorator, &a_message),
0);
int ticket_b;
std::string b_message("b");
EXPECT_GE(ticket_b = absl::debugging_internal::InstallSymbolDecorator(
DummySymbolDecorator, &b_message),
0);
int ticket_c;
std::string c_message("c");
EXPECT_GE(ticket_c = absl::debugging_internal::InstallSymbolDecorator(
DummySymbolDecorator, &c_message),
0);
char *address = reinterpret_cast<char *>(4);
EXPECT_STREQ("abc", TrySymbolize(address));
EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_b));
EXPECT_STREQ("ac", TrySymbolize(address + 4));
EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_a));
EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_c));
}
static int in_data_section = 1;
TEST(Symbolize, ForEachSection) {
int fd = TEMP_FAILURE_RETRY(open("/proc/self/exe", O_RDONLY));
ASSERT_NE(fd, -1);
std::vector<std::string> sections;
ASSERT_TRUE(absl::debugging_internal::ForEachSection(
fd, [§ions](const absl::string_view name, const ElfW(Shdr) &) {
sections.emplace_back(name);
return true;
}));
EXPECT_THAT(sections, Contains(".text"));
EXPECT_THAT(sections, Contains(".rodata"));
EXPECT_THAT(sections, Contains(".bss"));
++in_data_section;
EXPECT_THAT(sections, Contains(".data"));
close(fd);
}
#endif
extern "C" {
inline void *ABSL_ATTRIBUTE_ALWAYS_INLINE inline_func() {
void *pc = nullptr;
#if defined(__i386__)
__asm__ __volatile__("call 1f;\n 1: pop %[PC]" : [PC] "=r"(pc));
#elif defined(__x86_64__)
__asm__ __volatile__("leaq 0(%%rip),%[PC];\n" : [PC] "=r"(pc));
#endif
return pc;
}
void *ABSL_ATTRIBUTE_NOINLINE non_inline_func() {
void *pc = nullptr;
#if defined(__i386__)
__asm__ __volatile__("call 1f;\n 1: pop %[PC]" : [PC] "=r"(pc));
#elif defined(__x86_64__)
__asm__ __volatile__("leaq 0(%%rip),%[PC];\n" : [PC] "=r"(pc));
#endif
return pc;
}
void ABSL_ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() {
#if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE) && \
(defined(__i386__) || defined(__x86_64__))
void *pc = non_inline_func();
const char *symbol = TrySymbolize(pc);
CHECK_NE(symbol, nullptr) << "TestWithPCInsideNonInlineFunction failed";
CHECK_STREQ(symbol, "non_inline_func")
<< "TestWithPCInsideNonInlineFunction failed";
std::cout << "TestWithPCInsideNonInlineFunction passed" << std::endl;
#endif
}
void ABSL_ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() {
#if defined(ABSL_HAVE_ATTRIBUTE_ALWAYS_INLINE) && \
(defined(__i386__) || defined(__x86_64__))
void *pc = inline_func();
const char *symbol = TrySymbolize(pc);
CHECK_NE(symbol, nullptr) << "TestWithPCInsideInlineFunction failed";
CHECK_STREQ(symbol, __FUNCTION__) << "TestWithPCInsideInlineFunction failed";
std::cout << "TestWithPCInsideInlineFunction passed" << std::endl;
#endif
}
}
#if defined(__arm__) && ABSL_HAVE_ATTRIBUTE(target) && \
((__ARM_ARCH >= 7) || !defined(__ARM_PCS_VFP))
__attribute__((target("thumb"))) int ArmThumbOverlapThumb(int x) {
return x * x * x;
}
__attribute__((target("arm"))) int ArmThumbOverlapArm(int x) {
return x * x * x;
}
void ABSL_ATTRIBUTE_NOINLINE TestArmThumbOverlap() {
#if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE)
const char *symbol = TrySymbolize((void *)&ArmThumbOverlapArm);
CHECK_NE(symbol, nullptr) << "TestArmThumbOverlap failed";
CHECK_STREQ("ArmThumbOverlapArm()", symbol) << "TestArmThumbOverlap failed";
std::cout << "TestArmThumbOverlap passed" << std::endl;
#endif
}
#endif
#elif defined(_WIN32)
#if !defined(ABSL_CONSUME_DLL)
TEST(Symbolize, Basics) {
EXPECT_STREQ("nonstatic_func", TrySymbolize((void *)(&nonstatic_func)));
const char *static_func_symbol = TrySymbolize((void *)(&static_func));
ASSERT_TRUE(static_func_symbol != nullptr);
EXPECT_TRUE(strstr(static_func_symbol, "static_func") != nullptr);
EXPECT_TRUE(nullptr == TrySymbolize(nullptr));
}
TEST(Symbolize, Truncation) {
constexpr char kNonStaticFunc[] = "nonstatic_func";
EXPECT_STREQ("nonstatic_func",
TrySymbolizeWithLimit((void *)(&nonstatic_func),
strlen(kNonStaticFunc) + 1));
EXPECT_STREQ("nonstatic_...",
TrySymbolizeWithLimit((void *)(&nonstatic_func),
strlen(kNonStaticFunc) + 0));
EXPECT_STREQ("nonstatic...",
TrySymbolizeWithLimit((void *)(&nonstatic_func),
strlen(kNonStaticFunc) - 1));
EXPECT_STREQ("n...", TrySymbolizeWithLimit((void *)(&nonstatic_func), 5));
EXPECT_STREQ("...", TrySymbolizeWithLimit((void *)(&nonstatic_func), 4));
EXPECT_STREQ("..", TrySymbolizeWithLimit((void *)(&nonstatic_func), 3));
EXPECT_STREQ(".", TrySymbolizeWithLimit((void *)(&nonstatic_func), 2));
EXPECT_STREQ("", TrySymbolizeWithLimit((void *)(&nonstatic_func), 1));
EXPECT_EQ(nullptr, TrySymbolizeWithLimit((void *)(&nonstatic_func), 0));
}
TEST(Symbolize, SymbolizeWithDemangling) {
const char *result = TrySymbolize((void *)(&Foo::func));
ASSERT_TRUE(result != nullptr);
EXPECT_TRUE(strstr(result, "Foo::func") != nullptr) << result;
}
#endif
#else
TEST(Symbolize, Unimplemented) {
char buf[64];
EXPECT_FALSE(absl::Symbolize((void *)(&nonstatic_func), buf, sizeof(buf)));
EXPECT_FALSE(absl::Symbolize((void *)(&static_func), buf, sizeof(buf)));
EXPECT_FALSE(absl::Symbolize((void *)(&Foo::func), buf, sizeof(buf)));
}
#endif
int main(int argc, char **argv) {
#if !defined(__EMSCRIPTEN__)
if (volatile_bool) {
LOG(INFO) << kHpageTextPadding;
}
#endif
#if ABSL_PER_THREAD_TLS
symbolize_test_thread_small[0] = 0;
symbolize_test_thread_big[0] = 0;
#endif
absl::InitializeSymbolizer(argv[0]);
testing::InitGoogleTest(&argc, argv);
#if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE) || \
defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE) || \
defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE)
TestWithPCInsideInlineFunction();
TestWithPCInsideNonInlineFunction();
TestWithReturnAddress();
#if defined(__arm__) && ABSL_HAVE_ATTRIBUTE(target) && \
((__ARM_ARCH >= 7) || !defined(__ARM_PCS_VFP))
TestArmThumbOverlap();
#endif
#endif
return RUN_ALL_TESTS();
} |
2,502 | cpp | abseil/abseil-cpp | stacktrace | absl/debugging/stacktrace.cc | absl/debugging/stacktrace_test.cc | #ifndef ABSL_DEBUGGING_STACKTRACE_H_
#define ABSL_DEBUGGING_STACKTRACE_H_
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
extern int GetStackFrames(void** result, int* sizes, int max_depth,
int skip_count);
extern int GetStackFramesWithContext(void** result, int* sizes, int max_depth,
int skip_count, const void* uc,
int* min_dropped_frames);
extern int GetStackTrace(void** result, int max_depth, int skip_count);
extern int GetStackTraceWithContext(void** result, int max_depth,
int skip_count, const void* uc,
int* min_dropped_frames);
extern void SetStackUnwinder(int (*unwinder)(void** pcs, int* sizes,
int max_depth, int skip_count,
const void* uc,
int* min_dropped_frames));
extern int DefaultStackUnwinder(void** pcs, int* sizes, int max_depth,
int skip_count, const void* uc,
int* min_dropped_frames);
namespace debugging_internal {
extern bool StackTraceWorksForTest();
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/debugging/stacktrace.h"
#include <atomic>
#include "absl/base/attributes.h"
#include "absl/base/port.h"
#include "absl/debugging/internal/stacktrace_config.h"
#if defined(ABSL_STACKTRACE_INL_HEADER)
#include ABSL_STACKTRACE_INL_HEADER
#else
# error Cannot calculate stack trace: will need to write for your environment
# include "absl/debugging/internal/stacktrace_aarch64-inl.inc"
# include "absl/debugging/internal/stacktrace_arm-inl.inc"
# include "absl/debugging/internal/stacktrace_emscripten-inl.inc"
# include "absl/debugging/internal/stacktrace_generic-inl.inc"
# include "absl/debugging/internal/stacktrace_powerpc-inl.inc"
# include "absl/debugging/internal/stacktrace_riscv-inl.inc"
# include "absl/debugging/internal/stacktrace_unimplemented-inl.inc"
# include "absl/debugging/internal/stacktrace_win32-inl.inc"
# include "absl/debugging/internal/stacktrace_x86-inl.inc"
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
typedef int (*Unwinder)(void**, int*, int, int, const void*, int*);
std::atomic<Unwinder> custom;
template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
ABSL_ATTRIBUTE_ALWAYS_INLINE inline int Unwind(void** result, int* sizes,
int max_depth, int skip_count,
const void* uc,
int* min_dropped_frames) {
Unwinder f = &UnwindImpl<IS_STACK_FRAMES, IS_WITH_CONTEXT>;
Unwinder g = custom.load(std::memory_order_acquire);
if (g != nullptr) f = g;
int size = (*f)(result, sizes, max_depth, skip_count + 1, uc,
min_dropped_frames);
ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
return size;
}
}
ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackFrames(
void** result, int* sizes, int max_depth, int skip_count) {
return Unwind<true, false>(result, sizes, max_depth, skip_count, nullptr,
nullptr);
}
ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int
GetStackFramesWithContext(void** result, int* sizes, int max_depth,
int skip_count, const void* uc,
int* min_dropped_frames) {
return Unwind<true, true>(result, sizes, max_depth, skip_count, uc,
min_dropped_frames);
}
ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackTrace(
void** result, int max_depth, int skip_count) {
return Unwind<false, false>(result, nullptr, max_depth, skip_count, nullptr,
nullptr);
}
ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int
GetStackTraceWithContext(void** result, int max_depth, int skip_count,
const void* uc, int* min_dropped_frames) {
return Unwind<false, true>(result, nullptr, max_depth, skip_count, uc,
min_dropped_frames);
}
void SetStackUnwinder(Unwinder w) {
custom.store(w, std::memory_order_release);
}
int DefaultStackUnwinder(void** pcs, int* sizes, int depth, int skip,
const void* uc, int* min_dropped_frames) {
skip++;
Unwinder f = nullptr;
if (sizes == nullptr) {
if (uc == nullptr) {
f = &UnwindImpl<false, false>;
} else {
f = &UnwindImpl<false, true>;
}
} else {
if (uc == nullptr) {
f = &UnwindImpl<true, false>;
} else {
f = &UnwindImpl<true, true>;
}
}
volatile int x = 0;
int n = (*f)(pcs, sizes, depth, skip, uc, min_dropped_frames);
x = 1; (void) x;
return n;
}
ABSL_NAMESPACE_END
} | #include "absl/debugging/stacktrace.h"
#include "gtest/gtest.h"
#include "absl/base/macros.h"
#include "absl/base/optimization.h"
namespace {
#if defined(__linux__) && (defined(__x86_64__) || defined(__aarch64__))
ABSL_ATTRIBUTE_NOINLINE void Unwind(void* p) {
ABSL_ATTRIBUTE_UNUSED static void* volatile sink = p;
constexpr int kSize = 16;
void* stack[kSize];
int frames[kSize];
absl::GetStackTrace(stack, kSize, 0);
absl::GetStackFrames(stack, frames, kSize, 0);
}
ABSL_ATTRIBUTE_NOINLINE void HugeFrame() {
char buffer[1 << 20];
Unwind(buffer);
ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
}
TEST(StackTrace, HugeFrame) {
HugeFrame();
ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
}
#endif
} |
2,503 | cpp | abseil/abseil-cpp | utf8_for_code_point | absl/debugging/internal/utf8_for_code_point.cc | absl/debugging/internal/utf8_for_code_point_test.cc | #ifndef ABSL_DEBUGGING_INTERNAL_UTF8_FOR_CODE_POINT_H_
#define ABSL_DEBUGGING_INTERNAL_UTF8_FOR_CODE_POINT_H_
#include <cstdint>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
struct Utf8ForCodePoint {
explicit Utf8ForCodePoint(uint64_t code_point);
bool ok() const { return length != 0; }
char bytes[4] = {};
uint32_t length = 0;
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/debugging/internal/utf8_for_code_point.h"
#include <cstdint>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
namespace {
constexpr uint32_t kMinSurrogate = 0xd800, kMaxSurrogate = 0xdfff;
constexpr uint32_t kMax1ByteCodePoint = 0x7f;
constexpr uint32_t kMax2ByteCodePoint = 0x7ff;
constexpr uint32_t kMax3ByteCodePoint = 0xffff;
constexpr uint32_t kMaxCodePoint = 0x10ffff;
}
Utf8ForCodePoint::Utf8ForCodePoint(uint64_t code_point) {
if (code_point <= kMax1ByteCodePoint) {
length = 1;
bytes[0] = static_cast<char>(code_point);
return;
}
if (code_point <= kMax2ByteCodePoint) {
length = 2;
bytes[0] = static_cast<char>(0xc0 | (code_point >> 6));
bytes[1] = static_cast<char>(0x80 | (code_point & 0x3f));
return;
}
if (kMinSurrogate <= code_point && code_point <= kMaxSurrogate) return;
if (code_point <= kMax3ByteCodePoint) {
length = 3;
bytes[0] = static_cast<char>(0xe0 | (code_point >> 12));
bytes[1] = static_cast<char>(0x80 | ((code_point >> 6) & 0x3f));
bytes[2] = static_cast<char>(0x80 | (code_point & 0x3f));
return;
}
if (code_point > kMaxCodePoint) return;
length = 4;
bytes[0] = static_cast<char>(0xf0 | (code_point >> 18));
bytes[1] = static_cast<char>(0x80 | ((code_point >> 12) & 0x3f));
bytes[2] = static_cast<char>(0x80 | ((code_point >> 6) & 0x3f));
bytes[3] = static_cast<char>(0x80 | (code_point & 0x3f));
}
}
ABSL_NAMESPACE_END
} | #include "absl/debugging/internal/utf8_for_code_point.h"
#include <cstdint>
#include "gtest/gtest.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
namespace {
TEST(Utf8ForCodePointTest, RecognizesTheSmallestCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0});
ASSERT_EQ(utf8.length, 1);
EXPECT_EQ(utf8.bytes[0], '\0');
}
TEST(Utf8ForCodePointTest, RecognizesAsciiSmallA) {
Utf8ForCodePoint utf8(uint64_t{'a'});
ASSERT_EQ(utf8.length, 1);
EXPECT_EQ(utf8.bytes[0], 'a');
}
TEST(Utf8ForCodePointTest, RecognizesTheLargestOneByteCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0x7f});
ASSERT_EQ(utf8.length, 1);
EXPECT_EQ(utf8.bytes[0], '\x7f');
}
TEST(Utf8ForCodePointTest, RecognizesTheSmallestTwoByteCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0x80});
ASSERT_EQ(utf8.length, 2);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xc2));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x80));
}
TEST(Utf8ForCodePointTest, RecognizesSmallNWithTilde) {
Utf8ForCodePoint utf8(uint64_t{0xf1});
ASSERT_EQ(utf8.length, 2);
const char* want = "ñ";
EXPECT_EQ(utf8.bytes[0], want[0]);
EXPECT_EQ(utf8.bytes[1], want[1]);
}
TEST(Utf8ForCodePointTest, RecognizesCapitalPi) {
Utf8ForCodePoint utf8(uint64_t{0x3a0});
ASSERT_EQ(utf8.length, 2);
const char* want = "Π";
EXPECT_EQ(utf8.bytes[0], want[0]);
EXPECT_EQ(utf8.bytes[1], want[1]);
}
TEST(Utf8ForCodePointTest, RecognizesTheLargestTwoByteCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0x7ff});
ASSERT_EQ(utf8.length, 2);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xdf));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0xbf));
}
TEST(Utf8ForCodePointTest, RecognizesTheSmallestThreeByteCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0x800});
ASSERT_EQ(utf8.length, 3);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xe0));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0xa0));
EXPECT_EQ(utf8.bytes[2], static_cast<char>(0x80));
}
TEST(Utf8ForCodePointTest, RecognizesTheChineseCharacterZhong1AsInZhong1Wen2) {
Utf8ForCodePoint utf8(uint64_t{0x4e2d});
ASSERT_EQ(utf8.length, 3);
const char* want = "中";
EXPECT_EQ(utf8.bytes[0], want[0]);
EXPECT_EQ(utf8.bytes[1], want[1]);
EXPECT_EQ(utf8.bytes[2], want[2]);
}
TEST(Utf8ForCodePointTest, RecognizesOneBeforeTheSmallestSurrogate) {
Utf8ForCodePoint utf8(uint64_t{0xd7ff});
ASSERT_EQ(utf8.length, 3);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xed));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x9f));
EXPECT_EQ(utf8.bytes[2], static_cast<char>(0xbf));
}
TEST(Utf8ForCodePointTest, RejectsTheSmallestSurrogate) {
Utf8ForCodePoint utf8(uint64_t{0xd800});
EXPECT_EQ(utf8.length, 0);
}
TEST(Utf8ForCodePointTest, RejectsTheLargestSurrogate) {
Utf8ForCodePoint utf8(uint64_t{0xdfff});
EXPECT_EQ(utf8.length, 0);
}
TEST(Utf8ForCodePointTest, RecognizesOnePastTheLargestSurrogate) {
Utf8ForCodePoint utf8(uint64_t{0xe000});
ASSERT_EQ(utf8.length, 3);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xee));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x80));
EXPECT_EQ(utf8.bytes[2], static_cast<char>(0x80));
}
TEST(Utf8ForCodePointTest, RecognizesTheLargestThreeByteCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0xffff});
ASSERT_EQ(utf8.length, 3);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xef));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0xbf));
EXPECT_EQ(utf8.bytes[2], static_cast<char>(0xbf));
}
TEST(Utf8ForCodePointTest, RecognizesTheSmallestFourByteCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0x10000});
ASSERT_EQ(utf8.length, 4);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xf0));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x90));
EXPECT_EQ(utf8.bytes[2], static_cast<char>(0x80));
EXPECT_EQ(utf8.bytes[3], static_cast<char>(0x80));
}
TEST(Utf8ForCodePointTest, RecognizesTheJackOfHearts) {
Utf8ForCodePoint utf8(uint64_t{0x1f0bb});
ASSERT_EQ(utf8.length, 4);
const char* want = "🂻";
EXPECT_EQ(utf8.bytes[0], want[0]);
EXPECT_EQ(utf8.bytes[1], want[1]);
EXPECT_EQ(utf8.bytes[2], want[2]);
EXPECT_EQ(utf8.bytes[3], want[3]);
}
TEST(Utf8ForCodePointTest, RecognizesTheLargestFourByteCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0x10ffff});
ASSERT_EQ(utf8.length, 4);
EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xf4));
EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x8f));
EXPECT_EQ(utf8.bytes[2], static_cast<char>(0xbf));
EXPECT_EQ(utf8.bytes[3], static_cast<char>(0xbf));
}
TEST(Utf8ForCodePointTest, RejectsTheSmallestOverlargeCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0x110000});
EXPECT_EQ(utf8.length, 0);
}
TEST(Utf8ForCodePointTest, RejectsAThroughlyOverlargeCodePoint) {
Utf8ForCodePoint utf8(uint64_t{0xffffffff00000000});
EXPECT_EQ(utf8.length, 0);
}
TEST(Utf8ForCodePointTest, OkReturnsTrueForAValidCodePoint) {
EXPECT_TRUE(Utf8ForCodePoint(uint64_t{0}).ok());
}
TEST(Utf8ForCodePointTest, OkReturnsFalseForAnInvalidCodePoint) {
EXPECT_FALSE(Utf8ForCodePoint(uint64_t{0xffffffff00000000}).ok());
}
}
}
ABSL_NAMESPACE_END
} |
2,504 | cpp | abseil/abseil-cpp | demangle | absl/debugging/internal/demangle.cc | absl/debugging/internal/demangle_test.cc | #ifndef ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_
#define ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_
#include <string>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
bool Demangle(const char* mangled, char* out, size_t out_size);
std::string DemangleString(const char* mangled);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/debugging/internal/demangle.h"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <string>
#include "absl/base/config.h"
#include "absl/debugging/internal/demangle_rust.h"
#if ABSL_INTERNAL_HAS_CXA_DEMANGLE
#include <cxxabi.h>
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
typedef struct {
const char *abbrev;
const char *real_name;
int arity;
} AbbrevPair;
static const AbbrevPair kOperatorList[] = {
{"nw", "new", 0},
{"na", "new[]", 0},
{"dl", "delete", 1},
{"da", "delete[]", 1},
{"aw", "co_await", 1},
{"ps", "+", 1},
{"ng", "-", 1},
{"ad", "&", 1},
{"de", "*", 1},
{"co", "~", 1},
{"pl", "+", 2},
{"mi", "-", 2},
{"ml", "*", 2},
{"dv", "/", 2},
{"rm", "%", 2},
{"an", "&", 2},
{"or", "|", 2},
{"eo", "^", 2},
{"aS", "=", 2},
{"pL", "+=", 2},
{"mI", "-=", 2},
{"mL", "*=", 2},
{"dV", "/=", 2},
{"rM", "%=", 2},
{"aN", "&=", 2},
{"oR", "|=", 2},
{"eO", "^=", 2},
{"ls", "<<", 2},
{"rs", ">>", 2},
{"lS", "<<=", 2},
{"rS", ">>=", 2},
{"ss", "<=>", 2},
{"eq", "==", 2},
{"ne", "!=", 2},
{"lt", "<", 2},
{"gt", ">", 2},
{"le", "<=", 2},
{"ge", ">=", 2},
{"nt", "!", 1},
{"aa", "&&", 2},
{"oo", "||", 2},
{"pp", "++", 1},
{"mm", "--", 1},
{"cm", ",", 2},
{"pm", "->*", 2},
{"pt", "->", 0},
{"cl", "()", 0},
{"ix", "[]", 2},
{"qu", "?", 3},
{"st", "sizeof", 0},
{"sz", "sizeof", 1},
{"sZ", "sizeof...", 0},
{nullptr, nullptr, 0},
};
static const AbbrevPair kBuiltinTypeList[] = {
{"v", "void", 0},
{"w", "wchar_t", 0},
{"b", "bool", 0},
{"c", "char", 0},
{"a", "signed char", 0},
{"h", "unsigned char", 0},
{"s", "short", 0},
{"t", "unsigned short", 0},
{"i", "int", 0},
{"j", "unsigned int", 0},
{"l", "long", 0},
{"m", "unsigned long", 0},
{"x", "long long", 0},
{"y", "unsigned long long", 0},
{"n", "__int128", 0},
{"o", "unsigned __int128", 0},
{"f", "float", 0},
{"d", "double", 0},
{"e", "long double", 0},
{"g", "__float128", 0},
{"z", "ellipsis", 0},
{"De", "decimal128", 0},
{"Dd", "decimal64", 0},
{"Dc", "decltype(auto)", 0},
{"Da", "auto", 0},
{"Dn", "std::nullptr_t", 0},
{"Df", "decimal32", 0},
{"Di", "char32_t", 0},
{"Du", "char8_t", 0},
{"Ds", "char16_t", 0},
{"Dh", "float16", 0},
{nullptr, nullptr, 0},
};
static const AbbrevPair kSubstitutionList[] = {
{"St", "", 0},
{"Sa", "allocator", 0},
{"Sb", "basic_string", 0},
{"Ss", "string", 0},
{"Si", "istream", 0},
{"So", "ostream", 0},
{"Sd", "iostream", 0},
{nullptr, nullptr, 0},
};
typedef struct {
int mangled_idx;
int out_cur_idx;
int prev_name_idx;
unsigned int prev_name_length : 16;
signed int nest_level : 15;
unsigned int append : 1;
} ParseState;
static_assert(sizeof(ParseState) == 4 * sizeof(int),
"unexpected size of ParseState");
typedef struct {
const char *mangled_begin;
char *out;
int out_end_idx;
int recursion_depth;
int steps;
ParseState parse_state;
#ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
int high_water_mark;
bool too_complex;
#endif
} State;
namespace {
#ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
void UpdateHighWaterMark(State *state) {
if (state->high_water_mark < state->parse_state.mangled_idx) {
state->high_water_mark = state->parse_state.mangled_idx;
}
}
void ReportHighWaterMark(State *state) {
const size_t input_length = std::strlen(state->mangled_begin);
if (input_length + 6 > static_cast<size_t>(state->out_end_idx) ||
state->too_complex) {
if (state->out_end_idx > 0) state->out[0] = '\0';
return;
}
const size_t high_water_mark = static_cast<size_t>(state->high_water_mark);
std::memcpy(state->out, state->mangled_begin, high_water_mark);
std::memcpy(state->out + high_water_mark, "--!--", 5);
std::memcpy(state->out + high_water_mark + 5,
state->mangled_begin + high_water_mark,
input_length - high_water_mark);
state->out[input_length + 5] = '\0';
}
#else
void UpdateHighWaterMark(State *) {}
void ReportHighWaterMark(State *) {}
#endif
class ComplexityGuard {
public:
explicit ComplexityGuard(State *state) : state_(state) {
++state->recursion_depth;
++state->steps;
}
~ComplexityGuard() { --state_->recursion_depth; }
static constexpr int kRecursionDepthLimit = 256;
static constexpr int kParseStepsLimit = 1 << 17;
bool IsTooComplex() const {
if (state_->recursion_depth > kRecursionDepthLimit ||
state_->steps > kParseStepsLimit) {
#ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
state_->too_complex = true;
#endif
return true;
}
return false;
}
private:
State *state_;
};
}
static size_t StrLen(const char *str) {
size_t len = 0;
while (*str != '\0') {
++str;
++len;
}
return len;
}
static bool AtLeastNumCharsRemaining(const char *str, size_t n) {
for (size_t i = 0; i < n; ++i) {
if (str[i] == '\0') {
return false;
}
}
return true;
}
static bool StrPrefix(const char *str, const char *prefix) {
size_t i = 0;
while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) {
++i;
}
return prefix[i] == '\0';
}
static void InitState(State* state,
const char* mangled,
char* out,
size_t out_size) {
state->mangled_begin = mangled;
state->out = out;
state->out_end_idx = static_cast<int>(out_size);
state->recursion_depth = 0;
state->steps = 0;
#ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK
state->high_water_mark = 0;
state->too_complex = false;
#endif
state->parse_state.mangled_idx = 0;
state->parse_state.out_cur_idx = 0;
state->parse_state.prev_name_idx = 0;
state->parse_state.prev_name_length = 0;
state->parse_state.nest_level = -1;
state->parse_state.append = true;
}
static inline const char *RemainingInput(State *state) {
return &state->mangled_begin[state->parse_state.mangled_idx];
}
static bool ParseOneCharToken(State *state, const char one_char_token) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
if (RemainingInput(state)[0] == one_char_token) {
++state->parse_state.mangled_idx;
UpdateHighWaterMark(state);
return true;
}
return false;
}
static bool ParseTwoCharToken(State *state, const char *two_char_token) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
if (RemainingInput(state)[0] == two_char_token[0] &&
RemainingInput(state)[1] == two_char_token[1]) {
state->parse_state.mangled_idx += 2;
UpdateHighWaterMark(state);
return true;
}
return false;
}
static bool ParseThreeCharToken(State *state, const char *three_char_token) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
if (RemainingInput(state)[0] == three_char_token[0] &&
RemainingInput(state)[1] == three_char_token[1] &&
RemainingInput(state)[2] == three_char_token[2]) {
state->parse_state.mangled_idx += 3;
UpdateHighWaterMark(state);
return true;
}
return false;
}
static bool ParseLongToken(State *state, const char *long_token) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
int i = 0;
for (; long_token[i] != '\0'; ++i) {
if (RemainingInput(state)[i] != long_token[i]) return false;
}
state->parse_state.mangled_idx += i;
UpdateHighWaterMark(state);
return true;
}
static bool ParseCharClass(State *state, const char *char_class) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
if (RemainingInput(state)[0] == '\0') {
return false;
}
const char *p = char_class;
for (; *p != '\0'; ++p) {
if (RemainingInput(state)[0] == *p) {
++state->parse_state.mangled_idx;
UpdateHighWaterMark(state);
return true;
}
}
return false;
}
static bool ParseDigit(State *state, int *digit) {
char c = RemainingInput(state)[0];
if (ParseCharClass(state, "0123456789")) {
if (digit != nullptr) {
*digit = c - '0';
}
return true;
}
return false;
}
static bool Optional(bool ) { return true; }
typedef bool (*ParseFunc)(State *);
static bool OneOrMore(ParseFunc parse_func, State *state) {
if (parse_func(state)) {
while (parse_func(state)) {
}
return true;
}
return false;
}
static bool ZeroOrMore(ParseFunc parse_func, State *state) {
while (parse_func(state)) {
}
return true;
}
static void Append(State *state, const char *const str, const size_t length) {
for (size_t i = 0; i < length; ++i) {
if (state->parse_state.out_cur_idx + 1 <
state->out_end_idx) {
state->out[state->parse_state.out_cur_idx++] = str[i];
} else {
state->parse_state.out_cur_idx = state->out_end_idx + 1;
break;
}
}
if (state->parse_state.out_cur_idx < state->out_end_idx) {
state->out[state->parse_state.out_cur_idx] =
'\0';
}
}
static bool IsLower(char c) { return c >= 'a' && c <= 'z'; }
static bool IsAlpha(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
static bool IsFunctionCloneSuffix(const char *str) {
size_t i = 0;
while (str[i] != '\0') {
bool parsed = false;
if (str[i] == '.' && (IsAlpha(str[i + 1]) || str[i + 1] == '_')) {
parsed = true;
i += 2;
while (IsAlpha(str[i]) || str[i] == '_') {
++i;
}
}
if (str[i] == '.' && IsDigit(str[i + 1])) {
parsed = true;
i += 2;
while (IsDigit(str[i])) {
++i;
}
}
if (!parsed)
return false;
}
return true;
}
static bool EndsWith(State *state, const char chr) {
return state->parse_state.out_cur_idx > 0 &&
state->parse_state.out_cur_idx < state->out_end_idx &&
chr == state->out[state->parse_state.out_cur_idx - 1];
}
static void MaybeAppendWithLength(State *state, const char *const str,
const size_t length) {
if (state->parse_state.append && length > 0) {
if (str[0] == '<' && EndsWith(state, '<')) {
Append(state, " ", 1);
}
if (state->parse_state.out_cur_idx < state->out_end_idx &&
(IsAlpha(str[0]) || str[0] == '_')) {
state->parse_state.prev_name_idx = state->parse_state.out_cur_idx;
state->parse_state.prev_name_length = static_cast<unsigned int>(length);
}
Append(state, str, length);
}
}
static bool MaybeAppendDecimal(State *state, int val) {
constexpr size_t kMaxLength = 20;
char buf[kMaxLength];
if (state->parse_state.append) {
char *p = &buf[kMaxLength];
do {
*--p = static_cast<char>((val % 10) + '0');
val /= 10;
} while (p > buf && val != 0);
Append(state, p, kMaxLength - static_cast<size_t>(p - buf));
}
return true;
}
static bool MaybeAppend(State *state, const char *const str) {
if (state->parse_state.append) {
size_t length = StrLen(str);
MaybeAppendWithLength(state, str, length);
}
return true;
}
static bool EnterNestedName(State *state) {
state->parse_state.nest_level = 0;
return true;
}
static bool LeaveNestedName(State *state, int16_t prev_value) {
state->parse_state.nest_level = prev_value;
return true;
}
static bool DisableAppend(State *state) {
state->parse_state.append = false;
return true;
}
static bool RestoreAppend(State *state, bool prev_value) {
state->parse_state.append = prev_value;
return true;
}
static void MaybeIncreaseNestLevel(State *state) {
if (state->parse_state.nest_level > -1) {
++state->parse_state.nest_level;
}
}
static void MaybeAppendSeparator(State *state) {
if (state->parse_state.nest_level >= 1) {
MaybeAppend(state, "::");
}
}
static void MaybeCancelLastSeparator(State *state) {
if (state->parse_state.nest_level >= 1 && state->parse_state.append &&
state->parse_state.out_cur_idx >= 2) {
state->parse_state.out_cur_idx -= 2;
state->out[state->parse_state.out_cur_idx] = '\0';
}
}
static bool IdentifierIsAnonymousNamespace(State *state, size_t length) {
static const char anon_prefix[] = "_GLOBAL__N_";
return (length > (sizeof(anon_prefix) - 1) &&
StrPrefix(RemainingInput(state), anon_prefix));
}
static bool ParseMangledName(State *state);
static bool ParseEncoding(State *state);
static bool ParseName(State *state);
static bool ParseUnscopedName(State *state);
static bool ParseNestedName(State *state);
static bool ParsePrefix(State *state);
static bool ParseUnqualifiedName(State *state);
static bool ParseSourceName(State *state);
static bool ParseLocalSourceName(State *state);
static bool ParseUnnamedTypeName(State *state);
static bool ParseNumber(State *state, int *number_out);
static bool ParseFloatNumber(State *state);
static bool ParseSeqId(State *state);
static bool ParseIdentifier(State *state, size_t length);
static bool ParseOperatorName(State *state, int *arity);
static bool ParseConversionOperatorType(State *state);
static bool ParseSpecialName(State *state);
static bool ParseCallOffset(State *state);
static bool ParseNVOffset(State *state);
static bool ParseVOffset(State *state);
static bool ParseAbiTags(State *state);
static bool ParseCtorDtorName(State *state);
static bool ParseDecltype(State *state);
static bool ParseType(State *state);
static bool ParseCVQualifiers(State *state);
static bool ParseExtendedQualifier(State *state);
static bool ParseBuiltinType(State *state);
static bool ParseVendorExtendedType(State *state);
static bool ParseFunctionType(State *state);
static bool ParseBareFunctionType(State *state);
static bool ParseOverloadAttribute(State *state);
static bool ParseClassEnumType(State *state);
static bool ParseArrayType(State *state);
static bool ParsePointerToMemberType(State *state);
static bool ParseTemplateParam(State *state);
static bool ParseTemplateParamDecl(State *state);
static bool ParseTemplateTemplateParam(State *state);
static bool ParseTemplateArgs(State *state);
static bool ParseTemplateArg(State *state);
static bool ParseBaseUnresolvedName(State *state);
static bool ParseUnresolvedName(State *state);
static bool ParseUnresolvedQualifierLevel(State *state);
static bool ParseUnionSelector(State* state);
static bool ParseFunctionParam(State* state);
static bool ParseBracedExpression(State *state);
static bool ParseExpression(State *state);
static bool ParseInitializer(State *state);
static bool ParseExprPrimary(State *state);
static bool ParseExprCastValueAndTrailingE(State *state);
static bool ParseQRequiresClauseExpr(State *state);
static bool ParseRequirement(State *state);
static bool ParseTypeConstraint(State *state);
static bool ParseLocalName(State *state);
static bool ParseLocalNameSuffix(State *state);
static bool ParseDiscriminator(State *state);
static bool ParseSubstitution(State *state, bool accept_std);
static bool ParseMangledName(State *state) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
}
static bool ParseEncoding(State *state) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
if (ParseName(state)) {
if (!ParseBareFunctionType(state)) {
return true;
}
ParseQRequiresClauseExpr(state);
return true;
}
if (ParseSpecialName(state)) {
return true;
}
return false;
}
static bool ParseName(State *state) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
if (ParseNestedName(state) || ParseLocalName(state)) {
return true;
}
ParseState copy = state->parse_state;
if (ParseSubstitution(state, false) &&
ParseTemplateArgs(state)) {
return true;
}
state->parse_state = copy;
return ParseUnscopedName(state) && Optional(ParseTemplateArgs(state));
}
static bool ParseUnscopedName(State *state) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
if (ParseUnqualifiedName(state)) {
return true;
}
ParseState copy = state->parse_state;
if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") &&
ParseUnqualifiedName(state)) {
return true;
}
state->parse_state = copy;
return false;
}
static inline bool ParseRefQualifier(State *state) {
return ParseCharClass(state, "OR");
}
static bool ParseNestedName(State *state) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
ParseState copy = state->parse_state;
if (ParseOneCharToken(state, 'N') && EnterNestedName(state) &&
Optional(ParseCVQualifiers(state)) &&
Optional(ParseRefQualifier(state)) && ParsePrefix(state) &&
LeaveNestedName(state, copy.nest_level) &&
ParseOneCharToken(state, 'E')) {
return true;
}
state->parse_state = copy;
return false;
}
static bool ParsePrefix(State *state) {
ComplexityGuard guard(state);
if (guard.IsTooComplex()) return false;
bool has_ | #include "absl/debugging/internal/demangle.h"
#include <cstdlib>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/debugging/internal/stack_consumption.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
namespace {
using ::testing::ContainsRegex;
TEST(Demangle, FunctionTemplate) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooIiEiT_", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionTemplateWithNesting) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooI7WrapperIiEEiT_", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionTemplateWithNonTypeParamConstraint) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooITkSt8integraliEiT_", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionTemplateWithFunctionRequiresClause) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooIiEivQsr3stdE8integralIT_E", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionWithTemplateParamRequiresClause) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooIiQsr3stdE8integralIT_EEiv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionWithTemplateParamAndFunctionRequiresClauses) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooIiQsr3stdE8integralIT_EEivQsr3stdE8integralIS0_E",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionTemplateBacktracksOnMalformedRequiresClause) {
char tmp[100];
ASSERT_FALSE(Demangle("_Z3fooIiQEiT_", tmp, sizeof(tmp)));
}
TEST(Demangle, FunctionTemplateWithAutoParam) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooITnDaLi1EEvv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionTemplateWithNonTypeParamPack) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooITpTnRiJEiEvT0_", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, FunctionTemplateTemplateParamWithConstrainedArg) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooITtTyE5FooerEvv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, ConstrainedAutoInFunctionTemplate) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z1fITnDk1CLi0EEvv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "f<>()");
}
TEST(Demangle, ConstrainedFriendFunctionTemplate) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZN2ns1YIiEF1yES1_QLb1E", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "ns::Y<>::friend y()");
}
TEST(Demangle, ConstrainedFriendOperatorTemplate) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZN2ns1YIiEFdeES1_QLb1E", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "ns::Y<>::friend operator*()");
}
TEST(Demangle, NonTemplateBuiltinType) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3foou17__my_builtin_type", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo()");
}
TEST(Demangle, SingleArgTemplateBuiltinType) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooIiEu17__my_builtin_typeIT_Ev", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, TwoArgTemplateBuiltinType) {
char tmp[100];
ASSERT_TRUE(
Demangle("_Z3fooIicEu17__my_builtin_typeIT_T0_Ev", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, TypeNestedUnderTemplatedBuiltinType) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z1fIRK1CENu20__remove_reference_tIT_E4typeES3_",
tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, TemplateTemplateParamSubstitution) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z3fooITtTyTnTL0__E8FoolableEvv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "foo<>()");
}
TEST(Demangle, TemplateParamSubstitutionWithGenericLambda) {
char tmp[100];
ASSERT_TRUE(
Demangle("_ZN5FooerIiE3fooIiEEvNS0_UlTL0__TL0_0_E_E", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "Fooer<>::foo<>()");
}
TEST(Demangle, LambdaRequiresTrue) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QLb1E", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresSimpleExpression) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QeqplLi2ELi2ELi4E",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionContainingTrue) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXLb1EE", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionContainingConcept) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXsr3stdE7same_asIDtfp_EiEE",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionContainingNoexceptExpression) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXplfp_fp_NE", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionContainingReturnTypeConstraint) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXplfp_fp_RNSt7same_asIDtfp_EEEE",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionWithBothNoexceptAndReturnType) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXplfp_fp_NRNSt7same_asIDtfp_EEEE",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionContainingType) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clI1SEEDaT_QrqTNS2_1TEE", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionNestingAnotherRequires) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqQLb1EE", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, LambdaRequiresRequiresExpressionContainingTwoRequirements) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXLb1EXeqplLi2ELi2ELi4EE",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "$_0::operator()<>()");
}
TEST(Demangle, RequiresExpressionWithItsOwnParameter) {
char tmp[100];
ASSERT_TRUE(Demangle("_Z1fIiE1SIXrQT__XplfL0p_fp_EEES1_", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "f<>()");
}
TEST(Demangle, LambdaWithExplicitTypeArgument) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZZ1fIiET_S0_ENKUlTyS0_E_clIiEEDaS0_",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "f<>()::{lambda()#1}::operator()<>()");
}
TEST(Demangle, LambdaWithExplicitPackArgument) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZZ1fIiET_S0_ENKUlTpTyDpT_E_clIJiEEEDaS2_",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "f<>()::{lambda()#1}::operator()<>()");
}
TEST(Demangle, LambdaInClassMemberDefaultArgument) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd_NKUlvE_clEv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()");
ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd0_NKUlvE_clEv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "S::f()::{default arg#2}::{lambda()#1}::operator()()");
ASSERT_FALSE(Demangle("_ZZN1S1fEPFvvEEdn1_NKUlvE_clEv", tmp, sizeof(tmp)));
}
TEST(Demangle, AvoidSignedOverflowForUnfortunateParameterNumbers) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483645_NKUlvE_clEv",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp,
"S::f()::{default arg#2147483647}::{lambda()#1}::operator()()");
ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483646_NKUlvE_clEv",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()");
ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483647_NKUlvE_clEv",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()");
ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483648_NKUlvE_clEv",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()");
}
TEST(Demangle, SubstpackNotationForTroublesomeTemplatePack) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZN1AIJEE1fIJEEEvDpO1BI_SUBSTPACK_T_E",
tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "A<>::f<>()");
}
TEST(Demangle, TemplateTemplateParamAppearingAsBackrefFollowedByTemplateArgs) {
char tmp[100];
ASSERT_TRUE(Demangle("_ZN1WI1SE1fIiEEDTclsrS0_IT_EE1mEEv", tmp, sizeof(tmp)));
EXPECT_STREQ(tmp, "W<>::f<>()");
}
TEST(Demangle, CornerCases) {
char tmp[10];
EXPECT_TRUE(Demangle("_Z6foobarv", tmp, sizeof(tmp)));
EXPECT_STREQ("foobar()", tmp);
EXPECT_TRUE(Demangle("_Z6foobarv", tmp, 9));
EXPECT_STREQ("foobar()", tmp);
EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 8));
EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 1));
EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 0));
EXPECT_FALSE(Demangle("_Z6foobarv", nullptr, 0));
EXPECT_FALSE(Demangle("_Z1000000", tmp, 9));
}
TEST(Demangle, Clones) {
char tmp[20];
EXPECT_TRUE(Demangle("_ZL3Foov", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.clone.3", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.constprop.80", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.isra.18", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.isra.2.constprop.18", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.__uniq.12345", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.__uniq.12345.isra.2.constprop.18", tmp,
sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.clo", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.123", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.clone.foo", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.clone.123.456", tmp, sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_TRUE(Demangle("_ZL3Foov.part.9.165493.constprop.775.31805", tmp,
sizeof(tmp)));
EXPECT_STREQ("Foo()", tmp);
EXPECT_FALSE(Demangle("_ZL3Foov.", tmp, sizeof(tmp)));
EXPECT_FALSE(Demangle("_ZL3Foov.abc123", tmp, sizeof(tmp)));
EXPECT_FALSE(Demangle("_ZL3Foov.clone.", tmp, sizeof(tmp)));
EXPECT_FALSE(Demangle("_ZL3Foov.isra.2.constprop.", tmp, sizeof(tmp)));
}
TEST(Demangle, Discriminators) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gEv", tmp, sizeof(tmp)));
EXPECT_STREQ("f()::S::g()", tmp);
EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE_0v", tmp, sizeof(tmp)));
EXPECT_STREQ("f()::S::g()", tmp);
EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE_9v", tmp, sizeof(tmp)));
EXPECT_STREQ("f()::S::g()", tmp);
EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE__10_v", tmp, sizeof(tmp)));
EXPECT_STREQ("f()::S::g()", tmp);
}
TEST(Demangle, SingleDigitDiscriminatorFollowedByADigit) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE_911return_type", tmp, sizeof(tmp)));
EXPECT_STREQ("f()::S::g()", tmp);
}
TEST(Demangle, LiteralOfGlobalNamespaceEnumType) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fIL1E42EEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, NullptrLiterals) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fILDnEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fILDn0EEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, StringLiterals) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fILA42_KcEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, ComplexFloatingPointLiterals) {
char tmp[80];
EXPECT_TRUE(Demangle(
"_Z1fIiEvRAszpltlCdstT_ELS0_0000000000000000_4010000000000000E_c",
tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, Float128) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvDF128_Ev", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator _Float128()", tmp);
}
TEST(Demangle, Float128x) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvDF128xEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator _Float128x()", tmp);
}
TEST(Demangle, Bfloat16) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvDF16bEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator std::bfloat16_t()", tmp);
}
TEST(Demangle, SimpleSignedBitInt) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvDB256_Ev", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator _BitInt(256)()", tmp);
}
TEST(Demangle, SimpleUnsignedBitInt) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvDU256_Ev", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator unsigned _BitInt(256)()", tmp);
}
TEST(Demangle, DependentBitInt) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvDBT__ILi256EEEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator _BitInt(?)<>()", tmp);
}
TEST(Demangle, ConversionToPointerType) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvPiEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator int*()", tmp);
}
TEST(Demangle, ConversionToLvalueReferenceType) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvRiEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator int&()", tmp);
}
TEST(Demangle, ConversionToRvalueReferenceType) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvOiEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator int&&()", tmp);
}
TEST(Demangle, ConversionToComplexFloatingPointType) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvCfEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator float _Complex()", tmp);
}
TEST(Demangle, ConversionToImaginaryFloatingPointType) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvGfEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator float _Imaginary()", tmp);
}
TEST(Demangle, ConversionToPointerToCvQualifiedType) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvPrVKiEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator int const volatile restrict*()", tmp);
}
TEST(Demangle, ConversionToLayeredPointerType) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvPKPKiEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator int const* const*()", tmp);
}
TEST(Demangle, ConversionToTypeWithExtendedQualifier) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZNK1ScvPU5AS128KiEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::operator int*()", tmp);
}
TEST(Demangle, GlobalInitializers) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZGR1v", tmp, sizeof(tmp)));
EXPECT_STREQ("reference temporary for v", tmp);
EXPECT_TRUE(Demangle("_ZGR1v_", tmp, sizeof(tmp)));
EXPECT_STREQ("reference temporary for v", tmp);
EXPECT_TRUE(Demangle("_ZGR1v0_", tmp, sizeof(tmp)));
EXPECT_STREQ("reference temporary for v", tmp);
EXPECT_TRUE(Demangle("_ZGR1v1Z_", tmp, sizeof(tmp)));
EXPECT_STREQ("reference temporary for v", tmp);
}
TEST(Demangle, StructuredBindings) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZDC1x1yE", tmp, sizeof(tmp)));
EXPECT_TRUE(Demangle("_ZGRDC1x1yE_", tmp, sizeof(tmp)));
}
TEST(Demangle, AbiTags) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1aB3abc", tmp, sizeof(tmp)));
EXPECT_STREQ("a[abi:abc]", tmp);
EXPECT_TRUE(Demangle("_ZN1BC2B3xyzEv", tmp, sizeof(tmp)));
EXPECT_STREQ("B::B[abi:xyz]()", tmp);
EXPECT_TRUE(Demangle("_Z1CB3barB3foov", tmp, sizeof(tmp)));
EXPECT_STREQ("C[abi:bar][abi:foo]()", tmp);
}
TEST(Demangle, SimpleGnuVectorSize) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fDv8_i", tmp, sizeof(tmp)));
EXPECT_STREQ("f()", tmp);
}
TEST(Demangle, GnuVectorSizeIsATemplateParameter) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fILi32EEvDvT__i", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, GnuVectorSizeIsADependentOperatorExpression) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fILi32EEvDvmlLi2ET__i", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, SimpleAddressSpace) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fPU5AS128Ki", tmp, sizeof(tmp)));
EXPECT_STREQ("f()", tmp);
}
TEST(Demangle, DependentAddressSpace) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fILi128EEvPU2ASIT_Ei", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, TransactionSafeEntryPoint) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZGTt1fv", tmp, sizeof(tmp)));
EXPECT_STREQ("transaction clone for f()", tmp);
}
TEST(Demangle, TransactionSafeFunctionType) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fPDxFvvE", tmp, sizeof(tmp)));
EXPECT_STREQ("f()", tmp);
}
TEST(Demangle, TemplateParameterObject) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fIXtl1SLi1ELi2EEEXadL_ZTAXtlS0_Li1ELi2EEEEEEvv",
tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_ZTAXtl1SLi1ELi2EEE", tmp, sizeof(tmp)));
EXPECT_STREQ("template parameter object", tmp);
}
TEST(Demangle, EnableIfAttributeOnGlobalFunction) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fUa9enable_ifIXgefL0p_Li0EEEl", tmp, sizeof(tmp)));
EXPECT_STREQ("f()", tmp);
}
TEST(Demangle, EnableIfAttributeOnNamespaceScopeFunction) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZN2ns1fEUa9enable_ifIXgefL0p_Li0EEEl",
tmp, sizeof(tmp)));
EXPECT_STREQ("ns::f()", tmp);
}
TEST(Demangle, EnableIfAttributeOnFunctionTemplate) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fIiEUa9enable_ifIXgefL0p_tliEEET_S0_",
tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, ThisPointerInDependentSignature) {
char tmp[80];
EXPECT_TRUE(Demangle("_ZN1S1fIiEEDTcl1gIT_EfpTEEv", tmp, sizeof(tmp)));
EXPECT_STREQ("S::f<>()", tmp);
}
TEST(Demangle, DependentMemberOperatorCall) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fI1CEDTcldtfp_onclEET_", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, TypeNestedUnderDecltype) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fIiENDTtl1SIT_EEE1tEv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, ElaboratedTypes) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fIiEvTsN1SIT_E1CE", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fIiEvTuN1SIT_E1CE", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fIiEvTeN1SIT_E1CE", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, SubobjectAddresses) {
char tmp[80];
EXPECT_TRUE(Demangle("_Z1fIXsoKcL_Z1aE123EEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aEEEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE123EEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE123pEEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE__1_234EEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE123_456pEEEvv", tmp, sizeof(tmp)));
EXPECT_STREQ("f<>()", tmp);
}
TEST(Demangle, Preincrement) {
char tmp[80]; |
2,505 | cpp | abseil/abseil-cpp | stack_consumption | absl/debugging/internal/stack_consumption.cc | absl/debugging/internal/stack_consumption_test.cc | #ifndef ABSL_DEBUGGING_INTERNAL_STACK_CONSUMPTION_H_
#define ABSL_DEBUGGING_INTERNAL_STACK_CONSUMPTION_H_
#include "absl/base/config.h"
#ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
#error ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION cannot be set directly
#elif !defined(__APPLE__) && !defined(_WIN32) && \
(defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || \
defined(__aarch64__) || defined(__riscv))
#define ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION 1
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
int GetSignalHandlerStackConsumption(void (*signal_handler)(int));
}
ABSL_NAMESPACE_END
}
#endif
#endif
#include "absl/debugging/internal/stack_consumption.h"
#ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
#include <signal.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "absl/base/attributes.h"
#include "absl/base/internal/raw_logging.h"
#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
#define MAP_ANONYMOUS MAP_ANON
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
namespace {
#if defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || \
defined(__aarch64__) || defined(__riscv)
constexpr bool kStackGrowsDown = true;
#else
#error Need to define kStackGrowsDown
#endif
void EmptySignalHandler(int) {}
constexpr int kAlternateStackSize = 64 << 10;
constexpr int kSafetyMargin = 32;
constexpr char kAlternateStackFillValue = 0x55;
int GetStackConsumption(const void* const altstack) {
const char* begin;
int increment;
if (kStackGrowsDown) {
begin = reinterpret_cast<const char*>(altstack);
increment = 1;
} else {
begin = reinterpret_cast<const char*>(altstack) + kAlternateStackSize - 1;
increment = -1;
}
for (int usage_count = kAlternateStackSize; usage_count > 0; --usage_count) {
if (*begin != kAlternateStackFillValue) {
ABSL_RAW_CHECK(usage_count <= kAlternateStackSize - kSafetyMargin,
"Buffer has overflowed or is about to overflow");
return usage_count;
}
begin += increment;
}
ABSL_RAW_LOG(FATAL, "Unreachable code");
return -1;
}
}
int GetSignalHandlerStackConsumption(void (*signal_handler)(int)) {
void* altstack = mmap(nullptr, kAlternateStackSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
ABSL_RAW_CHECK(altstack != MAP_FAILED, "mmap() failed");
stack_t sigstk;
memset(&sigstk, 0, sizeof(sigstk));
sigstk.ss_sp = altstack;
sigstk.ss_size = kAlternateStackSize;
sigstk.ss_flags = 0;
stack_t old_sigstk;
memset(&old_sigstk, 0, sizeof(old_sigstk));
ABSL_RAW_CHECK(sigaltstack(&sigstk, &old_sigstk) == 0,
"sigaltstack() failed");
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
struct sigaction old_sa1, old_sa2;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_ONSTACK;
sa.sa_handler = EmptySignalHandler;
ABSL_RAW_CHECK(sigaction(SIGUSR1, &sa, &old_sa1) == 0, "sigaction() failed");
sa.sa_handler = signal_handler;
ABSL_RAW_CHECK(sigaction(SIGUSR2, &sa, &old_sa2) == 0, "sigaction() failed");
ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
memset(altstack, kAlternateStackFillValue, kAlternateStackSize);
ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
int base_stack_consumption = GetStackConsumption(altstack);
ABSL_RAW_CHECK(kill(getpid(), SIGUSR2) == 0, "kill() failed");
int signal_handler_stack_consumption = GetStackConsumption(altstack);
if (old_sigstk.ss_sp == nullptr && old_sigstk.ss_size == 0 &&
(old_sigstk.ss_flags & SS_DISABLE)) {
old_sigstk.ss_size = static_cast<size_t>(MINSIGSTKSZ);
}
ABSL_RAW_CHECK(sigaltstack(&old_sigstk, nullptr) == 0,
"sigaltstack() failed");
ABSL_RAW_CHECK(sigaction(SIGUSR1, &old_sa1, nullptr) == 0,
"sigaction() failed");
ABSL_RAW_CHECK(sigaction(SIGUSR2, &old_sa2, nullptr) == 0,
"sigaction() failed");
ABSL_RAW_CHECK(munmap(altstack, kAlternateStackSize) == 0, "munmap() failed");
if (signal_handler_stack_consumption != -1 && base_stack_consumption != -1) {
return signal_handler_stack_consumption - base_stack_consumption;
}
return -1;
}
}
ABSL_NAMESPACE_END
}
#else
#ifdef __APPLE__
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
extern const char kAvoidEmptyStackConsumptionLibraryWarning;
const char kAvoidEmptyStackConsumptionLibraryWarning = 0;
}
ABSL_NAMESPACE_END
}
#endif
#endif | #include "absl/debugging/internal/stack_consumption.h"
#ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
#include <string.h>
#include "gtest/gtest.h"
#include "absl/log/log.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
namespace {
static void SimpleSignalHandler(int signo) {
char buf[100];
memset(buf, 'a', sizeof(buf));
if (signo == 0) {
LOG(INFO) << static_cast<void*>(buf);
}
}
TEST(SignalHandlerStackConsumptionTest, MeasuresStackConsumption) {
EXPECT_GE(GetSignalHandlerStackConsumption(SimpleSignalHandler), 100);
}
}
}
ABSL_NAMESPACE_END
}
#endif |
2,506 | cpp | abseil/abseil-cpp | demangle_rust | absl/debugging/internal/demangle_rust.cc | absl/debugging/internal/demangle_rust_test.cc | #ifndef ABSL_DEBUGGING_INTERNAL_DEMANGLE_RUST_H_
#define ABSL_DEBUGGING_INTERNAL_DEMANGLE_RUST_H_
#include <cstddef>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
bool DemangleRustSymbolEncoding(const char* mangled, char* out,
size_t out_size);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/debugging/internal/demangle_rust.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
namespace {
constexpr int kMaxReturns = 1 << 17;
bool IsDigit(char c) { return '0' <= c && c <= '9'; }
bool IsLower(char c) { return 'a' <= c && c <= 'z'; }
bool IsUpper(char c) { return 'A' <= c && c <= 'Z'; }
bool IsAlpha(char c) { return IsLower(c) || IsUpper(c); }
bool IsIdentifierChar(char c) { return IsAlpha(c) || IsDigit(c) || c == '_'; }
bool IsLowerHexDigit(char c) { return IsDigit(c) || ('a' <= c && c <= 'f'); }
const char* BasicTypeName(char c) {
switch (c) {
case 'a': return "i8";
case 'b': return "bool";
case 'c': return "char";
case 'd': return "f64";
case 'e': return "str";
case 'f': return "f32";
case 'h': return "u8";
case 'i': return "isize";
case 'j': return "usize";
case 'l': return "i32";
case 'm': return "u32";
case 'n': return "i128";
case 'o': return "u128";
case 'p': return "_";
case 's': return "i16";
case 't': return "u16";
case 'u': return "()";
case 'v': return "...";
case 'x': return "i64";
case 'y': return "u64";
case 'z': return "!";
}
return nullptr;
}
class RustSymbolParser {
public:
RustSymbolParser(const char* encoding, char* out, char* const out_end)
: encoding_(encoding), out_(out), out_end_(out_end) {
if (out_ != out_end_) *out_ = '\0';
}
ABSL_MUST_USE_RESULT bool Parse() && {
#define ABSL_DEMANGLER_RECURSE(callee, caller) \
do { \
if (recursion_depth_ == kStackSize) return false; \
\
recursion_stack_[recursion_depth_++] = caller; \
goto callee; \
\
case caller: {} \
} while (0)
int iter = 0;
goto whole_encoding;
for (; iter < kMaxReturns && recursion_depth_ > 0; ++iter) {
switch (recursion_stack_[--recursion_depth_]) {
whole_encoding:
if (!Eat('_') || !Eat('R')) return false;
ABSL_DEMANGLER_RECURSE(path, kInstantiatingCrate);
if (IsAlpha(Peek())) {
++silence_depth_;
ABSL_DEMANGLER_RECURSE(path, kVendorSpecificSuffix);
}
switch (Take()) {
case '.': case '$': case '\0': return true;
}
return false;
path:
switch (Take()) {
case 'C': goto crate_root;
case 'M': goto inherent_impl;
case 'X': goto trait_impl;
case 'Y': goto trait_definition;
case 'N': goto nested_path;
case 'I': goto generic_args;
case 'B': goto path_backref;
default: return false;
}
crate_root:
if (!ParseIdentifier()) return false;
continue;
inherent_impl:
if (!Emit("<")) return false;
ABSL_DEMANGLER_RECURSE(impl_path, kInherentImplType);
ABSL_DEMANGLER_RECURSE(type, kInherentImplEnding);
if (!Emit(">")) return false;
continue;
trait_impl:
if (!Emit("<")) return false;
ABSL_DEMANGLER_RECURSE(impl_path, kTraitImplType);
ABSL_DEMANGLER_RECURSE(type, kTraitImplInfix);
if (!Emit(" as ")) return false;
ABSL_DEMANGLER_RECURSE(path, kTraitImplEnding);
if (!Emit(">")) return false;
continue;
impl_path:
++silence_depth_;
{
int ignored_disambiguator;
if (!ParseDisambiguator(ignored_disambiguator)) return false;
}
ABSL_DEMANGLER_RECURSE(path, kImplPathEnding);
--silence_depth_;
continue;
trait_definition:
if (!Emit("<")) return false;
ABSL_DEMANGLER_RECURSE(type, kTraitDefinitionInfix);
if (!Emit(" as ")) return false;
ABSL_DEMANGLER_RECURSE(path, kTraitDefinitionEnding);
if (!Emit(">")) return false;
continue;
nested_path:
if (IsUpper(Peek())) {
if (!PushNamespace(Take())) return false;
ABSL_DEMANGLER_RECURSE(path, kIdentifierInUppercaseNamespace);
if (!Emit("::")) return false;
if (!ParseIdentifier(PopNamespace())) return false;
continue;
}
if (IsLower(Take())) {
ABSL_DEMANGLER_RECURSE(path, kIdentifierInLowercaseNamespace);
if (!Emit("::")) return false;
if (!ParseIdentifier()) return false;
continue;
}
return false;
type:
if (IsLower(Peek())) {
const char* type_name = BasicTypeName(Take());
if (type_name == nullptr || !Emit(type_name)) return false;
continue;
}
if (Eat('A')) {
if (!Emit("[")) return false;
ABSL_DEMANGLER_RECURSE(type, kArraySize);
if (!Emit("; ")) return false;
ABSL_DEMANGLER_RECURSE(constant, kFinishArray);
if (!Emit("]")) return false;
continue;
}
if (Eat('S')) {
if (!Emit("[")) return false;
ABSL_DEMANGLER_RECURSE(type, kSliceEnding);
if (!Emit("]")) return false;
continue;
}
if (Eat('T')) goto tuple_type;
if (Eat('R')) {
if (!Emit("&")) return false;
if (!ParseOptionalLifetime()) return false;
goto type;
}
if (Eat('Q')) {
if (!Emit("&mut ")) return false;
if (!ParseOptionalLifetime()) return false;
goto type;
}
if (Eat('P')) {
if (!Emit("*const ")) return false;
goto type;
}
if (Eat('O')) {
if (!Emit("*mut ")) return false;
goto type;
}
if (Eat('F')) goto fn_type;
if (Eat('D')) goto dyn_trait_type;
if (Eat('B')) goto type_backref;
goto path;
tuple_type:
if (!Emit("(")) return false;
if (Eat('E')) {
if (!Emit(")")) return false;
continue;
}
ABSL_DEMANGLER_RECURSE(type, kAfterFirstTupleElement);
if (Eat('E')) {
if (!Emit(",)")) return false;
continue;
}
if (!Emit(", ")) return false;
ABSL_DEMANGLER_RECURSE(type, kAfterSecondTupleElement);
if (Eat('E')) {
if (!Emit(")")) return false;
continue;
}
if (!Emit(", ")) return false;
ABSL_DEMANGLER_RECURSE(type, kAfterThirdTupleElement);
if (Eat('E')) {
if (!Emit(")")) return false;
continue;
}
if (!Emit(", ...)")) return false;
++silence_depth_;
while (!Eat('E')) {
ABSL_DEMANGLER_RECURSE(type, kAfterSubsequentTupleElement);
}
--silence_depth_;
continue;
fn_type:
if (!Emit("fn...")) return false;
++silence_depth_;
if (!ParseOptionalBinder()) return false;
(void)Eat('U');
if (Eat('K')) {
if (!Eat('C') && !ParseUndisambiguatedIdentifier()) return false;
}
while (!Eat('E')) {
ABSL_DEMANGLER_RECURSE(type, kContinueParameterList);
}
ABSL_DEMANGLER_RECURSE(type, kFinishFn);
--silence_depth_;
continue;
dyn_trait_type:
if (!Emit("dyn ")) return false;
if (!ParseOptionalBinder()) return false;
if (!Eat('E')) {
ABSL_DEMANGLER_RECURSE(dyn_trait, kBeginAutoTraits);
while (!Eat('E')) {
if (!Emit(" + ")) return false;
ABSL_DEMANGLER_RECURSE(dyn_trait, kContinueAutoTraits);
}
}
if (!ParseRequiredLifetime()) return false;
continue;
dyn_trait:
ABSL_DEMANGLER_RECURSE(path, kContinueDynTrait);
if (Peek() == 'p') {
if (!Emit("<>")) return false;
++silence_depth_;
while (Eat('p')) {
if (!ParseUndisambiguatedIdentifier()) return false;
ABSL_DEMANGLER_RECURSE(type, kContinueAssocBinding);
}
--silence_depth_;
}
continue;
constant:
if (Eat('B')) goto const_backref;
if (Eat('p')) {
if (!Emit("_")) return false;
continue;
}
++silence_depth_;
ABSL_DEMANGLER_RECURSE(type, kConstData);
--silence_depth_;
if (Eat('n') && !EmitChar('-')) return false;
if (!Emit("0x")) return false;
if (Eat('0')) {
if (!EmitChar('0')) return false;
if (!Eat('_')) return false;
continue;
}
while (IsLowerHexDigit(Peek())) {
if (!EmitChar(Take())) return false;
}
if (!Eat('_')) return false;
continue;
generic_args:
ABSL_DEMANGLER_RECURSE(path, kBeginGenericArgList);
if (!Emit("::<>")) return false;
++silence_depth_;
while (!Eat('E')) {
ABSL_DEMANGLER_RECURSE(generic_arg, kContinueGenericArgList);
}
--silence_depth_;
continue;
generic_arg:
if (Peek() == 'L') {
if (!ParseOptionalLifetime()) return false;
continue;
}
if (Eat('K')) goto constant;
goto type;
path_backref:
if (!BeginBackref()) return false;
if (silence_depth_ == 0) {
ABSL_DEMANGLER_RECURSE(path, kPathBackrefEnding);
}
EndBackref();
continue;
type_backref:
if (!BeginBackref()) return false;
if (silence_depth_ == 0) {
ABSL_DEMANGLER_RECURSE(type, kTypeBackrefEnding);
}
EndBackref();
continue;
const_backref:
if (!BeginBackref()) return false;
if (silence_depth_ == 0) {
ABSL_DEMANGLER_RECURSE(constant, kConstantBackrefEnding);
}
EndBackref();
continue;
}
}
return false;
}
private:
enum ReturnAddress : uint8_t {
kInstantiatingCrate,
kVendorSpecificSuffix,
kIdentifierInUppercaseNamespace,
kIdentifierInLowercaseNamespace,
kInherentImplType,
kInherentImplEnding,
kTraitImplType,
kTraitImplInfix,
kTraitImplEnding,
kImplPathEnding,
kTraitDefinitionInfix,
kTraitDefinitionEnding,
kArraySize,
kFinishArray,
kSliceEnding,
kAfterFirstTupleElement,
kAfterSecondTupleElement,
kAfterThirdTupleElement,
kAfterSubsequentTupleElement,
kContinueParameterList,
kFinishFn,
kBeginAutoTraits,
kContinueAutoTraits,
kContinueDynTrait,
kContinueAssocBinding,
kConstData,
kBeginGenericArgList,
kContinueGenericArgList,
kPathBackrefEnding,
kTypeBackrefEnding,
kConstantBackrefEnding,
};
enum {
kStackSize = 256,
kNamespaceStackSize = 64,
kPositionStackSize = 16,
};
char Peek() const { return encoding_[pos_]; }
char Take() { return encoding_[pos_++]; }
ABSL_MUST_USE_RESULT bool Eat(char want) {
if (encoding_[pos_] != want) return false;
++pos_;
return true;
}
ABSL_MUST_USE_RESULT bool EmitChar(char c) {
if (silence_depth_ > 0) return true;
if (out_end_ - out_ < 2) return false;
*out_++ = c;
*out_ = '\0';
return true;
}
ABSL_MUST_USE_RESULT bool Emit(const char* token) {
if (silence_depth_ > 0) return true;
const size_t token_length = std::strlen(token);
const size_t bytes_to_copy = token_length + 1;
if (static_cast<size_t>(out_end_ - out_) < bytes_to_copy) return false;
std::memcpy(out_, token, bytes_to_copy);
out_ += token_length;
return true;
}
ABSL_MUST_USE_RESULT bool EmitDisambiguator(int disambiguator) {
if (disambiguator < 0) return EmitChar('?');
if (disambiguator == 0) return EmitChar('0');
char digits[3 * sizeof(disambiguator)] = {};
size_t leading_digit_index = sizeof(digits) - 1;
for (; disambiguator > 0; disambiguator /= 10) {
digits[--leading_digit_index] =
static_cast<char>('0' + disambiguator % 10);
}
return Emit(digits + leading_digit_index);
}
ABSL_MUST_USE_RESULT bool ParseDisambiguator(int& value) {
value = -1;
if (!Eat('s')) {
value = 0;
return true;
}
int base_62_value = 0;
if (!ParseBase62Number(base_62_value)) return false;
value = base_62_value < 0 ? -1 : base_62_value + 1;
return true;
}
ABSL_MUST_USE_RESULT bool ParseBase62Number(int& value) {
value = -1;
if (Eat('_')) {
value = 0;
return true;
}
int encoded_number = 0;
bool overflowed = false;
while (IsAlpha(Peek()) || IsDigit(Peek())) {
const char c = Take();
if (encoded_number >= std::numeric_limits<int>::max()/62) {
overflowed = true;
} else {
int digit;
if (IsDigit(c)) {
digit = c - '0';
} else if (IsLower(c)) {
digit = c - 'a' + 10;
} else {
digit = c - 'A' + 36;
}
encoded_number = 62 * encoded_number + digit;
}
}
if (!Eat('_')) return false;
if (!overflowed) value = encoded_number + 1;
return true;
}
ABSL_MUST_USE_RESULT bool ParseIdentifier(char uppercase_namespace = '\0') {
int disambiguator = 0;
if (!ParseDisambiguator(disambiguator)) return false;
return ParseUndisambiguatedIdentifier(uppercase_namespace, disambiguator);
}
ABSL_MUST_USE_RESULT bool ParseUndisambiguatedIdentifier(
char uppercase_namespace = '\0', int disambiguator = 0) {
const bool is_punycoded = Eat('u');
if (!IsDigit(Peek())) return false;
int num_bytes = 0;
if (!ParseDecimalNumber(num_bytes)) return false;
(void)Eat('_');
if (uppercase_namespace == '\0') {
if (is_punycoded && !Emit("{Punycode ")) return false;
} else {
switch (uppercase_namespace) {
case 'C':
if (!Emit("{closure")) return false;
break;
case 'S':
if (!Emit("{shim")) return false;
break;
default:
if (!EmitChar('{') || !EmitChar(uppercase_namespace)) return false;
break;
}
if (num_bytes > 0 && !Emit(":")) return false;
}
for (int i = 0; i < num_bytes; ++i) {
const char c = Take();
if (!IsIdentifierChar(c) &&
(is_punycoded || (c & 0x80) == 0)) {
return false;
}
if (!EmitChar(c)) return false;
}
if (uppercase_namespace != '\0') {
if (!EmitChar('#')) return false;
if (!EmitDisambiguator(disambiguator)) return false;
}
if (uppercase_namespace != '\0' || is_punycoded) {
if (!EmitChar('}')) return false;
}
return true;
}
ABSL_MUST_USE_RESULT bool ParseDecimalNumber(int& value) {
value = -1;
if (!IsDigit(Peek())) return false;
int encoded_number = Take() - '0';
if (encoded_number == 0) {
value = 0;
return true;
}
while (IsDigit(Peek()) &&
encoded_number < std::numeric_limits<int>::max()/10) {
encoded_number = 10 * encoded_number + (Take() - '0');
}
if (IsDigit(Peek())) return false;
value = encoded_number;
return true;
}
ABSL_MUST_USE_RESULT bool ParseOptionalBinder() {
if (!Eat('G')) return true;
int ignored_binding_count;
return ParseBase62Number(ignored_binding_count);
}
ABSL_MUST_USE_RESULT bool ParseOptionalLifetime() {
if (!Eat('L')) return true;
int ignored_de_bruijn_index;
return ParseBase62Number(ignored_de_bruijn_index);
}
ABSL_MUST_USE_RESULT bool ParseRequiredLifetime() {
if (Peek() != 'L') return false;
return ParseOptionalLifetime();
}
ABSL_MUST_USE_RESULT bool PushNamespace(ch | #include "absl/debugging/internal/demangle_rust.h"
#include <cstddef>
#include <string>
#include "gtest/gtest.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
namespace {
std::string ResultOfDemangling(const char* mangled, size_t buffer_size) {
std::string buffer(buffer_size + 1, '~');
constexpr char kCanaryCharacter = 0x7f;
buffer[buffer_size] = kCanaryCharacter;
if (!DemangleRustSymbolEncoding(mangled, &buffer[0], buffer_size)) {
return "Failed parse";
}
if (buffer[buffer_size] != kCanaryCharacter) {
return "Buffer overrun by output: " + buffer.substr(0, buffer_size + 1)
+ "...";
}
return buffer.data();
}
#define EXPECT_DEMANGLING(mangled, plaintext) \
do { \
[] { \
constexpr size_t plenty_of_space = sizeof(plaintext) + 128; \
constexpr size_t just_enough_space = sizeof(plaintext); \
constexpr size_t one_byte_too_few = sizeof(plaintext) - 1; \
const char* expected_plaintext = plaintext; \
const char* expected_error = "Failed parse"; \
ASSERT_EQ(ResultOfDemangling(mangled, plenty_of_space), \
expected_plaintext); \
ASSERT_EQ(ResultOfDemangling(mangled, just_enough_space), \
expected_plaintext); \
ASSERT_EQ(ResultOfDemangling(mangled, one_byte_too_few), \
expected_error); \
}(); \
} while (0)
#define EXPECT_DEMANGLING_FAILS(mangled) \
do { \
constexpr size_t plenty_of_space = 1024; \
const char* expected_error = "Failed parse"; \
EXPECT_EQ(ResultOfDemangling(mangled, plenty_of_space), expected_error); \
} while (0)
TEST(DemangleRust, EmptyDemangling) {
EXPECT_TRUE(DemangleRustSymbolEncoding("_RC0", nullptr, 0));
}
TEST(DemangleRust, FunctionAtCrateLevel) {
EXPECT_DEMANGLING("_RNvC10crate_name9func_name", "crate_name::func_name");
EXPECT_DEMANGLING(
"_RNvCs09azAZ_10crate_name9func_name", "crate_name::func_name");
}
TEST(DemangleRust, TruncationsOfFunctionAtCrateLevel) {
EXPECT_DEMANGLING_FAILS("_R");
EXPECT_DEMANGLING_FAILS("_RN");
EXPECT_DEMANGLING_FAILS("_RNvC");
EXPECT_DEMANGLING_FAILS("_RNvC10");
EXPECT_DEMANGLING_FAILS("_RNvC10crate_nam");
EXPECT_DEMANGLING_FAILS("_RNvC10crate_name");
EXPECT_DEMANGLING_FAILS("_RNvC10crate_name9");
EXPECT_DEMANGLING_FAILS("_RNvC10crate_name9func_nam");
EXPECT_DEMANGLING_FAILS("_RNvCs");
EXPECT_DEMANGLING_FAILS("_RNvCs09azAZ");
EXPECT_DEMANGLING_FAILS("_RNvCs09azAZ_");
}
TEST(DemangleRust, VendorSuffixes) {
EXPECT_DEMANGLING("_RNvC10crate_name9func_name.!@#", "crate_name::func_name");
EXPECT_DEMANGLING("_RNvC10crate_name9func_name$!@#", "crate_name::func_name");
}
TEST(DemangleRust, UnicodeIdentifiers) {
EXPECT_DEMANGLING("_RNvC7ice_cap17Eyjafjallajökull",
"ice_cap::Eyjafjallajökull");
EXPECT_DEMANGLING("_RNvC7ice_caps_u19Eyjafjallajkull_jtb",
"ice_cap::{Punycode Eyjafjallajkull_jtb}");
}
TEST(DemangleRust, FunctionInModule) {
EXPECT_DEMANGLING("_RNvNtCs09azAZ_10crate_name11module_name9func_name",
"crate_name::module_name::func_name");
}
TEST(DemangleRust, FunctionInFunction) {
EXPECT_DEMANGLING(
"_RNvNvCs09azAZ_10crate_name15outer_func_name15inner_func_name",
"crate_name::outer_func_name::inner_func_name");
}
TEST(DemangleRust, ClosureInFunction) {
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_name0",
"crate_name::func_name::{closure#0}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_name0Cs123_12client_crate",
"crate_name::func_name::{closure#0}");
}
TEST(DemangleRust, ClosureNumbering) {
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_names_0Cs123_12client_crate",
"crate_name::func_name::{closure#1}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_names0_0Cs123_12client_crate",
"crate_name::func_name::{closure#2}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_names9_0Cs123_12client_crate",
"crate_name::func_name::{closure#11}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_namesa_0Cs123_12client_crate",
"crate_name::func_name::{closure#12}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_namesz_0Cs123_12client_crate",
"crate_name::func_name::{closure#37}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_namesA_0Cs123_12client_crate",
"crate_name::func_name::{closure#38}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_namesZ_0Cs123_12client_crate",
"crate_name::func_name::{closure#63}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_names10_0Cs123_12client_crate",
"crate_name::func_name::{closure#64}");
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_namesg6_0Cs123_12client_crate",
"crate_name::func_name::{closure#1000}");
}
TEST(DemangleRust, ClosureNumberOverflowingInt) {
EXPECT_DEMANGLING(
"_RNCNvCs09azAZ_10crate_name9func_names1234567_0Cs123_12client_crate",
"crate_name::func_name::{closure#?}");
}
TEST(DemangleRust, UnexpectedlyNamedClosure) {
EXPECT_DEMANGLING(
"_RNCNvCs123_10crate_name9func_name12closure_nameCs456_12client_crate",
"crate_name::func_name::{closure:closure_name#0}");
EXPECT_DEMANGLING(
"_RNCNvCs123_10crate_name9func_names2_12closure_nameCs456_12client_crate",
"crate_name::func_name::{closure:closure_name#4}");
}
TEST(DemangleRust, ItemNestedInsideClosure) {
EXPECT_DEMANGLING(
"_RNvNCNvCs123_10crate_name9func_name015inner_func_nameCs_12client_crate",
"crate_name::func_name::{closure#0}::inner_func_name");
}
TEST(DemangleRust, Shim) {
EXPECT_DEMANGLING(
"_RNSNvCs123_10crate_name9func_name6vtableCs456_12client_crate",
"crate_name::func_name::{shim:vtable#0}");
}
TEST(DemangleRust, UnknownUppercaseNamespace) {
EXPECT_DEMANGLING(
"_RNXNvCs123_10crate_name9func_name14mystery_objectCs456_12client_crate",
"crate_name::func_name::{X:mystery_object#0}");
}
TEST(DemangleRust, NestedUppercaseNamespaces) {
EXPECT_DEMANGLING(
"_RNCNXNYCs123_10crate_names0_1ys1_1xs2_0Cs456_12client_crate",
"crate_name::{Y:y#2}::{X:x#3}::{closure#4}");
}
TEST(DemangleRust, TraitDefinition) {
EXPECT_DEMANGLING(
"_RNvYNtC7crate_a9my_structNtC7crate_b8my_trait1f",
"<crate_a::my_struct as crate_b::my_trait>::f");
}
TEST(DemangleRust, BasicTypeNames) {
EXPECT_DEMANGLING("_RNvYaNtC1c1t1f", "<i8 as c::t>::f");
EXPECT_DEMANGLING("_RNvYbNtC1c1t1f", "<bool as c::t>::f");
EXPECT_DEMANGLING("_RNvYcNtC1c1t1f", "<char as c::t>::f");
EXPECT_DEMANGLING("_RNvYdNtC1c1t1f", "<f64 as c::t>::f");
EXPECT_DEMANGLING("_RNvYeNtC1c1t1f", "<str as c::t>::f");
EXPECT_DEMANGLING("_RNvYfNtC1c1t1f", "<f32 as c::t>::f");
EXPECT_DEMANGLING("_RNvYhNtC1c1t1f", "<u8 as c::t>::f");
EXPECT_DEMANGLING("_RNvYiNtC1c1t1f", "<isize as c::t>::f");
EXPECT_DEMANGLING("_RNvYjNtC1c1t1f", "<usize as c::t>::f");
EXPECT_DEMANGLING("_RNvYlNtC1c1t1f", "<i32 as c::t>::f");
EXPECT_DEMANGLING("_RNvYmNtC1c1t1f", "<u32 as c::t>::f");
EXPECT_DEMANGLING("_RNvYnNtC1c1t1f", "<i128 as c::t>::f");
EXPECT_DEMANGLING("_RNvYoNtC1c1t1f", "<u128 as c::t>::f");
EXPECT_DEMANGLING("_RNvYpNtC1c1t1f", "<_ as c::t>::f");
EXPECT_DEMANGLING("_RNvYsNtC1c1t1f", "<i16 as c::t>::f");
EXPECT_DEMANGLING("_RNvYtNtC1c1t1f", "<u16 as c::t>::f");
EXPECT_DEMANGLING("_RNvYuNtC1c1t1f", "<() as c::t>::f");
EXPECT_DEMANGLING("_RNvYvNtC1c1t1f", "<... as c::t>::f");
EXPECT_DEMANGLING("_RNvYxNtC1c1t1f", "<i64 as c::t>::f");
EXPECT_DEMANGLING("_RNvYyNtC1c1t1f", "<u64 as c::t>::f");
EXPECT_DEMANGLING("_RNvYzNtC1c1t1f", "<! as c::t>::f");
EXPECT_DEMANGLING_FAILS("_RNvYkNtC1c1t1f");
}
TEST(DemangleRust, SliceTypes) {
EXPECT_DEMANGLING("_RNvYSlNtC1c1t1f", "<[i32] as c::t>::f");
EXPECT_DEMANGLING("_RNvYSNtC1d1sNtC1c1t1f", "<[d::s] as c::t>::f");
}
TEST(DemangleRust, ImmutableReferenceTypes) {
EXPECT_DEMANGLING("_RNvYRlNtC1c1t1f", "<&i32 as c::t>::f");
EXPECT_DEMANGLING("_RNvYRNtC1d1sNtC1c1t1f", "<&d::s as c::t>::f");
}
TEST(DemangleRust, MutableReferenceTypes) {
EXPECT_DEMANGLING("_RNvYQlNtC1c1t1f", "<&mut i32 as c::t>::f");
EXPECT_DEMANGLING("_RNvYQNtC1d1sNtC1c1t1f", "<&mut d::s as c::t>::f");
}
TEST(DemangleRust, ConstantRawPointerTypes) {
EXPECT_DEMANGLING("_RNvYPlNtC1c1t1f", "<*const i32 as c::t>::f");
EXPECT_DEMANGLING("_RNvYPNtC1d1sNtC1c1t1f", "<*const d::s as c::t>::f");
}
TEST(DemangleRust, MutableRawPointerTypes) {
EXPECT_DEMANGLING("_RNvYOlNtC1c1t1f", "<*mut i32 as c::t>::f");
EXPECT_DEMANGLING("_RNvYONtC1d1sNtC1c1t1f", "<*mut d::s as c::t>::f");
}
TEST(DemangleRust, TupleLength0) {
EXPECT_DEMANGLING("_RNvYTENtC1c1t1f", "<() as c::t>::f");
}
TEST(DemangleRust, TupleLength1) {
EXPECT_DEMANGLING("_RNvYTlENtC1c1t1f", "<(i32,) as c::t>::f");
EXPECT_DEMANGLING("_RNvYTNtC1d1sENtC1c1t1f", "<(d::s,) as c::t>::f");
}
TEST(DemangleRust, TupleLength2) {
EXPECT_DEMANGLING("_RNvYTlmENtC1c1t1f", "<(i32, u32) as c::t>::f");
EXPECT_DEMANGLING("_RNvYTNtC1d1xNtC1e1yENtC1c1t1f",
"<(d::x, e::y) as c::t>::f");
}
TEST(DemangleRust, TupleLength3) {
EXPECT_DEMANGLING("_RNvYTlmnENtC1c1t1f", "<(i32, u32, i128) as c::t>::f");
EXPECT_DEMANGLING("_RNvYTNtC1d1xNtC1e1yNtC1f1zENtC1c1t1f",
"<(d::x, e::y, f::z) as c::t>::f");
}
TEST(DemangleRust, LongerTuplesAbbreviated) {
EXPECT_DEMANGLING("_RNvYTlmnoENtC1c1t1f",
"<(i32, u32, i128, ...) as c::t>::f");
EXPECT_DEMANGLING("_RNvYTlmnNtC1d1xNtC1e1yENtC1c1t1f",
"<(i32, u32, i128, ...) as c::t>::f");
}
TEST(DemangleRust, PathBackrefToCrate) {
EXPECT_DEMANGLING("_RNvYNtC8my_crate9my_structNtB4_8my_trait1f",
"<my_crate::my_struct as my_crate::my_trait>::f");
}
TEST(DemangleRust, PathBackrefToNestedPath) {
EXPECT_DEMANGLING("_RNvYNtNtC1c1m1sNtB4_1t1f", "<c::m::s as c::m::t>::f");
}
TEST(DemangleRust, PathBackrefAsInstantiatingCrate) {
EXPECT_DEMANGLING("_RNCNvC8my_crate7my_func0B3_",
"my_crate::my_func::{closure#0}");
}
TEST(DemangleRust, TypeBackrefsNestedInTuple) {
EXPECT_DEMANGLING("_RNvYTTRlB4_ERB3_ENtC1c1t1f",
"<((&i32, &i32), &(&i32, &i32)) as c::t>::f");
}
TEST(DemangleRust, NoInfiniteLoopOnBackrefToTheWhole) {
EXPECT_DEMANGLING_FAILS("_RB_");
EXPECT_DEMANGLING_FAILS("_RNvB_1sNtC1c1t1f");
}
TEST(DemangleRust, NoCrashOnForwardBackref) {
EXPECT_DEMANGLING_FAILS("_RB0_");
EXPECT_DEMANGLING_FAILS("_RB1_");
EXPECT_DEMANGLING_FAILS("_RB2_");
EXPECT_DEMANGLING_FAILS("_RB3_");
EXPECT_DEMANGLING_FAILS("_RB4_");
}
TEST(DemangleRust, PathBackrefsDoNotRecurseDuringSilence) {
EXPECT_DEMANGLING("_RNvYTlmnNtB_1sENtC1c1t1f",
"<(i32, u32, i128, ...) as c::t>::f");
}
TEST(DemangleRust, TypeBackrefsDoNotRecurseDuringSilence) {
EXPECT_DEMANGLING("_RNvYTlmnB2_ENtC1c1t1f",
"<(i32, u32, i128, ...) as c::t>::f");
}
TEST(DemangleRust, ConstBackrefsDoNotRecurseDuringSilence) {
EXPECT_DEMANGLING("_RINvC1c1fAlB_E", "c::f::<>");
}
TEST(DemangleRust, ReturnFromBackrefToInputPosition256) {
EXPECT_DEMANGLING("_RNvYNtC1c238very_long_type_"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABC"
"NtB4_1t1f",
"<c::very_long_type_"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij"
"ABCDEFGHIJabcdefghijABC"
" as c::t>::f");
}
TEST(DemangleRust, EmptyGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fE", "c::f::<>");
}
TEST(DemangleRust, OneSimpleTypeInGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1flE",
"c::f::<>");
}
TEST(DemangleRust, OneTupleInGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fTlmEE",
"c::f::<>");
}
TEST(DemangleRust, OnePathInGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fNtC1d1sE",
"c::f::<>");
}
TEST(DemangleRust, LongerGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1flmRNtC1d1sE",
"c::f::<>");
}
TEST(DemangleRust, BackrefInGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fRlB7_NtB2_1sE",
"c::f::<>");
}
TEST(DemangleRust, NestedGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fINtB2_1slEmE",
"c::f::<>");
}
TEST(DemangleRust, MonomorphicEntityNestedInsideGeneric) {
EXPECT_DEMANGLING("_RNvINvC1c1fppE1g",
"c::f::<>::g");
}
TEST(DemangleRust, ArrayTypeWithSimpleElementType) {
EXPECT_DEMANGLING("_RNvYAlj1f_NtC1c1t1f", "<[i32; 0x1f] as c::t>::f");
}
TEST(DemangleRust, ArrayTypeWithComplexElementType) {
EXPECT_DEMANGLING("_RNvYAINtC1c1slEj1f_NtB6_1t1f",
"<[c::s::<>; 0x1f] as c::t>::f");
}
TEST(DemangleRust, NestedArrayType) {
EXPECT_DEMANGLING("_RNvYAAlj1f_j2e_NtC1c1t1f",
"<[[i32; 0x1f]; 0x2e] as c::t>::f");
}
TEST(DemangleRust, BackrefArraySize) {
EXPECT_DEMANGLING("_RNvYAAlj1f_B5_NtC1c1t1f",
"<[[i32; 0x1f]; 0x1f] as c::t>::f");
}
TEST(DemangleRust, ZeroArraySize) {
EXPECT_DEMANGLING("_RNvYAlj0_NtC1c1t1f", "<[i32; 0x0] as c::t>::f");
}
TEST(DemangleRust, SurprisingMinusesInArraySize) {
EXPECT_DEMANGLING("_RNvYAljn0_NtC1c1t1f", "<[i32; -0x0] as c::t>::f");
EXPECT_DEMANGLING("_RNvYAljn42_NtC1c1t1f", "<[i32; -0x42] as c::t>::f");
}
TEST(DemangleRust, NumberAsGenericArg) {
EXPECT_DEMANGLING("_RINvC1c1fKl8_E",
"c::f::<>");
}
TEST(DemangleRust, NumberAsFirstOfTwoGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fKl8_mE",
"c::f::<>");
}
TEST(DemangleRust, NumberAsSecondOfTwoGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fmKl8_E",
"c::f::<>");
}
TEST(DemangleRust, NumberPlaceholder) {
EXPECT_DEMANGLING("_RNvINvC1c1fKpE1g",
"c::f::<>::g");
}
TEST(DemangleRust, InherentImplWithoutDisambiguator) {
EXPECT_DEMANGLING("_RNvMNtC8my_crate6my_modNtB2_9my_struct7my_func",
"<my_crate::my_mod::my_struct>::my_func");
}
TEST(DemangleRust, InherentImplWithDisambiguator) {
EXPECT_DEMANGLING("_RNvMs_NtC8my_crate6my_modNtB4_9my_struct7my_func",
"<my_crate::my_mod::my_struct>::my_func");
}
TEST(DemangleRust, TraitImplWithoutDisambiguator) {
EXPECT_DEMANGLING("_RNvXC8my_crateNtB2_9my_structNtB2_8my_trait7my_func",
"<my_crate::my_struct as my_crate::my_trait>::my_func");
}
TEST(DemangleRust, TraitImplWithDisambiguator) {
EXPECT_DEMANGLING("_RNvXs_C8my_crateNtB4_9my_structNtB4_8my_trait7my_func",
"<my_crate::my_struct as my_crate::my_trait>::my_func");
}
TEST(DemangleRust, TraitImplWithNonpathSelfType) {
EXPECT_DEMANGLING("_RNvXC8my_crateRlNtB2_8my_trait7my_func",
"<&i32 as my_crate::my_trait>::my_func");
}
TEST(DemangleRust, ThunkType) {
EXPECT_DEMANGLING("_RNvYFEuNtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, NontrivialFunctionReturnType) {
EXPECT_DEMANGLING(
"_RNvYFERTlmENtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, OneParameterType) {
EXPECT_DEMANGLING("_RNvYFlEuNtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, TwoParameterTypes) {
EXPECT_DEMANGLING("_RNvYFlmEuNtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, ExternC) {
EXPECT_DEMANGLING("_RNvYFKCEuNtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, ExternOther) {
EXPECT_DEMANGLING(
"_RNvYFK5not_CEuNtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, Unsafe) {
EXPECT_DEMANGLING("_RNvYFUEuNtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, Binder) {
EXPECT_DEMANGLING(
"_RNvYFG_RL0_lEB5_NtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, AllFnSigFeaturesInOrder) {
EXPECT_DEMANGLING(
"_RNvYFG_UKCRL0_lEB8_NtC1c1t1f",
"<fn... as c::t>::f");
}
TEST(DemangleRust, LifetimeInGenericArgs) {
EXPECT_DEMANGLING("_RINvC1c1fINtB2_1sL_EE",
"c::f::<>");
}
TEST(DemangleRust, EmptyDynTrait) {
EXPECT_DEMANGLING("_RNvYDEL_NtC1c1t1f",
"<dyn as c::t>::f");
}
TEST(DemangleRust, SimpleDynTrait) {
EXPECT_DEMANGLING("_RNvYDNtC1c1tEL_NtC1d1u1f",
"<dyn c::t as d::u>::f");
}
TEST(DemangleRust, DynTraitWithOneAssociatedType) {
EXPECT_DEMANGLING(
"_RNvYDNtC1c1tp1xlEL_NtC1d1u1f",
"<dyn c::t<> as d::u>::f");
}
TEST(DemangleRust, DynTraitWithTwoAssociatedTypes) {
EXPECT_DEMANGLING(
"_RNvYDNtC1c1tp1xlp1ymEL_NtC1d1u1f",
"<dyn c::t<> as d::u>::f");
}
TEST(DemangleRust, DynTraitPlusAutoTrait) {
EXPECT_DEMANGLING(
"_RNvYDNtC1c1tNtNtC3std6marker4SendEL_NtC1d1u1f",
"<dyn c::t + std::marker::Send as d::u>::f");
}
TEST(DemangleRust, DynTraitPlusTwoAutoTraits) {
EXPECT_DEMANGLING(
"_RNvYDNtC1c1tNtNtC3std6marker4CopyNtBc_4SyncEL_NtC1d1u1f",
"<dyn c::t + std::marker::Copy + std::marker::Sync as d::u>::f");
}
TEST(DemangleRust, HigherRankedDynTrait) {
EXPECT_DEMANGLING(
"_RNvYDG_INtC1c1tRL0_lEEL_NtC1d1u1f",
"<dyn c::t::<> as d::u>::f");
}
}
}
ABSL_NAMESPACE_END
} |
2,507 | cpp | abseil/abseil-cpp | raw_hash_set | absl/container/internal/raw_hash_set.cc | absl/container/internal/raw_hash_set_test.cc | #ifndef ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
#define ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <memory>
#include <tuple>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/macros.h"
#include "absl/base/optimization.h"
#include "absl/base/options.h"
#include "absl/base/port.h"
#include "absl/base/prefetch.h"
#include "absl/container/internal/common.h"
#include "absl/container/internal/compressed_tuple.h"
#include "absl/container/internal/container_memory.h"
#include "absl/container/internal/hash_policy_traits.h"
#include "absl/container/internal/hashtable_debug_hooks.h"
#include "absl/container/internal/hashtablez_sampler.h"
#include "absl/memory/memory.h"
#include "absl/meta/type_traits.h"
#include "absl/numeric/bits.h"
#include "absl/utility/utility.h"
#ifdef ABSL_INTERNAL_HAVE_SSE2
#include <emmintrin.h>
#endif
#ifdef ABSL_INTERNAL_HAVE_SSSE3
#include <tmmintrin.h>
#endif
#ifdef _MSC_VER
#include <intrin.h>
#endif
#ifdef ABSL_INTERNAL_HAVE_ARM_NEON
#include <arm_neon.h>
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace container_internal {
#ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS
#error ABSL_SWISSTABLE_ENABLE_GENERATIONS cannot be directly set
#elif (defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
defined(ABSL_HAVE_HWADDRESS_SANITIZER) || \
defined(ABSL_HAVE_MEMORY_SANITIZER)) && \
!defined(NDEBUG_SANITIZER)
#define ABSL_SWISSTABLE_ENABLE_GENERATIONS
#endif
using GenerationType = uint8_t;
constexpr GenerationType SentinelEmptyGeneration() { return 0; }
constexpr GenerationType NextGeneration(GenerationType generation) {
return ++generation == SentinelEmptyGeneration() ? ++generation : generation;
}
#ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS
constexpr bool SwisstableGenerationsEnabled() { return true; }
constexpr size_t NumGenerationBytes() { return sizeof(GenerationType); }
#else
constexpr bool SwisstableGenerationsEnabled() { return false; }
constexpr size_t NumGenerationBytes() { return 0; }
#endif
template <typename AllocType>
void SwapAlloc(AllocType& lhs, AllocType& rhs,
std::true_type ) {
using std::swap;
swap(lhs, rhs);
}
template <typename AllocType>
void SwapAlloc(AllocType& lhs, AllocType& rhs,
std::false_type ) {
(void)lhs;
(void)rhs;
assert(lhs == rhs &&
"It's UB to call swap with unequal non-propagating allocators.");
}
template <typename AllocType>
void CopyAlloc(AllocType& lhs, AllocType& rhs,
std::true_type ) {
lhs = rhs;
}
template <typename AllocType>
void CopyAlloc(AllocType&, AllocType&, std::false_type ) {}
template <size_t Width>
class probe_seq {
public:
probe_seq(size_t hash, size_t mask) {
assert(((mask + 1) & mask) == 0 && "not a mask");
mask_ = mask;
offset_ = hash & mask_;
}
size_t offset() const { return offset_; }
size_t offset(size_t i) const { return (offset_ + i) & mask_; }
void next() {
index_ += Width;
offset_ += index_;
offset_ &= mask_;
}
size_t index() const { return index_; }
private:
size_t mask_;
size_t offset_;
size_t index_ = 0;
};
template <class ContainerKey, class Hash, class Eq>
struct RequireUsableKey {
template <class PassedKey, class... Args>
std::pair<
decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())),
decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(),
std::declval<const PassedKey&>()))>*
operator()(const PassedKey&, const Args&...) const;
};
template <class E, class Policy, class Hash, class Eq, class... Ts>
struct IsDecomposable : std::false_type {};
template <class Policy, class Hash, class Eq, class... Ts>
struct IsDecomposable<
absl::void_t<decltype(Policy::apply(
RequireUsableKey<typename Policy::key_type, Hash, Eq>(),
std::declval<Ts>()...))>,
Policy, Hash, Eq, Ts...> : std::true_type {};
template <class T>
constexpr bool IsNoThrowSwappable(std::true_type = {} ) {
using std::swap;
return noexcept(swap(std::declval<T&>(), std::declval<T&>()));
}
template <class T>
constexpr bool IsNoThrowSwappable(std::false_type ) {
return false;
}
template <typename T>
uint32_t TrailingZeros(T x) {
ABSL_ASSUME(x != 0);
return static_cast<uint32_t>(countr_zero(x));
}
constexpr uint64_t kMsbs8Bytes = 0x8080808080808080ULL;
template <class T, int SignificantBits, int Shift = 0>
class NonIterableBitMask {
public:
explicit NonIterableBitMask(T mask) : mask_(mask) {}
explicit operator bool() const { return this->mask_ != 0; }
uint32_t LowestBitSet() const {
return container_internal::TrailingZeros(mask_) >> Shift;
}
uint32_t HighestBitSet() const {
return static_cast<uint32_t>((bit_width(mask_) - 1) >> Shift);
}
uint32_t TrailingZeros() const {
return container_internal::TrailingZeros(mask_) >> Shift;
}
uint32_t LeadingZeros() const {
constexpr int total_significant_bits = SignificantBits << Shift;
constexpr int extra_bits = sizeof(T) * 8 - total_significant_bits;
return static_cast<uint32_t>(
countl_zero(static_cast<T>(mask_ << extra_bits))) >>
Shift;
}
T mask_;
};
template <class T, int SignificantBits, int Shift = 0,
bool NullifyBitsOnIteration = false>
class BitMask : public NonIterableBitMask<T, SignificantBits, Shift> {
using Base = NonIterableBitMask<T, SignificantBits, Shift>;
static_assert(std::is_unsigned<T>::value, "");
static_assert(Shift == 0 || Shift == 3, "");
static_assert(!NullifyBitsOnIteration || Shift == 3, "");
public:
explicit BitMask(T mask) : Base(mask) {
if (Shift == 3 && !NullifyBitsOnIteration) {
assert(this->mask_ == (this->mask_ & kMsbs8Bytes));
}
}
using value_type = int;
using iterator = BitMask;
using const_iterator = BitMask;
BitMask& operator++() {
if (Shift == 3 && NullifyBitsOnIteration) {
this->mask_ &= kMsbs8Bytes;
}
this->mask_ &= (this->mask_ - 1);
return *this;
}
uint32_t operator*() const { return Base::LowestBitSet(); }
BitMask begin() const { return *this; }
BitMask end() const { return BitMask(0); }
private:
friend bool operator==(const BitMask& a, const BitMask& b) {
return a.mask_ == b.mask_;
}
friend bool operator!=(const BitMask& a, const BitMask& b) {
return a.mask_ != b.mask_;
}
};
using h2_t = uint8_t;
enum class ctrl_t : int8_t {
kEmpty = -128,
kDeleted = -2,
kSentinel = -1,
};
static_assert(
(static_cast<int8_t>(ctrl_t::kEmpty) &
static_cast<int8_t>(ctrl_t::kDeleted) &
static_cast<int8_t>(ctrl_t::kSentinel) & 0x80) != 0,
"Special markers need to have the MSB to make checking for them efficient");
static_assert(
ctrl_t::kEmpty < ctrl_t::kSentinel && ctrl_t::kDeleted < ctrl_t::kSentinel,
"ctrl_t::kEmpty and ctrl_t::kDeleted must be smaller than "
"ctrl_t::kSentinel to make the SIMD test of IsEmptyOrDeleted() efficient");
static_assert(
ctrl_t::kSentinel == static_cast<ctrl_t>(-1),
"ctrl_t::kSentinel must be -1 to elide loading it from memory into SIMD "
"registers (pcmpeqd xmm, xmm)");
static_assert(ctrl_t::kEmpty == static_cast<ctrl_t>(-128),
"ctrl_t::kEmpty must be -128 to make the SIMD check for its "
"existence efficient (psignb xmm, xmm)");
static_assert(
(~static_cast<int8_t>(ctrl_t::kEmpty) &
~static_cast<int8_t>(ctrl_t::kDeleted) &
static_cast<int8_t>(ctrl_t::kSentinel) & 0x7F) != 0,
"ctrl_t::kEmpty and ctrl_t::kDeleted must share an unset bit that is not "
"shared by ctrl_t::kSentinel to make the scalar test for "
"MaskEmptyOrDeleted() efficient");
static_assert(ctrl_t::kDeleted == static_cast<ctrl_t>(-2),
"ctrl_t::kDeleted must be -2 to make the implementation of "
"ConvertSpecialToEmptyAndFullToDeleted efficient");
ABSL_DLL extern const ctrl_t kEmptyGroup[32];
inline ctrl_t* EmptyGroup() {
return const_cast<ctrl_t*>(kEmptyGroup + 16);
}
ABSL_DLL extern const ctrl_t kSooControl[17];
inline ctrl_t* SooControl() {
return const_cast<ctrl_t*>(kSooControl);
}
inline bool IsSooControl(const ctrl_t* ctrl) { return ctrl == SooControl(); }
GenerationType* EmptyGeneration();
inline bool IsEmptyGeneration(const GenerationType* generation) {
return *generation == SentinelEmptyGeneration();
}
bool ShouldInsertBackwardsForDebug(size_t capacity, size_t hash,
const ctrl_t* ctrl);
ABSL_ATTRIBUTE_ALWAYS_INLINE inline bool ShouldInsertBackwards(
ABSL_ATTRIBUTE_UNUSED size_t capacity, ABSL_ATTRIBUTE_UNUSED size_t hash,
ABSL_ATTRIBUTE_UNUSED const ctrl_t* ctrl) {
#if defined(NDEBUG)
return false;
#else
return ShouldInsertBackwardsForDebug(capacity, hash, ctrl);
#endif
}
template <class Mask>
ABSL_ATTRIBUTE_ALWAYS_INLINE inline auto GetInsertionOffset(
Mask mask, ABSL_ATTRIBUTE_UNUSED size_t capacity,
ABSL_ATTRIBUTE_UNUSED size_t hash,
ABSL_ATTRIBUTE_UNUSED const ctrl_t* ctrl) {
#if defined(NDEBUG)
return mask.LowestBitSet();
#else
return ShouldInsertBackwardsForDebug(capacity, hash, ctrl)
? mask.HighestBitSet()
: mask.LowestBitSet();
#endif
}
inline size_t PerTableSalt(const ctrl_t* ctrl) {
return reinterpret_cast<uintptr_t>(ctrl) >> 12;
}
inline size_t H1(size_t hash, const ctrl_t* ctrl) {
return (hash >> 7) ^ PerTableSalt(ctrl);
}
inline h2_t H2(size_t hash) { return hash & 0x7F; }
inline bool IsEmpty(ctrl_t c) { return c == ctrl_t::kEmpty; }
inline bool IsFull(ctrl_t c) {
return static_cast<std::underlying_type_t<ctrl_t>>(c) >= 0;
}
inline bool IsDeleted(ctrl_t c) { return c == ctrl_t::kDeleted; }
inline bool IsEmptyOrDeleted(ctrl_t c) { return c < ctrl_t::kSentinel; }
#ifdef ABSL_INTERNAL_HAVE_SSE2
inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) {
#if defined(__GNUC__) && !defined(__clang__)
if (std::is_unsigned<char>::value) {
const __m128i mask = _mm_set1_epi8(0x80);
const __m128i diff = _mm_subs_epi8(b, a);
return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask);
}
#endif
return _mm_cmpgt_epi8(a, b);
}
struct GroupSse2Impl {
static constexpr size_t kWidth = 16;
explicit GroupSse2Impl(const ctrl_t* pos) {
ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos));
}
BitMask<uint16_t, kWidth> Match(h2_t hash) const {
auto match = _mm_set1_epi8(static_cast<char>(hash));
BitMask<uint16_t, kWidth> result = BitMask<uint16_t, kWidth>(0);
result = BitMask<uint16_t, kWidth>(
static_cast<uint16_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))));
return result;
}
NonIterableBitMask<uint16_t, kWidth> MaskEmpty() const {
#ifdef ABSL_INTERNAL_HAVE_SSSE3
return NonIterableBitMask<uint16_t, kWidth>(
static_cast<uint16_t>(_mm_movemask_epi8(_mm_sign_epi8(ctrl, ctrl))));
#else
auto match = _mm_set1_epi8(static_cast<char>(ctrl_t::kEmpty));
return NonIterableBitMask<uint16_t, kWidth>(
static_cast<uint16_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))));
#endif
}
BitMask<uint16_t, kWidth> MaskFull() const {
return BitMask<uint16_t, kWidth>(
static_cast<uint16_t>(_mm_movemask_epi8(ctrl) ^ 0xffff));
}
auto MaskNonFull() const {
return BitMask<uint16_t, kWidth>(
static_cast<uint16_t>(_mm_movemask_epi8(ctrl)));
}
NonIterableBitMask<uint16_t, kWidth> MaskEmptyOrDeleted() const {
auto special = _mm_set1_epi8(static_cast<char>(ctrl_t::kSentinel));
return NonIterableBitMask<uint16_t, kWidth>(static_cast<uint16_t>(
_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl))));
}
uint32_t CountLeadingEmptyOrDeleted() const {
auto special = _mm_set1_epi8(static_cast<char>(ctrl_t::kSentinel));
return TrailingZeros(static_cast<uint32_t>(
_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1));
}
void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
auto msbs = _mm_set1_epi8(static_cast<char>(-128));
auto x126 = _mm_set1_epi8(126);
#ifdef ABSL_INTERNAL_HAVE_SSSE3
auto res = _mm_or_si128(_mm_shuffle_epi8(x126, ctrl), msbs);
#else
auto zero = _mm_setzero_si128();
auto special_mask = _mm_cmpgt_epi8_fixed(zero, ctrl);
auto res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126));
#endif
_mm_storeu_si128(reinterpret_cast<__m128i*>(dst), res);
}
__m128i ctrl;
};
#endif
#if defined(ABSL_INTERNAL_HAVE_ARM_NEON) && defined(ABSL_IS_LITTLE_ENDIAN)
struct GroupAArch64Impl {
static constexpr size_t kWidth = 8;
explicit GroupAArch64Impl(const ctrl_t* pos) {
ctrl = vld1_u8(reinterpret_cast<const uint8_t*>(pos));
}
auto Match(h2_t hash) const {
uint8x8_t dup = vdup_n_u8(hash);
auto mask = vceq_u8(ctrl, dup);
return BitMask<uint64_t, kWidth, 3,
true>(
vget_lane_u64(vreinterpret_u64_u8(mask), 0));
}
NonIterableBitMask<uint64_t, kWidth, 3> MaskEmpty() const {
uint64_t mask =
vget_lane_u64(vreinterpret_u64_u8(vceq_s8(
vdup_n_s8(static_cast<int8_t>(ctrl_t::kEmpty)),
vreinterpret_s8_u8(ctrl))),
0);
return NonIterableBitMask<uint64_t, kWidth, 3>(mask);
}
auto MaskFull() const {
uint64_t mask = vget_lane_u64(
vreinterpret_u64_u8(vcge_s8(vreinterpret_s8_u8(ctrl),
vdup_n_s8(static_cast<int8_t>(0)))),
0);
return BitMask<uint64_t, kWidth, 3,
true>(mask);
}
auto MaskNonFull() const {
uint64_t mask = vget_lane_u64(
vreinterpret_u64_u8(vclt_s8(vreinterpret_s8_u8(ctrl),
vdup_n_s8(static_cast<int8_t>(0)))),
0);
return BitMask<uint64_t, kWidth, 3,
true>(mask);
}
NonIterableBitMask<uint64_t, kWidth, 3> MaskEmptyOrDeleted() const {
uint64_t mask =
vget_lane_u64(vreinterpret_u64_u8(vcgt_s8(
vdup_n_s8(static_cast<int8_t>(ctrl_t::kSentinel)),
vreinterpret_s8_u8(ctrl))), | #include "absl/container/internal/raw_hash_set.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <ostream>
#include <random>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/cycleclock.h"
#include "absl/base/prefetch.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/internal/container_memory.h"
#include "absl/container/internal/hash_function_defaults.h"
#include "absl/container/internal/hash_policy_testing.h"
#include "absl/container/internal/hashtable_debug.h"
#include "absl/container/internal/hashtablez_sampler.h"
#include "absl/container/internal/test_allocator.h"
#include "absl/container/internal/test_instance_tracker.h"
#include "absl/container/node_hash_set.h"
#include "absl/functional/function_ref.h"
#include "absl/hash/hash.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace container_internal {
struct RawHashSetTestOnlyAccess {
template <typename C>
static auto GetCommon(const C& c) -> decltype(c.common()) {
return c.common();
}
template <typename C>
static auto GetSlots(const C& c) -> decltype(c.slot_array()) {
return c.slot_array();
}
template <typename C>
static size_t CountTombstones(const C& c) {
return c.common().TombstonesCount();
}
};
namespace {
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::Eq;
using ::testing::Ge;
using ::testing::Lt;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
ctrl_t CtrlT(int i) { return static_cast<ctrl_t>(i); }
TEST(GrowthInfoTest, GetGrowthLeft) {
GrowthInfo gi;
gi.InitGrowthLeftNoDeleted(5);
EXPECT_EQ(gi.GetGrowthLeft(), 5);
gi.OverwriteFullAsDeleted();
EXPECT_EQ(gi.GetGrowthLeft(), 5);
}
TEST(GrowthInfoTest, HasNoDeleted) {
GrowthInfo gi;
gi.InitGrowthLeftNoDeleted(5);
EXPECT_TRUE(gi.HasNoDeleted());
gi.OverwriteFullAsDeleted();
EXPECT_FALSE(gi.HasNoDeleted());
gi.InitGrowthLeftNoDeleted(5);
EXPECT_TRUE(gi.HasNoDeleted());
}
TEST(GrowthInfoTest, HasNoDeletedAndGrowthLeft) {
GrowthInfo gi;
gi.InitGrowthLeftNoDeleted(5);
EXPECT_TRUE(gi.HasNoDeletedAndGrowthLeft());
gi.OverwriteFullAsDeleted();
EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft());
gi.InitGrowthLeftNoDeleted(0);
EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft());
gi.OverwriteFullAsDeleted();
EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft());
gi.InitGrowthLeftNoDeleted(5);
EXPECT_TRUE(gi.HasNoDeletedAndGrowthLeft());
}
TEST(GrowthInfoTest, HasNoGrowthLeftAndNoDeleted) {
GrowthInfo gi;
gi.InitGrowthLeftNoDeleted(1);
EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted());
gi.OverwriteEmptyAsFull();
EXPECT_TRUE(gi.HasNoGrowthLeftAndNoDeleted());
gi.OverwriteFullAsDeleted();
EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted());
gi.OverwriteFullAsEmpty();
EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted());
gi.InitGrowthLeftNoDeleted(0);
EXPECT_TRUE(gi.HasNoGrowthLeftAndNoDeleted());
gi.OverwriteFullAsEmpty();
EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted());
}
TEST(GrowthInfoTest, OverwriteFullAsEmpty) {
GrowthInfo gi;
gi.InitGrowthLeftNoDeleted(5);
gi.OverwriteFullAsEmpty();
EXPECT_EQ(gi.GetGrowthLeft(), 6);
gi.OverwriteFullAsDeleted();
EXPECT_EQ(gi.GetGrowthLeft(), 6);
gi.OverwriteFullAsEmpty();
EXPECT_EQ(gi.GetGrowthLeft(), 7);
EXPECT_FALSE(gi.HasNoDeleted());
}
TEST(GrowthInfoTest, OverwriteEmptyAsFull) {
GrowthInfo gi;
gi.InitGrowthLeftNoDeleted(5);
gi.OverwriteEmptyAsFull();
EXPECT_EQ(gi.GetGrowthLeft(), 4);
gi.OverwriteFullAsDeleted();
EXPECT_EQ(gi.GetGrowthLeft(), 4);
gi.OverwriteEmptyAsFull();
EXPECT_EQ(gi.GetGrowthLeft(), 3);
EXPECT_FALSE(gi.HasNoDeleted());
}
TEST(GrowthInfoTest, OverwriteControlAsFull) {
GrowthInfo gi;
gi.InitGrowthLeftNoDeleted(5);
gi.OverwriteControlAsFull(ctrl_t::kEmpty);
EXPECT_EQ(gi.GetGrowthLeft(), 4);
gi.OverwriteControlAsFull(ctrl_t::kDeleted);
EXPECT_EQ(gi.GetGrowthLeft(), 4);
gi.OverwriteFullAsDeleted();
gi.OverwriteControlAsFull(ctrl_t::kDeleted);
EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft());
EXPECT_FALSE(gi.HasNoDeleted());
}
TEST(Util, NormalizeCapacity) {
EXPECT_EQ(1, NormalizeCapacity(0));
EXPECT_EQ(1, NormalizeCapacity(1));
EXPECT_EQ(3, NormalizeCapacity(2));
EXPECT_EQ(3, NormalizeCapacity(3));
EXPECT_EQ(7, NormalizeCapacity(4));
EXPECT_EQ(7, NormalizeCapacity(7));
EXPECT_EQ(15, NormalizeCapacity(8));
EXPECT_EQ(15, NormalizeCapacity(15));
EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 1));
EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 2));
}
TEST(Util, GrowthAndCapacity) {
for (size_t growth = 0; growth < 10000; ++growth) {
SCOPED_TRACE(growth);
size_t capacity = NormalizeCapacity(GrowthToLowerboundCapacity(growth));
EXPECT_THAT(CapacityToGrowth(capacity), Ge(growth));
if (capacity + 1 < Group::kWidth) {
EXPECT_THAT(CapacityToGrowth(capacity), Eq(capacity));
} else {
EXPECT_THAT(CapacityToGrowth(capacity), Lt(capacity));
}
if (growth != 0 && capacity > 1) {
EXPECT_THAT(CapacityToGrowth(capacity / 2), Lt(growth));
}
}
for (size_t capacity = Group::kWidth - 1; capacity < 10000;
capacity = 2 * capacity + 1) {
SCOPED_TRACE(capacity);
size_t growth = CapacityToGrowth(capacity);
EXPECT_THAT(growth, Lt(capacity));
EXPECT_LE(GrowthToLowerboundCapacity(growth), capacity);
EXPECT_EQ(NormalizeCapacity(GrowthToLowerboundCapacity(growth)), capacity);
}
}
TEST(Util, probe_seq) {
probe_seq<16> seq(0, 127);
auto gen = [&]() {
size_t res = seq.offset();
seq.next();
return res;
};
std::vector<size_t> offsets(8);
std::generate_n(offsets.begin(), 8, gen);
EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64));
seq = probe_seq<16>(128, 127);
std::generate_n(offsets.begin(), 8, gen);
EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64));
}
TEST(BitMask, Smoke) {
EXPECT_FALSE((BitMask<uint8_t, 8>(0)));
EXPECT_TRUE((BitMask<uint8_t, 8>(5)));
EXPECT_THAT((BitMask<uint8_t, 8>(0)), ElementsAre());
EXPECT_THAT((BitMask<uint8_t, 8>(0x1)), ElementsAre(0));
EXPECT_THAT((BitMask<uint8_t, 8>(0x2)), ElementsAre(1));
EXPECT_THAT((BitMask<uint8_t, 8>(0x3)), ElementsAre(0, 1));
EXPECT_THAT((BitMask<uint8_t, 8>(0x4)), ElementsAre(2));
EXPECT_THAT((BitMask<uint8_t, 8>(0x5)), ElementsAre(0, 2));
EXPECT_THAT((BitMask<uint8_t, 8>(0x55)), ElementsAre(0, 2, 4, 6));
EXPECT_THAT((BitMask<uint8_t, 8>(0xAA)), ElementsAre(1, 3, 5, 7));
}
TEST(BitMask, WithShift_MatchPortable) {
uint64_t ctrl = 0x1716151413121110;
uint64_t hash = 0x12;
constexpr uint64_t lsbs = 0x0101010101010101ULL;
auto x = ctrl ^ (lsbs * hash);
uint64_t mask = (x - lsbs) & ~x & kMsbs8Bytes;
EXPECT_EQ(0x0000000080800000, mask);
BitMask<uint64_t, 8, 3> b(mask);
EXPECT_EQ(*b, 2);
}
constexpr uint64_t kSome8BytesMask = 0x8000808080008000ULL;
constexpr uint64_t kSome8BytesMaskAllOnes = 0xff00ffffff00ff00ULL;
constexpr auto kSome8BytesMaskBits = std::array<int, 5>{1, 3, 4, 5, 7};
TEST(BitMask, WithShift_FullMask) {
EXPECT_THAT((BitMask<uint64_t, 8, 3>(kMsbs8Bytes)),
ElementsAre(0, 1, 2, 3, 4, 5, 6, 7));
EXPECT_THAT(
(BitMask<uint64_t, 8, 3, true>(kMsbs8Bytes)),
ElementsAre(0, 1, 2, 3, 4, 5, 6, 7));
EXPECT_THAT(
(BitMask<uint64_t, 8, 3, true>(~uint64_t{0})),
ElementsAre(0, 1, 2, 3, 4, 5, 6, 7));
}
TEST(BitMask, WithShift_EmptyMask) {
EXPECT_THAT((BitMask<uint64_t, 8, 3>(0)), ElementsAre());
EXPECT_THAT((BitMask<uint64_t, 8, 3, true>(0)),
ElementsAre());
}
TEST(BitMask, WithShift_SomeMask) {
EXPECT_THAT((BitMask<uint64_t, 8, 3>(kSome8BytesMask)),
ElementsAreArray(kSome8BytesMaskBits));
EXPECT_THAT((BitMask<uint64_t, 8, 3, true>(
kSome8BytesMask)),
ElementsAreArray(kSome8BytesMaskBits));
EXPECT_THAT((BitMask<uint64_t, 8, 3, true>(
kSome8BytesMaskAllOnes)),
ElementsAreArray(kSome8BytesMaskBits));
}
TEST(BitMask, WithShift_SomeMaskExtraBitsForNullify) {
uint64_t extra_bits = 77;
for (int i = 0; i < 100; ++i) {
uint64_t extra_mask = extra_bits & kSome8BytesMaskAllOnes;
EXPECT_THAT((BitMask<uint64_t, 8, 3, true>(
kSome8BytesMask | extra_mask)),
ElementsAreArray(kSome8BytesMaskBits))
<< i << " " << extra_mask;
extra_bits = (extra_bits + 1) * 3;
}
}
TEST(BitMask, LeadingTrailing) {
EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).LeadingZeros()), 3);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).TrailingZeros()), 6);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).LeadingZeros()), 15);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).TrailingZeros()), 0);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).LeadingZeros()), 0);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).TrailingZeros()), 15);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).LeadingZeros()), 3);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).TrailingZeros()), 1);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).LeadingZeros()), 7);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).TrailingZeros()), 0);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).LeadingZeros()), 0);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).TrailingZeros()), 7);
}
TEST(Group, EmptyGroup) {
for (h2_t h = 0; h != 128; ++h) EXPECT_FALSE(Group{EmptyGroup()}.Match(h));
}
TEST(Group, Match) {
if (Group::kWidth == 16) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3),
ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1),
CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)};
EXPECT_THAT(Group{group}.Match(0), ElementsAre());
EXPECT_THAT(Group{group}.Match(1), ElementsAre(1, 11, 12, 13, 14, 15));
EXPECT_THAT(Group{group}.Match(3), ElementsAre(3, 10));
EXPECT_THAT(Group{group}.Match(5), ElementsAre(5, 9));
EXPECT_THAT(Group{group}.Match(7), ElementsAre(7, 8));
} else if (Group::kWidth == 8) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2),
ctrl_t::kDeleted, CtrlT(2), CtrlT(1),
ctrl_t::kSentinel, CtrlT(1)};
EXPECT_THAT(Group{group}.Match(0), ElementsAre());
EXPECT_THAT(Group{group}.Match(1), ElementsAre(1, 5, 7));
EXPECT_THAT(Group{group}.Match(2), ElementsAre(2, 4));
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Group, MaskEmpty) {
if (Group::kWidth == 16) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3),
ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1),
CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)};
EXPECT_THAT(Group{group}.MaskEmpty().LowestBitSet(), 0);
EXPECT_THAT(Group{group}.MaskEmpty().HighestBitSet(), 4);
} else if (Group::kWidth == 8) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2),
ctrl_t::kDeleted, CtrlT(2), CtrlT(1),
ctrl_t::kSentinel, CtrlT(1)};
EXPECT_THAT(Group{group}.MaskEmpty().LowestBitSet(), 0);
EXPECT_THAT(Group{group}.MaskEmpty().HighestBitSet(), 0);
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Group, MaskFull) {
if (Group::kWidth == 16) {
ctrl_t group[] = {
ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3),
ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
CtrlT(7), CtrlT(5), ctrl_t::kDeleted, CtrlT(1),
CtrlT(1), ctrl_t::kSentinel, ctrl_t::kEmpty, CtrlT(1)};
EXPECT_THAT(Group{group}.MaskFull(),
ElementsAre(1, 3, 5, 7, 8, 9, 11, 12, 15));
} else if (Group::kWidth == 8) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kEmpty,
ctrl_t::kDeleted, CtrlT(2), ctrl_t::kSentinel,
ctrl_t::kSentinel, CtrlT(1)};
EXPECT_THAT(Group{group}.MaskFull(), ElementsAre(1, 4, 7));
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Group, MaskNonFull) {
if (Group::kWidth == 16) {
ctrl_t group[] = {
ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3),
ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
CtrlT(7), CtrlT(5), ctrl_t::kDeleted, CtrlT(1),
CtrlT(1), ctrl_t::kSentinel, ctrl_t::kEmpty, CtrlT(1)};
EXPECT_THAT(Group{group}.MaskNonFull(),
ElementsAre(0, 2, 4, 6, 10, 13, 14));
} else if (Group::kWidth == 8) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kEmpty,
ctrl_t::kDeleted, CtrlT(2), ctrl_t::kSentinel,
ctrl_t::kSentinel, CtrlT(1)};
EXPECT_THAT(Group{group}.MaskNonFull(), ElementsAre(0, 2, 3, 5, 6));
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Group, MaskEmptyOrDeleted) {
if (Group::kWidth == 16) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kEmpty, CtrlT(3),
ctrl_t::kDeleted, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1),
CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)};
EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().LowestBitSet(), 0);
EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().HighestBitSet(), 4);
} else if (Group::kWidth == 8) {
ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2),
ctrl_t::kDeleted, CtrlT(2), CtrlT(1),
ctrl_t::kSentinel, CtrlT(1)};
EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().LowestBitSet(), 0);
EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().HighestBitSet(), 3);
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Batch, DropDeletes) {
constexpr size_t kCapacity = 63;
constexpr size_t kGroupWidth = container_internal::Group::kWidth;
std::vector<ctrl_t> ctrl(kCapacity + 1 + kGroupWidth);
ctrl[kCapacity] = ctrl_t::kSentinel;
std::vector<ctrl_t> pattern = {
ctrl_t::kEmpty, CtrlT(2), ctrl_t::kDeleted, CtrlT(2),
ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted};
for (size_t i = 0; i != kCapacity; ++i) {
ctrl[i] = pattern[i % pattern.size()];
if (i < kGroupWidth - 1)
ctrl[i + kCapacity + 1] = pattern[i % pattern.size()];
}
ConvertDeletedToEmptyAndFullToDeleted(ctrl.data(), kCapacity);
ASSERT_EQ(ctrl[kCapacity], ctrl_t::kSentinel);
for (size_t i = 0; i < kCapacity + kGroupWidth; ++i) {
ctrl_t expected = pattern[i % (kCapacity + 1) % pattern.size()];
if (i == kCapacity) expected = ctrl_t::kSentinel;
if (expected == ctrl_t::kDeleted) expected = ctrl_t::kEmpty;
if (IsFull(expected)) expected = ctrl_t::kDeleted;
EXPECT_EQ(ctrl[i], expected)
<< i << " " << static_cast<int>(pattern[i % pattern.size()]);
}
}
TEST(Group, CountLeadingEmptyOrDeleted) {
const std::vector<ctrl_t> empty_examples = {ctrl_t::kEmpty, ctrl_t::kDeleted};
const std::vector<ctrl_t> full_examples = {
CtrlT(0), CtrlT(1), CtrlT(2), CtrlT(3),
CtrlT(5), CtrlT(9), CtrlT(127), ctrl_t::kSentinel};
for (ctrl_t empty : empty_examples) {
std::vector<ctrl_t> e(Group::kWidth, empty);
EXPECT_EQ(Group::kWidth, Group{e.data()}.CountLeadingEmptyOrDeleted());
for (ctrl_t full : full_examples) {
for (size_t i = 0; i != Group::kWidth; ++i) {
std::vector<ctrl_t> f(Group::kWidth, empty);
f[i] = full;
EXPECT_EQ(i, Group{f.data()}.CountLeadingEmptyOrDeleted());
}
std::vector<ctrl_t> f(Group::kWidth, empty);
f[Group::kWidth * 2 / 3] = full;
f[Group::kWidth / 2] = full;
EXPECT_EQ(Group::kWidth / 2,
Group{f.data()}.CountLeadingEmptyOrDeleted());
}
}
}
template <class T, bool kTransferable = false, bool kSoo = false>
struct ValuePolicy {
using slot_type = T;
using key_type = T;
using init_type = T;
template <class Allocator, class... Args>
static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
absl::allocator_traits<Allocator>::construct(*alloc, slot,
std::forward<Args>(args)...);
}
template <class Allocator>
static void destroy(Allocator* alloc, slot_type* slot) {
absl::allocator_traits<Allocator>::destroy(*alloc, slot);
}
template <class Allocator>
static std::integral_constant<bool, kTransferable> transfer(
Allocator* alloc, slot_type* new_slot, slot_type* old_slot) {
construct(alloc, new_slot, std::move(*old_slot));
destroy(alloc, old_slot);
return {};
}
static T& element(slot_type* slot) { return *slot; }
template <class F, class... Args>
static decltype(absl::container_internal::DecomposeValue(
std::declval<F>(), std::declval<Args>()...))
apply(F&& f, Args&&... args) {
return absl::container_internal::DecomposeValue(
std::forward<F>(f), std::forward<Args>(args)...);
}
template <class Hash>
static constexpr HashSlotFn get_hash_slot_fn() {
return nullptr;
}
static constexpr bool soo_enabled() { return kSoo; }
};
using IntPolicy = ValuePolicy<int64_t>;
using Uint8Policy = ValuePolicy<uint8_t>;
using TranferableIntPolicy = ValuePolicy<int64_t, true>;
template <int N>
class SizedValue {
public:
SizedValue(int64_t v) {
vals_[0] = v;
}
SizedValue() : SizedValue(0) {}
SizedValue(const SizedValue&) = default;
SizedValue& operator=(const SizedValue&) = default;
int64_t operator*() const {
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
return vals_[0];
#if !defined(__clang__) && defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}
explicit operator int() const { return **this; }
explicit operator int64_t() const { return **this; }
template <typename H>
friend H AbslHashValue(H h, SizedValue sv) {
return H::combine(std::move(h), *sv);
}
bool operator==(const SizedValue& rhs) const { return **this == *rhs; }
private:
int64_t vals_[N / sizeof(int64_t)];
};
template <int N, bool kSoo>
using SizedValuePolicy =
ValuePolicy<SizedValue<N>, true, kSoo>;
class StringPolicy {
template <class F, class K, class V,
class = typename std::enable_if<
std::is_convertible<const K&, absl::string_view>::value>::type>
decltype(std::declval<F>()(
std::declval<const absl::string_view&>(), std::piecewise_construct,
std::declval<std::tuple<K>>(),
std::declval<V>())) static apply_impl(F&& f,
std::pair<std::tuple<K>, V> p) {
const absl::string_view& key = std::get<0>(p.first);
return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
std::move(p.second));
}
public:
struct slot_type {
struct ctor {};
template <class... Ts>
explicit slot_type(ctor, Ts&&... ts) : pair(std::forward<Ts>(ts)...) {}
std::pair<std::string, std::string> pair;
};
using key_type = std::string;
using init_type = std::pair<std::string, std::string>;
template <class allocator_type, class... Args>
static void construct(allocator_type* alloc, slot_type* slot, Args... args) {
std::allocator_traits<allocator_type>::construct(
*alloc, slot, typename slot_type::ctor(), std::forward<Args>(args)...);
}
template <class allocator_type>
static void destroy(allocator_type* alloc, slot_type* slot) {
std::allocator_traits<allocator_type>::destroy(*alloc, slot);
}
template <class allocator_type>
static void transfer(allocator_type* alloc, slot_type* new_slot,
slot_type* old_slot) {
construct(alloc, new_slot, std::move(old_slot->pair));
destroy(alloc, old_slot);
}
static std::pair<std::string, std::string>& element(slot_type* slot) {
return slot->pair;
}
template <class F, class... Args>
static auto apply(F&& f, Args&&... args)
-> decltype(apply_impl(std::forward<F>(f),
PairArgs(std::forward<Args>(args)...))) {
return apply_impl(std::forward<F>(f),
PairArgs(std::forward<Args>(args)...));
}
template <class Hash>
static constexpr HashSlotFn get_hash_slot_fn() {
return nullptr;
}
};
struct StringHash : absl::Hash<absl::string_view> {
using is_transparent = void;
};
struct StringEq : std::equal_to<absl::string_view> {
using is_transparent = void;
};
struct StringTable
: raw_hash_set<StringPolicy, StringHash, StringEq, std::allocator<int>> {
using Base = typename StringTable::raw_hash_set;
StringTable() = default;
using Base::Base;
};
template <typename T, bool kTransferable = false, bool kSoo = false>
struct ValueTable
: raw_hash_set<ValuePolicy<T, kTransferable, kSoo>, hash_default_hash<T>,
std::equal_to<T>, std::allocator<T>> {
using Base = typename ValueTable::raw_hash_set;
using Base::Base;
};
using IntTable = ValueTable<int64_t>;
using Uint8Table = ValueTable<uint8_t>;
using TransferableIntTable = ValueTable<int64_t, true>;
constexpr size_t kNonSooSize = sizeof(HeapOrSoo) + 8;
static_assert(sizeof(SizedValue<kNonSooSize>) >= kNonSooSize, "too small");
using NonSooIntTable = ValueTable<SizedValue<kNonSooSize>>;
using SooIntTable = ValueTable<int64_t, true, true>;
template <typename T>
struct CustomAlloc : std::allocator<T> {
CustomAlloc() = default;
template <typename U>
explicit CustomAlloc(const CustomAlloc<U>& ) {}
template <class U>
struct rebind {
using other = CustomAlloc<U>;
};
};
struct CustomAllocIntTable
: raw_hash_set<IntPolicy, hash_default_hash<int64_t>,
std::equal_to<int64_t>, CustomAlloc<int64_t>> {
using Base = typename CustomAllocIntTable::raw_hash_set;
using Base::Base;
};
struct MinimumAlignmentUint8Table
: raw_hash_set<Uint8Policy, hash_default_hash<uint8_t>,
std::equal_to<uint8_t>, MinimumAlignmentAlloc<uint8_t>> {
using Base = typename MinimumAlignmentUint8Table::raw_hash_set;
using Base::Base;
};
template <typename T>
struct FreezableAlloc : std::allocator<T> {
explicit FreezableAlloc(bool* f) : frozen(f) {}
template <typename U>
explicit FreezableAlloc(const FreezableAlloc<U>& other)
: frozen(other.frozen) {}
template <class U>
struct rebind {
using other = FreezableAlloc<U>;
};
T* allocate(size_t n) {
EXPECT_FALSE(*frozen);
return std::allocator<T>::allocate(n);
}
bool* frozen;
};
template <int N>
struct FreezableSizedValueSooTable
: raw_hash_set<SizedValuePolicy<N, true>,
container_internal::hash_default_hash<SizedValue<N>>,
std::equal_to<SizedValue<N>>,
FreezableAlloc<SizedValue<N>>> {
using Base = typename FreezableSizedValueSooTable::raw_hash_set;
using Base::Base;
};
struct BadFastHash {
template <class T>
size_t operator()(const T&) const {
return 0;
}
};
struct BadHashFreezableIntTable
: raw_hash_set<IntPolicy, BadFastHash, std::equal_to<int64_t>,
FreezableAlloc<int64_t>> {
using Base = typename BadHashFreezableIntTable::raw_hash_set;
using Base::Base;
};
struct BadTable : raw_hash_set<IntPolicy, BadFastHash, std::equal_to<int>,
std::allocator<int>> {
using Base = typename BadTable::raw_hash_set;
BadTable() = default;
using Base::Base;
};
TEST(Table, EmptyFunctorOptimization) {
static_assert(std::is_empty<std::equal_to<absl::string_view>>::value, "");
static_assert(std::is_empty<std::allocator<int>>::value, "");
struct MockTable {
void* ctrl;
void* slots;
size_t size;
size_t capacity;
};
struct StatelessHash {
size_t operator()(absl::string_view) const { return 0; }
};
struct StatefulHash : StatelessHash {
size_t dummy;
};
struct GenerationData {
size_t reserved_growth;
size_t reservation_size;
GenerationType* generation;
};
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#endif
constexpr size_t mock_size = sizeof(MockTable);
constexpr size_t generation_size =
SwisstableGenerationsEnabled() ? sizeof(GenerationData) : 0;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
EXPECT_EQ(
mock_size + generation_size,
sizeof(
raw_hash_set<StringPolicy, StatelessHash,
std::equal_to<absl::string_view>, std::allocator<int>>));
EXPECT_EQ(
mock_size + sizeof(StatefulHash) + generation_size,
sizeof(
raw_hash_set<StringPolicy, StatefulHash,
std::equal_to<absl::string_view>, std::allocator<int>>));
}
template <class TableType>
class SooTest : public testing::Test {};
using SooTableTypes = ::testing::Types<SooIntTable, NonSooIntTable>;
TYPED_TEST_SUITE(SooTest, SooTableTypes);
TYPED_TEST(SooTest, Empty) {
TypeParam t;
EXPECT_EQ(0, t.size());
EXPECT_TRUE(t.empty());
}
TYPED_TEST(SooTest, LookupEmpty) {
TypeParam t;
auto it = t.find(0);
EXPECT_TRUE(it == t.end());
}
TYPED_TEST(SooTest, Insert1) {
TypeParam t;
EXPECT_TRUE(t.find(0) == t.end());
auto res = t.emplace(0);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 0);
EXPECT_EQ(1, t.size());
EXPECT_THAT(*t.find(0), 0);
}
TYPED_TEST(SooTest, Insert2) {
TypeParam t;
EXPECT_TRUE(t.find(0) == t.end());
auto res = t.emplace(0);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 0);
EXPECT_EQ(1, t.size());
EXPECT_TRUE(t.find(1) == t.end());
res = t.emplace(1);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 1);
EXPECT_EQ(2, t.size());
EXPECT_THAT(*t.find(0), 0);
EXPECT_THAT(*t.find(1), 1);
}
TEST(Table, InsertCollision) {
BadTable t;
EXPECT_TRUE(t.find(1) == t.end());
auto res = t.emplace(1);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 1);
EXPECT_EQ(1, t.size());
EXPECT_TRUE(t.find(2) == t.end());
res = t.emplace(2);
EXPECT_THAT(*res.first, 2);
EXPECT_TRUE(res.second);
EXPECT_EQ(2, t.size());
EXPECT_THAT(*t.find(1), 1);
EXPECT_THAT(*t.find(2), 2);
}
TEST(Table, InsertCollisionAndFindAfterDelete) {
BadTable t;
constexpr size_t kNumInserts = Group::kWidth * 2 + 5;
for (size_t i = 0; i < kNumInserts; ++i) {
auto res = t.emplace(i);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, i);
EXPECT_EQ(i + 1, t.size());
}
for (size_t i = 0; i < kNumInserts; ++i) {
EXPECT_EQ(1, t.erase(i)) << i;
for (size_t j = i + 1; j < kNumInserts; ++j) {
EXPECT_THAT(*t.find(j), j);
auto res = t.emplace(j);
EXPECT_FALSE(res.second) << i << " " << j;
EXPECT_THAT(*res.first, j);
EXPECT_EQ(kNumInserts - i - 1, t.size());
}
}
EXPECT_TRUE(t.empty());
}
TYPED_TEST(SooTest, EraseInSmallTables) {
for (int64_t size = 0; size < 64; ++size) {
TypeParam t;
for (int64_t i = 0; i < size; ++i) {
t.insert(i);
}
for (int64_t i = 0; i < size; ++i) {
t.erase(i);
EXPECT_EQ(t.size(), size - i - 1);
for (int64_t j = i + 1; j < size; ++j) {
EXPECT_THAT(*t.find(j), j);
}
}
EXPECT_TRUE(t.empty());
}
}
TYPED_TEST(SooTest, InsertWithinCapacity) {
TypeParam t;
t.reserve(10);
const size_t original_capacity = t.capacity();
const auto addr = [&](int i) {
return reinterpret_cast<uintptr_t>(&*t.find(i));
};
t.insert(0);
EXPECT_THAT(t.capacity(), original_capacity);
const uintptr_t original_addr_0 = addr(0);
t.insert(1);
EXPECT_THAT(t.capacity(), original_capacity);
EXPECT_THAT(addr(0), original_addr_0);
for (int i = 0; i < 100; ++i) {
t.insert(i % 10);
}
EXPECT_THAT(t.capacity(), original_capacity);
EXPECT_THAT(addr(0), original_addr_0);
std::vector<int> dup_range;
for (int i = 0; i < 100; ++i) {
dup_range.push_back(i % 10);
}
t.insert(dup_range.begin(), dup_range.end());
EXPECT_THAT(t.capacity(), original_capacity);
EXPECT_THAT(addr(0), original_addr_0);
}
template <class TableType>
class SmallTableResizeTest : public testing::Test {};
using SmallTableTypes =
::testing::Types<IntTable, TransferableIntTable, SooIntTable>;
TYPED_TEST_SUITE(SmallTableResizeTest, SmallTableTypes);
TYPED_TEST(SmallTableResizeTest, InsertIntoSmallTable) {
TypeParam t;
for (int i = 0; i < 32; ++i) {
t.insert(i);
ASSERT_EQ(t.size(), i + 1);
for (int j = 0; j < i + 1; ++j) {
EXPECT_TRUE(t.find(j) != t.end());
EXPECT_EQ(*t.find(j), j);
}
}
}
TYPED_TEST(SmallTableResizeTest, ResizeGrowSmallTables) {
for (size_t source_size = 0; source_size < 32; ++source_size) {
for (size_t target_size = source_size; target_size < 32; ++target_size) {
for (bool rehash : {false, true}) {
TypeParam t;
for (size_t i = 0; i < source_size; ++i) {
t.insert(static_cast<int>(i));
}
if (rehash) {
t.rehash(target_size);
} else {
t.reserve(target_size);
}
for (size_t i = 0; i < source_size; ++i) {
EXPECT_TRUE(t.find(static_cast<int>(i)) != t.end());
EXPECT_EQ(*t.find(static_cast<int>(i)), static_cast<int>(i));
}
}
}
}
}
TYPED_TEST(SmallTableResizeTest, ResizeReduceSmallTable |
2,508 | cpp | abseil/abseil-cpp | hashtablez_sampler | absl/container/internal/hashtablez_sampler.cc | absl/container/internal/hashtablez_sampler_test.cc | #ifndef ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
#define ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/per_thread_tls.h"
#include "absl/base/optimization.h"
#include "absl/base/thread_annotations.h"
#include "absl/profiling/internal/sample_recorder.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/utility/utility.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace container_internal {
struct HashtablezInfo : public profiling_internal::Sample<HashtablezInfo> {
HashtablezInfo();
~HashtablezInfo();
HashtablezInfo(const HashtablezInfo&) = delete;
HashtablezInfo& operator=(const HashtablezInfo&) = delete;
void PrepareForSampling(int64_t stride, size_t inline_element_size_value,
size_t key_size, size_t value_size,
uint16_t soo_capacity_value)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(init_mu);
std::atomic<size_t> capacity;
std::atomic<size_t> size;
std::atomic<size_t> num_erases;
std::atomic<size_t> num_rehashes;
std::atomic<size_t> max_probe_length;
std::atomic<size_t> total_probe_length;
std::atomic<size_t> hashes_bitwise_or;
std::atomic<size_t> hashes_bitwise_and;
std::atomic<size_t> hashes_bitwise_xor;
std::atomic<size_t> max_reserve;
static constexpr int kMaxStackDepth = 64;
absl::Time create_time;
int32_t depth;
uint16_t soo_capacity;
void* stack[kMaxStackDepth];
size_t inline_element_size;
size_t key_size;
size_t value_size;
};
void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length);
void RecordReservationSlow(HashtablezInfo* info, size_t target_capacity);
void RecordClearedReservationSlow(HashtablezInfo* info);
void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
size_t capacity);
void RecordInsertSlow(HashtablezInfo* info, size_t hash,
size_t distance_from_desired);
void RecordEraseSlow(HashtablezInfo* info);
struct SamplingState {
int64_t next_sample;
int64_t sample_stride;
};
HashtablezInfo* SampleSlow(SamplingState& next_sample,
size_t inline_element_size, size_t key_size,
size_t value_size, uint16_t soo_capacity);
void UnsampleSlow(HashtablezInfo* info);
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
#error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
#endif
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
class HashtablezInfoHandle {
public:
explicit HashtablezInfoHandle() : info_(nullptr) {}
explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
void Unregister() {
if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
UnsampleSlow(info_);
}
inline bool IsSampled() const { return ABSL_PREDICT_FALSE(info_ != nullptr); }
inline void RecordStorageChanged(size_t size, size_t capacity) {
if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
RecordStorageChangedSlow(info_, size, capacity);
}
inline void RecordRehash(size_t total_probe_length) {
if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
RecordRehashSlow(info_, total_probe_length);
}
inline void RecordReservation(size_t target_capacity) {
if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
RecordReservationSlow(info_, target_capacity);
}
inline void RecordClearedReservation() {
if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
RecordClearedReservationSlow(info_);
}
inline void RecordInsert(size_t hash, size_t distance_from_desired) {
if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
RecordInsertSlow(info_, hash, distance_from_desired);
}
inline void RecordErase() {
if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
RecordEraseSlow(info_);
}
friend inline void swap(HashtablezInfoHandle& lhs,
HashtablezInfoHandle& rhs) {
std::swap(lhs.info_, rhs.info_);
}
private:
friend class HashtablezInfoHandlePeer;
HashtablezInfo* info_;
};
#else
class HashtablezInfoHandle {
public:
explicit HashtablezInfoHandle() = default;
explicit HashtablezInfoHandle(std::nullptr_t) {}
inline void Unregister() {}
inline bool IsSampled() const { return false; }
inline void RecordStorageChanged(size_t , size_t ) {}
inline void RecordRehash(size_t ) {}
inline void RecordReservation(size_t ) {}
inline void RecordClearedReservation() {}
inline void RecordInsert(size_t , size_t ) {}
inline void RecordErase() {}
friend inline void swap(HashtablezInfoHandle& ,
HashtablezInfoHandle& ) {}
};
#endif
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
extern ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample;
#endif
inline HashtablezInfoHandle Sample(
ABSL_ATTRIBUTE_UNUSED size_t inline_element_size,
ABSL_ATTRIBUTE_UNUSED size_t key_size,
ABSL_ATTRIBUTE_UNUSED size_t value_size,
ABSL_ATTRIBUTE_UNUSED uint16_t soo_capacity) {
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
if (ABSL_PREDICT_TRUE(--global_next_sample.next_sample > 0)) {
return HashtablezInfoHandle(nullptr);
}
return HashtablezInfoHandle(SampleSlow(global_next_sample,
inline_element_size, key_size,
value_size, soo_capacity));
#else
return HashtablezInfoHandle(nullptr);
#endif
}
using HashtablezSampler =
::absl::profiling_internal::SampleRecorder<HashtablezInfo>;
HashtablezSampler& GlobalHashtablezSampler();
using HashtablezConfigListener = void (*)();
void SetHashtablezConfigListener(HashtablezConfigListener l);
bool IsHashtablezEnabled();
void SetHashtablezEnabled(bool enabled);
void SetHashtablezEnabledInternal(bool enabled);
int32_t GetHashtablezSampleParameter();
void SetHashtablezSampleParameter(int32_t rate);
void SetHashtablezSampleParameterInternal(int32_t rate);
size_t GetHashtablezMaxSamples();
void SetHashtablezMaxSamples(size_t max);
void SetHashtablezMaxSamplesInternal(size_t max);
extern "C" bool ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)();
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/container/internal/hashtablez_sampler.h"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/per_thread_tls.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/macros.h"
#include "absl/base/no_destructor.h"
#include "absl/base/optimization.h"
#include "absl/debugging/stacktrace.h"
#include "absl/memory/memory.h"
#include "absl/profiling/internal/exponential_biased.h"
#include "absl/profiling/internal/sample_recorder.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/utility/utility.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace container_internal {
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr int HashtablezInfo::kMaxStackDepth;
#endif
namespace {
ABSL_CONST_INIT std::atomic<bool> g_hashtablez_enabled{
false
};
ABSL_CONST_INIT std::atomic<int32_t> g_hashtablez_sample_parameter{1 << 10};
std::atomic<HashtablezConfigListener> g_hashtablez_config_listener{nullptr};
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
ABSL_PER_THREAD_TLS_KEYWORD absl::profiling_internal::ExponentialBiased
g_exponential_biased_generator;
#endif
void TriggerHashtablezConfigListener() {
auto* listener = g_hashtablez_config_listener.load(std::memory_order_acquire);
if (listener != nullptr) listener();
}
}
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample = {0, 0};
#endif
HashtablezSampler& GlobalHashtablezSampler() {
static absl::NoDestructor<HashtablezSampler> sampler;
return *sampler;
}
HashtablezInfo::HashtablezInfo() = default;
HashtablezInfo::~HashtablezInfo() = default;
void HashtablezInfo::PrepareForSampling(int64_t stride,
size_t inline_element_size_value,
size_t key_size_value,
size_t value_size_value,
uint16_t soo_capacity_value) {
capacity.store(0, std::memory_order_relaxed);
size.store(0, std::memory_order_relaxed);
num_erases.store(0, std::memory_order_relaxed);
num_rehashes.store(0, std::memory_order_relaxed);
max_probe_length.store(0, std::memory_order_relaxed);
total_probe_length.store(0, std::memory_order_relaxed);
hashes_bitwise_or.store(0, std::memory_order_relaxed);
hashes_bitwise_and.store(~size_t{}, std::memory_order_relaxed);
hashes_bitwise_xor.store(0, std::memory_order_relaxed);
max_reserve.store(0, std::memory_order_relaxed);
create_time = absl::Now();
weight = stride;
depth = absl::GetStackTrace(stack, HashtablezInfo::kMaxStackDepth,
0);
inline_element_size = inline_element_size_value;
key_size = key_size_value;
value_size = value_size_value;
soo_capacity = soo_capacity_value;
}
static bool ShouldForceSampling() {
enum ForceState {
kDontForce,
kForce,
kUninitialized
};
ABSL_CONST_INIT static std::atomic<ForceState> global_state{
kUninitialized};
ForceState state = global_state.load(std::memory_order_relaxed);
if (ABSL_PREDICT_TRUE(state == kDontForce)) return false;
if (state == kUninitialized) {
state = ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)()
? kForce
: kDontForce;
global_state.store(state, std::memory_order_relaxed);
}
return state == kForce;
}
HashtablezInfo* SampleSlow(SamplingState& next_sample,
size_t inline_element_size, size_t key_size,
size_t value_size, uint16_t soo_capacity) {
if (ABSL_PREDICT_FALSE(ShouldForceSampling())) {
next_sample.next_sample = 1;
const int64_t old_stride = exchange(next_sample.sample_stride, 1);
HashtablezInfo* result = GlobalHashtablezSampler().Register(
old_stride, inline_element_size, key_size, value_size, soo_capacity);
return result;
}
#if !defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
next_sample = {
std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max(),
};
return nullptr;
#else
bool first = next_sample.next_sample < 0;
const int64_t next_stride = g_exponential_biased_generator.GetStride(
g_hashtablez_sample_parameter.load(std::memory_order_relaxed));
next_sample.next_sample = next_stride;
const int64_t old_stride = exchange(next_sample.sample_stride, next_stride);
ABSL_ASSERT(next_stride >= 1);
if (!g_hashtablez_enabled.load(std::memory_order_relaxed)) return nullptr;
if (first) {
if (ABSL_PREDICT_TRUE(--next_sample.next_sample > 0)) return nullptr;
return SampleSlow(next_sample, inline_element_size, key_size, value_size,
soo_capacity);
}
return GlobalHashtablezSampler().Register(old_stride, inline_element_size,
key_size, value_size, soo_capacity);
#endif
}
void UnsampleSlow(HashtablezInfo* info) {
GlobalHashtablezSampler().Unregister(info);
}
void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
#ifdef ABSL_INTERNAL_HAVE_SSE2
total_probe_length /= 16;
#else
total_probe_length /= 8;
#endif
info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
info->num_erases.store(0, std::memory_order_relaxed);
info->num_rehashes.store(
1 + info->num_rehashes.load(std::memory_order_relaxed),
std::memory_order_relaxed);
}
void RecordReservationSlow(HashtablezInfo* info, size_t target_capacity) {
info->max_reserve.store(
(std::max)(info->max_reserve.load(std::memory_order_relaxed),
target_capacity),
std::memory_order_relaxed);
}
void RecordClearedReservationSlow(HashtablezInfo* info) {
info->max_reserve.store(0, std::memory_order_relaxed);
}
void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
size_t capacity) {
info->size.store(size, std::memory_order_relaxed);
info->capacity.store(capacity, std::memory_order_relaxed);
if (size == 0) {
info->total_probe_length.store(0, std::memory_order_relaxed);
info->num_erases.store(0, std::memory_order_relaxed);
}
}
void RecordInsertSlow(HashtablezInfo* info, size_t hash,
size_t distance_from_desired) {
size_t probe_length = distance_from_desired;
#ifdef ABSL_INTERNAL_HAVE_SSE2
probe_length /= 16;
#else
probe_length /= 8;
#endif
info->hashes_bitwise_and.fetch_and(hash, std::memory_order_relaxed);
info->hashes_bitwise_or.fetch_or(hash, std::memory_order_relaxed);
info->hashes_bitwise_xor.fetch_xor(hash, std::memory_order_relaxed);
info->max_probe_length.store(
std::max(info->max_probe_length.load(std::memory_order_relaxed),
probe_length),
std::memory_order_relaxed);
info->total_probe_length.fetch_add(probe_length, std::memory_order_relaxed);
info->size.fetch_add(1, std::memory_order_relaxed);
}
void RecordEraseSlow(HashtablezInfo* info) {
info->size.fetch_sub(1, std::memory_order_relaxed);
info->num_erases.store(1 + info->num_erases.load(std::memory_order_relaxed),
std::memory_order_relaxed);
}
void SetHashtablezConfigListener(HashtablezConfigListener l) {
g_hashtablez_config_listener.store(l, std::memory_order_release);
}
bool IsHashtablezEnabled() {
return g_hashtablez_enabled.load(std::memory_order_acquire);
}
void SetHashtablezEnabled(bool enabled) {
SetHashtablezEnabledInternal(enabled);
TriggerHashtablezConfigListener();
}
void SetHashtablezEnabledInternal(bool enabled) {
g_hashtablez_enabled.store(enabled, std::memory_order_release);
}
int32_t GetHashtablezSampleParameter() {
return g_hashtablez_sample_parameter.load(std::memory_order_acquire);
}
void SetHashtablezSampleParameter(int32_t rate) {
SetHashtablezSampleParameterInternal(rate);
TriggerHashtablezConfigListener();
}
void SetHashtablezSampleParameterInternal(int32_t rate) {
if (rate > 0) {
g_hashtablez_sample_parameter.store(rate, std::memory_order_release);
} else {
ABSL_RAW_LOG(ERROR, "Invalid hashtablez sample rate: %lld",
static_cast<long long>(rate));
}
}
size_t GetHashtablezMaxSamples() {
return GlobalHashtablezSampler().GetMaxSamples();
}
void SetHashtablezMaxSamples(size_t max) {
SetHashtablezMaxSamplesInternal(max);
TriggerHashtablezConfigListener();
}
void SetHashtablezMaxSamplesInternal(size_t max) {
if (max > 0) {
GlobalHashtablezSampler().SetMaxSamples(max);
} else {
ABSL_RAW_LOG(ERROR, "Invalid hashtablez max samples: 0");
}
}
}
ABSL_NAMESPACE_END
} | #include "absl/container/internal/hashtablez_sampler.h"
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <random>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/profiling/internal/sample_recorder.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/synchronization/internal/thread_pool.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#ifdef ABSL_INTERNAL_HAVE_SSE2
constexpr int kProbeLength = 16;
#else
constexpr int kProbeLength = 8;
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace container_internal {
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
class HashtablezInfoHandlePeer {
public:
static HashtablezInfo* GetInfo(HashtablezInfoHandle* h) { return h->info_; }
};
#else
class HashtablezInfoHandlePeer {
public:
static HashtablezInfo* GetInfo(HashtablezInfoHandle*) { return nullptr; }
};
#endif
namespace {
using ::absl::synchronization_internal::ThreadPool;
using ::testing::IsEmpty;
using ::testing::UnorderedElementsAre;
std::vector<size_t> GetSizes(HashtablezSampler* s) {
std::vector<size_t> res;
s->Iterate([&](const HashtablezInfo& info) {
res.push_back(info.size.load(std::memory_order_acquire));
});
return res;
}
HashtablezInfo* Register(HashtablezSampler* s, size_t size) {
const int64_t test_stride = 123;
const size_t test_element_size = 17;
const size_t test_key_size = 3;
const size_t test_value_size = 5;
auto* info =
s->Register(test_stride, test_element_size, test_key_size,
test_value_size, 0);
assert(info != nullptr);
info->size.store(size);
return info;
}
TEST(HashtablezInfoTest, PrepareForSampling) {
absl::Time test_start = absl::Now();
const int64_t test_stride = 123;
const size_t test_element_size = 17;
const size_t test_key_size = 15;
const size_t test_value_size = 13;
HashtablezInfo info;
absl::MutexLock l(&info.init_mu);
info.PrepareForSampling(test_stride, test_element_size,
test_key_size,
test_value_size,
1);
EXPECT_EQ(info.capacity.load(), 0);
EXPECT_EQ(info.size.load(), 0);
EXPECT_EQ(info.num_erases.load(), 0);
EXPECT_EQ(info.num_rehashes.load(), 0);
EXPECT_EQ(info.max_probe_length.load(), 0);
EXPECT_EQ(info.total_probe_length.load(), 0);
EXPECT_EQ(info.hashes_bitwise_or.load(), 0);
EXPECT_EQ(info.hashes_bitwise_and.load(), ~size_t{});
EXPECT_EQ(info.hashes_bitwise_xor.load(), 0);
EXPECT_EQ(info.max_reserve.load(), 0);
EXPECT_GE(info.create_time, test_start);
EXPECT_EQ(info.weight, test_stride);
EXPECT_EQ(info.inline_element_size, test_element_size);
EXPECT_EQ(info.key_size, test_key_size);
EXPECT_EQ(info.value_size, test_value_size);
EXPECT_EQ(info.soo_capacity, 1);
info.capacity.store(1, std::memory_order_relaxed);
info.size.store(1, std::memory_order_relaxed);
info.num_erases.store(1, std::memory_order_relaxed);
info.max_probe_length.store(1, std::memory_order_relaxed);
info.total_probe_length.store(1, std::memory_order_relaxed);
info.hashes_bitwise_or.store(1, std::memory_order_relaxed);
info.hashes_bitwise_and.store(1, std::memory_order_relaxed);
info.hashes_bitwise_xor.store(1, std::memory_order_relaxed);
info.max_reserve.store(1, std::memory_order_relaxed);
info.create_time = test_start - absl::Hours(20);
info.PrepareForSampling(test_stride * 2, test_element_size,
test_key_size,
test_value_size,
0);
EXPECT_EQ(info.capacity.load(), 0);
EXPECT_EQ(info.size.load(), 0);
EXPECT_EQ(info.num_erases.load(), 0);
EXPECT_EQ(info.num_rehashes.load(), 0);
EXPECT_EQ(info.max_probe_length.load(), 0);
EXPECT_EQ(info.total_probe_length.load(), 0);
EXPECT_EQ(info.hashes_bitwise_or.load(), 0);
EXPECT_EQ(info.hashes_bitwise_and.load(), ~size_t{});
EXPECT_EQ(info.hashes_bitwise_xor.load(), 0);
EXPECT_EQ(info.max_reserve.load(), 0);
EXPECT_EQ(info.weight, 2 * test_stride);
EXPECT_EQ(info.inline_element_size, test_element_size);
EXPECT_EQ(info.key_size, test_key_size);
EXPECT_EQ(info.value_size, test_value_size);
EXPECT_GE(info.create_time, test_start);
EXPECT_EQ(info.soo_capacity, 0);
}
TEST(HashtablezInfoTest, RecordStorageChanged) {
HashtablezInfo info;
absl::MutexLock l(&info.init_mu);
const int64_t test_stride = 21;
const size_t test_element_size = 19;
const size_t test_key_size = 17;
const size_t test_value_size = 15;
info.PrepareForSampling(test_stride, test_element_size,
test_key_size,
test_value_size,
0);
RecordStorageChangedSlow(&info, 17, 47);
EXPECT_EQ(info.size.load(), 17);
EXPECT_EQ(info.capacity.load(), 47);
RecordStorageChangedSlow(&info, 20, 20);
EXPECT_EQ(info.size.load(), 20);
EXPECT_EQ(info.capacity.load(), 20);
}
TEST(HashtablezInfoTest, RecordInsert) {
HashtablezInfo info;
absl::MutexLock l(&info.init_mu);
const int64_t test_stride = 25;
const size_t test_element_size = 23;
const size_t test_key_size = 21;
const size_t test_value_size = 19;
info.PrepareForSampling(test_stride, test_element_size,
test_key_size,
test_value_size,
0);
EXPECT_EQ(info.max_probe_length.load(), 0);
RecordInsertSlow(&info, 0x0000FF00, 6 * kProbeLength);
EXPECT_EQ(info.max_probe_length.load(), 6);
EXPECT_EQ(info.hashes_bitwise_and.load(), 0x0000FF00);
EXPECT_EQ(info.hashes_bitwise_or.load(), 0x0000FF00);
EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x0000FF00);
RecordInsertSlow(&info, 0x000FF000, 4 * kProbeLength);
EXPECT_EQ(info.max_probe_length.load(), 6);
EXPECT_EQ(info.hashes_bitwise_and.load(), 0x0000F000);
EXPECT_EQ(info.hashes_bitwise_or.load(), 0x000FFF00);
EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x000F0F00);
RecordInsertSlow(&info, 0x00FF0000, 12 * kProbeLength);
EXPECT_EQ(info.max_probe_length.load(), 12);
EXPECT_EQ(info.hashes_bitwise_and.load(), 0x00000000);
EXPECT_EQ(info.hashes_bitwise_or.load(), 0x00FFFF00);
EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x00F00F00);
}
TEST(HashtablezInfoTest, RecordErase) {
const int64_t test_stride = 31;
const size_t test_element_size = 29;
const size_t test_key_size = 27;
const size_t test_value_size = 25;
HashtablezInfo info;
absl::MutexLock l(&info.init_mu);
info.PrepareForSampling(test_stride, test_element_size,
test_key_size,
test_value_size,
1);
EXPECT_EQ(info.num_erases.load(), 0);
EXPECT_EQ(info.size.load(), 0);
RecordInsertSlow(&info, 0x0000FF00, 6 * kProbeLength);
EXPECT_EQ(info.size.load(), 1);
RecordEraseSlow(&info);
EXPECT_EQ(info.size.load(), 0);
EXPECT_EQ(info.num_erases.load(), 1);
EXPECT_EQ(info.inline_element_size, test_element_size);
EXPECT_EQ(info.key_size, test_key_size);
EXPECT_EQ(info.value_size, test_value_size);
EXPECT_EQ(info.soo_capacity, 1);
}
TEST(HashtablezInfoTest, RecordRehash) {
const int64_t test_stride = 33;
const size_t test_element_size = 31;
const size_t test_key_size = 29;
const size_t test_value_size = 27;
HashtablezInfo info;
absl::MutexLock l(&info.init_mu);
info.PrepareForSampling(test_stride, test_element_size,
test_key_size,
test_value_size,
0);
RecordInsertSlow(&info, 0x1, 0);
RecordInsertSlow(&info, 0x2, kProbeLength);
RecordInsertSlow(&info, 0x4, kProbeLength);
RecordInsertSlow(&info, 0x8, 2 * kProbeLength);
EXPECT_EQ(info.size.load(), 4);
EXPECT_EQ(info.total_probe_length.load(), 4);
RecordEraseSlow(&info);
RecordEraseSlow(&info);
EXPECT_EQ(info.size.load(), 2);
EXPECT_EQ(info.total_probe_length.load(), 4);
EXPECT_EQ(info.num_erases.load(), 2);
RecordRehashSlow(&info, 3 * kProbeLength);
EXPECT_EQ(info.size.load(), 2);
EXPECT_EQ(info.total_probe_length.load(), 3);
EXPECT_EQ(info.num_erases.load(), 0);
EXPECT_EQ(info.num_rehashes.load(), 1);
EXPECT_EQ(info.inline_element_size, test_element_size);
EXPECT_EQ(info.key_size, test_key_size);
EXPECT_EQ(info.value_size, test_value_size);
EXPECT_EQ(info.soo_capacity, 0);
}
TEST(HashtablezInfoTest, RecordReservation) {
HashtablezInfo info;
absl::MutexLock l(&info.init_mu);
const int64_t test_stride = 35;
const size_t test_element_size = 33;
const size_t test_key_size = 31;
const size_t test_value_size = 29;
info.PrepareForSampling(test_stride, test_element_size,
test_key_size,
test_value_size,
0);
RecordReservationSlow(&info, 3);
EXPECT_EQ(info.max_reserve.load(), 3);
RecordReservationSlow(&info, 2);
EXPECT_EQ(info.max_reserve.load(), 3);
RecordReservationSlow(&info, 10);
EXPECT_EQ(info.max_reserve.load(), 10);
}
#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
TEST(HashtablezSamplerTest, SmallSampleParameter) {
const size_t test_element_size = 31;
const size_t test_key_size = 33;
const size_t test_value_size = 35;
SetHashtablezEnabled(true);
SetHashtablezSampleParameter(100);
for (int i = 0; i < 1000; ++i) {
SamplingState next_sample = {0, 0};
HashtablezInfo* sample =
SampleSlow(next_sample, test_element_size,
test_key_size, test_value_size,
0);
EXPECT_GT(next_sample.next_sample, 0);
EXPECT_EQ(next_sample.next_sample, next_sample.sample_stride);
EXPECT_NE(sample, nullptr);
UnsampleSlow(sample);
}
}
TEST(HashtablezSamplerTest, LargeSampleParameter) {
const size_t test_element_size = 31;
const size_t test_key_size = 33;
const size_t test_value_size = 35;
SetHashtablezEnabled(true);
SetHashtablezSampleParameter(std::numeric_limits<int32_t>::max());
for (int i = 0; i < 1000; ++i) {
SamplingState next_sample = {0, 0};
HashtablezInfo* sample =
SampleSlow(next_sample, test_element_size,
test_key_size, test_value_size,
0);
EXPECT_GT(next_sample.next_sample, 0);
EXPECT_EQ(next_sample.next_sample, next_sample.sample_stride);
EXPECT_NE(sample, nullptr);
UnsampleSlow(sample);
}
}
TEST(HashtablezSamplerTest, Sample) {
const size_t test_element_size = 31;
const size_t test_key_size = 33;
const size_t test_value_size = 35;
SetHashtablezEnabled(true);
SetHashtablezSampleParameter(100);
int64_t num_sampled = 0;
int64_t total = 0;
double sample_rate = 0.0;
for (int i = 0; i < 1000000; ++i) {
HashtablezInfoHandle h =
Sample(test_element_size,
test_key_size, test_value_size,
0);
++total;
if (h.IsSampled()) {
++num_sampled;
}
sample_rate = static_cast<double>(num_sampled) / total;
if (0.005 < sample_rate && sample_rate < 0.015) break;
}
EXPECT_NEAR(sample_rate, 0.01, 0.005);
}
TEST(HashtablezSamplerTest, Handle) {
auto& sampler = GlobalHashtablezSampler();
const int64_t test_stride = 41;
const size_t test_element_size = 39;
const size_t test_key_size = 37;
const size_t test_value_size = 35;
HashtablezInfoHandle h(sampler.Register(test_stride, test_element_size,
test_key_size,
test_value_size,
0));
auto* info = HashtablezInfoHandlePeer::GetInfo(&h);
info->hashes_bitwise_and.store(0x12345678, std::memory_order_relaxed);
bool found = false;
sampler.Iterate([&](const HashtablezInfo& h) {
if (&h == info) {
EXPECT_EQ(h.weight, test_stride);
EXPECT_EQ(h.hashes_bitwise_and.load(), 0x12345678);
found = true;
}
});
EXPECT_TRUE(found);
h.Unregister();
h = HashtablezInfoHandle();
found = false;
sampler.Iterate([&](const HashtablezInfo& h) {
if (&h == info) {
if (h.hashes_bitwise_and.load() == 0x12345678) {
found = true;
}
}
});
EXPECT_FALSE(found);
}
#endif
TEST(HashtablezSamplerTest, Registration) {
HashtablezSampler sampler;
auto* info1 = Register(&sampler, 1);
EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1));
auto* info2 = Register(&sampler, 2);
EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1, 2));
info1->size.store(3);
EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(3, 2));
sampler.Unregister(info1);
sampler.Unregister(info2);
}
TEST(HashtablezSamplerTest, Unregistration) {
HashtablezSampler sampler;
std::vector<HashtablezInfo*> infos;
for (size_t i = 0; i < 3; ++i) {
infos.push_back(Register(&sampler, i));
}
EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 1, 2));
sampler.Unregister(infos[1]);
EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2));
infos.push_back(Register(&sampler, 3));
infos.push_back(Register(&sampler, 4));
EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 3, 4));
sampler.Unregister(infos[3]);
EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 4));
sampler.Unregister(infos[0]);
sampler.Unregister(infos[2]);
sampler.Unregister(infos[4]);
EXPECT_THAT(GetSizes(&sampler), IsEmpty());
}
TEST(HashtablezSamplerTest, MultiThreaded) {
HashtablezSampler sampler;
Notification stop;
ThreadPool pool(10);
for (int i = 0; i < 10; ++i) {
const int64_t sampling_stride = 11 + i % 3;
const size_t elt_size = 10 + i % 2;
const size_t key_size = 12 + i % 4;
const size_t value_size = 13 + i % 5;
pool.Schedule([&sampler, &stop, sampling_stride, elt_size, key_size,
value_size]() {
std::random_device rd;
std::mt19937 gen(rd());
std::vector<HashtablezInfo*> infoz;
while (!stop.HasBeenNotified()) {
if (infoz.empty()) {
infoz.push_back(sampler.Register(sampling_stride, elt_size,
key_size,
value_size,
0));
}
switch (std::uniform_int_distribution<>(0, 2)(gen)) {
case 0: {
infoz.push_back(sampler.Register(sampling_stride, elt_size,
key_size,
value_size,
0));
break;
}
case 1: {
size_t p =
std::uniform_int_distribution<>(0, infoz.size() - 1)(gen);
HashtablezInfo* info = infoz[p];
infoz[p] = infoz.back();
infoz.pop_back();
EXPECT_EQ(info->weight, sampling_stride);
sampler.Unregister(info);
break;
}
case 2: {
absl::Duration oldest = absl::ZeroDuration();
sampler.Iterate([&](const HashtablezInfo& info) {
oldest = std::max(oldest, absl::Now() - info.create_time);
});
ASSERT_GE(oldest, absl::ZeroDuration());
break;
}
}
}
});
}
absl::SleepFor(absl::Seconds(3));
stop.Notify();
}
TEST(HashtablezSamplerTest, Callback) {
HashtablezSampler sampler;
auto* info1 = Register(&sampler, 1);
auto* info2 = Register(&sampler, 2);
static const HashtablezInfo* expected;
auto callback = [](const HashtablezInfo& info) {
EXPECT_EQ(&info, expected);
};
EXPECT_EQ(sampler.SetDisposeCallback(callback), nullptr);
expected = info1;
sampler.Unregister(info1);
EXPECT_EQ(callback, sampler.SetDisposeCallback(nullptr));
expected = nullptr;
sampler.Unregister(info2);
}
}
}
ABSL_NAMESPACE_END
} |
2,509 | cpp | abseil/abseil-cpp | test_instance_tracker | absl/container/internal/test_instance_tracker.cc | absl/container/internal/test_instance_tracker_test.cc | #ifndef ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
#define ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
#include <cstdlib>
#include <ostream>
#include "absl/types/compare.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace test_internal {
class BaseCountedInstance {
public:
explicit BaseCountedInstance(int x) : value_(x) {
++num_instances_;
++num_live_instances_;
}
BaseCountedInstance(const BaseCountedInstance& x)
: value_(x.value_), is_live_(x.is_live_) {
++num_instances_;
if (is_live_) ++num_live_instances_;
++num_copies_;
}
BaseCountedInstance(BaseCountedInstance&& x)
: value_(x.value_), is_live_(x.is_live_) {
x.is_live_ = false;
++num_instances_;
++num_moves_;
}
~BaseCountedInstance() {
--num_instances_;
if (is_live_) --num_live_instances_;
}
BaseCountedInstance& operator=(const BaseCountedInstance& x) {
value_ = x.value_;
if (is_live_) --num_live_instances_;
is_live_ = x.is_live_;
if (is_live_) ++num_live_instances_;
++num_copies_;
return *this;
}
BaseCountedInstance& operator=(BaseCountedInstance&& x) {
value_ = x.value_;
if (is_live_) --num_live_instances_;
is_live_ = x.is_live_;
x.is_live_ = false;
++num_moves_;
return *this;
}
bool operator==(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ == x.value_;
}
bool operator!=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ != x.value_;
}
bool operator<(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ < x.value_;
}
bool operator>(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ > x.value_;
}
bool operator<=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ <= x.value_;
}
bool operator>=(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ >= x.value_;
}
absl::weak_ordering compare(const BaseCountedInstance& x) const {
++num_comparisons_;
return value_ < x.value_
? absl::weak_ordering::less
: value_ == x.value_ ? absl::weak_ordering::equivalent
: absl::weak_ordering::greater;
}
int value() const {
if (!is_live_) std::abort();
return value_;
}
friend std::ostream& operator<<(std::ostream& o,
const BaseCountedInstance& v) {
return o << "[value:" << v.value() << "]";
}
static void SwapImpl(
BaseCountedInstance& lhs,
BaseCountedInstance& rhs) {
using std::swap;
swap(lhs.value_, rhs.value_);
swap(lhs.is_live_, rhs.is_live_);
++BaseCountedInstance::num_swaps_;
}
private:
friend class InstanceTracker;
int value_;
bool is_live_ = true;
static int num_instances_;
static int num_live_instances_;
static int num_moves_;
static int num_copies_;
static int num_swaps_;
static int num_comparisons_;
};
class InstanceTracker {
public:
InstanceTracker()
: start_instances_(BaseCountedInstance::num_instances_),
start_live_instances_(BaseCountedInstance::num_live_instances_) {
ResetCopiesMovesSwaps();
}
~InstanceTracker() {
if (instances() != 0) std::abort();
if (live_instances() != 0) std::abort();
}
int instances() const {
return BaseCountedInstance::num_instances_ - start_instances_;
}
int live_instances() const {
return BaseCountedInstance::num_live_instances_ - start_live_instances_;
}
int moves() const { return BaseCountedInstance::num_moves_ - start_moves_; }
int copies() const {
return BaseCountedInstance::num_copies_ - start_copies_;
}
int swaps() const { return BaseCountedInstance::num_swaps_ - start_swaps_; }
int comparisons() const {
return BaseCountedInstance::num_comparisons_ - start_comparisons_;
}
void ResetCopiesMovesSwaps() {
start_moves_ = BaseCountedInstance::num_moves_;
start_copies_ = BaseCountedInstance::num_copies_;
start_swaps_ = BaseCountedInstance::num_swaps_;
start_comparisons_ = BaseCountedInstance::num_comparisons_;
}
private:
int start_instances_;
int start_live_instances_;
int start_moves_;
int start_copies_;
int start_swaps_;
int start_comparisons_;
};
class CopyableOnlyInstance : public BaseCountedInstance {
public:
explicit CopyableOnlyInstance(int x) : BaseCountedInstance(x) {}
CopyableOnlyInstance(const CopyableOnlyInstance& rhs) = default;
CopyableOnlyInstance& operator=(const CopyableOnlyInstance& rhs) = default;
friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return false; }
};
class CopyableMovableInstance : public BaseCountedInstance {
public:
explicit CopyableMovableInstance(int x) : BaseCountedInstance(x) {}
CopyableMovableInstance(const CopyableMovableInstance& rhs) = default;
CopyableMovableInstance(CopyableMovableInstance&& rhs) = default;
CopyableMovableInstance& operator=(const CopyableMovableInstance& rhs) =
default;
CopyableMovableInstance& operator=(CopyableMovableInstance&& rhs) = default;
friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return true; }
};
class MovableOnlyInstance : public BaseCountedInstance {
public:
explicit MovableOnlyInstance(int x) : BaseCountedInstance(x) {}
MovableOnlyInstance(MovableOnlyInstance&& other) = default;
MovableOnlyInstance& operator=(MovableOnlyInstance&& other) = default;
friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) {
BaseCountedInstance::SwapImpl(lhs, rhs);
}
static bool supports_move() { return true; }
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/container/internal/test_instance_tracker.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace test_internal {
int BaseCountedInstance::num_instances_ = 0;
int BaseCountedInstance::num_live_instances_ = 0;
int BaseCountedInstance::num_moves_ = 0;
int BaseCountedInstance::num_copies_ = 0;
int BaseCountedInstance::num_swaps_ = 0;
int BaseCountedInstance::num_comparisons_ = 0;
}
ABSL_NAMESPACE_END
} | #include "absl/container/internal/test_instance_tracker.h"
#include "gtest/gtest.h"
namespace {
using absl::test_internal::CopyableMovableInstance;
using absl::test_internal::CopyableOnlyInstance;
using absl::test_internal::InstanceTracker;
using absl::test_internal::MovableOnlyInstance;
TEST(TestInstanceTracker, CopyableMovable) {
InstanceTracker tracker;
CopyableMovableInstance src(1);
EXPECT_EQ(1, src.value()) << src;
CopyableMovableInstance copy(src);
CopyableMovableInstance move(std::move(src));
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
EXPECT_EQ(0, tracker.swaps());
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(2, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
CopyableMovableInstance copy_assign(1);
copy_assign = copy;
CopyableMovableInstance move_assign(1);
move_assign = std::move(move);
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
EXPECT_EQ(0, tracker.swaps());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(3, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
{
using std::swap;
swap(move_assign, copy);
swap(copy, move_assign);
EXPECT_EQ(2, tracker.swaps());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(3, tracker.live_instances());
}
}
TEST(TestInstanceTracker, CopyableOnly) {
InstanceTracker tracker;
CopyableOnlyInstance src(1);
EXPECT_EQ(1, src.value()) << src;
CopyableOnlyInstance copy(src);
CopyableOnlyInstance copy2(std::move(src));
EXPECT_EQ(2, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(3, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
CopyableOnlyInstance copy_assign(1);
copy_assign = copy;
CopyableOnlyInstance copy_assign2(1);
copy_assign2 = std::move(copy2);
EXPECT_EQ(2, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(5, tracker.live_instances());
tracker.ResetCopiesMovesSwaps();
{
using std::swap;
swap(src, copy);
swap(copy, src);
EXPECT_EQ(2, tracker.swaps());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(5, tracker.instances());
EXPECT_EQ(5, tracker.live_instances());
}
}
TEST(TestInstanceTracker, MovableOnly) {
InstanceTracker tracker;
MovableOnlyInstance src(1);
EXPECT_EQ(1, src.value()) << src;
MovableOnlyInstance move(std::move(src));
MovableOnlyInstance move_assign(2);
move_assign = std::move(move);
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(1, tracker.live_instances());
EXPECT_EQ(2, tracker.moves());
EXPECT_EQ(0, tracker.copies());
tracker.ResetCopiesMovesSwaps();
{
using std::swap;
MovableOnlyInstance other(2);
swap(move_assign, other);
swap(other, move_assign);
EXPECT_EQ(2, tracker.swaps());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
EXPECT_EQ(4, tracker.instances());
EXPECT_EQ(2, tracker.live_instances());
}
}
TEST(TestInstanceTracker, ExistingInstances) {
CopyableMovableInstance uncounted_instance(1);
CopyableMovableInstance uncounted_live_instance(
std::move(uncounted_instance));
InstanceTracker tracker;
EXPECT_EQ(0, tracker.instances());
EXPECT_EQ(0, tracker.live_instances());
EXPECT_EQ(0, tracker.copies());
{
CopyableMovableInstance instance1(1);
EXPECT_EQ(1, tracker.instances());
EXPECT_EQ(1, tracker.live_instances());
EXPECT_EQ(0, tracker.copies());
EXPECT_EQ(0, tracker.moves());
{
InstanceTracker tracker2;
CopyableMovableInstance instance2(instance1);
CopyableMovableInstance instance3(std::move(instance2));
EXPECT_EQ(3, tracker.instances());
EXPECT_EQ(2, tracker.live_instances());
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
EXPECT_EQ(2, tracker2.instances());
EXPECT_EQ(1, tracker2.live_instances());
EXPECT_EQ(1, tracker2.copies());
EXPECT_EQ(1, tracker2.moves());
}
EXPECT_EQ(1, tracker.instances());
EXPECT_EQ(1, tracker.live_instances());
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
}
EXPECT_EQ(0, tracker.instances());
EXPECT_EQ(0, tracker.live_instances());
EXPECT_EQ(1, tracker.copies());
EXPECT_EQ(1, tracker.moves());
}
TEST(TestInstanceTracker, Comparisons) {
InstanceTracker tracker;
MovableOnlyInstance one(1), two(2);
EXPECT_EQ(0, tracker.comparisons());
EXPECT_FALSE(one == two);
EXPECT_EQ(1, tracker.comparisons());
EXPECT_TRUE(one != two);
EXPECT_EQ(2, tracker.comparisons());
EXPECT_TRUE(one < two);
EXPECT_EQ(3, tracker.comparisons());
EXPECT_FALSE(one > two);
EXPECT_EQ(4, tracker.comparisons());
EXPECT_TRUE(one <= two);
EXPECT_EQ(5, tracker.comparisons());
EXPECT_FALSE(one >= two);
EXPECT_EQ(6, tracker.comparisons());
EXPECT_TRUE(one.compare(two) < 0);
EXPECT_EQ(7, tracker.comparisons());
tracker.ResetCopiesMovesSwaps();
EXPECT_EQ(0, tracker.comparisons());
}
} |
2,510 | cpp | abseil/abseil-cpp | log_severity | absl/base/log_severity.cc | absl/base/log_severity_test.cc | #ifndef ABSL_BASE_LOG_SEVERITY_H_
#define ABSL_BASE_LOG_SEVERITY_H_
#include <array>
#include <ostream>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
enum class LogSeverity : int {
kInfo = 0,
kWarning = 1,
kError = 2,
kFatal = 3,
};
constexpr std::array<absl::LogSeverity, 4> LogSeverities() {
return {{absl::LogSeverity::kInfo, absl::LogSeverity::kWarning,
absl::LogSeverity::kError, absl::LogSeverity::kFatal}};
}
#ifdef NDEBUG
static constexpr absl::LogSeverity kLogDebugFatal = absl::LogSeverity::kError;
#else
static constexpr absl::LogSeverity kLogDebugFatal = absl::LogSeverity::kFatal;
#endif
constexpr const char* LogSeverityName(absl::LogSeverity s) {
switch (s) {
case absl::LogSeverity::kInfo: return "INFO";
case absl::LogSeverity::kWarning: return "WARNING";
case absl::LogSeverity::kError: return "ERROR";
case absl::LogSeverity::kFatal: return "FATAL";
}
return "UNKNOWN";
}
constexpr absl::LogSeverity NormalizeLogSeverity(absl::LogSeverity s) {
absl::LogSeverity n = s;
if (n < absl::LogSeverity::kInfo) n = absl::LogSeverity::kInfo;
if (n > absl::LogSeverity::kFatal) n = absl::LogSeverity::kError;
return n;
}
constexpr absl::LogSeverity NormalizeLogSeverity(int s) {
return absl::NormalizeLogSeverity(static_cast<absl::LogSeverity>(s));
}
std::ostream& operator<<(std::ostream& os, absl::LogSeverity s);
enum class LogSeverityAtLeast : int {
kInfo = static_cast<int>(absl::LogSeverity::kInfo),
kWarning = static_cast<int>(absl::LogSeverity::kWarning),
kError = static_cast<int>(absl::LogSeverity::kError),
kFatal = static_cast<int>(absl::LogSeverity::kFatal),
kInfinity = 1000,
};
std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtLeast s);
enum class LogSeverityAtMost : int {
kNegativeInfinity = -1000,
kInfo = static_cast<int>(absl::LogSeverity::kInfo),
kWarning = static_cast<int>(absl::LogSeverity::kWarning),
kError = static_cast<int>(absl::LogSeverity::kError),
kFatal = static_cast<int>(absl::LogSeverity::kFatal),
};
std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtMost s);
#define COMPOP(op1, op2, T) \
constexpr bool operator op1(absl::T lhs, absl::LogSeverity rhs) { \
return static_cast<absl::LogSeverity>(lhs) op1 rhs; \
} \
constexpr bool operator op2(absl::LogSeverity lhs, absl::T rhs) { \
return lhs op2 static_cast<absl::LogSeverity>(rhs); \
}
COMPOP(>, <, LogSeverityAtLeast)
COMPOP(<=, >=, LogSeverityAtLeast)
COMPOP(<, >, LogSeverityAtMost)
COMPOP(>=, <=, LogSeverityAtMost)
#undef COMPOP
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/log_severity.h"
#include <ostream>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
std::ostream& operator<<(std::ostream& os, absl::LogSeverity s) {
if (s == absl::NormalizeLogSeverity(s)) return os << absl::LogSeverityName(s);
return os << "absl::LogSeverity(" << static_cast<int>(s) << ")";
}
std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtLeast s) {
switch (s) {
case absl::LogSeverityAtLeast::kInfo:
case absl::LogSeverityAtLeast::kWarning:
case absl::LogSeverityAtLeast::kError:
case absl::LogSeverityAtLeast::kFatal:
return os << ">=" << static_cast<absl::LogSeverity>(s);
case absl::LogSeverityAtLeast::kInfinity:
return os << "INFINITY";
}
return os;
}
std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtMost s) {
switch (s) {
case absl::LogSeverityAtMost::kInfo:
case absl::LogSeverityAtMost::kWarning:
case absl::LogSeverityAtMost::kError:
case absl::LogSeverityAtMost::kFatal:
return os << "<=" << static_cast<absl::LogSeverity>(s);
case absl::LogSeverityAtMost::kNegativeInfinity:
return os << "NEGATIVE_INFINITY";
}
return os;
}
ABSL_NAMESPACE_END
} | #include "absl/base/log_severity.h"
#include <cstdint>
#include <ios>
#include <limits>
#include <ostream>
#include <sstream>
#include <string>
#include <tuple>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/flags/internal/flag.h"
#include "absl/flags/marshalling.h"
#include "absl/strings/str_cat.h"
namespace {
using ::testing::Eq;
using ::testing::IsFalse;
using ::testing::IsTrue;
using ::testing::TestWithParam;
using ::testing::Values;
template <typename T>
std::string StreamHelper(T value) {
std::ostringstream stream;
stream << value;
return stream.str();
}
TEST(StreamTest, Works) {
EXPECT_THAT(StreamHelper(static_cast<absl::LogSeverity>(-100)),
Eq("absl::LogSeverity(-100)"));
EXPECT_THAT(StreamHelper(absl::LogSeverity::kInfo), Eq("INFO"));
EXPECT_THAT(StreamHelper(absl::LogSeverity::kWarning), Eq("WARNING"));
EXPECT_THAT(StreamHelper(absl::LogSeverity::kError), Eq("ERROR"));
EXPECT_THAT(StreamHelper(absl::LogSeverity::kFatal), Eq("FATAL"));
EXPECT_THAT(StreamHelper(static_cast<absl::LogSeverity>(4)),
Eq("absl::LogSeverity(4)"));
}
static_assert(absl::flags_internal::FlagUseValueAndInitBitStorage<
absl::LogSeverity>::value,
"Flags of type absl::LogSeverity ought to be lock-free.");
using ParseFlagFromOutOfRangeIntegerTest = TestWithParam<int64_t>;
INSTANTIATE_TEST_SUITE_P(
Instantiation, ParseFlagFromOutOfRangeIntegerTest,
Values(static_cast<int64_t>(std::numeric_limits<int>::min()) - 1,
static_cast<int64_t>(std::numeric_limits<int>::max()) + 1));
TEST_P(ParseFlagFromOutOfRangeIntegerTest, ReturnsError) {
const std::string to_parse = absl::StrCat(GetParam());
absl::LogSeverity value;
std::string error;
EXPECT_THAT(absl::ParseFlag(to_parse, &value, &error), IsFalse()) << value;
}
using ParseFlagFromAlmostOutOfRangeIntegerTest = TestWithParam<int>;
INSTANTIATE_TEST_SUITE_P(Instantiation,
ParseFlagFromAlmostOutOfRangeIntegerTest,
Values(std::numeric_limits<int>::min(),
std::numeric_limits<int>::max()));
TEST_P(ParseFlagFromAlmostOutOfRangeIntegerTest, YieldsExpectedValue) {
const auto expected = static_cast<absl::LogSeverity>(GetParam());
const std::string to_parse = absl::StrCat(GetParam());
absl::LogSeverity value;
std::string error;
ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
EXPECT_THAT(value, Eq(expected));
}
using ParseFlagFromIntegerMatchingEnumeratorTest =
TestWithParam<std::tuple<absl::string_view, absl::LogSeverity>>;
INSTANTIATE_TEST_SUITE_P(
Instantiation, ParseFlagFromIntegerMatchingEnumeratorTest,
Values(std::make_tuple("0", absl::LogSeverity::kInfo),
std::make_tuple(" 0", absl::LogSeverity::kInfo),
std::make_tuple("-0", absl::LogSeverity::kInfo),
std::make_tuple("+0", absl::LogSeverity::kInfo),
std::make_tuple("00", absl::LogSeverity::kInfo),
std::make_tuple("0 ", absl::LogSeverity::kInfo),
std::make_tuple("0x0", absl::LogSeverity::kInfo),
std::make_tuple("1", absl::LogSeverity::kWarning),
std::make_tuple("+1", absl::LogSeverity::kWarning),
std::make_tuple("2", absl::LogSeverity::kError),
std::make_tuple("3", absl::LogSeverity::kFatal)));
TEST_P(ParseFlagFromIntegerMatchingEnumeratorTest, YieldsExpectedValue) {
const absl::string_view to_parse = std::get<0>(GetParam());
const absl::LogSeverity expected = std::get<1>(GetParam());
absl::LogSeverity value;
std::string error;
ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
EXPECT_THAT(value, Eq(expected));
}
using ParseFlagFromOtherIntegerTest =
TestWithParam<std::tuple<absl::string_view, int>>;
INSTANTIATE_TEST_SUITE_P(Instantiation, ParseFlagFromOtherIntegerTest,
Values(std::make_tuple("-1", -1),
std::make_tuple("4", 4),
std::make_tuple("010", 10),
std::make_tuple("0x10", 16)));
TEST_P(ParseFlagFromOtherIntegerTest, YieldsExpectedValue) {
const absl::string_view to_parse = std::get<0>(GetParam());
const auto expected = static_cast<absl::LogSeverity>(std::get<1>(GetParam()));
absl::LogSeverity value;
std::string error;
ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
EXPECT_THAT(value, Eq(expected));
}
using ParseFlagFromEnumeratorTest =
TestWithParam<std::tuple<absl::string_view, absl::LogSeverity>>;
INSTANTIATE_TEST_SUITE_P(
Instantiation, ParseFlagFromEnumeratorTest,
Values(std::make_tuple("INFO", absl::LogSeverity::kInfo),
std::make_tuple("info", absl::LogSeverity::kInfo),
std::make_tuple("kInfo", absl::LogSeverity::kInfo),
std::make_tuple("iNfO", absl::LogSeverity::kInfo),
std::make_tuple("kInFo", absl::LogSeverity::kInfo),
std::make_tuple("WARNING", absl::LogSeverity::kWarning),
std::make_tuple("warning", absl::LogSeverity::kWarning),
std::make_tuple("kWarning", absl::LogSeverity::kWarning),
std::make_tuple("WaRnInG", absl::LogSeverity::kWarning),
std::make_tuple("KwArNiNg", absl::LogSeverity::kWarning),
std::make_tuple("ERROR", absl::LogSeverity::kError),
std::make_tuple("error", absl::LogSeverity::kError),
std::make_tuple("kError", absl::LogSeverity::kError),
std::make_tuple("eRrOr", absl::LogSeverity::kError),
std::make_tuple("kErRoR", absl::LogSeverity::kError),
std::make_tuple("FATAL", absl::LogSeverity::kFatal),
std::make_tuple("fatal", absl::LogSeverity::kFatal),
std::make_tuple("kFatal", absl::LogSeverity::kFatal),
std::make_tuple("FaTaL", absl::LogSeverity::kFatal),
std::make_tuple("KfAtAl", absl::LogSeverity::kFatal),
std::make_tuple("DFATAL", absl::kLogDebugFatal),
std::make_tuple("dfatal", absl::kLogDebugFatal),
std::make_tuple("kLogDebugFatal", absl::kLogDebugFatal),
std::make_tuple("dFaTaL", absl::kLogDebugFatal),
std::make_tuple("kLoGdEbUgFaTaL", absl::kLogDebugFatal)));
TEST_P(ParseFlagFromEnumeratorTest, YieldsExpectedValue) {
const absl::string_view to_parse = std::get<0>(GetParam());
const absl::LogSeverity expected = std::get<1>(GetParam());
absl::LogSeverity value;
std::string error;
ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
EXPECT_THAT(value, Eq(expected));
}
using ParseFlagFromGarbageTest = TestWithParam<absl::string_view>;
INSTANTIATE_TEST_SUITE_P(Instantiation, ParseFlagFromGarbageTest,
Values("", "\0", " ", "garbage", "kkinfo", "I",
"kDFATAL", "LogDebugFatal", "lOgDeBuGfAtAl"));
TEST_P(ParseFlagFromGarbageTest, ReturnsError) {
const absl::string_view to_parse = GetParam();
absl::LogSeverity value;
std::string error;
EXPECT_THAT(absl::ParseFlag(to_parse, &value, &error), IsFalse()) << value;
}
using UnparseFlagToEnumeratorTest =
TestWithParam<std::tuple<absl::LogSeverity, absl::string_view>>;
INSTANTIATE_TEST_SUITE_P(
Instantiation, UnparseFlagToEnumeratorTest,
Values(std::make_tuple(absl::LogSeverity::kInfo, "INFO"),
std::make_tuple(absl::LogSeverity::kWarning, "WARNING"),
std::make_tuple(absl::LogSeverity::kError, "ERROR"),
std::make_tuple(absl::LogSeverity::kFatal, "FATAL")));
TEST_P(UnparseFlagToEnumeratorTest, ReturnsExpectedValueAndRoundTrips) {
const absl::LogSeverity to_unparse = std::get<0>(GetParam());
const absl::string_view expected = std::get<1>(GetParam());
const std::string stringified_value = absl::UnparseFlag(to_unparse);
EXPECT_THAT(stringified_value, Eq(expected));
absl::LogSeverity reparsed_value;
std::string error;
EXPECT_THAT(absl::ParseFlag(stringified_value, &reparsed_value, &error),
IsTrue());
EXPECT_THAT(reparsed_value, Eq(to_unparse));
}
using UnparseFlagToOtherIntegerTest = TestWithParam<int>;
INSTANTIATE_TEST_SUITE_P(Instantiation, UnparseFlagToOtherIntegerTest,
Values(std::numeric_limits<int>::min(), -1, 4,
std::numeric_limits<int>::max()));
TEST_P(UnparseFlagToOtherIntegerTest, ReturnsExpectedValueAndRoundTrips) {
const absl::LogSeverity to_unparse =
static_cast<absl::LogSeverity>(GetParam());
const std::string expected = absl::StrCat(GetParam());
const std::string stringified_value = absl::UnparseFlag(to_unparse);
EXPECT_THAT(stringified_value, Eq(expected));
absl::LogSeverity reparsed_value;
std::string error;
EXPECT_THAT(absl::ParseFlag(stringified_value, &reparsed_value, &error),
IsTrue());
EXPECT_THAT(reparsed_value, Eq(to_unparse));
}
TEST(LogThresholdTest, LogSeverityAtLeastTest) {
EXPECT_LT(absl::LogSeverity::kError, absl::LogSeverityAtLeast::kFatal);
EXPECT_GT(absl::LogSeverityAtLeast::kError, absl::LogSeverity::kInfo);
EXPECT_LE(absl::LogSeverityAtLeast::kInfo, absl::LogSeverity::kError);
EXPECT_GE(absl::LogSeverity::kError, absl::LogSeverityAtLeast::kInfo);
}
TEST(LogThresholdTest, LogSeverityAtMostTest) {
EXPECT_GT(absl::LogSeverity::kError, absl::LogSeverityAtMost::kWarning);
EXPECT_LT(absl::LogSeverityAtMost::kError, absl::LogSeverity::kFatal);
EXPECT_GE(absl::LogSeverityAtMost::kFatal, absl::LogSeverity::kError);
EXPECT_LE(absl::LogSeverity::kWarning, absl::LogSeverityAtMost::kError);
}
TEST(LogThresholdTest, Extremes) {
EXPECT_LT(absl::LogSeverity::kFatal, absl::LogSeverityAtLeast::kInfinity);
EXPECT_GT(absl::LogSeverity::kInfo,
absl::LogSeverityAtMost::kNegativeInfinity);
}
TEST(LogThresholdTest, Output) {
EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kInfo), Eq(">=INFO"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kWarning),
Eq(">=WARNING"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kError), Eq(">=ERROR"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kFatal), Eq(">=FATAL"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kInfinity),
Eq("INFINITY"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kInfo), Eq("<=INFO"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kWarning), Eq("<=WARNING"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kError), Eq("<=ERROR"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kFatal), Eq("<=FATAL"));
EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kNegativeInfinity),
Eq("NEGATIVE_INFINITY"));
}
} |
2,511 | cpp | abseil/abseil-cpp | strerror | absl/base/internal/strerror.cc | absl/base/internal/strerror_test.cc | #ifndef ABSL_BASE_INTERNAL_STRERROR_H_
#define ABSL_BASE_INTERNAL_STRERROR_H_
#include <string>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
std::string StrError(int errnum);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/strerror.h"
#include <array>
#include <cerrno>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <string>
#include <type_traits>
#include "absl/base/internal/errno_saver.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
const char* StrErrorAdaptor(int errnum, char* buf, size_t buflen) {
#if defined(_WIN32)
int rc = strerror_s(buf, buflen, errnum);
buf[buflen - 1] = '\0';
if (rc == 0 && strncmp(buf, "Unknown error", buflen) == 0) *buf = '\0';
return buf;
#else
auto ret = strerror_r(errnum, buf, buflen);
if (std::is_same<decltype(ret), int>::value) {
if (ret) *buf = '\0';
return buf;
} else {
return reinterpret_cast<const char*>(ret);
}
#endif
}
std::string StrErrorInternal(int errnum) {
char buf[100];
const char* str = StrErrorAdaptor(errnum, buf, sizeof buf);
if (*str == '\0') {
snprintf(buf, sizeof buf, "Unknown error %d", errnum);
str = buf;
}
return str;
}
constexpr int kSysNerr = 135;
std::array<std::string, kSysNerr>* NewStrErrorTable() {
auto* table = new std::array<std::string, kSysNerr>;
for (size_t i = 0; i < table->size(); ++i) {
(*table)[i] = StrErrorInternal(static_cast<int>(i));
}
return table;
}
}
std::string StrError(int errnum) {
absl::base_internal::ErrnoSaver errno_saver;
static const auto* table = NewStrErrorTable();
if (errnum >= 0 && static_cast<size_t>(errnum) < table->size()) {
return (*table)[static_cast<size_t>(errnum)];
}
return StrErrorInternal(errnum);
}
}
ABSL_NAMESPACE_END
} | #include "absl/base/internal/strerror.h"
#include <atomic>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <string>
#include <thread>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/match.h"
namespace {
using ::testing::AnyOf;
using ::testing::Eq;
TEST(StrErrorTest, ValidErrorCode) {
errno = ERANGE;
EXPECT_THAT(absl::base_internal::StrError(EDOM), Eq(strerror(EDOM)));
EXPECT_THAT(errno, Eq(ERANGE));
}
TEST(StrErrorTest, InvalidErrorCode) {
errno = ERANGE;
EXPECT_THAT(absl::base_internal::StrError(-1),
AnyOf(Eq("No error information"), Eq("Unknown error -1")));
EXPECT_THAT(errno, Eq(ERANGE));
}
TEST(StrErrorTest, MultipleThreads) {
const int kNumCodes = 1000;
std::vector<std::string> expected_strings(kNumCodes);
for (int i = 0; i < kNumCodes; ++i) {
expected_strings[i] = strerror(i);
}
std::atomic_int counter(0);
auto thread_fun = [&]() {
for (int i = 0; i < kNumCodes; ++i) {
++counter;
errno = ERANGE;
const std::string value = absl::base_internal::StrError(i);
int check_err = errno;
EXPECT_THAT(check_err, Eq(ERANGE));
if (!absl::StartsWith(value, "Unknown error ")) {
EXPECT_THAT(value, Eq(expected_strings[i]));
}
}
};
const int kNumThreads = 100;
std::vector<std::thread> threads;
for (int i = 0; i < kNumThreads; ++i) {
threads.push_back(std::thread(thread_fun));
}
for (auto& thread : threads) {
thread.join();
}
EXPECT_THAT(counter, Eq(kNumThreads * kNumCodes));
}
} |
2,512 | cpp | abseil/abseil-cpp | exception_safety_testing | absl/base/internal/exception_safety_testing.cc | absl/base/exception_safety_testing_test.cc | #ifndef ABSL_BASE_INTERNAL_EXCEPTION_SAFETY_TESTING_H_
#define ABSL_BASE_INTERNAL_EXCEPTION_SAFETY_TESTING_H_
#include "absl/base/config.h"
#ifdef ABSL_HAVE_EXCEPTIONS
#include <cstddef>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <iosfwd>
#include <string>
#include <tuple>
#include <unordered_map>
#include "gtest/gtest.h"
#include "absl/base/internal/pretty_function.h"
#include "absl/memory/memory.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/string_view.h"
#include "absl/strings/substitute.h"
#include "absl/utility/utility.h"
namespace testing {
enum class TypeSpec;
enum class AllocSpec;
constexpr TypeSpec operator|(TypeSpec a, TypeSpec b) {
using T = absl::underlying_type_t<TypeSpec>;
return static_cast<TypeSpec>(static_cast<T>(a) | static_cast<T>(b));
}
constexpr TypeSpec operator&(TypeSpec a, TypeSpec b) {
using T = absl::underlying_type_t<TypeSpec>;
return static_cast<TypeSpec>(static_cast<T>(a) & static_cast<T>(b));
}
constexpr AllocSpec operator|(AllocSpec a, AllocSpec b) {
using T = absl::underlying_type_t<AllocSpec>;
return static_cast<AllocSpec>(static_cast<T>(a) | static_cast<T>(b));
}
constexpr AllocSpec operator&(AllocSpec a, AllocSpec b) {
using T = absl::underlying_type_t<AllocSpec>;
return static_cast<AllocSpec>(static_cast<T>(a) & static_cast<T>(b));
}
namespace exceptions_internal {
std::string GetSpecString(TypeSpec);
std::string GetSpecString(AllocSpec);
struct NoThrowTag {};
struct StrongGuaranteeTagType {};
class TestException {
public:
explicit TestException(absl::string_view msg) : msg_(msg) {}
virtual ~TestException() {}
virtual const char* what() const noexcept { return msg_.c_str(); }
private:
std::string msg_;
};
class TestBadAllocException : public std::bad_alloc, public TestException {
public:
explicit TestBadAllocException(absl::string_view msg) : TestException(msg) {}
using TestException::what;
};
extern int countdown;
inline void SetCountdown(int i = 0) { countdown = i; }
inline void UnsetCountdown() { SetCountdown(-1); }
void MaybeThrow(absl::string_view msg, bool throw_bad_alloc = false);
testing::AssertionResult FailureMessage(const TestException& e,
int countdown) noexcept;
struct TrackedAddress {
bool is_alive;
std::string description;
};
class ConstructorTracker {
public:
explicit ConstructorTracker(int count) : countdown_(count) {
assert(current_tracker_instance_ == nullptr);
current_tracker_instance_ = this;
}
~ConstructorTracker() {
assert(current_tracker_instance_ == this);
current_tracker_instance_ = nullptr;
for (auto& it : address_map_) {
void* address = it.first;
TrackedAddress& tracked_address = it.second;
if (tracked_address.is_alive) {
ADD_FAILURE() << ErrorMessage(address, tracked_address.description,
countdown_, "Object was not destroyed.");
}
}
}
static void ObjectConstructed(void* address, std::string description) {
if (!CurrentlyTracking()) return;
TrackedAddress& tracked_address =
current_tracker_instance_->address_map_[address];
if (tracked_address.is_alive) {
ADD_FAILURE() << ErrorMessage(
address, tracked_address.description,
current_tracker_instance_->countdown_,
"Object was re-constructed. Current object was constructed by " +
description);
}
tracked_address = {true, std::move(description)};
}
static void ObjectDestructed(void* address) {
if (!CurrentlyTracking()) return;
auto it = current_tracker_instance_->address_map_.find(address);
if (it == current_tracker_instance_->address_map_.end()) return;
TrackedAddress& tracked_address = it->second;
if (!tracked_address.is_alive) {
ADD_FAILURE() << ErrorMessage(address, tracked_address.description,
current_tracker_instance_->countdown_,
"Object was re-destroyed.");
}
tracked_address.is_alive = false;
}
private:
static bool CurrentlyTracking() {
return current_tracker_instance_ != nullptr;
}
static std::string ErrorMessage(void* address,
const std::string& address_description,
int countdown,
const std::string& error_description) {
return absl::Substitute(
"With coundtown at $0:\n"
" $1\n"
" Object originally constructed by $2\n"
" Object address: $3\n",
countdown, error_description, address_description, address);
}
std::unordered_map<void*, TrackedAddress> address_map_;
int countdown_;
static ConstructorTracker* current_tracker_instance_;
};
class TrackedObject {
public:
TrackedObject(const TrackedObject&) = delete;
TrackedObject(TrackedObject&&) = delete;
protected:
explicit TrackedObject(std::string description) {
ConstructorTracker::ObjectConstructed(this, std::move(description));
}
~TrackedObject() noexcept { ConstructorTracker::ObjectDestructed(this); }
};
}
extern exceptions_internal::NoThrowTag nothrow_ctor;
extern exceptions_internal::StrongGuaranteeTagType strong_guarantee;
class ThrowingBool {
public:
ThrowingBool(bool b) noexcept : b_(b) {}
operator bool() const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return b_;
}
private:
bool b_;
};
enum class TypeSpec {
kEverythingThrows = 0,
kNoThrowCopy = 1,
kNoThrowMove = 1 << 1,
kNoThrowNew = 1 << 2,
};
template <TypeSpec Spec = TypeSpec::kEverythingThrows>
class ThrowingValue : private exceptions_internal::TrackedObject {
static constexpr bool IsSpecified(TypeSpec spec) {
return static_cast<bool>(Spec & spec);
}
static constexpr int kDefaultValue = 0;
static constexpr int kBadValue = 938550620;
public:
ThrowingValue() : TrackedObject(GetInstanceString(kDefaultValue)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ = kDefaultValue;
}
ThrowingValue(const ThrowingValue& other) noexcept(
IsSpecified(TypeSpec::kNoThrowCopy))
: TrackedObject(GetInstanceString(other.dummy_)) {
if (!IsSpecified(TypeSpec::kNoThrowCopy)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
}
dummy_ = other.dummy_;
}
ThrowingValue(ThrowingValue&& other) noexcept(
IsSpecified(TypeSpec::kNoThrowMove))
: TrackedObject(GetInstanceString(other.dummy_)) {
if (!IsSpecified(TypeSpec::kNoThrowMove)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
}
dummy_ = other.dummy_;
}
explicit ThrowingValue(int i) : TrackedObject(GetInstanceString(i)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ = i;
}
ThrowingValue(int i, exceptions_internal::NoThrowTag) noexcept
: TrackedObject(GetInstanceString(i)), dummy_(i) {}
~ThrowingValue() noexcept = default;
ThrowingValue& operator=(const ThrowingValue& other) noexcept(
IsSpecified(TypeSpec::kNoThrowCopy)) {
dummy_ = kBadValue;
if (!IsSpecified(TypeSpec::kNoThrowCopy)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
}
dummy_ = other.dummy_;
return *this;
}
ThrowingValue& operator=(ThrowingValue&& other) noexcept(
IsSpecified(TypeSpec::kNoThrowMove)) {
dummy_ = kBadValue;
if (!IsSpecified(TypeSpec::kNoThrowMove)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
}
dummy_ = other.dummy_;
return *this;
}
ThrowingValue operator+(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ + other.dummy_, nothrow_ctor);
}
ThrowingValue operator+() const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_, nothrow_ctor);
}
ThrowingValue operator-(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ - other.dummy_, nothrow_ctor);
}
ThrowingValue operator-() const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(-dummy_, nothrow_ctor);
}
ThrowingValue& operator++() {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
++dummy_;
return *this;
}
ThrowingValue operator++(int) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
auto out = ThrowingValue(dummy_, nothrow_ctor);
++dummy_;
return out;
}
ThrowingValue& operator--() {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
--dummy_;
return *this;
}
ThrowingValue operator--(int) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
auto out = ThrowingValue(dummy_, nothrow_ctor);
--dummy_;
return out;
}
ThrowingValue operator*(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ * other.dummy_, nothrow_ctor);
}
ThrowingValue operator/(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ / other.dummy_, nothrow_ctor);
}
ThrowingValue operator%(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ % other.dummy_, nothrow_ctor);
}
ThrowingValue operator<<(int shift) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ << shift, nothrow_ctor);
}
ThrowingValue operator>>(int shift) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ >> shift, nothrow_ctor);
}
friend ThrowingBool operator==(const ThrowingValue& a,
const ThrowingValue& b) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return a.dummy_ == b.dummy_;
}
friend ThrowingBool operator!=(const ThrowingValue& a,
const ThrowingValue& b) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return a.dummy_ != b.dummy_;
}
friend ThrowingBool operator<(const ThrowingValue& a,
const ThrowingValue& b) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return a.dummy_ < b.dummy_;
}
friend ThrowingBool operator<=(const ThrowingValue& a,
const ThrowingValue& b) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return a.dummy_ <= b.dummy_;
}
friend ThrowingBool operator>(const ThrowingValue& a,
const ThrowingValue& b) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return a.dummy_ > b.dummy_;
}
friend ThrowingBool operator>=(const ThrowingValue& a,
const ThrowingValue& b) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return a.dummy_ >= b.dummy_;
}
ThrowingBool operator!() const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return !dummy_;
}
ThrowingBool operator&&(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return dummy_ && other.dummy_;
}
ThrowingBool operator||(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return dummy_ || other.dummy_;
}
ThrowingValue operator~() const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(~dummy_, nothrow_ctor);
}
ThrowingValue operator&(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ & other.dummy_, nothrow_ctor);
}
ThrowingValue operator|(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ | other.dummy_, nothrow_ctor);
}
ThrowingValue operator^(const ThrowingValue& other) const {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return ThrowingValue(dummy_ ^ other.dummy_, nothrow_ctor);
}
ThrowingValue& operator+=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ += other.dummy_;
return *this;
}
ThrowingValue& operator-=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ -= other.dummy_;
return *this;
}
ThrowingValue& operator*=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ *= other.dummy_;
return *this;
}
ThrowingValue& operator/=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ /= other.dummy_;
return *this;
}
ThrowingValue& operator%=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ %= other.dummy_;
return *this;
}
ThrowingValue& operator&=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ &= other.dummy_;
return *this;
}
ThrowingValue& operator|=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ |= other.dummy_;
return *this;
}
ThrowingValue& operator^=(const ThrowingValue& other) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ ^= other.dummy_;
return *this;
}
ThrowingValue& operator<<=(int shift) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ <<= shift;
return *this;
}
ThrowingValue& operator>>=(int shift) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ >>= shift;
return *this;
}
void operator&() const = delete;
friend std::ostream& operator<<(std::ostream& os, const ThrowingValue& tv) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return os << GetInstanceString(tv.dummy_);
}
friend std::istream& operator>>(std::istream& is, const ThrowingValue&) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
return is;
}
static void* operator new(size_t s) noexcept(
IsSpecified(TypeSpec::kNoThrowNew)) {
if (!IsSpecified(TypeSpec::kNoThrowNew)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
}
return ::operator new(s);
}
static void* operator new[](size_t s) noexcept(
IsSpecified(TypeSpec::kNoThrowNew)) {
if (!IsSpecified(TypeSpec::kNoThrowNew)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
}
return ::operator new[](s);
}
template <typename... Args>
static void* operator new(size_t s, Args&&... args) noexcept(
IsSpecified(TypeSpec::kNoThrowNew)) {
if (!IsSpecified(TypeSpec::kNoThrowNew)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
}
return ::operator new(s, std::forward<Args>(args)...);
}
template <typename... Args>
static void* operator new[](size_t s, Args&&... args) noexcept(
IsSpecified(TypeSpec::kNoThrowNew)) {
if (!IsSpecified(TypeSpec::kNoThrowNew)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
}
return ::operator new[](s, std::forward<Args>(args)...);
}
void operator delete(void* p) noexcept { ::operator delete(p); }
template <typename... Args>
void operator delete(void* p, Args&&... args) noexcept {
::operator delete(p, std::forward<Args>(args)...);
}
void operator delete[](void* p) noexcept { return ::operator delete[](p); }
template <typename... Args>
void operator delete[](void* p, Args&&... args) noexcept {
return ::operator delete[](p, std::forward<Args>(args)...);
}
int& Get() noexcept { return dummy_; }
const int& Get() const noexcept { return dummy_; }
private:
static std::string GetInstanceString(int dummy) {
return absl::StrCat("ThrowingValue<",
exceptions_internal::GetSpecString(Spec), ">(", dummy,
")");
}
int dummy_;
};
template <TypeSpec Spec, typename T>
void operator,(const ThrowingValue<Spec>&, T&&) = delete;
template <TypeSpec Spec, typename T>
void operator,(T&&, const ThrowingValue<Spec>&) = delete;
enum class AllocSpec {
kEverythingThrows = 0,
kNoThrowAllocate = 1,
};
template <typename T, AllocSpec Spec = AllocSpec::kEverythingThrows>
class ThrowingAllocator : private exceptions_internal::TrackedObject {
static constexpr bool IsSpecified(AllocSpec spec) {
return static_cast<bool>(Spec & spec);
}
public:
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using void_pointer = void*;
using const_void_pointer = const void*;
using value_type = T;
using size_type = size_t;
using difference_type = ptrdiff_t;
using is_nothrow =
std::integral_constant<bool, Spec == AllocSpec::kNoThrowAllocate>;
using propagate_on_container_copy_assignment = std::true_type;
using propagate_on_container_move_assignment = std::true_type;
using propagate_on_container_swap = std::true_type;
using is_always_equal = std::false_type;
ThrowingAllocator() : TrackedObject(GetInstanceString(next_id_)) {
exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
dummy_ = std::make_shared<const int>(next_id_++);
}
template <typename U>
ThrowingAllocator(const ThrowingAllocator<U, Spec>& other) noexcept
: TrackedObject(GetInstanceString(*other.State())),
dummy_(other.State()) {}
ThrowingAllocator(const ThrowingAllocator& other) noexcept
: TrackedObject(GetInstanceString(*other.State())),
dummy_(other.State()) {}
template <typename U>
ThrowingAllocator(ThrowingAllocator<U, Spec>&& other) noexcept
: TrackedObject(GetInstanceString(*other.State())),
dummy_(std::move(other.State())) {}
ThrowingAllocator(ThrowingAllocator&& other) noexcept
: TrackedObject(GetInstanceString(*other.State())),
dummy_(std::move(other.State())) {}
~ThrowingAllocator() noexcept = default;
ThrowingAllocator& operator=(const ThrowingAllocator& other) noexcept {
dummy_ = other.State();
return *this;
}
template <typename U>
ThrowingAllocator& operator=(
const ThrowingAllocator<U, Spec>& other) noexcept {
dummy_ = other.State();
return *this;
}
template <typename U>
ThrowingAllocator& operator=(ThrowingAllocator<U, Spec>&& other) noexcept {
dummy_ = std::move(other.State());
return *this;
}
template <typename U>
struct rebind {
using other = ThrowingAllocator<U, Spec>;
};
pointer allocate(size_type n) noexcept(
IsSpecified(AllocSpec::kNoThrowAllocate)) {
ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION);
return static_cast<pointer>(::operator new(n * sizeof(T)));
}
pointer allocate(size_type n, const_void_pointer) noexcept(
IsSpecified(AllocSpec::kNoThrowAllocate)) {
return allocate(n);
}
void deallocate(pointer ptr, size_type) noexcept {
ReadState();
::operator delete(static_cast<void*>(ptr));
}
template <typename U, typename... Args>
void construct(U* ptr, Args&&... args) noexcept(
IsSpecified(AllocSpec::kNoThrowAllocate)) {
ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION);
::new (static_cast<void*>(ptr)) U(std::forward<Args>(args)...);
}
template <typename U>
void destroy(U* p) noexcept {
ReadState();
p->~U();
}
size_type max_size() const noexcept {
return (std::numeric_limits<difference_type>::max)() / sizeof(value_type);
}
ThrowingAllocator select_on_container_copy_construction() noexcept(
IsSpecified(AllocSpec::kNoThrowAllocate)) {
ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION);
return *this;
}
template <typename U>
bool operator==(const ThrowingAllocator<U, Spec>& other) const noexcept {
return dummy_ == other.dummy_;
}
template <typename U>
bool operator!=(const ThrowingAllocator<U, Spec>& other) const noexcept {
return dummy_ != other.dummy_;
}
template <typename, AllocSpec>
friend class ThrowingAllocator;
private:
static std::string GetInstanceString(int dummy) {
return absl::StrCat("ThrowingAllocator<",
exceptions_internal::GetSpecString(Spec), ">(", dummy,
")");
}
const std::shared_ptr<const int>& State() const { return dummy_; }
std::shared_ptr<const int>& State() { return dummy_; }
void ReadState() {
if (*dummy_ < 0) std::abort();
}
void ReadStateAndMaybeThrow(absl::string_view msg) const {
if (!IsSpecified(AllocSpec::kNoThrowAllocate)) {
exceptions_internal::MaybeThrow(
absl::Substitute("Allocator id $0 threw from $1", *dummy_, msg));
}
}
static int next_id_;
std::shared_ptr<const int> dummy_;
};
template <typename T, AllocSpec Spec>
int ThrowingAllocator<T, Spec>::next_id_ = 0;
template <typename T, typename... Args>
void TestThrowingCtor(Args&&... args) {
struct Cleanup {
~Cleanup() { exceptions_internal::UnsetCountdown(); }
} c;
for (int count = 0;; ++count) {
exceptions_internal::ConstructorTracker ct(count);
exceptions_internal::SetCountdown(count);
try {
T temp(std::forward<Args>(args)...);
static_cast<void>(temp);
break;
} catch (const exceptions_internal::TestException&) {
}
}
}
template <typename Operation>
testing::AssertionResult TestNothrowOp(const Operation& operation) {
struct Cleanup {
Cleanup() { exceptions_internal::SetCountdown(); }
~Cleanup() { exceptions_internal::UnsetCountdown(); }
} c;
try {
operation();
return testing::AssertionSuccess();
} catch (const exceptions_internal::TestException&) {
return testing::AssertionFailure()
<< "TestException thrown during call to operation() when nothrow "
"guarantee was expected.";
} catch (...) {
return testing::AssertionFailure()
<< "Unknown exception thrown during call to operation() when "
"nothrow guarantee was expected.";
}
}
namespace exceptions_internal {
struct UninitializedT {};
template <typename T>
class DefaultFactory {
public:
explicit DefaultFactory(const T& t) : t_(t) {}
std::unique_ptr<T> operator()() const { return absl::make_unique<T>(t_); }
private:
T t_;
};
template <size_t LazyContractsCount, typename LazyFactory,
typename LazyOperation>
using EnableIfTestable = typename absl::enable_if_t<
LazyContractsCount != 0 &&
!std::is_same<LazyFactory, UninitializedT>::value &&
!std::is_same<LazyOperation, UninitializedT>::value>;
template <typename Factory = UninitializedT,
typename Operation = UninitializedT, typename... Contracts>
class ExceptionSafetyTestBuilder;
}
exceptions_internal::ExceptionSafetyTestBuilder<> MakeExceptionSafetyTester();
namespace exceptions_internal {
template <typename T>
struct IsUniquePtr : std::false_type {};
template <typename T, typename D>
struct IsUniquePtr<std::unique_ptr<T, D>> : std::true_type {};
template <typename Factory>
struct FactoryPtrTypeHelper {
using type = decltype(std::declval<const Factory&>()());
static_assert(IsUniquePtr<type>::value, "Factories must return a unique_ptr");
};
template <typename Factory>
using FactoryPtrType = typename FactoryPtrTypeHelper<Factory>::type;
template <typename Factory>
using FactoryElementType = typename FactoryPtrType<Factory>::element_type;
template <typename T>
class ExceptionSafetyTest {
using Factory = std::function<std::unique_ptr<T>()>;
using Operation = std::function<void(T*)>;
using Contract = std::function<AssertionResult(T*)>;
public:
template <typename... Contracts>
explicit ExceptionSafetyTest(const Factory& f, const Operation& op,
const Contracts&... contracts)
: factory_(f), operation_(op), contracts_{WrapContract(contracts)...} {}
AssertionResult Test() const {
for (int count = 0;; ++count) {
exceptions_internal::ConstructorTracker ct(count);
for (const auto& contract : contracts_) {
auto t_ptr = factory_();
try {
SetCountdown(count);
operation_(t_ptr.get());
UnsetCountdown();
return AssertionSuccess();
} catch (const exceptions_internal::TestException& e) {
if (!contract(t_ptr.get())) {
return AssertionFailure() << e.what() << " failed contract check";
}
}
}
}
}
private:
template <typename ContractFn>
Contract WrapContract(const ContractFn& contract) {
return [contract](T* t_ptr) { return AssertionResult(contract(t_ptr)); };
}
Contract WrapContract(StrongGuaranteeTagType) {
return [this](T* t_ptr) { return AssertionResult(*factory_() == *t_ptr); };
}
Factory factory_;
Operation operation_;
std::vector<Contract> contracts_;
};
template <typename Factory, typename Operation, typename... Contracts>
class ExceptionSafetyTestBuilder {
public:
/*
* Returns a new ExceptionSafetyTestBuilder with an included T factory based
* on the provided T instance. The existing factory will not be included in
* the newly created tes | #include "absl/base/internal/exception_safety_testing.h"
#ifdef ABSL_HAVE_EXCEPTIONS
#include <cstddef>
#include <exception>
#include <iostream>
#include <list>
#include <type_traits>
#include <vector>
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
namespace testing {
namespace {
using ::testing::exceptions_internal::SetCountdown;
using ::testing::exceptions_internal::TestException;
using ::testing::exceptions_internal::UnsetCountdown;
template <typename F>
void ExpectNoThrow(const F& f) {
try {
f();
} catch (const TestException& e) {
ADD_FAILURE() << "Unexpected exception thrown from " << e.what();
}
}
TEST(ThrowingValueTest, Throws) {
SetCountdown();
EXPECT_THROW(ThrowingValue<> bomb, TestException);
SetCountdown(2);
ExpectNoThrow([]() { ThrowingValue<> bomb; });
ExpectNoThrow([]() { ThrowingValue<> bomb; });
EXPECT_THROW(ThrowingValue<> bomb, TestException);
UnsetCountdown();
}
template <typename F>
void TestOp(const F& f) {
ExpectNoThrow(f);
SetCountdown();
EXPECT_THROW(f(), TestException);
UnsetCountdown();
}
TEST(ThrowingValueTest, ThrowingCtors) {
ThrowingValue<> bomb;
TestOp([]() { ThrowingValue<> bomb(1); });
TestOp([&]() { ThrowingValue<> bomb1 = bomb; });
TestOp([&]() { ThrowingValue<> bomb1 = std::move(bomb); });
}
TEST(ThrowingValueTest, ThrowingAssignment) {
ThrowingValue<> bomb, bomb1;
TestOp([&]() { bomb = bomb1; });
TestOp([&]() { bomb = std::move(bomb1); });
{
ThrowingValue<> lhs(39), rhs(42);
ThrowingValue<> lhs_copy(lhs);
SetCountdown();
EXPECT_THROW(lhs = rhs, TestException);
UnsetCountdown();
EXPECT_NE(lhs, rhs);
EXPECT_NE(lhs_copy, lhs);
}
{
ThrowingValue<> lhs(39), rhs(42);
ThrowingValue<> lhs_copy(lhs), rhs_copy(rhs);
SetCountdown();
EXPECT_THROW(lhs = std::move(rhs), TestException);
UnsetCountdown();
EXPECT_NE(lhs, rhs_copy);
EXPECT_NE(lhs_copy, lhs);
}
}
TEST(ThrowingValueTest, ThrowingComparisons) {
ThrowingValue<> bomb1, bomb2;
TestOp([&]() { return bomb1 == bomb2; });
TestOp([&]() { return bomb1 != bomb2; });
TestOp([&]() { return bomb1 < bomb2; });
TestOp([&]() { return bomb1 <= bomb2; });
TestOp([&]() { return bomb1 > bomb2; });
TestOp([&]() { return bomb1 >= bomb2; });
}
TEST(ThrowingValueTest, ThrowingArithmeticOps) {
ThrowingValue<> bomb1(1), bomb2(2);
TestOp([&bomb1]() { +bomb1; });
TestOp([&bomb1]() { -bomb1; });
TestOp([&bomb1]() { ++bomb1; });
TestOp([&bomb1]() { bomb1++; });
TestOp([&bomb1]() { --bomb1; });
TestOp([&bomb1]() { bomb1--; });
TestOp([&]() { bomb1 + bomb2; });
TestOp([&]() { bomb1 - bomb2; });
TestOp([&]() { bomb1* bomb2; });
TestOp([&]() { bomb1 / bomb2; });
TestOp([&]() { bomb1 << 1; });
TestOp([&]() { bomb1 >> 1; });
}
TEST(ThrowingValueTest, ThrowingLogicalOps) {
ThrowingValue<> bomb1, bomb2;
TestOp([&bomb1]() { !bomb1; });
TestOp([&]() { bomb1&& bomb2; });
TestOp([&]() { bomb1 || bomb2; });
}
TEST(ThrowingValueTest, ThrowingBitwiseOps) {
ThrowingValue<> bomb1, bomb2;
TestOp([&bomb1]() { ~bomb1; });
TestOp([&]() { bomb1 & bomb2; });
TestOp([&]() { bomb1 | bomb2; });
TestOp([&]() { bomb1 ^ bomb2; });
}
TEST(ThrowingValueTest, ThrowingCompoundAssignmentOps) {
ThrowingValue<> bomb1(1), bomb2(2);
TestOp([&]() { bomb1 += bomb2; });
TestOp([&]() { bomb1 -= bomb2; });
TestOp([&]() { bomb1 *= bomb2; });
TestOp([&]() { bomb1 /= bomb2; });
TestOp([&]() { bomb1 %= bomb2; });
TestOp([&]() { bomb1 &= bomb2; });
TestOp([&]() { bomb1 |= bomb2; });
TestOp([&]() { bomb1 ^= bomb2; });
TestOp([&]() { bomb1 *= bomb2; });
}
TEST(ThrowingValueTest, ThrowingStreamOps) {
ThrowingValue<> bomb;
TestOp([&]() {
std::istringstream stream;
stream >> bomb;
});
TestOp([&]() {
std::stringstream stream;
stream << bomb;
});
}
TEST(ThrowingValueTest, StreamOpsOutput) {
using ::testing::TypeSpec;
exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
EXPECT_NONFATAL_FAILURE(
{
using Thrower = ThrowingValue<TypeSpec{}>;
auto thrower = Thrower(123);
thrower.~Thrower();
},
"ThrowingValue<>(123)");
EXPECT_NONFATAL_FAILURE(
{
using Thrower = ThrowingValue<TypeSpec::kNoThrowCopy>;
auto thrower = Thrower(234);
thrower.~Thrower();
},
"ThrowingValue<kNoThrowCopy>(234)");
EXPECT_NONFATAL_FAILURE(
{
using Thrower =
ThrowingValue<TypeSpec::kNoThrowMove | TypeSpec::kNoThrowNew>;
auto thrower = Thrower(345);
thrower.~Thrower();
},
"ThrowingValue<kNoThrowMove | kNoThrowNew>(345)");
EXPECT_NONFATAL_FAILURE(
{
using Thrower = ThrowingValue<static_cast<TypeSpec>(-1)>;
auto thrower = Thrower(456);
thrower.~Thrower();
},
"ThrowingValue<kNoThrowCopy | kNoThrowMove | kNoThrowNew>(456)");
}
template <typename F>
void TestAllocatingOp(const F& f) {
ExpectNoThrow(f);
SetCountdown();
EXPECT_THROW(f(), exceptions_internal::TestBadAllocException);
UnsetCountdown();
}
TEST(ThrowingValueTest, ThrowingAllocatingOps) {
TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>>(1); });
TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>[]>(2); });
}
TEST(ThrowingValueTest, NonThrowingMoveCtor) {
ThrowingValue<TypeSpec::kNoThrowMove> nothrow_ctor;
SetCountdown();
ExpectNoThrow([¬hrow_ctor]() {
ThrowingValue<TypeSpec::kNoThrowMove> nothrow1 = std::move(nothrow_ctor);
});
UnsetCountdown();
}
TEST(ThrowingValueTest, NonThrowingMoveAssign) {
ThrowingValue<TypeSpec::kNoThrowMove> nothrow_assign1, nothrow_assign2;
SetCountdown();
ExpectNoThrow([¬hrow_assign1, ¬hrow_assign2]() {
nothrow_assign1 = std::move(nothrow_assign2);
});
UnsetCountdown();
}
TEST(ThrowingValueTest, ThrowingCopyCtor) {
ThrowingValue<> tv;
TestOp([&]() { ThrowingValue<> tv_copy(tv); });
}
TEST(ThrowingValueTest, ThrowingCopyAssign) {
ThrowingValue<> tv1, tv2;
TestOp([&]() { tv1 = tv2; });
}
TEST(ThrowingValueTest, NonThrowingCopyCtor) {
ThrowingValue<TypeSpec::kNoThrowCopy> nothrow_ctor;
SetCountdown();
ExpectNoThrow([¬hrow_ctor]() {
ThrowingValue<TypeSpec::kNoThrowCopy> nothrow1(nothrow_ctor);
});
UnsetCountdown();
}
TEST(ThrowingValueTest, NonThrowingCopyAssign) {
ThrowingValue<TypeSpec::kNoThrowCopy> nothrow_assign1, nothrow_assign2;
SetCountdown();
ExpectNoThrow([¬hrow_assign1, ¬hrow_assign2]() {
nothrow_assign1 = nothrow_assign2;
});
UnsetCountdown();
}
TEST(ThrowingValueTest, ThrowingSwap) {
ThrowingValue<> bomb1, bomb2;
TestOp([&]() { std::swap(bomb1, bomb2); });
}
TEST(ThrowingValueTest, NonThrowingSwap) {
ThrowingValue<TypeSpec::kNoThrowMove> bomb1, bomb2;
ExpectNoThrow([&]() { std::swap(bomb1, bomb2); });
}
TEST(ThrowingValueTest, NonThrowingAllocation) {
ThrowingValue<TypeSpec::kNoThrowNew>* allocated;
ThrowingValue<TypeSpec::kNoThrowNew>* array;
ExpectNoThrow([&allocated]() {
allocated = new ThrowingValue<TypeSpec::kNoThrowNew>(1);
delete allocated;
});
ExpectNoThrow([&array]() {
array = new ThrowingValue<TypeSpec::kNoThrowNew>[2];
delete[] array;
});
}
TEST(ThrowingValueTest, NonThrowingDelete) {
auto* allocated = new ThrowingValue<>(1);
auto* array = new ThrowingValue<>[2];
SetCountdown();
ExpectNoThrow([allocated]() { delete allocated; });
SetCountdown();
ExpectNoThrow([array]() { delete[] array; });
UnsetCountdown();
}
TEST(ThrowingValueTest, NonThrowingPlacementDelete) {
constexpr int kArrayLen = 2;
constexpr size_t kExtraSpaceLen = sizeof(size_t) * 2;
alignas(ThrowingValue<>) unsigned char buf[sizeof(ThrowingValue<>)];
alignas(ThrowingValue<>) unsigned char
array_buf[kExtraSpaceLen + sizeof(ThrowingValue<>[kArrayLen])];
auto* placed = new (&buf) ThrowingValue<>(1);
auto placed_array = new (&array_buf) ThrowingValue<>[kArrayLen];
auto* placed_array_end = reinterpret_cast<unsigned char*>(placed_array) +
sizeof(ThrowingValue<>[kArrayLen]);
EXPECT_LE(placed_array_end, array_buf + sizeof(array_buf));
SetCountdown();
ExpectNoThrow([placed, &buf]() {
placed->~ThrowingValue<>();
ThrowingValue<>::operator delete(placed, &buf);
});
SetCountdown();
ExpectNoThrow([&, placed_array]() {
for (int i = 0; i < kArrayLen; ++i) placed_array[i].~ThrowingValue<>();
ThrowingValue<>::operator delete[](placed_array, &array_buf);
});
UnsetCountdown();
}
TEST(ThrowingValueTest, NonThrowingDestructor) {
auto* allocated = new ThrowingValue<>();
SetCountdown();
ExpectNoThrow([allocated]() { delete allocated; });
UnsetCountdown();
}
TEST(ThrowingBoolTest, ThrowingBool) {
ThrowingBool t = true;
if (t) {
}
EXPECT_TRUE(t);
TestOp([&]() { (void)!t; });
}
TEST(ThrowingAllocatorTest, MemoryManagement) {
ThrowingAllocator<int> int_alloc;
int* ip = int_alloc.allocate(1);
int_alloc.deallocate(ip, 1);
int* i_array = int_alloc.allocate(2);
int_alloc.deallocate(i_array, 2);
ThrowingAllocator<ThrowingValue<>> tv_alloc;
ThrowingValue<>* ptr = tv_alloc.allocate(1);
tv_alloc.deallocate(ptr, 1);
ThrowingValue<>* tv_array = tv_alloc.allocate(2);
tv_alloc.deallocate(tv_array, 2);
}
TEST(ThrowingAllocatorTest, CallsGlobalNew) {
ThrowingAllocator<ThrowingValue<>, AllocSpec::kNoThrowAllocate> nothrow_alloc;
ThrowingValue<>* ptr;
SetCountdown();
ExpectNoThrow([&]() { ptr = nothrow_alloc.allocate(1); });
nothrow_alloc.deallocate(ptr, 1);
UnsetCountdown();
}
TEST(ThrowingAllocatorTest, ThrowingConstructors) {
ThrowingAllocator<int> int_alloc;
int* ip = nullptr;
SetCountdown();
EXPECT_THROW(ip = int_alloc.allocate(1), TestException);
ExpectNoThrow([&]() { ip = int_alloc.allocate(1); });
*ip = 1;
SetCountdown();
EXPECT_THROW(int_alloc.construct(ip, 2), TestException);
EXPECT_EQ(*ip, 1);
int_alloc.deallocate(ip, 1);
UnsetCountdown();
}
TEST(ThrowingAllocatorTest, NonThrowingConstruction) {
{
ThrowingAllocator<int, AllocSpec::kNoThrowAllocate> int_alloc;
int* ip = nullptr;
SetCountdown();
ExpectNoThrow([&]() { ip = int_alloc.allocate(1); });
SetCountdown();
ExpectNoThrow([&]() { int_alloc.construct(ip, 2); });
EXPECT_EQ(*ip, 2);
int_alloc.deallocate(ip, 1);
UnsetCountdown();
}
{
ThrowingAllocator<int> int_alloc;
int* ip = nullptr;
ExpectNoThrow([&]() { ip = int_alloc.allocate(1); });
ExpectNoThrow([&]() { int_alloc.construct(ip, 2); });
EXPECT_EQ(*ip, 2);
int_alloc.deallocate(ip, 1);
}
{
ThrowingAllocator<ThrowingValue<>, AllocSpec::kNoThrowAllocate>
nothrow_alloc;
ThrowingValue<>* ptr;
SetCountdown();
ExpectNoThrow([&]() { ptr = nothrow_alloc.allocate(1); });
SetCountdown();
ExpectNoThrow(
[&]() { nothrow_alloc.construct(ptr, 2, testing::nothrow_ctor); });
EXPECT_EQ(ptr->Get(), 2);
nothrow_alloc.destroy(ptr);
nothrow_alloc.deallocate(ptr, 1);
UnsetCountdown();
}
{
ThrowingAllocator<int> a;
SetCountdown();
ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = a; });
SetCountdown();
ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = std::move(a); });
UnsetCountdown();
}
}
TEST(ThrowingAllocatorTest, ThrowingAllocatorConstruction) {
ThrowingAllocator<int> a;
TestOp([]() { ThrowingAllocator<int> a; });
TestOp([&]() { a.select_on_container_copy_construction(); });
}
TEST(ThrowingAllocatorTest, State) {
ThrowingAllocator<int> a1, a2;
EXPECT_NE(a1, a2);
auto a3 = a1;
EXPECT_EQ(a3, a1);
int* ip = a1.allocate(1);
EXPECT_EQ(a3, a1);
a3.deallocate(ip, 1);
EXPECT_EQ(a3, a1);
}
TEST(ThrowingAllocatorTest, InVector) {
std::vector<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> v;
for (int i = 0; i < 20; ++i) v.push_back({});
for (int i = 0; i < 20; ++i) v.pop_back();
}
TEST(ThrowingAllocatorTest, InList) {
std::list<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> l;
for (int i = 0; i < 20; ++i) l.push_back({});
for (int i = 0; i < 20; ++i) l.pop_back();
for (int i = 0; i < 20; ++i) l.push_front({});
for (int i = 0; i < 20; ++i) l.pop_front();
}
template <typename TesterInstance, typename = void>
struct NullaryTestValidator : public std::false_type {};
template <typename TesterInstance>
struct NullaryTestValidator<
TesterInstance,
absl::void_t<decltype(std::declval<TesterInstance>().Test())>>
: public std::true_type {};
template <typename TesterInstance>
bool HasNullaryTest(const TesterInstance&) {
return NullaryTestValidator<TesterInstance>::value;
}
void DummyOp(void*) {}
template <typename TesterInstance, typename = void>
struct UnaryTestValidator : public std::false_type {};
template <typename TesterInstance>
struct UnaryTestValidator<
TesterInstance,
absl::void_t<decltype(std::declval<TesterInstance>().Test(DummyOp))>>
: public std::true_type {};
template <typename TesterInstance>
bool HasUnaryTest(const TesterInstance&) {
return UnaryTestValidator<TesterInstance>::value;
}
TEST(ExceptionSafetyTesterTest, IncompleteTypesAreNotTestable) {
using T = exceptions_internal::UninitializedT;
auto op = [](T* t) {};
auto inv = [](T*) { return testing::AssertionSuccess(); };
auto fac = []() { return absl::make_unique<T>(); };
auto without_fac =
testing::MakeExceptionSafetyTester().WithOperation(op).WithContracts(
inv, testing::strong_guarantee);
EXPECT_FALSE(HasNullaryTest(without_fac));
EXPECT_FALSE(HasUnaryTest(without_fac));
auto without_op = testing::MakeExceptionSafetyTester()
.WithContracts(inv, testing::strong_guarantee)
.WithFactory(fac);
EXPECT_FALSE(HasNullaryTest(without_op));
EXPECT_TRUE(HasUnaryTest(without_op));
auto without_inv =
testing::MakeExceptionSafetyTester().WithOperation(op).WithFactory(fac);
EXPECT_FALSE(HasNullaryTest(without_inv));
EXPECT_FALSE(HasUnaryTest(without_inv));
}
struct ExampleStruct {};
std::unique_ptr<ExampleStruct> ExampleFunctionFactory() {
return absl::make_unique<ExampleStruct>();
}
void ExampleFunctionOperation(ExampleStruct*) {}
testing::AssertionResult ExampleFunctionContract(ExampleStruct*) {
return testing::AssertionSuccess();
}
struct {
std::unique_ptr<ExampleStruct> operator()() const {
return ExampleFunctionFactory();
}
} example_struct_factory;
struct {
void operator()(ExampleStruct*) const {}
} example_struct_operation;
struct {
testing::AssertionResult operator()(ExampleStruct* example_struct) const {
return ExampleFunctionContract(example_struct);
}
} example_struct_contract;
auto example_lambda_factory = []() { return ExampleFunctionFactory(); };
auto example_lambda_operation = [](ExampleStruct*) {};
auto example_lambda_contract = [](ExampleStruct* example_struct) {
return ExampleFunctionContract(example_struct);
};
TEST(ExceptionSafetyTesterTest, MixedFunctionTypes) {
EXPECT_TRUE(testing::MakeExceptionSafetyTester()
.WithFactory(ExampleFunctionFactory)
.WithOperation(ExampleFunctionOperation)
.WithContracts(ExampleFunctionContract)
.Test());
EXPECT_TRUE(testing::MakeExceptionSafetyTester()
.WithFactory(&ExampleFunctionFactory)
.WithOperation(&ExampleFunctionOperation)
.WithContracts(&ExampleFunctionContract)
.Test());
EXPECT_TRUE(testing::MakeExceptionSafetyTester()
.WithFactory(example_struct_factory)
.WithOperation(example_struct_operation)
.WithContracts(example_struct_contract)
.Test());
EXPECT_TRUE(testing::MakeExceptionSafetyTester()
.WithFactory(example_lambda_factory)
.WithOperation(example_lambda_operation)
.WithContracts(example_lambda_contract)
.Test());
}
struct NonNegative {
bool operator==(const NonNegative& other) const { return i == other.i; }
int i;
};
testing::AssertionResult CheckNonNegativeInvariants(NonNegative* g) {
if (g->i >= 0) {
return testing::AssertionSuccess();
}
return testing::AssertionFailure()
<< "i should be non-negative but is " << g->i;
}
struct {
template <typename T>
void operator()(T* t) const {
(*t)();
}
} invoker;
auto tester =
testing::MakeExceptionSafetyTester().WithOperation(invoker).WithContracts(
CheckNonNegativeInvariants);
auto strong_tester = tester.WithContracts(testing::strong_guarantee);
struct FailsBasicGuarantee : public NonNegative {
void operator()() {
--i;
ThrowingValue<> bomb;
++i;
}
};
TEST(ExceptionCheckTest, BasicGuaranteeFailure) {
EXPECT_FALSE(tester.WithInitialValue(FailsBasicGuarantee{}).Test());
}
struct FollowsBasicGuarantee : public NonNegative {
void operator()() {
++i;
ThrowingValue<> bomb;
}
};
TEST(ExceptionCheckTest, BasicGuarantee) {
EXPECT_TRUE(tester.WithInitialValue(FollowsBasicGuarantee{}).Test());
}
TEST(ExceptionCheckTest, StrongGuaranteeFailure) {
EXPECT_FALSE(strong_tester.WithInitialValue(FailsBasicGuarantee{}).Test());
EXPECT_FALSE(strong_tester.WithInitialValue(FollowsBasicGuarantee{}).Test());
}
struct BasicGuaranteeWithExtraContracts : public NonNegative {
void operator()() {
int old_i = i;
i = kExceptionSentinel;
ThrowingValue<> bomb;
i = ++old_i;
}
static constexpr int kExceptionSentinel = 9999;
};
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr int BasicGuaranteeWithExtraContracts::kExceptionSentinel;
#endif
TEST(ExceptionCheckTest, BasicGuaranteeWithExtraContracts) {
auto tester_with_val =
tester.WithInitialValue(BasicGuaranteeWithExtraContracts{});
EXPECT_TRUE(tester_with_val.Test());
EXPECT_TRUE(
tester_with_val
.WithContracts([](BasicGuaranteeWithExtraContracts* o) {
if (o->i == BasicGuaranteeWithExtraContracts::kExceptionSentinel) {
return testing::AssertionSuccess();
}
return testing::AssertionFailure()
<< "i should be "
<< BasicGuaranteeWithExtraContracts::kExceptionSentinel
<< ", but is " << o->i;
})
.Test());
}
struct FollowsStrongGuarantee : public NonNegative {
void operator()() { ThrowingValue<> bomb; }
};
TEST(ExceptionCheckTest, StrongGuarantee) {
EXPECT_TRUE(tester.WithInitialValue(FollowsStrongGuarantee{}).Test());
EXPECT_TRUE(strong_tester.WithInitialValue(FollowsStrongGuarantee{}).Test());
}
struct HasReset : public NonNegative {
void operator()() {
i = -1;
ThrowingValue<> bomb;
i = 1;
}
void reset() { i = 0; }
};
testing::AssertionResult CheckHasResetContracts(HasReset* h) {
h->reset();
return testing::AssertionResult(h->i == 0);
}
TEST(ExceptionCheckTest, ModifyingChecker) {
auto set_to_1000 = [](FollowsBasicGuarantee* g) {
g->i = 1000;
return testing::AssertionSuccess();
};
auto is_1000 = [](FollowsBasicGuarantee* g) {
return testing::AssertionResult(g->i == 1000);
};
auto increment = [](FollowsStrongGuarantee* g) {
++g->i;
return testing::AssertionSuccess();
};
EXPECT_FALSE(tester.WithInitialValue(FollowsBasicGuarantee{})
.WithContracts(set_to_1000, is_1000)
.Test());
EXPECT_TRUE(strong_tester.WithInitialValue(FollowsStrongGuarantee{})
.WithContracts(increment)
.Test());
EXPECT_TRUE(testing::MakeExceptionSafetyTester()
.WithInitialValue(HasReset{})
.WithContracts(CheckHasResetContracts)
.Test(invoker));
}
TEST(ExceptionSafetyTesterTest, ResetsCountdown) {
auto test =
testing::MakeExceptionSafetyTester()
.WithInitialValue(ThrowingValue<>())
.WithContracts([](ThrowingValue<>*) { return AssertionSuccess(); })
.WithOperation([](ThrowingValue<>*) {});
ASSERT_TRUE(test.Test());
EXPECT_TRUE(test.Test());
}
struct NonCopyable : public NonNegative {
NonCopyable(const NonCopyable&) = delete;
NonCopyable() : NonNegative{0} {}
void operator()() { ThrowingValue<> bomb; }
};
TEST(ExceptionCheckTest, NonCopyable) {
auto factory = []() { return absl::make_unique<NonCopyable>(); };
EXPECT_TRUE(tester.WithFactory(factory).Test());
EXPECT_TRUE(strong_tester.WithFactory(factory).Test());
}
struct NonEqualityComparable : public NonNegative {
void operator()() { ThrowingValue<> bomb; }
void ModifyOnThrow() {
++i;
ThrowingValue<> bomb;
static_cast<void>(bomb);
--i;
}
};
TEST(ExceptionCheckTest, NonEqualityComparable) {
auto nec_is_strong = [](NonEqualityComparable* nec) {
return testing::AssertionResult(nec->i == NonEqualityComparable().i);
};
auto strong_nec_tester = tester.WithInitialValue(NonEqualityComparable{})
.WithContracts(nec_is_strong);
EXPECT_TRUE(strong_nec_tester.Test());
EXPECT_FALSE(strong_nec_tester.Test(
[](NonEqualityComparable* n) { n->ModifyOnThrow(); }));
}
template <typename T>
struct ExhaustivenessTester {
void operator()() {
successes |= 1;
T b1;
static_cast<void>(b1);
successes |= (1 << 1);
T b2;
static_cast<void>(b2);
successes |= (1 << 2);
T b3;
static_cast<void>(b3);
successes |= (1 << 3);
}
bool operator==(const ExhaustivenessTester<ThrowingValue<>>&) const {
return true;
}
static unsigned char successes;
};
struct {
template <typename T>
testing::AssertionResult operator()(ExhaustivenessTester<T>*) const {
return testing::AssertionSuccess();
}
} CheckExhaustivenessTesterContracts;
template <typename T>
unsigned char ExhaustivenessTester<T>::successes = 0;
TEST(ExceptionCheckTest, Exhaustiveness) {
auto exhaust_tester = testing::MakeExceptionSafetyTester()
.WithContracts(CheckExhaustivenessTesterContracts)
.WithOperation(invoker);
EXPECT_TRUE(
exhaust_tester.WithInitialValue(ExhaustivenessTester<int>{}).Test());
EXPECT_EQ(ExhaustivenessTester<int>::successes, 0xF);
EXPECT_TRUE(
exhaust_tester.WithInitialValue(ExhaustivenessTester<ThrowingValue<>>{})
.WithContracts(testing::strong_guarantee)
.Test());
EXPECT_EQ(ExhaustivenessTester<ThrowingValue<>>::successes, 0xF);
}
struct LeaksIfCtorThrows : private exceptions_internal::TrackedObject {
LeaksIfCtorThrows() : TrackedObject(ABSL_PRETTY_FUNCTION) {
++counter;
ThrowingValue<> v;
static_cast<void>(v);
--counter;
}
LeaksIfCtorThrows(const LeaksIfCtorThrows&) noexcept
: TrackedObject(ABSL_PRETTY_FUNCTION) {}
static int counter;
};
int LeaksIfCtorThrows::counter = 0;
TEST(ExceptionCheckTest, TestLeakyCtor) {
testing::TestThrowingCtor<LeaksIfCtorThrows>();
EXPECT_EQ(LeaksIfCtorThrows::counter, 1);
LeaksIfCtorThrows::counter = 0;
}
struct Tracked : private exceptions_internal::TrackedObject {
Tracked() : TrackedObject(ABSL_PRETTY_FUNCTION) {}
};
TEST(ConstructorTrackerTest, CreatedBefore) {
Tracked a, b, c;
exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
}
TEST(ConstructorTrackerTest, CreatedAfter) {
exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
Tracked a, b, c;
}
TEST(ConstructorTrackerTest, NotDestroyedAfter) {
alignas(Tracked) unsigned char storage[sizeof(Tracked)];
EXPECT_NONFATAL_FAILURE(
{
exceptions_internal::ConstructorTracker ct(
exceptions_internal::countdown);
new (&storage) Tracked();
},
"not destroyed");
}
TEST(ConstructorTrackerTest, DestroyedTwice) {
exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
EXPECT_NONFATAL_FAILURE(
{
Tracked t;
t.~Tracked();
},
"re-destroyed");
}
TEST(ConstructorTrackerTest, ConstructedTwice) {
exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
alignas(Tracked) unsigned char storage[sizeof(Tracked)];
EXPECT_NONFATAL_FAILURE(
{
new (&storage) Tracked();
new (&storage) Tracked();
reinterpret_cast<Tracked*>(&storage)->~Tracked();
},
"re-constructed");
}
TEST(ThrowingValueTraitsTest, RelationalOperators) {
ThrowingValue<> a, b;
EXPECT_TRUE((std::is_convertible<decltype(a == b), bool>::value));
EXPECT_TRUE((std::is_convertible<decltype(a != b), bool>::value));
EXPECT_TRUE((std::is_convertible<decltype(a < b), bool>::value));
EXPECT_TRUE((std::is_convertible<decltype(a <= b), bool>::value));
EXPECT_TRUE((std::is_convertible<decltype(a > b), bool>::value));
EXPECT_TRUE((std::is_convertible<decltype(a >= b), bool>::value));
}
TEST(ThrowingAllocatorTraitsTest, Assignablility) {
EXPECT_TRUE(absl::is_move_assignable<ThrowingAllocator<int>>::value);
EXPECT_TRUE(absl::is_copy_assignable<ThrowingAllocator<int>>::value);
EXPECT_TRUE(std::is_nothrow_move_assignable<ThrowingAllocator<int>>::value);
EXPECT_TRUE(std::is_nothrow_copy_assignable<ThrowingAllocator<int>>::value);
}
}
}
#endif |
2,513 | cpp | abseil/abseil-cpp | thread_identity | absl/base/internal/thread_identity.cc | absl/base/internal/thread_identity_test.cc | #ifndef ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_
#define ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_
#ifndef _WIN32
#include <pthread.h>
#include <unistd.h>
#endif
#include <atomic>
#include <cstdint>
#include "absl/base/config.h"
#include "absl/base/internal/per_thread_tls.h"
#include "absl/base/optimization.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
struct SynchLocksHeld;
struct SynchWaitParams;
namespace base_internal {
class SpinLock;
struct ThreadIdentity;
struct PerThreadSynch {
static constexpr int kLowZeroBits = 8;
static constexpr int kAlignment = 1 << kLowZeroBits;
ThreadIdentity* thread_identity() {
return reinterpret_cast<ThreadIdentity*>(this);
}
PerThreadSynch* next;
PerThreadSynch* skip;
bool may_skip;
bool wake;
bool cond_waiter;
bool maybe_unlocking;
bool suppress_fatal_errors;
int priority;
enum State { kAvailable, kQueued };
std::atomic<State> state;
SynchWaitParams* waitp;
intptr_t readers;
int64_t next_priority_read_cycles;
SynchLocksHeld* all_locks;
};
struct ThreadIdentity {
PerThreadSynch per_thread_synch;
struct WaiterState {
alignas(void*) char data[256];
} waiter_state;
std::atomic<int>* blocked_count_ptr;
std::atomic<int> ticker;
std::atomic<int> wait_start;
std::atomic<bool> is_idle;
ThreadIdentity* next;
};
ThreadIdentity* CurrentThreadIdentityIfPresent();
using ThreadIdentityReclaimerFunction = void (*)(void*);
void SetCurrentThreadIdentity(ThreadIdentity* identity,
ThreadIdentityReclaimerFunction reclaimer);
void ClearCurrentThreadIdentity();
#ifdef ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
#error ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC cannot be directly set
#else
#define ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC 0
#endif
#ifdef ABSL_THREAD_IDENTITY_MODE_USE_TLS
#error ABSL_THREAD_IDENTITY_MODE_USE_TLS cannot be directly set
#else
#define ABSL_THREAD_IDENTITY_MODE_USE_TLS 1
#endif
#ifdef ABSL_THREAD_IDENTITY_MODE_USE_CPP11
#error ABSL_THREAD_IDENTITY_MODE_USE_CPP11 cannot be directly set
#else
#define ABSL_THREAD_IDENTITY_MODE_USE_CPP11 2
#endif
#ifdef ABSL_THREAD_IDENTITY_MODE
#error ABSL_THREAD_IDENTITY_MODE cannot be directly set
#elif defined(ABSL_FORCE_THREAD_IDENTITY_MODE)
#define ABSL_THREAD_IDENTITY_MODE ABSL_FORCE_THREAD_IDENTITY_MODE
#elif defined(_WIN32) && !defined(__MINGW32__)
#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11
#elif defined(__APPLE__) && defined(ABSL_HAVE_THREAD_LOCAL)
#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11
#elif ABSL_PER_THREAD_TLS && defined(__GOOGLE_GRTE_VERSION__) && \
(__GOOGLE_GRTE_VERSION__ >= 20140228L)
#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_TLS
#else
#define ABSL_THREAD_IDENTITY_MODE \
ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
#endif
#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
#if ABSL_PER_THREAD_TLS
ABSL_CONST_INIT extern ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity*
thread_identity_ptr;
#elif defined(ABSL_HAVE_THREAD_LOCAL)
ABSL_CONST_INIT extern thread_local ThreadIdentity* thread_identity_ptr;
#else
#error Thread-local storage not detected on this platform
#endif
#if !defined(__APPLE__) && !defined(ABSL_BUILD_DLL) && \
!defined(ABSL_CONSUME_DLL)
#define ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT 1
#endif
#ifdef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT
inline ThreadIdentity* CurrentThreadIdentityIfPresent() {
return thread_identity_ptr;
}
#endif
#elif ABSL_THREAD_IDENTITY_MODE != \
ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
#error Unknown ABSL_THREAD_IDENTITY_MODE
#endif
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/thread_identity.h"
#if !defined(_WIN32) || defined(__MINGW32__)
#include <pthread.h>
#ifndef __wasi__
#include <signal.h>
#endif
#endif
#include <atomic>
#include <cassert>
#include <memory>
#include "absl/base/attributes.h"
#include "absl/base/call_once.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/spinlock.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
#if ABSL_THREAD_IDENTITY_MODE != ABSL_THREAD_IDENTITY_MODE_USE_CPP11
namespace {
absl::once_flag init_thread_identity_key_once;
pthread_key_t thread_identity_pthread_key;
std::atomic<bool> pthread_key_initialized(false);
void AllocateThreadIdentityKey(ThreadIdentityReclaimerFunction reclaimer) {
pthread_key_create(&thread_identity_pthread_key, reclaimer);
pthread_key_initialized.store(true, std::memory_order_release);
}
}
#endif
#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
ABSL_CONST_INIT
#if ABSL_HAVE_ATTRIBUTE(visibility) && !defined(__APPLE__)
__attribute__((visibility("protected")))
#endif
#if ABSL_PER_THREAD_TLS
ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity* thread_identity_ptr = nullptr;
#elif defined(ABSL_HAVE_THREAD_LOCAL)
thread_local ThreadIdentity* thread_identity_ptr = nullptr;
#endif
#endif
void SetCurrentThreadIdentity(ThreadIdentity* identity,
ThreadIdentityReclaimerFunction reclaimer) {
assert(CurrentThreadIdentityIfPresent() == nullptr);
#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey,
reclaimer);
#if defined(__wasi__) || defined(__EMSCRIPTEN__) || defined(__MINGW32__) || \
defined(__hexagon__)
pthread_setspecific(thread_identity_pthread_key,
reinterpret_cast<void*>(identity));
#else
sigset_t all_signals;
sigset_t curr_signals;
sigfillset(&all_signals);
pthread_sigmask(SIG_SETMASK, &all_signals, &curr_signals);
pthread_setspecific(thread_identity_pthread_key,
reinterpret_cast<void*>(identity));
pthread_sigmask(SIG_SETMASK, &curr_signals, nullptr);
#endif
#elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS
absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey,
reclaimer);
pthread_setspecific(thread_identity_pthread_key,
reinterpret_cast<void*>(identity));
thread_identity_ptr = identity;
#elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
thread_local std::unique_ptr<ThreadIdentity, ThreadIdentityReclaimerFunction>
holder(identity, reclaimer);
thread_identity_ptr = identity;
#else
#error Unimplemented ABSL_THREAD_IDENTITY_MODE
#endif
}
#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
#ifndef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT
ThreadIdentity* CurrentThreadIdentityIfPresent() { return thread_identity_ptr; }
#endif
#endif
void ClearCurrentThreadIdentity() {
#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
thread_identity_ptr = nullptr;
#elif ABSL_THREAD_IDENTITY_MODE == \
ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
assert(CurrentThreadIdentityIfPresent() == nullptr);
#endif
}
#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
ThreadIdentity* CurrentThreadIdentityIfPresent() {
bool initialized = pthread_key_initialized.load(std::memory_order_acquire);
if (!initialized) {
return nullptr;
}
return reinterpret_cast<ThreadIdentity*>(
pthread_getspecific(thread_identity_pthread_key));
}
#endif
}
ABSL_NAMESPACE_END
} | #include "absl/base/internal/thread_identity.h"
#include <thread>
#include <vector>
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/internal/spinlock.h"
#include "absl/base/macros.h"
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/internal/per_thread_sem.h"
#include "absl/synchronization/mutex.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
ABSL_CONST_INIT static absl::base_internal::SpinLock map_lock(
absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
ABSL_CONST_INIT static int num_identities_reused ABSL_GUARDED_BY(map_lock);
static const void* const kCheckNoIdentity = reinterpret_cast<void*>(1);
static void TestThreadIdentityCurrent(const void* assert_no_identity) {
ThreadIdentity* identity;
if (assert_no_identity == kCheckNoIdentity) {
identity = CurrentThreadIdentityIfPresent();
EXPECT_TRUE(identity == nullptr);
}
identity = synchronization_internal::GetOrCreateCurrentThreadIdentity();
EXPECT_TRUE(identity != nullptr);
ThreadIdentity* identity_no_init;
identity_no_init = CurrentThreadIdentityIfPresent();
EXPECT_TRUE(identity == identity_no_init);
EXPECT_EQ(0, reinterpret_cast<intptr_t>(&identity->per_thread_synch) %
PerThreadSynch::kAlignment);
EXPECT_EQ(identity, identity->per_thread_synch.thread_identity());
absl::base_internal::SpinLockHolder l(&map_lock);
num_identities_reused++;
}
TEST(ThreadIdentityTest, BasicIdentityWorks) {
TestThreadIdentityCurrent(nullptr);
}
TEST(ThreadIdentityTest, BasicIdentityWorksThreaded) {
static const int kNumLoops = 3;
static const int kNumThreads = 32;
for (int iter = 0; iter < kNumLoops; iter++) {
std::vector<std::thread> threads;
for (int i = 0; i < kNumThreads; ++i) {
threads.push_back(
std::thread(TestThreadIdentityCurrent, kCheckNoIdentity));
}
for (auto& thread : threads) {
thread.join();
}
}
absl::base_internal::SpinLockHolder l(&map_lock);
EXPECT_LT(kNumThreads, num_identities_reused);
}
TEST(ThreadIdentityTest, ReusedThreadIdentityMutexTest) {
static const int kNumLoops = 10;
static const int kNumThreads = 12;
static const int kNumMutexes = 3;
static const int kNumLockLoops = 5;
Mutex mutexes[kNumMutexes];
for (int iter = 0; iter < kNumLoops; ++iter) {
std::vector<std::thread> threads;
for (int thread = 0; thread < kNumThreads; ++thread) {
threads.push_back(std::thread([&]() {
for (int l = 0; l < kNumLockLoops; ++l) {
for (int m = 0; m < kNumMutexes; ++m) {
MutexLock lock(&mutexes[m]);
}
}
}));
}
for (auto& thread : threads) {
thread.join();
}
}
}
}
}
ABSL_NAMESPACE_END
} |
2,514 | cpp | abseil/abseil-cpp | poison | absl/base/internal/poison.cc | absl/base/internal/poison_test.cc | #ifndef ABSL_BASE_INTERNAL_POISON_H_
#define ABSL_BASE_INTERNAL_POISON_H_
#include <atomic>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
extern std::atomic<void*> poison_data;
inline void* get_poisoned_pointer() {
return poison_data.load(std::memory_order_relaxed);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/poison.h"
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#if defined(ABSL_HAVE_ADDRESS_SANITIZER)
#include <sanitizer/asan_interface.h>
#elif defined(ABSL_HAVE_MEMORY_SANITIZER)
#include <sanitizer/msan_interface.h>
#elif defined(ABSL_HAVE_MMAP) && !defined(SGX_SIM)
#include <sys/mman.h>
#elif defined(_MSC_VER)
#include <windows.h>
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
constexpr size_t kPageSize = 1 << 12;
alignas(kPageSize) static char poison_page[kPageSize];
}
std::atomic<void*> poison_data = {&poison_page};
namespace {
#if defined(ABSL_HAVE_ADDRESS_SANITIZER)
void PoisonBlock(void* data) { ASAN_POISON_MEMORY_REGION(data, kPageSize); }
#elif defined(ABSL_HAVE_MEMORY_SANITIZER)
void PoisonBlock(void* data) { __msan_poison(data, kPageSize); }
#elif defined(ABSL_HAVE_MMAP)
void PoisonBlock(void* data) { mprotect(data, kPageSize, PROT_NONE); }
#elif defined(_MSC_VER)
void PoisonBlock(void* data) {
DWORD old_mode = 0;
VirtualProtect(data, kPageSize, PAGE_NOACCESS, &old_mode);
}
#else
void PoisonBlock(void* data) {
constexpr uint64_t kBadPtr = 0xBAD0BAD0BAD0BAD0;
poison_data = reinterpret_cast<void*>(static_cast<uintptr_t>(kBadPtr));
}
#endif
void* InitializePoisonedPointer() {
PoisonBlock(&poison_page);
return &poison_page;
}
}
ABSL_ATTRIBUTE_UNUSED void* force_initialize = InitializePoisonedPointer();
}
ABSL_NAMESPACE_END
} | #include "absl/base/internal/poison.h"
#include <iostream>
#include "gtest/gtest.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
TEST(PoisonTest, CrashesOnDereference) {
#ifdef __ANDROID__
GTEST_SKIP() << "On Android, poisoned pointer dereference times out instead "
"of crashing.";
#endif
void* poisoned_ptr = get_poisoned_pointer();
EXPECT_DEATH_IF_SUPPORTED(std::cout << *static_cast<int*>(poisoned_ptr), "");
}
}
}
ABSL_NAMESPACE_END
} |
2,515 | cpp | abseil/abseil-cpp | low_level_alloc | absl/base/internal/low_level_alloc.cc | absl/base/internal/low_level_alloc_test.cc | #ifndef ABSL_BASE_INTERNAL_LOW_LEVEL_ALLOC_H_
#define ABSL_BASE_INTERNAL_LOW_LEVEL_ALLOC_H_
#include <sys/types.h>
#include <cstdint>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#ifdef ABSL_LOW_LEVEL_ALLOC_MISSING
#error ABSL_LOW_LEVEL_ALLOC_MISSING cannot be directly set
#elif !defined(ABSL_HAVE_MMAP) && !defined(_WIN32)
#define ABSL_LOW_LEVEL_ALLOC_MISSING 1
#endif
#ifdef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
#error ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING cannot be directly set
#elif defined(_WIN32) || defined(__asmjs__) || defined(__wasm__) || \
defined(__hexagon__)
#define ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING 1
#endif
#include <cstddef>
#include "absl/base/port.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
class LowLevelAlloc {
public:
struct Arena;
static void *Alloc(size_t request) ABSL_ATTRIBUTE_SECTION(malloc_hook);
static void *AllocWithArena(size_t request, Arena *arena)
ABSL_ATTRIBUTE_SECTION(malloc_hook);
static void Free(void *s) ABSL_ATTRIBUTE_SECTION(malloc_hook);
enum {
kCallMallocHook = 0x0001,
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
kAsyncSignalSafe = 0x0002,
#endif
};
static Arena *NewArena(uint32_t flags);
static bool DeleteArena(Arena *arena);
static Arena *DefaultArena();
private:
LowLevelAlloc();
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/low_level_alloc.h"
#include <type_traits>
#include "absl/base/call_once.h"
#include "absl/base/config.h"
#include "absl/base/internal/direct_mmap.h"
#include "absl/base/internal/scheduling_mode.h"
#include "absl/base/macros.h"
#include "absl/base/thread_annotations.h"
#ifndef ABSL_LOW_LEVEL_ALLOC_MISSING
#ifndef _WIN32
#include <pthread.h>
#include <signal.h>
#include <sys/mman.h>
#include <unistd.h>
#else
#include <windows.h>
#endif
#ifdef __linux__
#include <sys/prctl.h>
#endif
#include <string.h>
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <cstddef>
#include <new>
#include "absl/base/dynamic_annotations.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/spinlock.h"
#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
#define MAP_ANONYMOUS MAP_ANON
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
static const int kMaxLevel = 30;
namespace {
struct AllocList {
struct Header {
uintptr_t size;
uintptr_t magic;
LowLevelAlloc::Arena *arena;
void *dummy_for_alignment;
} header;
int levels;
AllocList *next[kMaxLevel];
};
}
static int IntLog2(size_t size, size_t base) {
int result = 0;
for (size_t i = size; i > base; i >>= 1) {
result++;
}
return result;
}
static int Random(uint32_t *state) {
uint32_t r = *state;
int result = 1;
while ((((r = r * 1103515245 + 12345) >> 30) & 1) == 0) {
result++;
}
*state = r;
return result;
}
static int LLA_SkiplistLevels(size_t size, size_t base, uint32_t *random) {
size_t max_fit = (size - offsetof(AllocList, next)) / sizeof(AllocList *);
int level = IntLog2(size, base) + (random != nullptr ? Random(random) : 1);
if (static_cast<size_t>(level) > max_fit) level = static_cast<int>(max_fit);
if (level > kMaxLevel - 1) level = kMaxLevel - 1;
ABSL_RAW_CHECK(level >= 1, "block not big enough for even one level");
return level;
}
static AllocList *LLA_SkiplistSearch(AllocList *head, AllocList *e,
AllocList **prev) {
AllocList *p = head;
for (int level = head->levels - 1; level >= 0; level--) {
for (AllocList *n; (n = p->next[level]) != nullptr && n < e; p = n) {
}
prev[level] = p;
}
return (head->levels == 0) ? nullptr : prev[0]->next[0];
}
static void LLA_SkiplistInsert(AllocList *head, AllocList *e,
AllocList **prev) {
LLA_SkiplistSearch(head, e, prev);
for (; head->levels < e->levels; head->levels++) {
prev[head->levels] = head;
}
for (int i = 0; i != e->levels; i++) {
e->next[i] = prev[i]->next[i];
prev[i]->next[i] = e;
}
}
static void LLA_SkiplistDelete(AllocList *head, AllocList *e,
AllocList **prev) {
AllocList *found = LLA_SkiplistSearch(head, e, prev);
ABSL_RAW_CHECK(e == found, "element not in freelist");
for (int i = 0; i != e->levels && prev[i]->next[i] == e; i++) {
prev[i]->next[i] = e->next[i];
}
while (head->levels > 0 && head->next[head->levels - 1] == nullptr) {
head->levels--;
}
}
struct LowLevelAlloc::Arena {
explicit Arena(uint32_t flags_value);
base_internal::SpinLock mu;
AllocList freelist ABSL_GUARDED_BY(mu);
int32_t allocation_count ABSL_GUARDED_BY(mu);
const uint32_t flags;
const size_t pagesize;
const size_t round_up;
const size_t min_size;
uint32_t random ABSL_GUARDED_BY(mu);
};
namespace {
alignas(LowLevelAlloc::Arena) unsigned char default_arena_storage[sizeof(
LowLevelAlloc::Arena)];
alignas(LowLevelAlloc::Arena) unsigned char unhooked_arena_storage[sizeof(
LowLevelAlloc::Arena)];
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
alignas(
LowLevelAlloc::Arena) unsigned char unhooked_async_sig_safe_arena_storage
[sizeof(LowLevelAlloc::Arena)];
#endif
absl::once_flag create_globals_once;
void CreateGlobalArenas() {
new (&default_arena_storage)
LowLevelAlloc::Arena(LowLevelAlloc::kCallMallocHook);
new (&unhooked_arena_storage) LowLevelAlloc::Arena(0);
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
new (&unhooked_async_sig_safe_arena_storage)
LowLevelAlloc::Arena(LowLevelAlloc::kAsyncSignalSafe);
#endif
}
LowLevelAlloc::Arena *UnhookedArena() {
base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas);
return reinterpret_cast<LowLevelAlloc::Arena *>(&unhooked_arena_storage);
}
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
LowLevelAlloc::Arena *UnhookedAsyncSigSafeArena() {
base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas);
return reinterpret_cast<LowLevelAlloc::Arena *>(
&unhooked_async_sig_safe_arena_storage);
}
#endif
}
LowLevelAlloc::Arena *LowLevelAlloc::DefaultArena() {
base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas);
return reinterpret_cast<LowLevelAlloc::Arena *>(&default_arena_storage);
}
static const uintptr_t kMagicAllocated = 0x4c833e95U;
static const uintptr_t kMagicUnallocated = ~kMagicAllocated;
namespace {
class ABSL_SCOPED_LOCKABLE ArenaLock {
public:
explicit ArenaLock(LowLevelAlloc::Arena *arena)
ABSL_EXCLUSIVE_LOCK_FUNCTION(arena->mu)
: arena_(arena) {
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) != 0) {
sigset_t all;
sigfillset(&all);
mask_valid_ = pthread_sigmask(SIG_BLOCK, &all, &mask_) == 0;
}
#endif
arena_->mu.Lock();
}
~ArenaLock() { ABSL_RAW_CHECK(left_, "haven't left Arena region"); }
void Leave() ABSL_UNLOCK_FUNCTION() {
arena_->mu.Unlock();
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
if (mask_valid_) {
const int err = pthread_sigmask(SIG_SETMASK, &mask_, nullptr);
if (err != 0) {
ABSL_RAW_LOG(FATAL, "pthread_sigmask failed: %d", err);
}
}
#endif
left_ = true;
}
private:
bool left_ = false;
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
bool mask_valid_ = false;
sigset_t mask_;
#endif
LowLevelAlloc::Arena *arena_;
ArenaLock(const ArenaLock &) = delete;
ArenaLock &operator=(const ArenaLock &) = delete;
};
}
inline static uintptr_t Magic(uintptr_t magic, AllocList::Header *ptr) {
return magic ^ reinterpret_cast<uintptr_t>(ptr);
}
namespace {
size_t GetPageSize() {
#ifdef _WIN32
SYSTEM_INFO system_info;
GetSystemInfo(&system_info);
return std::max(system_info.dwPageSize, system_info.dwAllocationGranularity);
#elif defined(__wasm__) || defined(__asmjs__) || defined(__hexagon__)
return getpagesize();
#else
return static_cast<size_t>(sysconf(_SC_PAGESIZE));
#endif
}
size_t RoundedUpBlockSize() {
size_t round_up = 16;
while (round_up < sizeof(AllocList::Header)) {
round_up += round_up;
}
return round_up;
}
}
LowLevelAlloc::Arena::Arena(uint32_t flags_value)
: mu(base_internal::SCHEDULE_KERNEL_ONLY),
allocation_count(0),
flags(flags_value),
pagesize(GetPageSize()),
round_up(RoundedUpBlockSize()),
min_size(2 * round_up),
random(0) {
freelist.header.size = 0;
freelist.header.magic = Magic(kMagicUnallocated, &freelist.header);
freelist.header.arena = this;
freelist.levels = 0;
memset(freelist.next, 0, sizeof(freelist.next));
}
LowLevelAlloc::Arena *LowLevelAlloc::NewArena(uint32_t flags) {
Arena *meta_data_arena = DefaultArena();
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
if ((flags & LowLevelAlloc::kAsyncSignalSafe) != 0) {
meta_data_arena = UnhookedAsyncSigSafeArena();
} else
#endif
if ((flags & LowLevelAlloc::kCallMallocHook) == 0) {
meta_data_arena = UnhookedArena();
}
Arena *result =
new (AllocWithArena(sizeof(*result), meta_data_arena)) Arena(flags);
return result;
}
bool LowLevelAlloc::DeleteArena(Arena *arena) {
ABSL_RAW_CHECK(
arena != nullptr && arena != DefaultArena() && arena != UnhookedArena(),
"may not delete default arena");
ArenaLock section(arena);
if (arena->allocation_count != 0) {
section.Leave();
return false;
}
while (arena->freelist.next[0] != nullptr) {
AllocList *region = arena->freelist.next[0];
size_t size = region->header.size;
arena->freelist.next[0] = region->next[0];
ABSL_RAW_CHECK(
region->header.magic == Magic(kMagicUnallocated, ®ion->header),
"bad magic number in DeleteArena()");
ABSL_RAW_CHECK(region->header.arena == arena,
"bad arena pointer in DeleteArena()");
ABSL_RAW_CHECK(size % arena->pagesize == 0,
"empty arena has non-page-aligned block size");
ABSL_RAW_CHECK(reinterpret_cast<uintptr_t>(region) % arena->pagesize == 0,
"empty arena has non-page-aligned block");
int munmap_result;
#ifdef _WIN32
munmap_result = VirtualFree(region, 0, MEM_RELEASE);
ABSL_RAW_CHECK(munmap_result != 0,
"LowLevelAlloc::DeleteArena: VitualFree failed");
#else
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) == 0) {
munmap_result = munmap(region, size);
} else {
munmap_result = base_internal::DirectMunmap(region, size);
}
#else
munmap_result = munmap(region, size);
#endif
if (munmap_result != 0) {
ABSL_RAW_LOG(FATAL, "LowLevelAlloc::DeleteArena: munmap failed: %d",
errno);
}
#endif
}
section.Leave();
arena->~Arena();
Free(arena);
return true;
}
static inline uintptr_t CheckedAdd(uintptr_t a, uintptr_t b) {
uintptr_t sum = a + b;
ABSL_RAW_CHECK(sum >= a, "LowLevelAlloc arithmetic overflow");
return sum;
}
static inline uintptr_t RoundUp(uintptr_t addr, uintptr_t align) {
return CheckedAdd(addr, align - 1) & ~(align - 1);
}
static AllocList *Next(int i, AllocList *prev, LowLevelAlloc::Arena *arena) {
ABSL_RAW_CHECK(i < prev->levels, "too few levels in Next()");
AllocList *next = prev->next[i];
if (next != nullptr) {
ABSL_RAW_CHECK(
next->header.magic == Magic(kMagicUnallocated, &next->header),
"bad magic number in Next()");
ABSL_RAW_CHECK(next->header.arena == arena, "bad arena pointer in Next()");
if (prev != &arena->freelist) {
ABSL_RAW_CHECK(prev < next, "unordered freelist");
ABSL_RAW_CHECK(reinterpret_cast<char *>(prev) + prev->header.size <
reinterpret_cast<char *>(next),
"malformed freelist");
}
}
return next;
}
static void Coalesce(AllocList *a) {
AllocList *n = a->next[0];
if (n != nullptr && reinterpret_cast<char *>(a) + a->header.size ==
reinterpret_cast<char *>(n)) {
LowLevelAlloc::Arena *arena = a->header.arena;
a->header.size += n->header.size;
n->header.magic = 0;
n->header.arena = nullptr;
AllocList *prev[kMaxLevel];
LLA_SkiplistDelete(&arena->freelist, n, prev);
LLA_SkiplistDelete(&arena->freelist, a, prev);
a->levels =
LLA_SkiplistLevels(a->header.size, arena->min_size, &arena->random);
LLA_SkiplistInsert(&arena->freelist, a, prev);
}
}
static void AddToFreelist(void *v, LowLevelAlloc::Arena *arena) {
AllocList *f = reinterpret_cast<AllocList *>(reinterpret_cast<char *>(v) -
sizeof(f->header));
ABSL_RAW_CHECK(f->header.magic == Magic(kMagicAllocated, &f->header),
"bad magic number in AddToFreelist()");
ABSL_RAW_CHECK(f->header.arena == arena,
"bad arena pointer in AddToFreelist()");
f->levels =
LLA_SkiplistLevels(f->header.size, arena->min_size, &arena->random);
AllocList *prev[kMaxLevel];
LLA_SkiplistInsert(&arena->freelist, f, prev);
f->header.magic = Magic(kMagicUnallocated, &f->header);
Coalesce(f);
Coalesce(prev[0]);
}
void LowLevelAlloc::Free(void *v) {
if (v != nullptr) {
AllocList *f = reinterpret_cast<AllocList *>(reinterpret_cast<char *>(v) -
sizeof(f->header));
LowLevelAlloc::Arena *arena = f->header.arena;
ArenaLock section(arena);
AddToFreelist(v, arena);
ABSL_RAW_CHECK(arena->allocation_count > 0, "nothing in arena to free");
arena->allocation_count--;
section.Leave();
}
}
static void *DoAllocWithArena(size_t request, LowLevelAlloc::Arena *arena) {
void *result = nullptr;
if (request != 0) {
AllocList *s;
ArenaLock section(arena);
size_t req_rnd =
RoundUp(CheckedAdd(request, sizeof(s->header)), arena->round_up);
for (;;) {
int i = LLA_SkiplistLevels(req_rnd, arena->min_size, nullptr) - 1;
if (i < arena->freelist.levels) {
AllocList *before = &arena->freelist;
while ((s = Next(i, before, arena)) != nullptr &&
s->header.size < req_rnd) {
before = s;
}
if (s != nullptr) {
break;
}
}
arena->mu.Unlock();
size_t new_pages_size = RoundUp(req_rnd, arena->pagesize * 16);
void *new_pages;
#ifdef _WIN32
new_pages = VirtualAlloc(nullptr, new_pages_size,
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
ABSL_RAW_CHECK(new_pages != nullptr, "VirtualAlloc failed");
#else
#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) != 0) {
new_pages = base_internal::DirectMmap(nullptr, new_pages_size,
PROT_WRITE|PROT_READ, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
} else {
new_pages = mmap(nullptr, new_pages_size, PROT_WRITE | PROT_READ,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
}
#else
new_pages = mmap(nullptr, new_pages_size, PROT_WRITE | PROT_READ,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
#endif
if (new_pages == MAP_FAILED) {
ABSL_RAW_LOG(FATAL, "mmap error: %d", errno);
}
#ifdef __linux__
#if defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, new_pages, new_pages_size,
"absl");
#endif
#endif
#endif
arena->mu.Lock();
s = reinterpret_cast<AllocList *>(new_pages);
s->header.size = new_pages_size;
s->header.magic = Magic(kMagicAllocated, &s->header);
s->header.arena = arena;
AddToFreelist(&s->levels, arena);
}
AllocList *prev[kMaxLevel];
LLA_SkiplistDelete(&arena->freelist, s, prev);
if (CheckedAdd(req_rnd, arena->min_size) <= s->header.size) {
AllocList *n =
reinterpret_cast<AllocList *>(req_rnd + reinterpret_cast<char *>(s));
n->header.size = s->header.size - req_rnd;
n->header.magic = Magic(kMagicAllocated, &n->header);
n->header.arena = arena;
s->header.size = req_rnd;
AddToFreelist(&n->levels, arena);
}
s->header.magic = Magic(kMagicAllocated, &s->header);
ABSL_RAW_CHECK(s->header.arena == arena, "");
arena->allocation_count++;
section.Leave();
result = &s->levels;
}
ABSL_ANNOTATE_MEMORY_IS_UNINITIALIZED(result, request);
return result;
}
void *LowLevelAlloc::Alloc(size_t request) {
void *result = DoAllocWithArena(request, DefaultArena());
return result;
}
void *LowLevelAlloc::AllocWithArena(size_t request, Arena *arena) {
ABSL_RAW_CHECK(arena != nullptr, "must pass a valid arena");
void *result = DoAllocWithArena(request, arena);
return result;
}
}
ABSL_NAMESPACE_END
}
#endif | #include "absl/base/internal/low_level_alloc.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <unordered_map>
#include <utility>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#include "absl/container/node_hash_map.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
#define TEST_ASSERT(x) \
if (!(x)) { \
printf("TEST_ASSERT(%s) FAILED ON LINE %d\n", #x, __LINE__); \
abort(); \
}
struct BlockDesc {
char *ptr;
int len;
int fill;
};
static void CheckBlockDesc(const BlockDesc &d) {
for (int i = 0; i != d.len; i++) {
TEST_ASSERT((d.ptr[i] & 0xff) == ((d.fill + i) & 0xff));
}
}
static void RandomizeBlockDesc(BlockDesc *d) {
d->fill = rand() & 0xff;
for (int i = 0; i != d->len; i++) {
d->ptr[i] = (d->fill + i) & 0xff;
}
}
static bool using_low_level_alloc = false;
static void Test(bool use_new_arena, bool call_malloc_hook, int n) {
typedef absl::node_hash_map<int, BlockDesc> AllocMap;
AllocMap allocated;
AllocMap::iterator it;
BlockDesc block_desc;
int rnd;
LowLevelAlloc::Arena *arena = nullptr;
if (use_new_arena) {
int32_t flags = call_malloc_hook ? LowLevelAlloc::kCallMallocHook : 0;
arena = LowLevelAlloc::NewArena(flags);
}
for (int i = 0; i != n; i++) {
if (i != 0 && i % 10000 == 0) {
printf(".");
fflush(stdout);
}
switch (rand() & 1) {
case 0:
using_low_level_alloc = true;
block_desc.len = rand() & 0x3fff;
block_desc.ptr = reinterpret_cast<char *>(
arena == nullptr
? LowLevelAlloc::Alloc(block_desc.len)
: LowLevelAlloc::AllocWithArena(block_desc.len, arena));
using_low_level_alloc = false;
RandomizeBlockDesc(&block_desc);
rnd = rand();
it = allocated.find(rnd);
if (it != allocated.end()) {
CheckBlockDesc(it->second);
using_low_level_alloc = true;
LowLevelAlloc::Free(it->second.ptr);
using_low_level_alloc = false;
it->second = block_desc;
} else {
allocated[rnd] = block_desc;
}
break;
case 1:
it = allocated.begin();
if (it != allocated.end()) {
CheckBlockDesc(it->second);
using_low_level_alloc = true;
LowLevelAlloc::Free(it->second.ptr);
using_low_level_alloc = false;
allocated.erase(it);
}
break;
}
}
while ((it = allocated.begin()) != allocated.end()) {
CheckBlockDesc(it->second);
using_low_level_alloc = true;
LowLevelAlloc::Free(it->second.ptr);
using_low_level_alloc = false;
allocated.erase(it);
}
if (use_new_arena) {
TEST_ASSERT(LowLevelAlloc::DeleteArena(arena));
}
}
static struct BeforeMain {
BeforeMain() {
Test(false, false, 50000);
Test(true, false, 50000);
Test(true, true, 50000);
}
} before_main;
}
}
ABSL_NAMESPACE_END
}
int main(int argc, char *argv[]) {
printf("PASS\n");
#ifdef __EMSCRIPTEN__
MAIN_THREAD_EM_ASM({
if (ENVIRONMENT_IS_WEB) {
if (typeof TEST_FINISH === 'function') {
TEST_FINISH($0);
} else {
console.error('Attempted to exit with status ' + $0);
console.error('But TEST_FINSIHED is not a function.');
}
}
}, 0);
#endif
return 0;
} |
2,516 | cpp | abseil/abseil-cpp | raw_logging | absl/base/internal/raw_logging.cc | absl/base/raw_logging_test.cc | #ifndef ABSL_BASE_INTERNAL_RAW_LOGGING_H_
#define ABSL_BASE_INTERNAL_RAW_LOGGING_H_
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/atomic_hook.h"
#include "absl/base/log_severity.h"
#include "absl/base/macros.h"
#include "absl/base/optimization.h"
#include "absl/base/port.h"
#define ABSL_RAW_LOG(severity, ...) \
do { \
constexpr const char* absl_raw_log_internal_basename = \
::absl::raw_log_internal::Basename(__FILE__, sizeof(__FILE__) - 1); \
::absl::raw_log_internal::RawLog(ABSL_RAW_LOG_INTERNAL_##severity, \
absl_raw_log_internal_basename, __LINE__, \
__VA_ARGS__); \
ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_##severity; \
} while (0)
#define ABSL_RAW_CHECK(condition, message) \
do { \
if (ABSL_PREDICT_FALSE(!(condition))) { \
ABSL_RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \
} \
} while (0)
#define ABSL_INTERNAL_LOG(severity, message) \
do { \
constexpr const char* absl_raw_log_internal_filename = __FILE__; \
::absl::raw_log_internal::internal_log_function( \
ABSL_RAW_LOG_INTERNAL_##severity, absl_raw_log_internal_filename, \
__LINE__, message); \
ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_##severity; \
} while (0)
#define ABSL_INTERNAL_CHECK(condition, message) \
do { \
if (ABSL_PREDICT_FALSE(!(condition))) { \
std::string death_message = "Check " #condition " failed: "; \
death_message += std::string(message); \
ABSL_INTERNAL_LOG(FATAL, death_message); \
} \
} while (0)
#ifndef NDEBUG
#define ABSL_RAW_DLOG(severity, ...) ABSL_RAW_LOG(severity, __VA_ARGS__)
#define ABSL_RAW_DCHECK(condition, message) ABSL_RAW_CHECK(condition, message)
#else
#define ABSL_RAW_DLOG(severity, ...) \
while (false) ABSL_RAW_LOG(severity, __VA_ARGS__)
#define ABSL_RAW_DCHECK(condition, message) \
while (false) ABSL_RAW_CHECK(condition, message)
#endif
#define ABSL_RAW_LOG_INTERNAL_INFO ::absl::LogSeverity::kInfo
#define ABSL_RAW_LOG_INTERNAL_WARNING ::absl::LogSeverity::kWarning
#define ABSL_RAW_LOG_INTERNAL_ERROR ::absl::LogSeverity::kError
#define ABSL_RAW_LOG_INTERNAL_FATAL ::absl::LogSeverity::kFatal
#define ABSL_RAW_LOG_INTERNAL_DFATAL ::absl::kLogDebugFatal
#define ABSL_RAW_LOG_INTERNAL_LEVEL(severity) \
::absl::NormalizeLogSeverity(severity)
#define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_INFO
#define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_WARNING
#define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_ERROR
#define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_FATAL ABSL_UNREACHABLE()
#define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_DFATAL
#define ABSL_RAW_LOG_INTERNAL_MAYBE_UNREACHABLE_LEVEL(severity)
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace raw_log_internal {
void RawLog(absl::LogSeverity severity, const char* file, int line,
const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
void AsyncSignalSafeWriteError(const char* s, size_t len);
constexpr const char* Basename(const char* fname, int offset) {
return offset == 0 || fname[offset - 1] == '/' || fname[offset - 1] == '\\'
? fname + offset
: Basename(fname, offset - 1);
}
bool RawLoggingFullySupported();
using LogFilterAndPrefixHook = bool (*)(absl::LogSeverity severity,
const char* file, int line, char** buf,
int* buf_size);
using AbortHook = void (*)(const char* file, int line, const char* buf_start,
const char* prefix_end, const char* buf_end);
using InternalLogFunction = void (*)(absl::LogSeverity severity,
const char* file, int line,
const std::string& message);
ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL extern base_internal::AtomicHook<
InternalLogFunction>
internal_log_function;
void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func);
void RegisterAbortHook(AbortHook func);
void RegisterInternalLogFunction(InternalLogFunction func);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/raw_logging.h"
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#ifdef __EMSCRIPTEN__
#include <emscripten/console.h>
#endif
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/atomic_hook.h"
#include "absl/base/internal/errno_saver.h"
#include "absl/base/log_severity.h"
#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
defined(__hexagon__) || defined(__Fuchsia__) || \
defined(__native_client__) || defined(__OpenBSD__) || \
defined(__EMSCRIPTEN__) || defined(__ASYLO__)
#include <unistd.h>
#define ABSL_HAVE_POSIX_WRITE 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_POSIX_WRITE
#endif
#if (defined(__linux__) || defined(__FreeBSD__)) && !defined(__ANDROID__)
#include <sys/syscall.h>
#define ABSL_HAVE_SYSCALL_WRITE 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_SYSCALL_WRITE
#endif
#ifdef _WIN32
#include <io.h>
#define ABSL_HAVE_RAW_IO 1
#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
#else
#undef ABSL_HAVE_RAW_IO
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace raw_log_internal {
namespace {
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
constexpr char kTruncated[] = " ... (message truncated)\n";
bool VADoRawLog(char** buf, int* size, const char* format, va_list ap)
ABSL_PRINTF_ATTRIBUTE(3, 0);
bool VADoRawLog(char** buf, int* size, const char* format, va_list ap) {
if (*size < 0) return false;
int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
bool result = true;
if (n < 0 || n > *size) {
result = false;
if (static_cast<size_t>(*size) > sizeof(kTruncated)) {
n = *size - static_cast<int>(sizeof(kTruncated));
} else {
n = 0;
}
}
*size -= n;
*buf += n;
return result;
}
#endif
constexpr int kLogBufSize = 3000;
bool DoRawLog(char** buf, int* size, const char* format, ...)
ABSL_PRINTF_ATTRIBUTE(3, 4);
bool DoRawLog(char** buf, int* size, const char* format, ...) {
if (*size < 0) return false;
va_list ap;
va_start(ap, format);
int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
va_end(ap);
if (n < 0 || n > *size) return false;
*size -= n;
*buf += n;
return true;
}
bool DefaultLogFilterAndPrefix(absl::LogSeverity, const char* file, int line,
char** buf, int* buf_size) {
DoRawLog(buf, buf_size, "[%s : %d] RAW: ", file, line);
return true;
}
ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
absl::base_internal::AtomicHook<LogFilterAndPrefixHook>
log_filter_and_prefix_hook(DefaultLogFilterAndPrefix);
ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
absl::base_internal::AtomicHook<AbortHook> abort_hook;
void RawLogVA(absl::LogSeverity severity, const char* file, int line,
const char* format, va_list ap) ABSL_PRINTF_ATTRIBUTE(4, 0);
void RawLogVA(absl::LogSeverity severity, const char* file, int line,
const char* format, va_list ap) {
char buffer[kLogBufSize];
char* buf = buffer;
int size = sizeof(buffer);
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
bool enabled = true;
#else
bool enabled = false;
#endif
#ifdef ABSL_MIN_LOG_LEVEL
if (severity < static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) &&
severity < absl::LogSeverity::kFatal) {
enabled = false;
}
#endif
enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size);
const char* const prefix_end = buf;
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
if (enabled) {
bool no_chop = VADoRawLog(&buf, &size, format, ap);
if (no_chop) {
DoRawLog(&buf, &size, "\n");
} else {
DoRawLog(&buf, &size, "%s", kTruncated);
}
AsyncSignalSafeWriteError(buffer, strlen(buffer));
}
#else
static_cast<void>(format);
static_cast<void>(ap);
static_cast<void>(enabled);
#endif
if (severity == absl::LogSeverity::kFatal) {
abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
abort();
}
}
void DefaultInternalLog(absl::LogSeverity severity, const char* file, int line,
const std::string& message) {
RawLog(severity, file, line, "%.*s", static_cast<int>(message.size()),
message.data());
}
}
void AsyncSignalSafeWriteError(const char* s, size_t len) {
if (!len) return;
absl::base_internal::ErrnoSaver errno_saver;
#if defined(__EMSCRIPTEN__)
if (s[len - 1] == '\n') {
len--;
}
#if ABSL_INTERNAL_EMSCRIPTEN_VERSION >= 3001043
emscripten_errn(s, len);
#else
char buf[kLogBufSize];
if (len >= kLogBufSize) {
len = kLogBufSize - 1;
constexpr size_t trunc_len = sizeof(kTruncated) - 2;
memcpy(buf + len - trunc_len, kTruncated, trunc_len);
buf[len] = '\0';
len -= trunc_len;
} else {
buf[len] = '\0';
}
memcpy(buf, s, len);
_emscripten_err(buf);
#endif
#elif defined(ABSL_HAVE_SYSCALL_WRITE)
syscall(SYS_write, STDERR_FILENO, s, len);
#elif defined(ABSL_HAVE_POSIX_WRITE)
write(STDERR_FILENO, s, len);
#elif defined(ABSL_HAVE_RAW_IO)
_write( 2, s, static_cast<unsigned>(len));
#else
(void)s;
(void)len;
#endif
}
void RawLog(absl::LogSeverity severity, const char* file, int line,
const char* format, ...) {
va_list ap;
va_start(ap, format);
RawLogVA(severity, file, line, format, ap);
va_end(ap);
}
bool RawLoggingFullySupported() {
#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
return true;
#else
return false;
#endif
}
ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL
absl::base_internal::AtomicHook<InternalLogFunction>
internal_log_function(DefaultInternalLog);
void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func) {
log_filter_and_prefix_hook.Store(func);
}
void RegisterAbortHook(AbortHook func) { abort_hook.Store(func); }
void RegisterInternalLogFunction(InternalLogFunction func) {
internal_log_function.Store(func);
}
}
ABSL_NAMESPACE_END
} | #include "absl/base/internal/raw_logging.h"
#include <tuple>
#include "gtest/gtest.h"
#include "absl/strings/str_cat.h"
namespace {
TEST(RawLoggingCompilationTest, Log) {
ABSL_RAW_LOG(INFO, "RAW INFO: %d", 1);
ABSL_RAW_LOG(INFO, "RAW INFO: %d %d", 1, 2);
ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d", 1, 2, 3);
ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d", 1, 2, 3, 4);
ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d %d", 1, 2, 3, 4, 5);
ABSL_RAW_LOG(WARNING, "RAW WARNING: %d", 1);
ABSL_RAW_LOG(ERROR, "RAW ERROR: %d", 1);
}
TEST(RawLoggingCompilationTest, PassingCheck) {
ABSL_RAW_CHECK(true, "RAW CHECK");
}
const char kExpectedDeathOutput[] = "";
TEST(RawLoggingDeathTest, FailingCheck) {
EXPECT_DEATH_IF_SUPPORTED(ABSL_RAW_CHECK(1 == 0, "explanation"),
kExpectedDeathOutput);
}
TEST(RawLoggingDeathTest, LogFatal) {
EXPECT_DEATH_IF_SUPPORTED(ABSL_RAW_LOG(FATAL, "my dog has fleas"),
kExpectedDeathOutput);
}
TEST(InternalLog, CompilationTest) {
ABSL_INTERNAL_LOG(INFO, "Internal Log");
std::string log_msg = "Internal Log";
ABSL_INTERNAL_LOG(INFO, log_msg);
ABSL_INTERNAL_LOG(INFO, log_msg + " 2");
float d = 1.1f;
ABSL_INTERNAL_LOG(INFO, absl::StrCat("Internal log ", 3, " + ", d));
}
TEST(InternalLogDeathTest, FailingCheck) {
EXPECT_DEATH_IF_SUPPORTED(ABSL_INTERNAL_CHECK(1 == 0, "explanation"),
kExpectedDeathOutput);
}
TEST(InternalLogDeathTest, LogFatal) {
EXPECT_DEATH_IF_SUPPORTED(ABSL_INTERNAL_LOG(FATAL, "my dog has fleas"),
kExpectedDeathOutput);
}
} |
2,517 | cpp | abseil/abseil-cpp | throw_delegate | absl/base/internal/throw_delegate.cc | absl/base/throw_delegate_test.cc | #ifndef ABSL_BASE_INTERNAL_THROW_DELEGATE_H_
#define ABSL_BASE_INTERNAL_THROW_DELEGATE_H_
#include <string>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
[[noreturn]] void ThrowStdLogicError(const std::string& what_arg);
[[noreturn]] void ThrowStdLogicError(const char* what_arg);
[[noreturn]] void ThrowStdInvalidArgument(const std::string& what_arg);
[[noreturn]] void ThrowStdInvalidArgument(const char* what_arg);
[[noreturn]] void ThrowStdDomainError(const std::string& what_arg);
[[noreturn]] void ThrowStdDomainError(const char* what_arg);
[[noreturn]] void ThrowStdLengthError(const std::string& what_arg);
[[noreturn]] void ThrowStdLengthError(const char* what_arg);
[[noreturn]] void ThrowStdOutOfRange(const std::string& what_arg);
[[noreturn]] void ThrowStdOutOfRange(const char* what_arg);
[[noreturn]] void ThrowStdRuntimeError(const std::string& what_arg);
[[noreturn]] void ThrowStdRuntimeError(const char* what_arg);
[[noreturn]] void ThrowStdRangeError(const std::string& what_arg);
[[noreturn]] void ThrowStdRangeError(const char* what_arg);
[[noreturn]] void ThrowStdOverflowError(const std::string& what_arg);
[[noreturn]] void ThrowStdOverflowError(const char* what_arg);
[[noreturn]] void ThrowStdUnderflowError(const std::string& what_arg);
[[noreturn]] void ThrowStdUnderflowError(const char* what_arg);
[[noreturn]] void ThrowStdBadFunctionCall();
[[noreturn]] void ThrowStdBadAlloc();
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/throw_delegate.h"
#include <cstdlib>
#include <functional>
#include <new>
#include <stdexcept>
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
void ThrowStdLogicError(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::logic_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdLogicError(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::logic_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdInvalidArgument(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::invalid_argument(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdInvalidArgument(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::invalid_argument(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdDomainError(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::domain_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdDomainError(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::domain_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdLengthError(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::length_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdLengthError(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::length_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdOutOfRange(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::out_of_range(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdOutOfRange(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::out_of_range(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdRuntimeError(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::runtime_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdRuntimeError(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::runtime_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdRangeError(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::range_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdRangeError(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::range_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdOverflowError(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::overflow_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdOverflowError(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::overflow_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdUnderflowError(const std::string& what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::underflow_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
std::abort();
#endif
}
void ThrowStdUnderflowError(const char* what_arg) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::underflow_error(what_arg);
#else
ABSL_RAW_LOG(FATAL, "%s", what_arg);
std::abort();
#endif
}
void ThrowStdBadFunctionCall() {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::bad_function_call();
#else
std::abort();
#endif
}
void ThrowStdBadAlloc() {
#ifdef ABSL_HAVE_EXCEPTIONS
throw std::bad_alloc();
#else
std::abort();
#endif
}
}
ABSL_NAMESPACE_END
} | #include "absl/base/internal/throw_delegate.h"
#include <functional>
#include <new>
#include <stdexcept>
#include "absl/base/config.h"
#include "gtest/gtest.h"
namespace {
using absl::base_internal::ThrowStdLogicError;
using absl::base_internal::ThrowStdInvalidArgument;
using absl::base_internal::ThrowStdDomainError;
using absl::base_internal::ThrowStdLengthError;
using absl::base_internal::ThrowStdOutOfRange;
using absl::base_internal::ThrowStdRuntimeError;
using absl::base_internal::ThrowStdRangeError;
using absl::base_internal::ThrowStdOverflowError;
using absl::base_internal::ThrowStdUnderflowError;
using absl::base_internal::ThrowStdBadFunctionCall;
using absl::base_internal::ThrowStdBadAlloc;
constexpr const char* what_arg = "The quick brown fox jumps over the lazy dog";
template <typename E>
void ExpectThrowChar(void (*f)(const char*)) {
#ifdef ABSL_HAVE_EXCEPTIONS
try {
f(what_arg);
FAIL() << "Didn't throw";
} catch (const E& e) {
EXPECT_STREQ(e.what(), what_arg);
}
#else
EXPECT_DEATH_IF_SUPPORTED(f(what_arg), what_arg);
#endif
}
template <typename E>
void ExpectThrowString(void (*f)(const std::string&)) {
#ifdef ABSL_HAVE_EXCEPTIONS
try {
f(what_arg);
FAIL() << "Didn't throw";
} catch (const E& e) {
EXPECT_STREQ(e.what(), what_arg);
}
#else
EXPECT_DEATH_IF_SUPPORTED(f(what_arg), what_arg);
#endif
}
template <typename E>
void ExpectThrowNoWhat(void (*f)()) {
#ifdef ABSL_HAVE_EXCEPTIONS
try {
f();
FAIL() << "Didn't throw";
} catch (const E& e) {
}
#else
EXPECT_DEATH_IF_SUPPORTED(f(), "");
#endif
}
TEST(ThrowDelegate, ThrowStdLogicErrorChar) {
ExpectThrowChar<std::logic_error>(ThrowStdLogicError);
}
TEST(ThrowDelegate, ThrowStdInvalidArgumentChar) {
ExpectThrowChar<std::invalid_argument>(ThrowStdInvalidArgument);
}
TEST(ThrowDelegate, ThrowStdDomainErrorChar) {
ExpectThrowChar<std::domain_error>(ThrowStdDomainError);
}
TEST(ThrowDelegate, ThrowStdLengthErrorChar) {
ExpectThrowChar<std::length_error>(ThrowStdLengthError);
}
TEST(ThrowDelegate, ThrowStdOutOfRangeChar) {
ExpectThrowChar<std::out_of_range>(ThrowStdOutOfRange);
}
TEST(ThrowDelegate, ThrowStdRuntimeErrorChar) {
ExpectThrowChar<std::runtime_error>(ThrowStdRuntimeError);
}
TEST(ThrowDelegate, ThrowStdRangeErrorChar) {
ExpectThrowChar<std::range_error>(ThrowStdRangeError);
}
TEST(ThrowDelegate, ThrowStdOverflowErrorChar) {
ExpectThrowChar<std::overflow_error>(ThrowStdOverflowError);
}
TEST(ThrowDelegate, ThrowStdUnderflowErrorChar) {
ExpectThrowChar<std::underflow_error>(ThrowStdUnderflowError);
}
TEST(ThrowDelegate, ThrowStdLogicErrorString) {
ExpectThrowString<std::logic_error>(ThrowStdLogicError);
}
TEST(ThrowDelegate, ThrowStdInvalidArgumentString) {
ExpectThrowString<std::invalid_argument>(ThrowStdInvalidArgument);
}
TEST(ThrowDelegate, ThrowStdDomainErrorString) {
ExpectThrowString<std::domain_error>(ThrowStdDomainError);
}
TEST(ThrowDelegate, ThrowStdLengthErrorString) {
ExpectThrowString<std::length_error>(ThrowStdLengthError);
}
TEST(ThrowDelegate, ThrowStdOutOfRangeString) {
ExpectThrowString<std::out_of_range>(ThrowStdOutOfRange);
}
TEST(ThrowDelegate, ThrowStdRuntimeErrorString) {
ExpectThrowString<std::runtime_error>(ThrowStdRuntimeError);
}
TEST(ThrowDelegate, ThrowStdRangeErrorString) {
ExpectThrowString<std::range_error>(ThrowStdRangeError);
}
TEST(ThrowDelegate, ThrowStdOverflowErrorString) {
ExpectThrowString<std::overflow_error>(ThrowStdOverflowError);
}
TEST(ThrowDelegate, ThrowStdUnderflowErrorString) {
ExpectThrowString<std::underflow_error>(ThrowStdUnderflowError);
}
TEST(ThrowDelegate, ThrowStdBadFunctionCallNoWhat) {
#ifdef ABSL_HAVE_EXCEPTIONS
try {
ThrowStdBadFunctionCall();
FAIL() << "Didn't throw";
} catch (const std::bad_function_call&) {
}
#ifdef _LIBCPP_VERSION
catch (const std::exception&) {
}
#endif
#else
EXPECT_DEATH_IF_SUPPORTED(ThrowStdBadFunctionCall(), "");
#endif
}
TEST(ThrowDelegate, ThrowStdBadAllocNoWhat) {
ExpectThrowNoWhat<std::bad_alloc>(ThrowStdBadAlloc);
}
} |
2,518 | cpp | abseil/abseil-cpp | sysinfo | absl/base/internal/sysinfo.cc | absl/base/internal/sysinfo_test.cc | #ifndef ABSL_BASE_INTERNAL_SYSINFO_H_
#define ABSL_BASE_INTERNAL_SYSINFO_H_
#ifndef _WIN32
#include <sys/types.h>
#endif
#include <cstdint>
#include "absl/base/config.h"
#include "absl/base/port.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
double NominalCPUFrequency();
int NumCPUs();
#ifdef _WIN32
using pid_t = uint32_t;
#endif
pid_t GetTID();
pid_t GetCachedTID();
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/sysinfo.h"
#include "absl/base/attributes.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <fcntl.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#ifdef __linux__
#include <sys/syscall.h>
#endif
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif
#ifdef __FreeBSD__
#include <pthread_np.h>
#endif
#ifdef __NetBSD__
#include <lwp.h>
#endif
#if defined(__myriad2__)
#include <rtems.h>
#endif
#include <string.h>
#include <cassert>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <thread>
#include <utility>
#include <vector>
#include "absl/base/call_once.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/spinlock.h"
#include "absl/base/internal/unscaledcycleclock.h"
#include "absl/base/thread_annotations.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
#if defined(_WIN32)
DWORD Win32CountSetBits(ULONG_PTR bitMask) {
for (DWORD bitSetCount = 0; ; ++bitSetCount) {
if (bitMask == 0) return bitSetCount;
bitMask &= bitMask - 1;
}
}
int Win32NumCPUs() {
#pragma comment(lib, "kernel32.lib")
using Info = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;
DWORD info_size = sizeof(Info);
Info* info(static_cast<Info*>(malloc(info_size)));
if (info == nullptr) return 0;
bool success = GetLogicalProcessorInformation(info, &info_size);
if (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
free(info);
info = static_cast<Info*>(malloc(info_size));
if (info == nullptr) return 0;
success = GetLogicalProcessorInformation(info, &info_size);
}
DWORD logicalProcessorCount = 0;
if (success) {
Info* ptr = info;
DWORD byteOffset = 0;
while (byteOffset + sizeof(Info) <= info_size) {
switch (ptr->Relationship) {
case RelationProcessorCore:
logicalProcessorCount += Win32CountSetBits(ptr->ProcessorMask);
break;
case RelationNumaNode:
case RelationCache:
case RelationProcessorPackage:
break;
default:
break;
}
byteOffset += sizeof(Info);
ptr++;
}
}
free(info);
return static_cast<int>(logicalProcessorCount);
}
#endif
}
static int GetNumCPUs() {
#if defined(__myriad2__)
return 1;
#elif defined(_WIN32)
const int hardware_concurrency = Win32NumCPUs();
return hardware_concurrency ? hardware_concurrency : 1;
#elif defined(_AIX)
return sysconf(_SC_NPROCESSORS_ONLN);
#else
return static_cast<int>(std::thread::hardware_concurrency());
#endif
}
#if defined(_WIN32)
static double GetNominalCPUFrequency() {
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
!WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
return 1.0;
#else
#pragma comment(lib, "advapi32.lib")
HKEY key;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
KEY_READ, &key) == ERROR_SUCCESS) {
DWORD type = 0;
DWORD data = 0;
DWORD data_size = sizeof(data);
auto result = RegQueryValueExA(key, "~MHz", nullptr, &type,
reinterpret_cast<LPBYTE>(&data), &data_size);
RegCloseKey(key);
if (result == ERROR_SUCCESS && type == REG_DWORD &&
data_size == sizeof(data)) {
return data * 1e6;
}
}
return 1.0;
#endif
}
#elif defined(CTL_HW) && defined(HW_CPU_FREQ)
static double GetNominalCPUFrequency() {
unsigned freq;
size_t size = sizeof(freq);
int mib[2] = {CTL_HW, HW_CPU_FREQ};
if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) {
return static_cast<double>(freq);
}
return 1.0;
}
#else
static bool ReadLongFromFile(const char *file, long *value) {
bool ret = false;
#if defined(_POSIX_C_SOURCE)
const int file_mode = (O_RDONLY | O_CLOEXEC);
#else
const int file_mode = O_RDONLY;
#endif
int fd = open(file, file_mode);
if (fd != -1) {
char line[1024];
char *err;
memset(line, '\0', sizeof(line));
ssize_t len;
do {
len = read(fd, line, sizeof(line) - 1);
} while (len < 0 && errno == EINTR);
if (len <= 0) {
ret = false;
} else {
const long temp_value = strtol(line, &err, 10);
if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
*value = temp_value;
ret = true;
}
}
close(fd);
}
return ret;
}
#if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
static int64_t ReadMonotonicClockNanos() {
struct timespec t;
#ifdef CLOCK_MONOTONIC_RAW
int rc = clock_gettime(CLOCK_MONOTONIC_RAW, &t);
#else
int rc = clock_gettime(CLOCK_MONOTONIC, &t);
#endif
if (rc != 0) {
ABSL_INTERNAL_LOG(
FATAL, "clock_gettime() failed: (" + std::to_string(errno) + ")");
}
return int64_t{t.tv_sec} * 1000000000 + t.tv_nsec;
}
class UnscaledCycleClockWrapperForInitializeFrequency {
public:
static int64_t Now() { return base_internal::UnscaledCycleClock::Now(); }
};
struct TimeTscPair {
int64_t time;
int64_t tsc;
};
static TimeTscPair GetTimeTscPair() {
int64_t best_latency = std::numeric_limits<int64_t>::max();
TimeTscPair best;
for (int i = 0; i < 10; ++i) {
int64_t t0 = ReadMonotonicClockNanos();
int64_t tsc = UnscaledCycleClockWrapperForInitializeFrequency::Now();
int64_t t1 = ReadMonotonicClockNanos();
int64_t latency = t1 - t0;
if (latency < best_latency) {
best_latency = latency;
best.time = t0;
best.tsc = tsc;
}
}
return best;
}
static double MeasureTscFrequencyWithSleep(int sleep_nanoseconds) {
auto t0 = GetTimeTscPair();
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = sleep_nanoseconds;
while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {}
auto t1 = GetTimeTscPair();
double elapsed_ticks = t1.tsc - t0.tsc;
double elapsed_time = (t1.time - t0.time) * 1e-9;
return elapsed_ticks / elapsed_time;
}
static double MeasureTscFrequency() {
double last_measurement = -1.0;
int sleep_nanoseconds = 1000000;
for (int i = 0; i < 8; ++i) {
double measurement = MeasureTscFrequencyWithSleep(sleep_nanoseconds);
if (measurement * 0.99 < last_measurement &&
last_measurement < measurement * 1.01) {
return measurement;
}
last_measurement = measurement;
sleep_nanoseconds *= 2;
}
return last_measurement;
}
#endif
static double GetNominalCPUFrequency() {
long freq = 0;
if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) {
return freq * 1e3;
}
#if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
return MeasureTscFrequency();
#else
if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
&freq)) {
return freq * 1e3;
}
return 1.0;
#endif
}
#endif
ABSL_CONST_INIT static once_flag init_num_cpus_once;
ABSL_CONST_INIT static int num_cpus = 0;
int NumCPUs() {
base_internal::LowLevelCallOnce(
&init_num_cpus_once, []() { num_cpus = GetNumCPUs(); });
return num_cpus;
}
ABSL_CONST_INIT static once_flag init_nominal_cpu_frequency_once;
ABSL_CONST_INIT static double nominal_cpu_frequency = 1.0;
double NominalCPUFrequency() {
base_internal::LowLevelCallOnce(
&init_nominal_cpu_frequency_once,
[]() { nominal_cpu_frequency = GetNominalCPUFrequency(); });
return nominal_cpu_frequency;
}
#if defined(_WIN32)
pid_t GetTID() {
return pid_t{GetCurrentThreadId()};
}
#elif defined(__linux__)
#ifndef SYS_gettid
#define SYS_gettid __NR_gettid
#endif
pid_t GetTID() {
return static_cast<pid_t>(syscall(SYS_gettid));
}
#elif defined(__akaros__)
pid_t GetTID() {
if (in_vcore_context())
return 0;
return reinterpret_cast<struct pthread_tcb *>(current_uthread)->id;
}
#elif defined(__myriad2__)
pid_t GetTID() {
uint32_t tid;
rtems_task_ident(RTEMS_SELF, 0, &tid);
return tid;
}
#elif defined(__APPLE__)
pid_t GetTID() {
uint64_t tid;
pthread_threadid_np(nullptr, &tid);
return static_cast<pid_t>(tid);
}
#elif defined(__FreeBSD__)
pid_t GetTID() { return static_cast<pid_t>(pthread_getthreadid_np()); }
#elif defined(__OpenBSD__)
pid_t GetTID() { return getthrid(); }
#elif defined(__NetBSD__)
pid_t GetTID() { return static_cast<pid_t>(_lwp_self()); }
#elif defined(__native_client__)
pid_t GetTID() {
auto* thread = pthread_self();
static_assert(sizeof(pid_t) == sizeof(thread),
"In NaCL int expected to be the same size as a pointer");
return reinterpret_cast<pid_t>(thread);
}
#else
pid_t GetTID() {
return static_cast<pid_t>(pthread_self());
}
#endif
pid_t GetCachedTID() {
#ifdef ABSL_HAVE_THREAD_LOCAL
static thread_local pid_t thread_id = GetTID();
return thread_id;
#else
return GetTID();
#endif
}
}
ABSL_NAMESPACE_END
} | #include "absl/base/internal/sysinfo.h"
#ifndef _WIN32
#include <sys/types.h>
#include <unistd.h>
#endif
#include <thread>
#include <unordered_set>
#include <vector>
#include "gtest/gtest.h"
#include "absl/synchronization/barrier.h"
#include "absl/synchronization/mutex.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
TEST(SysinfoTest, NumCPUs) {
EXPECT_NE(NumCPUs(), 0)
<< "NumCPUs() should not have the default value of 0";
}
TEST(SysinfoTest, GetTID) {
EXPECT_EQ(GetTID(), GetTID());
#ifdef __native_client__
return;
#endif
for (int i = 0; i < 10; ++i) {
constexpr int kNumThreads = 10;
Barrier all_threads_done(kNumThreads);
std::vector<std::thread> threads;
Mutex mutex;
std::unordered_set<pid_t> tids;
for (int j = 0; j < kNumThreads; ++j) {
threads.push_back(std::thread([&]() {
pid_t id = GetTID();
{
MutexLock lock(&mutex);
ASSERT_TRUE(tids.find(id) == tids.end());
tids.insert(id);
}
all_threads_done.Block();
}));
}
for (auto& thread : threads) {
thread.join();
}
}
}
#ifdef __linux__
TEST(SysinfoTest, LinuxGetTID) {
EXPECT_EQ(GetTID(), getpid());
}
#endif
}
}
ABSL_NAMESPACE_END
} |
2,519 | cpp | abseil/abseil-cpp | scoped_set_env | absl/base/internal/scoped_set_env.cc | absl/base/internal/scoped_set_env_test.cc | #ifndef ABSL_BASE_INTERNAL_SCOPED_SET_ENV_H_
#define ABSL_BASE_INTERNAL_SCOPED_SET_ENV_H_
#include <string>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
class ScopedSetEnv {
public:
ScopedSetEnv(const char* var_name, const char* new_value);
~ScopedSetEnv();
private:
std::string var_name_;
std::string old_value_;
bool was_unset_;
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/base/internal/scoped_set_env.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include <cstdlib>
#include "absl/base/internal/raw_logging.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace base_internal {
namespace {
#ifdef _WIN32
const int kMaxEnvVarValueSize = 1024;
#endif
void SetEnvVar(const char* name, const char* value) {
#ifdef _WIN32
SetEnvironmentVariableA(name, value);
#else
if (value == nullptr) {
::unsetenv(name);
} else {
::setenv(name, value, 1);
}
#endif
}
}
ScopedSetEnv::ScopedSetEnv(const char* var_name, const char* new_value)
: var_name_(var_name), was_unset_(false) {
#ifdef _WIN32
char buf[kMaxEnvVarValueSize];
auto get_res = GetEnvironmentVariableA(var_name_.c_str(), buf, sizeof(buf));
ABSL_INTERNAL_CHECK(get_res < sizeof(buf), "value exceeds buffer size");
if (get_res == 0) {
was_unset_ = (GetLastError() == ERROR_ENVVAR_NOT_FOUND);
} else {
old_value_.assign(buf, get_res);
}
SetEnvironmentVariableA(var_name_.c_str(), new_value);
#else
const char* val = ::getenv(var_name_.c_str());
if (val == nullptr) {
was_unset_ = true;
} else {
old_value_ = val;
}
#endif
SetEnvVar(var_name_.c_str(), new_value);
}
ScopedSetEnv::~ScopedSetEnv() {
SetEnvVar(var_name_.c_str(), was_unset_ ? nullptr : old_value_.c_str());
}
}
ABSL_NAMESPACE_END
} | #ifdef _WIN32
#include <windows.h>
#endif
#include "gtest/gtest.h"
#include "absl/base/internal/scoped_set_env.h"
namespace {
using absl::base_internal::ScopedSetEnv;
std::string GetEnvVar(const char* name) {
#ifdef _WIN32
char buf[1024];
auto get_res = GetEnvironmentVariableA(name, buf, sizeof(buf));
if (get_res >= sizeof(buf)) {
return "TOO_BIG";
}
if (get_res == 0) {
return "UNSET";
}
return std::string(buf, get_res);
#else
const char* val = ::getenv(name);
if (val == nullptr) {
return "UNSET";
}
return val;
#endif
}
TEST(ScopedSetEnvTest, SetNonExistingVarToString) {
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
{
ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
}
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
}
TEST(ScopedSetEnvTest, SetNonExistingVarToNull) {
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
{
ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr);
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
}
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
}
TEST(ScopedSetEnvTest, SetExistingVarToString) {
ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
{
ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "new_value");
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "new_value");
}
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
}
TEST(ScopedSetEnvTest, SetExistingVarToNull) {
ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
{
ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr);
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
}
EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
}
} |
2,520 | cpp | abseil/abseil-cpp | gaussian_distribution | absl/random/gaussian_distribution.cc | absl/random/gaussian_distribution_test.cc | #ifndef ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_
#define ABSL_RANDOM_GAUSSIAN_DISTRIBUTION_H_
#include <cmath>
#include <cstdint>
#include <istream>
#include <limits>
#include <type_traits>
#include "absl/base/config.h"
#include "absl/random/internal/fast_uniform_bits.h"
#include "absl/random/internal/generate_real.h"
#include "absl/random/internal/iostream_state_saver.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
class ABSL_DLL gaussian_distribution_base {
public:
template <typename URBG>
inline double zignor(URBG& g);
private:
friend class TableGenerator;
template <typename URBG>
inline double zignor_fallback(URBG& g,
bool neg);
static constexpr double kR = 3.442619855899;
static constexpr double kRInv = 0.29047645161474317;
static constexpr double kV = 9.91256303526217e-3;
static constexpr uint64_t kMask = 0x07f;
struct Tables {
double x[kMask + 2];
double f[kMask + 2];
};
static const Tables zg_;
random_internal::FastUniformBits<uint64_t> fast_u64_;
};
}
template <typename RealType = double>
class gaussian_distribution : random_internal::gaussian_distribution_base {
public:
using result_type = RealType;
class param_type {
public:
using distribution_type = gaussian_distribution;
explicit param_type(result_type mean = 0, result_type stddev = 1)
: mean_(mean), stddev_(stddev) {}
result_type mean() const { return mean_; }
result_type stddev() const { return stddev_; }
friend bool operator==(const param_type& a, const param_type& b) {
return a.mean_ == b.mean_ && a.stddev_ == b.stddev_;
}
friend bool operator!=(const param_type& a, const param_type& b) {
return !(a == b);
}
private:
result_type mean_;
result_type stddev_;
static_assert(
std::is_floating_point<RealType>::value,
"Class-template absl::gaussian_distribution<> must be parameterized "
"using a floating-point type.");
};
gaussian_distribution() : gaussian_distribution(0) {}
explicit gaussian_distribution(result_type mean, result_type stddev = 1)
: param_(mean, stddev) {}
explicit gaussian_distribution(const param_type& p) : param_(p) {}
void reset() {}
template <typename URBG>
result_type operator()(URBG& g) {
return (*this)(g, param_);
}
template <typename URBG>
result_type operator()(URBG& g,
const param_type& p);
param_type param() const { return param_; }
void param(const param_type& p) { param_ = p; }
result_type(min)() const {
return -std::numeric_limits<result_type>::infinity();
}
result_type(max)() const {
return std::numeric_limits<result_type>::infinity();
}
result_type mean() const { return param_.mean(); }
result_type stddev() const { return param_.stddev(); }
friend bool operator==(const gaussian_distribution& a,
const gaussian_distribution& b) {
return a.param_ == b.param_;
}
friend bool operator!=(const gaussian_distribution& a,
const gaussian_distribution& b) {
return a.param_ != b.param_;
}
private:
param_type param_;
};
template <typename RealType>
template <typename URBG>
typename gaussian_distribution<RealType>::result_type
gaussian_distribution<RealType>::operator()(
URBG& g,
const param_type& p) {
return p.mean() + p.stddev() * static_cast<result_type>(zignor(g));
}
template <typename CharT, typename Traits, typename RealType>
std::basic_ostream<CharT, Traits>& operator<<(
std::basic_ostream<CharT, Traits>& os,
const gaussian_distribution<RealType>& x) {
auto saver = random_internal::make_ostream_state_saver(os);
os.precision(random_internal::stream_precision_helper<RealType>::kPrecision);
os << x.mean() << os.fill() << x.stddev();
return os;
}
template <typename CharT, typename Traits, typename RealType>
std::basic_istream<CharT, Traits>& operator>>(
std::basic_istream<CharT, Traits>& is,
gaussian_distribution<RealType>& x) {
using result_type = typename gaussian_distribution<RealType>::result_type;
using param_type = typename gaussian_distribution<RealType>::param_type;
auto saver = random_internal::make_istream_state_saver(is);
auto mean = random_internal::read_floating_point<result_type>(is);
if (is.fail()) return is;
auto stddev = random_internal::read_floating_point<result_type>(is);
if (!is.fail()) {
x.param(param_type(mean, stddev));
}
return is;
}
namespace random_internal {
template <typename URBG>
inline double gaussian_distribution_base::zignor_fallback(URBG& g, bool neg) {
using random_internal::GeneratePositiveTag;
using random_internal::GenerateRealFromBits;
double x, y;
do {
x = kRInv *
std::log(GenerateRealFromBits<double, GeneratePositiveTag, false>(
fast_u64_(g)));
y = -std::log(
GenerateRealFromBits<double, GeneratePositiveTag, false>(fast_u64_(g)));
} while ((y + y) < (x * x));
return neg ? (x - kR) : (kR - x);
}
template <typename URBG>
inline double gaussian_distribution_base::zignor(
URBG& g) {
using random_internal::GeneratePositiveTag;
using random_internal::GenerateRealFromBits;
using random_internal::GenerateSignedTag;
while (true) {
uint64_t bits = fast_u64_(g);
int i = static_cast<int>(bits & kMask);
double j = GenerateRealFromBits<double, GenerateSignedTag, false>(
bits);
const double x = j * zg_.x[i];
if (std::abs(x) < zg_.x[i + 1]) {
return x;
}
if (i == 0) {
return zignor_fallback(g, j < 0);
}
double v = GenerateRealFromBits<double, GeneratePositiveTag, false>(
fast_u64_(g));
if ((zg_.f[i + 1] + v * (zg_.f[i] - zg_.f[i + 1])) <
std::exp(-0.5 * x * x)) {
return x;
}
}
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/gaussian_distribution.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
const gaussian_distribution_base::Tables
gaussian_distribution_base::zg_ = {
{3.7130862467425505, 3.442619855899000214, 3.223084984581141565,
3.083228858216868318, 2.978696252647779819, 2.894344007021528942,
2.82312535054891045, 2.761169372387176857, 2.706113573121819549,
2.656406411261359679, 2.610972248431847387, 2.56903362592493778,
2.530009672388827457, 2.493454522095372106, 2.459018177411830486,
2.426420645533749809, 2.395434278011062457, 2.365871370117638595,
2.337575241339236776, 2.310413683698762988, 2.284274059677471769,
2.25905957386919809, 2.234686395590979036, 2.21108140887870297,
2.188180432076048731, 2.165926793748921497, 2.144270182360394905,
2.123165708673976138, 2.102573135189237608, 2.082456237992015957,
2.062782274508307978, 2.043521536655067194, 2.02464697337738464,
2.006133869963471206, 1.987959574127619033, 1.970103260854325633,
1.952545729553555764, 1.935269228296621957, 1.918257300864508963,
1.901494653105150423, 1.884967035707758143, 1.868661140994487768,
1.852564511728090002, 1.836665460258444904, 1.820952996596124418,
1.805416764219227366, 1.790046982599857506, 1.77483439558606837,
1.759770224899592339, 1.744846128113799244, 1.730054160563729182,
1.71538674071366648, 1.700836618569915748, 1.686396846779167014,
1.6720607540975998, 1.657821920954023254, 1.643674156862867441,
1.629611479470633562, 1.615628095043159629, 1.601718380221376581,
1.587876864890574558, 1.574098216022999264, 1.560377222366167382,
1.546708779859908844, 1.533087877674041755, 1.519509584765938559,
1.505969036863201937, 1.492461423781352714, 1.478981976989922842,
1.465525957342709296, 1.452088642889222792, 1.438665316684561546,
1.425251254514058319, 1.411841712447055919, 1.398431914131003539,
1.385017037732650058, 1.371592202427340812, 1.358152454330141534,
1.34469275175354519, 1.331207949665625279, 1.317692783209412299,
1.304141850128615054, 1.290549591926194894, 1.27691027356015363,
1.263217961454619287, 1.249466499573066436, 1.23564948326336066,
1.221760230539994385, 1.207791750415947662, 1.193736707833126465,
1.17958738466398616, 1.165335636164750222, 1.150972842148865416,
1.136489852013158774, 1.121876922582540237, 1.107123647534034028,
1.092218876907275371, 1.077150624892893482, 1.061905963694822042,
1.046470900764042922, 1.030830236068192907, 1.014967395251327842,
0.9988642334929808131, 0.9825008035154263464, 0.9658550794011470098,
0.9489026255113034436, 0.9316161966151479401, 0.9139652510230292792,
0.8959153525809346874, 0.8774274291129204872, 0.8584568431938099931,
0.8389522142975741614, 0.8188539067003538507, 0.7980920606440534693,
0.7765839878947563557, 0.7542306644540520688, 0.7309119106424850631,
0.7064796113354325779, 0.6807479186691505202, 0.6534786387399710295,
0.6243585973360461505, 0.5929629424714434327, 0.5586921784081798625,
0.5206560387620546848, 0.4774378372966830431, 0.4265479863554152429,
0.3628714310970211909, 0.2723208648139477384, 0},
{0.001014352564120377413, 0.002669629083880922793, 0.005548995220771345792,
0.008624484412859888607, 0.01183947865788486861, 0.01516729801054656976,
0.01859210273701129151, 0.02210330461592709475, 0.02569329193593428151,
0.02935631744000685023, 0.03308788614622575758, 0.03688438878665621645,
0.04074286807444417458, 0.04466086220049143157, 0.04863629585986780496,
0.05266740190305100461, 0.05675266348104984759, 0.06089077034804041277,
0.06508058521306804567, 0.06932111739357792179, 0.07361150188411341722,
0.07795098251397346301, 0.08233889824223575293, 0.08677467189478028919,
0.09125780082683036809, 0.095787849121731522, 0.1003644410286559929,
0.1049872554094214289, 0.1096560210148404546, 0.1143705124488661323,
0.1191305467076509556, 0.1239359802028679736, 0.1287867061959434012,
0.1336826525834396151, 0.1386237799845948804, 0.1436100800906280339,
0.1486415742423425057, 0.1537183122081819397, 0.1588403711394795748,
0.1640078546834206341, 0.1692208922373653057, 0.1744796383307898324,
0.1797842721232958407, 0.1851349970089926078, 0.1905320403191375633,
0.1959756531162781534, 0.2014661100743140865, 0.2070037094399269362,
0.2125887730717307134, 0.2182216465543058426, 0.2239026993850088965,
0.229632325232116602, 0.2354109422634795556, 0.2412389935454402889,
0.2471169475123218551, 0.2530452985073261551, 0.2590245673962052742,
0.2650553022555897087, 0.271138079138385224, 0.2772735029191887857,
0.2834622082232336471, 0.2897048604429605656, 0.2960021568469337061,
0.3023548277864842593, 0.3087636380061818397, 0.3152293880650116065,
0.3217529158759855901, 0.3283350983728509642, 0.3349768533135899506,
0.3416791412315512977, 0.3484429675463274756, 0.355269384847918035,
0.3621594953693184626, 0.3691144536644731522, 0.376135469510563536,
0.3832238110559021416, 0.3903808082373155797, 0.3976078564938743676,
0.404906420807223999, 0.4122780401026620578, 0.4197243320495753771,
0.4272469983049970721, 0.4348478302499918513, 0.4425287152754694975,
0.4502916436820402768, 0.458138716267873114, 0.4660721526894572309,
0.4740943006930180559, 0.4822076463294863724, 0.4904148252838453348,
0.4987186354709807201, 0.5071220510755701794, 0.5156282382440030565,
0.5242405726729852944, 0.5329626593838373561, 0.5417983550254266145,
0.5507517931146057588, 0.5598274127040882009, 0.5690299910679523787,
0.5783646811197646898, 0.5878370544347081283, 0.5974531509445183408,
0.6072195366251219584, 0.6171433708188825973, 0.6272324852499290282,
0.6374954773350440806, 0.6479418211102242475, 0.6585820000500898219,
0.6694276673488921414, 0.6804918409973358395, 0.6917891434366769676,
0.7033360990161600101, 0.7151515074105005976, 0.7272569183441868201,
0.7396772436726493094, 0.7524415591746134169, 0.7655841738977066102,
0.7791460859296898134, 0.7931770117713072832, 0.8077382946829627652,
0.8229072113814113187, 0.8387836052959920519, 0.8555006078694531446,
0.873243048910072206, 0.8922816507840289901, 0.9130436479717434217,
0.9362826816850632339, 0.9635996931270905952, 1}};
}
ABSL_NAMESPACE_END
} | #include "absl/random/gaussian_distribution.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <ios>
#include <iterator>
#include <random>
#include <string>
#include <type_traits>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/macros.h"
#include "absl/log/log.h"
#include "absl/numeric/internal/representation.h"
#include "absl/random/internal/chi_square.h"
#include "absl/random/internal/distribution_test_util.h"
#include "absl/random/internal/sequence_urbg.h"
#include "absl/random/random.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/strip.h"
namespace {
using absl::random_internal::kChiSquared;
template <typename RealType>
class GaussianDistributionInterfaceTest : public ::testing::Test {};
using RealTypes =
std::conditional<absl::numeric_internal::IsDoubleDouble(),
::testing::Types<float, double>,
::testing::Types<float, double, long double>>::type;
TYPED_TEST_SUITE(GaussianDistributionInterfaceTest, RealTypes);
TYPED_TEST(GaussianDistributionInterfaceTest, SerializeTest) {
using param_type =
typename absl::gaussian_distribution<TypeParam>::param_type;
const TypeParam kParams[] = {
1,
std::nextafter(TypeParam(1), TypeParam(0)),
std::nextafter(TypeParam(1), TypeParam(2)),
TypeParam(1e-8), TypeParam(1e-4), TypeParam(2), TypeParam(1e4),
TypeParam(1e8), TypeParam(1e20), TypeParam(2.5),
std::numeric_limits<TypeParam>::infinity(),
std::numeric_limits<TypeParam>::max(),
std::numeric_limits<TypeParam>::epsilon(),
std::nextafter(std::numeric_limits<TypeParam>::min(),
TypeParam(1)),
std::numeric_limits<TypeParam>::min(),
std::numeric_limits<TypeParam>::denorm_min(),
std::numeric_limits<TypeParam>::min() / 2,
std::nextafter(std::numeric_limits<TypeParam>::min(),
TypeParam(0)),
};
constexpr int kCount = 1000;
absl::InsecureBitGen gen;
for (const auto mod : {0, 1, 2, 3}) {
for (const auto x : kParams) {
if (!std::isfinite(x)) continue;
for (const auto y : kParams) {
const TypeParam mean = (mod & 0x1) ? -x : x;
const TypeParam stddev = (mod & 0x2) ? -y : y;
const param_type param(mean, stddev);
absl::gaussian_distribution<TypeParam> before(mean, stddev);
EXPECT_EQ(before.mean(), param.mean());
EXPECT_EQ(before.stddev(), param.stddev());
{
absl::gaussian_distribution<TypeParam> via_param(param);
EXPECT_EQ(via_param, before);
EXPECT_EQ(via_param.param(), before.param());
}
auto sample_min = before.max();
auto sample_max = before.min();
for (int i = 0; i < kCount; i++) {
auto sample = before(gen);
if (sample > sample_max) sample_max = sample;
if (sample < sample_min) sample_min = sample;
EXPECT_GE(sample, before.min()) << before;
EXPECT_LE(sample, before.max()) << before;
}
if (!std::is_same<TypeParam, long double>::value) {
LOG(INFO) << "Range{" << mean << ", " << stddev << "}: " << sample_min
<< ", " << sample_max;
}
std::stringstream ss;
ss << before;
if (!std::isfinite(mean) || !std::isfinite(stddev)) {
continue;
}
absl::gaussian_distribution<TypeParam> after(-0.53f, 2.3456f);
EXPECT_NE(before.mean(), after.mean());
EXPECT_NE(before.stddev(), after.stddev());
EXPECT_NE(before.param(), after.param());
EXPECT_NE(before, after);
ss >> after;
EXPECT_EQ(before.mean(), after.mean());
EXPECT_EQ(before.stddev(), after.stddev())
<< ss.str() << " "
<< (ss.good() ? "good " : "")
<< (ss.bad() ? "bad " : "")
<< (ss.eof() ? "eof " : "")
<< (ss.fail() ? "fail " : "");
}
}
}
}
class GaussianModel {
public:
GaussianModel(double mean, double stddev) : mean_(mean), stddev_(stddev) {}
double mean() const { return mean_; }
double variance() const { return stddev() * stddev(); }
double stddev() const { return stddev_; }
double skew() const { return 0; }
double kurtosis() const { return 3.0; }
double InverseCDF(double p) {
ABSL_ASSERT(p >= 0.0);
ABSL_ASSERT(p < 1.0);
return mean() + stddev() * -absl::random_internal::InverseNormalSurvival(p);
}
private:
const double mean_;
const double stddev_;
};
struct Param {
double mean;
double stddev;
double p_fail;
int trials;
};
class GaussianDistributionTests : public testing::TestWithParam<Param>,
public GaussianModel {
public:
GaussianDistributionTests()
: GaussianModel(GetParam().mean, GetParam().stddev) {}
template <typename D>
bool SingleZTest(const double p, const size_t samples);
template <typename D>
double SingleChiSquaredTest();
absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
};
template <typename D>
bool GaussianDistributionTests::SingleZTest(const double p,
const size_t samples) {
D dis(mean(), stddev());
std::vector<double> data;
data.reserve(samples);
for (size_t i = 0; i < samples; i++) {
const double x = dis(rng_);
data.push_back(x);
}
const double max_err = absl::random_internal::MaxErrorTolerance(p);
const auto m = absl::random_internal::ComputeDistributionMoments(data);
const double z = absl::random_internal::ZScore(mean(), m);
const bool pass = absl::random_internal::Near("z", z, 0.0, max_err);
const double jb =
static_cast<double>(m.n) / 6.0 *
(std::pow(m.skewness, 2.0) + std::pow(m.kurtosis - 3.0, 2.0) / 4.0);
if (!pass || jb > 9.21) {
LOG(INFO)
<< "p=" << p << " max_err=" << max_err << "\n"
" mean=" << m.mean << " vs. " << mean() << "\n"
" stddev=" << std::sqrt(m.variance) << " vs. " << stddev() << "\n"
" skewness=" << m.skewness << " vs. " << skew() << "\n"
" kurtosis=" << m.kurtosis << " vs. " << kurtosis() << "\n"
" z=" << z << " vs. 0\n"
" jb=" << jb << " vs. 9.21";
}
return pass;
}
template <typename D>
double GaussianDistributionTests::SingleChiSquaredTest() {
const size_t kSamples = 10000;
const int kBuckets = 50;
std::vector<double> cutoffs;
const double kInc = 1.0 / static_cast<double>(kBuckets);
for (double p = kInc; p < 1.0; p += kInc) {
cutoffs.push_back(InverseCDF(p));
}
if (cutoffs.back() != std::numeric_limits<double>::infinity()) {
cutoffs.push_back(std::numeric_limits<double>::infinity());
}
D dis(mean(), stddev());
std::vector<int32_t> counts(cutoffs.size(), 0);
for (int j = 0; j < kSamples; j++) {
const double x = dis(rng_);
auto it = std::upper_bound(cutoffs.begin(), cutoffs.end(), x);
counts[std::distance(cutoffs.begin(), it)]++;
}
const int dof = static_cast<int>(counts.size()) - 1;
const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
const double expected =
static_cast<double>(kSamples) / static_cast<double>(counts.size());
double chi_square = absl::random_internal::ChiSquareWithExpected(
std::begin(counts), std::end(counts), expected);
double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
if (chi_square > threshold) {
for (size_t i = 0; i < cutoffs.size(); i++) {
LOG(INFO) << i << " : (" << cutoffs[i] << ") = " << counts[i];
}
LOG(INFO) << "mean=" << mean() << " stddev=" << stddev() << "\n"
" expected " << expected << "\n"
<< kChiSquared << " " << chi_square << " (" << p << ")\n"
<< kChiSquared << " @ 0.98 = " << threshold;
}
return p;
}
TEST_P(GaussianDistributionTests, ZTest) {
const size_t kSamples = 10000;
const auto& param = GetParam();
const int expected_failures =
std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail)));
const double p = absl::random_internal::RequiredSuccessProbability(
param.p_fail, param.trials);
int failures = 0;
for (int i = 0; i < param.trials; i++) {
failures +=
SingleZTest<absl::gaussian_distribution<double>>(p, kSamples) ? 0 : 1;
}
EXPECT_LE(failures, expected_failures);
}
TEST_P(GaussianDistributionTests, ChiSquaredTest) {
const int kTrials = 20;
int failures = 0;
for (int i = 0; i < kTrials; i++) {
double p_value =
SingleChiSquaredTest<absl::gaussian_distribution<double>>();
if (p_value < 0.0025) {
failures++;
}
}
EXPECT_LE(failures, 4);
}
std::vector<Param> GenParams() {
return {
Param{0.0, 1.0, 0.01, 100},
Param{0.0, 1e2, 0.01, 100},
Param{0.0, 1e4, 0.01, 100},
Param{0.0, 1e8, 0.01, 100},
Param{0.0, 1e16, 0.01, 100},
Param{0.0, 1e-3, 0.01, 100},
Param{0.0, 1e-5, 0.01, 100},
Param{0.0, 1e-9, 0.01, 100},
Param{0.0, 1e-17, 0.01, 100},
Param{1.0, 1.0, 0.01, 100},
Param{1.0, 1e2, 0.01, 100},
Param{1.0, 1e-2, 0.01, 100},
Param{1e2, 1.0, 0.01, 100},
Param{-1e2, 1.0, 0.01, 100},
Param{1e2, 1e6, 0.01, 100},
Param{-1e2, 1e6, 0.01, 100},
Param{1e4, 1e4, 0.01, 100},
Param{1e8, 1e4, 0.01, 100},
Param{1e12, 1e4, 0.01, 100},
};
}
std::string ParamName(const ::testing::TestParamInfo<Param>& info) {
const auto& p = info.param;
std::string name = absl::StrCat("mean_", absl::SixDigits(p.mean), "__stddev_",
absl::SixDigits(p.stddev));
return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
}
INSTANTIATE_TEST_SUITE_P(All, GaussianDistributionTests,
::testing::ValuesIn(GenParams()), ParamName);
TEST(GaussianDistributionTest, StabilityTest) {
absl::random_internal::sequence_urbg urbg(
{0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
std::vector<int> output(11);
{
absl::gaussian_distribution<double> dist;
std::generate(std::begin(output), std::end(output),
[&] { return static_cast<int>(10000000.0 * dist(urbg)); });
EXPECT_EQ(13, urbg.invocations());
EXPECT_THAT(output,
testing::ElementsAre(1494, 25518841, 9991550, 1351856,
-20373238, 3456682, 333530, -6804981,
-15279580, -16459654, 1494));
}
urbg.reset();
{
absl::gaussian_distribution<float> dist;
std::generate(std::begin(output), std::end(output),
[&] { return static_cast<int>(1000000.0f * dist(urbg)); });
EXPECT_EQ(13, urbg.invocations());
EXPECT_THAT(
output,
testing::ElementsAre(149, 2551884, 999155, 135185, -2037323, 345668,
33353, -680498, -1527958, -1645965, 149));
}
}
TEST(GaussianDistributionTest, AlgorithmBounds) {
absl::gaussian_distribution<double> dist;
const uint64_t kValues[] = {
0x1000000000000100ull, 0x2000000000000100ull, 0x3000000000000100ull,
0x4000000000000100ull, 0x5000000000000100ull, 0x6000000000000100ull,
0x9000000000000100ull, 0xa000000000000100ull, 0xb000000000000100ull,
0xc000000000000100ull, 0xd000000000000100ull, 0xe000000000000100ull};
const uint64_t kExtraValues[] = {
0x7000000000000100ull, 0x7800000000000100ull,
0x7c00000000000100ull, 0x7e00000000000100ull,
0xf000000000000100ull, 0xf800000000000100ull,
0xfc00000000000100ull, 0xfe00000000000100ull};
auto make_box = [](uint64_t v, uint64_t box) {
return (v & 0xffffffffffffff80ull) | box;
};
for (uint64_t box = 0; box < 0x7f; box++) {
for (const uint64_t v : kValues) {
absl::random_internal::sequence_urbg urbg(
{make_box(v, box), 0x0003eb76f6f7f755ull, 0x5FCEA50FDB2F953Bull});
auto a = dist(urbg);
EXPECT_EQ(1, urbg.invocations()) << box << " " << std::hex << v;
if (v & 0x8000000000000000ull) {
EXPECT_LT(a, 0.0) << box << " " << std::hex << v;
} else {
EXPECT_GT(a, 0.0) << box << " " << std::hex << v;
}
}
if (box > 10 && box < 100) {
for (const uint64_t v : kExtraValues) {
absl::random_internal::sequence_urbg urbg(
{make_box(v, box), 0x0003eb76f6f7f755ull, 0x5FCEA50FDB2F953Bull});
auto a = dist(urbg);
EXPECT_EQ(1, urbg.invocations()) << box << " " << std::hex << v;
if (v & 0x8000000000000000ull) {
EXPECT_LT(a, 0.0) << box << " " << std::hex << v;
} else {
EXPECT_GT(a, 0.0) << box << " " << std::hex << v;
}
}
}
}
auto make_fallback = [](uint64_t v) { return (v & 0xffffffffffffff80ull); };
double tail[2];
{
absl::random_internal::sequence_urbg urbg(
{make_fallback(0x7800000000000000ull), 0x13CCA830EB61BD96ull,
0x00000076f6f7f755ull});
tail[0] = dist(urbg);
EXPECT_EQ(3, urbg.invocations());
EXPECT_GT(tail[0], 0);
}
{
absl::random_internal::sequence_urbg urbg(
{make_fallback(0xf800000000000000ull), 0x13CCA830EB61BD96ull,
0x00000076f6f7f755ull});
tail[1] = dist(urbg);
EXPECT_EQ(3, urbg.invocations());
EXPECT_LT(tail[1], 0);
}
EXPECT_EQ(tail[0], -tail[1]);
EXPECT_EQ(418610, static_cast<int64_t>(tail[0] * 100000.0));
{
absl::random_internal::sequence_urbg urbg(
{make_box(0x7f00000000000000ull, 120), 0xe000000000000001ull,
0x13CCA830EB61BD96ull});
tail[0] = dist(urbg);
EXPECT_EQ(2, urbg.invocations());
EXPECT_GT(tail[0], 0);
}
{
absl::random_internal::sequence_urbg urbg(
{make_box(0xff00000000000000ull, 120), 0xe000000000000001ull,
0x13CCA830EB61BD96ull});
tail[1] = dist(urbg);
EXPECT_EQ(2, urbg.invocations());
EXPECT_LT(tail[1], 0);
}
EXPECT_EQ(tail[0], -tail[1]);
EXPECT_EQ(61948, static_cast<int64_t>(tail[0] * 100000.0));
{
absl::random_internal::sequence_urbg urbg(
{make_box(0xff00000000000000ull, 120), 0x1000000000000001,
make_box(0x1000000000000100ull, 50), 0x13CCA830EB61BD96ull});
dist(urbg);
EXPECT_EQ(3, urbg.invocations());
}
}
} |
2,521 | cpp | abseil/abseil-cpp | seed_sequences | absl/random/seed_sequences.cc | absl/random/seed_sequences_test.cc | #ifndef ABSL_RANDOM_SEED_SEQUENCES_H_
#define ABSL_RANDOM_SEED_SEQUENCES_H_
#include <iterator>
#include <random>
#include "absl/base/config.h"
#include "absl/base/nullability.h"
#include "absl/random/internal/salted_seed_seq.h"
#include "absl/random/internal/seed_material.h"
#include "absl/random/seed_gen_exception.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
using SeedSeq = random_internal::SaltedSeedSeq<std::seed_seq>;
template <typename URBG>
SeedSeq CreateSeedSeqFrom(URBG* urbg) {
SeedSeq::result_type
seed_material[random_internal::kEntropyBlocksNeeded];
if (!random_internal::ReadSeedMaterialFromURBG(
urbg, absl::MakeSpan(seed_material))) {
random_internal::ThrowSeedGenException();
}
return SeedSeq(std::begin(seed_material), std::end(seed_material));
}
SeedSeq MakeSeedSeq();
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/seed_sequences.h"
#include "absl/random/internal/pool_urbg.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
SeedSeq MakeSeedSeq() {
SeedSeq::result_type seed_material[8];
random_internal::RandenPool<uint32_t>::Fill(absl::MakeSpan(seed_material));
return SeedSeq(std::begin(seed_material), std::end(seed_material));
}
ABSL_NAMESPACE_END
} | #include "absl/random/seed_sequences.h"
#include <iterator>
#include <random>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/random/internal/nonsecure_base.h"
#include "absl/random/random.h"
namespace {
TEST(SeedSequences, Examples) {
{
absl::SeedSeq seed_seq({1, 2, 3});
absl::BitGen bitgen(seed_seq);
EXPECT_NE(0, bitgen());
}
{
absl::BitGen engine;
auto seed_seq = absl::CreateSeedSeqFrom(&engine);
absl::BitGen bitgen(seed_seq);
EXPECT_NE(engine(), bitgen());
}
{
auto seed_seq = absl::MakeSeedSeq();
std::mt19937 random(seed_seq);
EXPECT_NE(0, random());
}
}
TEST(CreateSeedSeqFrom, CompatibleWithStdTypes) {
using ExampleNonsecureURBG =
absl::random_internal::NonsecureURBGBase<std::minstd_rand0>;
ExampleNonsecureURBG rng;
auto seq_from_rng = absl::CreateSeedSeqFrom(&rng);
std::mt19937_64{seq_from_rng};
}
TEST(CreateSeedSeqFrom, CompatibleWithBitGenerator) {
absl::BitGen rng;
auto seq_from_rng = absl::CreateSeedSeqFrom(&rng);
std::mt19937_64{seq_from_rng};
}
TEST(CreateSeedSeqFrom, CompatibleWithInsecureBitGen) {
absl::InsecureBitGen rng;
auto seq_from_rng = absl::CreateSeedSeqFrom(&rng);
std::mt19937_64{seq_from_rng};
}
TEST(CreateSeedSeqFrom, CompatibleWithRawURBG) {
std::random_device urandom;
auto seq_from_rng = absl::CreateSeedSeqFrom(&urandom);
std::mt19937_64{seq_from_rng};
}
template <typename URBG>
void TestReproducibleVariateSequencesForNonsecureURBG() {
const size_t kNumVariates = 1000;
URBG rng;
auto reusable_seed = absl::CreateSeedSeqFrom(&rng);
typename URBG::result_type variates[kNumVariates];
{
URBG child(reusable_seed);
for (auto& variate : variates) {
variate = child();
}
}
{
URBG child(reusable_seed);
for (auto& variate : variates) {
ASSERT_EQ(variate, child());
}
}
}
TEST(CreateSeedSeqFrom, ReproducesVariateSequencesForInsecureBitGen) {
TestReproducibleVariateSequencesForNonsecureURBG<absl::InsecureBitGen>();
}
TEST(CreateSeedSeqFrom, ReproducesVariateSequencesForBitGenerator) {
TestReproducibleVariateSequencesForNonsecureURBG<absl::BitGen>();
}
} |
2,522 | cpp | abseil/abseil-cpp | discrete_distribution | absl/random/discrete_distribution.cc | absl/random/discrete_distribution_test.cc | #ifndef ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_
#define ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_
#include <cassert>
#include <cmath>
#include <istream>
#include <limits>
#include <numeric>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/random/bernoulli_distribution.h"
#include "absl/random/internal/iostream_state_saver.h"
#include "absl/random/uniform_int_distribution.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
template <typename IntType = int>
class discrete_distribution {
public:
using result_type = IntType;
class param_type {
public:
using distribution_type = discrete_distribution;
param_type() { init(); }
template <typename InputIterator>
explicit param_type(InputIterator begin, InputIterator end)
: p_(begin, end) {
init();
}
explicit param_type(std::initializer_list<double> weights) : p_(weights) {
init();
}
template <class UnaryOperation>
explicit param_type(size_t nw, double xmin, double xmax,
UnaryOperation fw) {
if (nw > 0) {
p_.reserve(nw);
double delta = (xmax - xmin) / static_cast<double>(nw);
assert(delta > 0);
double t = delta * 0.5;
for (size_t i = 0; i < nw; ++i) {
p_.push_back(fw(xmin + i * delta + t));
}
}
init();
}
const std::vector<double>& probabilities() const { return p_; }
size_t n() const { return p_.size() - 1; }
friend bool operator==(const param_type& a, const param_type& b) {
return a.probabilities() == b.probabilities();
}
friend bool operator!=(const param_type& a, const param_type& b) {
return !(a == b);
}
private:
friend class discrete_distribution;
void init();
std::vector<double> p_;
std::vector<std::pair<double, size_t>> q_;
static_assert(std::is_integral<result_type>::value,
"Class-template absl::discrete_distribution<> must be "
"parameterized using an integral type.");
};
discrete_distribution() : param_() {}
explicit discrete_distribution(const param_type& p) : param_(p) {}
template <typename InputIterator>
explicit discrete_distribution(InputIterator begin, InputIterator end)
: param_(begin, end) {}
explicit discrete_distribution(std::initializer_list<double> weights)
: param_(weights) {}
template <class UnaryOperation>
explicit discrete_distribution(size_t nw, double xmin, double xmax,
UnaryOperation fw)
: param_(nw, xmin, xmax, std::move(fw)) {}
void reset() {}
template <typename URBG>
result_type operator()(URBG& g) {
return (*this)(g, param_);
}
template <typename URBG>
result_type operator()(URBG& g,
const param_type& p);
const param_type& param() const { return param_; }
void param(const param_type& p) { param_ = p; }
result_type(min)() const { return 0; }
result_type(max)() const {
return static_cast<result_type>(param_.n());
}
const std::vector<double>& probabilities() const {
return param_.probabilities();
}
friend bool operator==(const discrete_distribution& a,
const discrete_distribution& b) {
return a.param_ == b.param_;
}
friend bool operator!=(const discrete_distribution& a,
const discrete_distribution& b) {
return a.param_ != b.param_;
}
private:
param_type param_;
};
namespace random_internal {
std::vector<std::pair<double, size_t>> InitDiscreteDistribution(
std::vector<double>* probabilities);
}
template <typename IntType>
void discrete_distribution<IntType>::param_type::init() {
if (p_.empty()) {
p_.push_back(1.0);
q_.emplace_back(1.0, 0);
} else {
assert(n() <= (std::numeric_limits<IntType>::max)());
q_ = random_internal::InitDiscreteDistribution(&p_);
}
}
template <typename IntType>
template <typename URBG>
typename discrete_distribution<IntType>::result_type
discrete_distribution<IntType>::operator()(
URBG& g,
const param_type& p) {
const auto idx = absl::uniform_int_distribution<result_type>(0, p.n())(g);
const auto& q = p.q_[idx];
const bool selected = absl::bernoulli_distribution(q.first)(g);
return selected ? idx : static_cast<result_type>(q.second);
}
template <typename CharT, typename Traits, typename IntType>
std::basic_ostream<CharT, Traits>& operator<<(
std::basic_ostream<CharT, Traits>& os,
const discrete_distribution<IntType>& x) {
auto saver = random_internal::make_ostream_state_saver(os);
const auto& probabilities = x.param().probabilities();
os << probabilities.size();
os.precision(random_internal::stream_precision_helper<double>::kPrecision);
for (const auto& p : probabilities) {
os << os.fill() << p;
}
return os;
}
template <typename CharT, typename Traits, typename IntType>
std::basic_istream<CharT, Traits>& operator>>(
std::basic_istream<CharT, Traits>& is,
discrete_distribution<IntType>& x) {
using param_type = typename discrete_distribution<IntType>::param_type;
auto saver = random_internal::make_istream_state_saver(is);
size_t n;
std::vector<double> p;
is >> n;
if (is.fail()) return is;
if (n > 0) {
p.reserve(n);
for (IntType i = 0; i < n && !is.fail(); ++i) {
auto tmp = random_internal::read_floating_point<double>(is);
if (is.fail()) return is;
p.push_back(tmp);
}
}
x.param(param_type(p.begin(), p.end()));
return is;
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/discrete_distribution.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
std::vector<std::pair<double, size_t>> InitDiscreteDistribution(
std::vector<double>* probabilities) {
assert(probabilities);
assert(!probabilities->empty());
double sum = std::accumulate(std::begin(*probabilities),
std::end(*probabilities), 0.0);
if (std::fabs(sum - 1.0) > 1e-6) {
for (double& item : *probabilities) {
item = item / sum;
}
}
const size_t n = probabilities->size();
std::vector<std::pair<double, size_t>> q;
q.reserve(n);
std::vector<size_t> over;
std::vector<size_t> under;
size_t idx = 0;
for (const double item : *probabilities) {
assert(item >= 0);
const double v = item * n;
q.emplace_back(v, 0);
if (v < 1.0) {
under.push_back(idx++);
} else {
over.push_back(idx++);
}
}
while (!over.empty() && !under.empty()) {
auto lo = under.back();
under.pop_back();
auto hi = over.back();
over.pop_back();
q[lo].second = hi;
const double r = q[hi].first - (1.0 - q[lo].first);
q[hi].first = r;
if (r < 1.0) {
under.push_back(hi);
} else {
over.push_back(hi);
}
}
for (auto i : over) {
q[i] = {1.0, i};
}
for (auto i : under) {
q[i] = {1.0, i};
}
return q;
}
}
ABSL_NAMESPACE_END
} | #include "absl/random/discrete_distribution.h"
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <numeric>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/log/log.h"
#include "absl/random/internal/chi_square.h"
#include "absl/random/internal/distribution_test_util.h"
#include "absl/random/internal/pcg_engine.h"
#include "absl/random/internal/sequence_urbg.h"
#include "absl/random/random.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/strip.h"
namespace {
template <typename IntType>
class DiscreteDistributionTypeTest : public ::testing::Test {};
using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t,
uint32_t, int64_t, uint64_t>;
TYPED_TEST_SUITE(DiscreteDistributionTypeTest, IntTypes);
TYPED_TEST(DiscreteDistributionTypeTest, ParamSerializeTest) {
using param_type =
typename absl::discrete_distribution<TypeParam>::param_type;
absl::discrete_distribution<TypeParam> empty;
EXPECT_THAT(empty.probabilities(), testing::ElementsAre(1.0));
absl::discrete_distribution<TypeParam> before({1.0, 2.0, 1.0});
double s = 0;
for (const auto& x : before.probabilities()) {
s += x;
}
EXPECT_EQ(s, 1.0);
EXPECT_THAT(before.probabilities(), testing::ElementsAre(0.25, 0.5, 0.25));
{
std::vector<double> data({1.0, 2.0, 1.0});
absl::discrete_distribution<TypeParam> via_param{
param_type(std::begin(data), std::end(data))};
EXPECT_EQ(via_param, before);
}
std::stringstream ss;
ss << before;
absl::discrete_distribution<TypeParam> after;
EXPECT_NE(before, after);
ss >> after;
EXPECT_EQ(before, after);
}
TYPED_TEST(DiscreteDistributionTypeTest, Constructor) {
auto fn = [](double x) { return x; };
{
absl::discrete_distribution<int> unary(0, 1.0, 9.0, fn);
EXPECT_THAT(unary.probabilities(), testing::ElementsAre(1.0));
}
{
absl::discrete_distribution<int> unary(2, 1.0, 9.0, fn);
EXPECT_THAT(unary.probabilities(), testing::ElementsAre(0.3, 0.7));
}
}
TEST(DiscreteDistributionTest, InitDiscreteDistribution) {
using testing::_;
using testing::Pair;
{
std::vector<double> p({1.0, 2.0, 3.0});
std::vector<std::pair<double, size_t>> q =
absl::random_internal::InitDiscreteDistribution(&p);
EXPECT_THAT(p, testing::ElementsAre(1 / 6.0, 2 / 6.0, 3 / 6.0));
EXPECT_THAT(q, testing::ElementsAre(Pair(0.5, 2),
Pair(1.0, _),
Pair(1.0, _)));
}
{
std::vector<double> p({1.0, 2.0, 3.0, 5.0, 2.0});
std::vector<std::pair<double, size_t>> q =
absl::random_internal::InitDiscreteDistribution(&p);
EXPECT_THAT(p, testing::ElementsAre(1 / 13.0, 2 / 13.0, 3 / 13.0, 5 / 13.0,
2 / 13.0));
constexpr double b0 = 1.0 / 13.0 / 0.2;
constexpr double b1 = 2.0 / 13.0 / 0.2;
constexpr double b3 = (5.0 / 13.0 / 0.2) - ((1 - b0) + (1 - b1) + (1 - b1));
EXPECT_THAT(q, testing::ElementsAre(Pair(b0, 3),
Pair(b1, 3),
Pair(1.0, _),
Pair(b3, 2),
Pair(b1, 3)));
}
}
TEST(DiscreteDistributionTest, ChiSquaredTest50) {
using absl::random_internal::kChiSquared;
constexpr size_t kTrials = 10000;
constexpr int kBuckets = 50;
const int kThreshold =
absl::random_internal::ChiSquareValue(kBuckets, 0.99999);
std::vector<double> weights(kBuckets, 0);
std::iota(std::begin(weights), std::end(weights), 1);
absl::discrete_distribution<int> dist(std::begin(weights), std::end(weights));
absl::random_internal::pcg64_2018_engine rng(0x2B7E151628AED2A6);
std::vector<int32_t> counts(kBuckets, 0);
for (size_t i = 0; i < kTrials; i++) {
auto x = dist(rng);
counts[x]++;
}
double sum = 0;
for (double x : weights) {
sum += x;
}
for (double& x : weights) {
x = kTrials * (x / sum);
}
double chi_square =
absl::random_internal::ChiSquare(std::begin(counts), std::end(counts),
std::begin(weights), std::end(weights));
if (chi_square > kThreshold) {
double p_value =
absl::random_internal::ChiSquarePValue(chi_square, kBuckets);
std::string msg;
for (size_t i = 0; i < counts.size(); i++) {
absl::StrAppend(&msg, i, ": ", counts[i], " vs ", weights[i], "\n");
}
absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n");
absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ",
kThreshold);
LOG(INFO) << msg;
FAIL() << msg;
}
}
TEST(DiscreteDistributionTest, StabilityTest) {
absl::random_internal::sequence_urbg urbg(
{0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
std::vector<int> output(6);
{
absl::discrete_distribution<int32_t> dist({1.0, 2.0, 3.0, 5.0, 2.0});
EXPECT_EQ(0, dist.min());
EXPECT_EQ(4, dist.max());
for (auto& v : output) {
v = dist(urbg);
}
EXPECT_EQ(12, urbg.invocations());
}
EXPECT_THAT(output, testing::ElementsAre(3, 3, 1, 3, 3, 3));
{
urbg.reset();
absl::discrete_distribution<int64_t> dist({1.0, 2.0, 3.0, 5.0, 2.0});
EXPECT_EQ(0, dist.min());
EXPECT_EQ(4, dist.max());
for (auto& v : output) {
v = dist(urbg);
}
EXPECT_EQ(12, urbg.invocations());
}
EXPECT_THAT(output, testing::ElementsAre(3, 3, 0, 3, 0, 4));
}
} |
2,523 | cpp | abseil/abseil-cpp | randen_hwaes | absl/random/internal/randen_hwaes.cc | absl/random/internal/randen_hwaes_test.cc | #ifndef ABSL_RANDOM_INTERNAL_RANDEN_HWAES_H_
#define ABSL_RANDOM_INTERNAL_RANDEN_HWAES_H_
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
class RandenHwAes {
public:
static void Generate(const void* keys, void* state_void);
static void Absorb(const void* seed_void, void* state_void);
static const void* GetKeys();
};
bool HasRandenHwAesImplementation();
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/randen_hwaes.h"
#include <cstdint>
#include <cstring>
#include "absl/base/attributes.h"
#include "absl/numeric/int128.h"
#include "absl/random/internal/platform.h"
#include "absl/random/internal/randen_traits.h"
#if ABSL_HAVE_ACCELERATED_AES
#if defined(ABSL_ARCH_X86_64) || defined(ABSL_ARCH_X86_32) || \
defined(ABSL_ARCH_PPC) || defined(ABSL_ARCH_ARM) || \
defined(ABSL_ARCH_AARCH64)
#define ABSL_RANDEN_HWAES_IMPL 1
#endif
#endif
#if !defined(ABSL_RANDEN_HWAES_IMPL)
#include <cstdio>
#include <cstdlib>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
bool HasRandenHwAesImplementation() { return false; }
const void* RandenHwAes::GetKeys() {
const int d = ABSL_RANDOM_INTERNAL_AES_DISPATCH;
fprintf(stderr, "AES Hardware detection failed (%d).\n", d);
exit(1);
return nullptr;
}
void RandenHwAes::Absorb(const void*, void*) {
const int d = ABSL_RANDOM_INTERNAL_AES_DISPATCH;
fprintf(stderr, "AES Hardware detection failed (%d).\n", d);
exit(1);
}
void RandenHwAes::Generate(const void*, void*) {
const int d = ABSL_RANDOM_INTERNAL_AES_DISPATCH;
fprintf(stderr, "AES Hardware detection failed (%d).\n", d);
exit(1);
}
}
ABSL_NAMESPACE_END
}
#else
namespace {
using absl::random_internal::RandenTraits;
}
#if (defined(__clang__) || defined(__GNUC__))
#if defined(ABSL_ARCH_X86_64) || defined(ABSL_ARCH_X86_32)
#define ABSL_TARGET_CRYPTO __attribute__((target("aes")))
#elif defined(ABSL_ARCH_PPC)
#define ABSL_TARGET_CRYPTO __attribute__((target("crypto")))
#else
#define ABSL_TARGET_CRYPTO
#endif
#else
#define ABSL_TARGET_CRYPTO
#endif
#if defined(ABSL_ARCH_PPC)
#include <altivec.h>
#undef vector
#undef bool
using Vector128 = __vector unsigned long long;
namespace {
inline ABSL_TARGET_CRYPTO Vector128 ReverseBytes(const Vector128& v) {
const __vector unsigned char perm = {15, 14, 13, 12, 11, 10, 9, 8,
7, 6, 5, 4, 3, 2, 1, 0};
return vec_perm(v, v, perm);
}
inline ABSL_TARGET_CRYPTO Vector128 Vector128Load(const void* from) {
return vec_vsx_ld(0, reinterpret_cast<const Vector128*>(from));
}
inline ABSL_TARGET_CRYPTO void Vector128Store(const Vector128& v, void* to) {
vec_vsx_st(v, 0, reinterpret_cast<Vector128*>(to));
}
inline ABSL_TARGET_CRYPTO Vector128 AesRound(const Vector128& state,
const Vector128& round_key) {
return Vector128(__builtin_crypto_vcipher(state, round_key));
}
inline ABSL_TARGET_CRYPTO void SwapEndian(absl::uint128* state) {
for (uint32_t block = 0; block < RandenTraits::kFeistelBlocks; ++block) {
Vector128Store(ReverseBytes(Vector128Load(state + block)), state + block);
}
}
}
#elif defined(ABSL_ARCH_ARM) || defined(ABSL_ARCH_AARCH64)
#include <arm_neon.h>
using Vector128 = uint8x16_t;
namespace {
inline ABSL_TARGET_CRYPTO Vector128 Vector128Load(const void* from) {
return vld1q_u8(reinterpret_cast<const uint8_t*>(from));
}
inline ABSL_TARGET_CRYPTO void Vector128Store(const Vector128& v, void* to) {
vst1q_u8(reinterpret_cast<uint8_t*>(to), v);
}
inline ABSL_TARGET_CRYPTO Vector128 AesRound(const Vector128& state,
const Vector128& round_key) {
return vaesmcq_u8(vaeseq_u8(state, uint8x16_t{})) ^ round_key;
}
inline ABSL_TARGET_CRYPTO void SwapEndian(void*) {}
}
#elif defined(ABSL_ARCH_X86_64) || defined(ABSL_ARCH_X86_32)
#include <immintrin.h>
namespace {
class Vector128 {
public:
inline explicit Vector128(const __m128i& v) : data_(v) {}
inline __m128i data() const { return data_; }
inline Vector128& operator^=(const Vector128& other) {
data_ = _mm_xor_si128(data_, other.data());
return *this;
}
private:
__m128i data_;
};
inline ABSL_TARGET_CRYPTO Vector128 Vector128Load(const void* from) {
return Vector128(_mm_load_si128(reinterpret_cast<const __m128i*>(from)));
}
inline ABSL_TARGET_CRYPTO void Vector128Store(const Vector128& v, void* to) {
_mm_store_si128(reinterpret_cast<__m128i*>(to), v.data());
}
inline ABSL_TARGET_CRYPTO Vector128 AesRound(const Vector128& state,
const Vector128& round_key) {
return Vector128(_mm_aesenc_si128(state.data(), round_key.data()));
}
inline ABSL_TARGET_CRYPTO void SwapEndian(void*) {}
}
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#endif
namespace {
inline ABSL_TARGET_CRYPTO void BlockShuffle(absl::uint128* state) {
static_assert(RandenTraits::kFeistelBlocks == 16,
"Expecting 16 FeistelBlocks.");
constexpr size_t shuffle[RandenTraits::kFeistelBlocks] = {
7, 2, 13, 4, 11, 8, 3, 6, 15, 0, 9, 10, 1, 14, 5, 12};
const Vector128 v0 = Vector128Load(state + shuffle[0]);
const Vector128 v1 = Vector128Load(state + shuffle[1]);
const Vector128 v2 = Vector128Load(state + shuffle[2]);
const Vector128 v3 = Vector128Load(state + shuffle[3]);
const Vector128 v4 = Vector128Load(state + shuffle[4]);
const Vector128 v5 = Vector128Load(state + shuffle[5]);
const Vector128 v6 = Vector128Load(state + shuffle[6]);
const Vector128 v7 = Vector128Load(state + shuffle[7]);
const Vector128 w0 = Vector128Load(state + shuffle[8]);
const Vector128 w1 = Vector128Load(state + shuffle[9]);
const Vector128 w2 = Vector128Load(state + shuffle[10]);
const Vector128 w3 = Vector128Load(state + shuffle[11]);
const Vector128 w4 = Vector128Load(state + shuffle[12]);
const Vector128 w5 = Vector128Load(state + shuffle[13]);
const Vector128 w6 = Vector128Load(state + shuffle[14]);
const Vector128 w7 = Vector128Load(state + shuffle[15]);
Vector128Store(v0, state + 0);
Vector128Store(v1, state + 1);
Vector128Store(v2, state + 2);
Vector128Store(v3, state + 3);
Vector128Store(v4, state + 4);
Vector128Store(v5, state + 5);
Vector128Store(v6, state + 6);
Vector128Store(v7, state + 7);
Vector128Store(w0, state + 8);
Vector128Store(w1, state + 9);
Vector128Store(w2, state + 10);
Vector128Store(w3, state + 11);
Vector128Store(w4, state + 12);
Vector128Store(w5, state + 13);
Vector128Store(w6, state + 14);
Vector128Store(w7, state + 15);
}
inline ABSL_TARGET_CRYPTO const absl::uint128* FeistelRound(
absl::uint128* state,
const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) {
static_assert(RandenTraits::kFeistelBlocks == 16,
"Expecting 16 FeistelBlocks.");
const Vector128 s0 = Vector128Load(state + 0);
const Vector128 s1 = Vector128Load(state + 1);
const Vector128 s2 = Vector128Load(state + 2);
const Vector128 s3 = Vector128Load(state + 3);
const Vector128 s4 = Vector128Load(state + 4);
const Vector128 s5 = Vector128Load(state + 5);
const Vector128 s6 = Vector128Load(state + 6);
const Vector128 s7 = Vector128Load(state + 7);
const Vector128 s8 = Vector128Load(state + 8);
const Vector128 s9 = Vector128Load(state + 9);
const Vector128 s10 = Vector128Load(state + 10);
const Vector128 s11 = Vector128Load(state + 11);
const Vector128 s12 = Vector128Load(state + 12);
const Vector128 s13 = Vector128Load(state + 13);
const Vector128 s14 = Vector128Load(state + 14);
const Vector128 s15 = Vector128Load(state + 15);
const Vector128 e0 = AesRound(s0, Vector128Load(keys + 0));
const Vector128 e2 = AesRound(s2, Vector128Load(keys + 1));
const Vector128 e4 = AesRound(s4, Vector128Load(keys + 2));
const Vector128 e6 = AesRound(s6, Vector128Load(keys + 3));
const Vector128 e8 = AesRound(s8, Vector128Load(keys + 4));
const Vector128 e10 = AesRound(s10, Vector128Load(keys + 5));
const Vector128 e12 = AesRound(s12, Vector128Load(keys + 6));
const Vector128 e14 = AesRound(s14, Vector128Load(keys + 7));
const Vector128 o1 = AesRound(e0, s1);
const Vector128 o3 = AesRound(e2, s3);
const Vector128 o5 = AesRound(e4, s5);
const Vector128 o7 = AesRound(e6, s7);
const Vector128 o9 = AesRound(e8, s9);
const Vector128 o11 = AesRound(e10, s11);
const Vector128 o13 = AesRound(e12, s13);
const Vector128 o15 = AesRound(e14, s15);
Vector128Store(o1, state + 1);
Vector128Store(o3, state + 3);
Vector128Store(o5, state + 5);
Vector128Store(o7, state + 7);
Vector128Store(o9, state + 9);
Vector128Store(o11, state + 11);
Vector128Store(o13, state + 13);
Vector128Store(o15, state + 15);
return keys + 8;
}
inline ABSL_TARGET_CRYPTO void Permute(
absl::uint128* state,
const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) {
#ifdef __clang__
#pragma clang loop unroll_count(2)
#endif
for (size_t round = 0; round < RandenTraits::kFeistelRounds; ++round) {
keys = FeistelRound(state, keys);
BlockShuffle(state);
}
}
}
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
bool HasRandenHwAesImplementation() { return true; }
const void* ABSL_TARGET_CRYPTO RandenHwAes::GetKeys() {
#if defined(ABSL_ARCH_PPC)
return kRandenRoundKeysBE;
#else
return kRandenRoundKeys;
#endif
}
void ABSL_TARGET_CRYPTO RandenHwAes::Absorb(const void* seed_void,
void* state_void) {
static_assert(RandenTraits::kCapacityBytes / sizeof(Vector128) == 1,
"Unexpected Randen kCapacityBlocks");
static_assert(RandenTraits::kStateBytes / sizeof(Vector128) == 16,
"Unexpected Randen kStateBlocks");
auto* state = reinterpret_cast<absl::uint128 * ABSL_RANDOM_INTERNAL_RESTRICT>(
state_void);
const auto* seed =
reinterpret_cast<const absl::uint128 * ABSL_RANDOM_INTERNAL_RESTRICT>(
seed_void);
Vector128 b1 = Vector128Load(state + 1);
b1 ^= Vector128Load(seed + 0);
Vector128Store(b1, state + 1);
Vector128 b2 = Vector128Load(state + 2);
b2 ^= Vector128Load(seed + 1);
Vector128Store(b2, state + 2);
Vector128 b3 = Vector128Load(state + 3);
b3 ^= Vector128Load(seed + 2);
Vector128Store(b3, state + 3);
Vector128 b4 = Vector128Load(state + 4);
b4 ^= Vector128Load(seed + 3);
Vector128Store(b4, state + 4);
Vector128 b5 = Vector128Load(state + 5);
b5 ^= Vector128Load(seed + 4);
Vector128Store(b5, state + 5);
Vector128 b6 = Vector128Load(state + 6);
b6 ^= Vector128Load(seed + 5);
Vector128Store(b6, state + 6);
Vector128 b7 = Vector128Load(state + 7);
b7 ^= Vector128Load(seed + 6);
Vector128Store(b7, state + 7);
Vector128 b8 = Vector128Load(state + 8);
b8 ^= Vector128Load(seed + 7);
Vector128Store(b8, state + 8);
Vector128 b9 = Vector128Load(state + 9);
b9 ^= Vector128Load(seed + 8);
Vector128Store(b9, state + 9);
Vector128 b10 = Vector128Load(state + 10);
b10 ^= Vector128Load(seed + 9);
Vector128Store(b10, state + 10);
Vector128 b11 = Vector128Load(state + 11);
b11 ^= Vector128Load(seed + 10);
Vector128Store(b11, state + 11);
Vector128 b12 = Vector128Load(state + 12);
b12 ^= Vector128Load(seed + 11);
Vector128Store(b12, state + 12);
Vector128 b13 = Vector128Load(state + 13);
b13 ^= Vector128Load(seed + 12);
Vector128Store(b13, state + 13);
Vector128 b14 = Vector128Load(state + 14);
b14 ^= Vector128Load(seed + 13);
Vector128Store(b14, state + 14);
Vector128 b15 = Vector128Load(state + 15);
b15 ^= Vector128Load(seed + 14);
Vector128Store(b15, state + 15);
}
void ABSL_TARGET_CRYPTO RandenHwAes::Generate(const void* keys_void,
void* state_void) {
static_assert(RandenTraits::kCapacityBytes == sizeof(Vector128),
"Capacity mismatch");
auto* state = reinterpret_cast<absl::uint128*>(state_void);
const auto* keys = reinterpret_cast<const absl::uint128*>(keys_void);
const Vector128 prev_inner = Vector128Load(state);
SwapEndian(state);
Permute(state, keys);
SwapEndian(state);
Vector128 inner = Vector128Load(state);
inner ^= prev_inner;
Vector128Store(inner, state);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
ABSL_NAMESPACE_END
}
#endif | #include "absl/random/internal/randen_hwaes.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/log/log.h"
#include "absl/random/internal/platform.h"
#include "absl/random/internal/randen_detect.h"
#include "absl/random/internal/randen_traits.h"
#include "absl/strings/str_format.h"
namespace {
using absl::random_internal::RandenHwAes;
using absl::random_internal::RandenTraits;
TEST(RandenHwAesTest, Default) {
EXPECT_TRUE(absl::random_internal::CPUSupportsRandenHwAes());
constexpr uint8_t kGolden[] = {
0xee, 0xd3, 0xe6, 0x0e, 0x09, 0x34, 0x65, 0x6c, 0xc6, 0x33, 0x53, 0x9d,
0x9b, 0x2b, 0x4e, 0x04, 0x77, 0x39, 0x43, 0x4e, 0x13, 0x4f, 0xc1, 0xc3,
0xee, 0x10, 0x04, 0xd9, 0x7c, 0xf4, 0xa9, 0xdd, 0x10, 0xca, 0xd8, 0x7f,
0x08, 0xf3, 0x7b, 0x88, 0x12, 0x29, 0xc7, 0x45, 0xf5, 0x80, 0xb7, 0xf0,
0x9f, 0x59, 0x96, 0x76, 0xd3, 0xb1, 0xdb, 0x15, 0x59, 0x6d, 0x3c, 0xff,
0xba, 0x63, 0xec, 0x30, 0xa6, 0x20, 0x7f, 0x6f, 0x60, 0x73, 0x9f, 0xb2,
0x4c, 0xa5, 0x49, 0x6f, 0x31, 0x8a, 0x80, 0x02, 0x0e, 0xe5, 0xc8, 0xd5,
0xf9, 0xea, 0x8f, 0x3b, 0x8a, 0xde, 0xd9, 0x3f, 0x5e, 0x60, 0xbf, 0x9c,
0xbb, 0x3b, 0x18, 0x78, 0x1a, 0xae, 0x70, 0xc9, 0xd5, 0x1e, 0x30, 0x56,
0xd3, 0xff, 0xb2, 0xd8, 0x37, 0x3c, 0xc7, 0x0f, 0xfe, 0x27, 0xb3, 0xf4,
0x19, 0x9a, 0x8f, 0xeb, 0x76, 0x8d, 0xfd, 0xcd, 0x9d, 0x0c, 0x42, 0x91,
0xeb, 0x06, 0xa5, 0xc3, 0x56, 0x95, 0xff, 0x3e, 0xdd, 0x05, 0xaf, 0xd5,
0xa1, 0xc4, 0x83, 0x8f, 0xb7, 0x1b, 0xdb, 0x48, 0x8c, 0xfe, 0x6b, 0x0d,
0x0e, 0x92, 0x23, 0x70, 0x42, 0x6d, 0x95, 0x34, 0x58, 0x57, 0xd3, 0x58,
0x40, 0xb8, 0x87, 0x6b, 0xc2, 0xf4, 0x1e, 0xed, 0xf3, 0x2d, 0x0b, 0x3e,
0xa2, 0x32, 0xef, 0x8e, 0xfc, 0x54, 0x11, 0x43, 0xf3, 0xab, 0x7c, 0x49,
0x8b, 0x9a, 0x02, 0x70, 0x05, 0x37, 0x24, 0x4e, 0xea, 0xe5, 0x90, 0xf0,
0x49, 0x57, 0x8b, 0xd8, 0x2f, 0x69, 0x70, 0xa9, 0x82, 0xa5, 0x51, 0xc6,
0xf5, 0x42, 0x63, 0xbb, 0x2c, 0xec, 0xfc, 0x78, 0xdb, 0x55, 0x2f, 0x61,
0x45, 0xb7, 0x3c, 0x46, 0xe3, 0xaf, 0x16, 0x18, 0xad, 0xe4, 0x2e, 0x35,
0x7e, 0xda, 0x01, 0xc1, 0x74, 0xf3, 0x6f, 0x02, 0x51, 0xe8, 0x3d, 0x1c,
0x82, 0xf0, 0x1e, 0x81,
};
alignas(16) uint8_t state[RandenTraits::kStateBytes];
std::memset(state, 0, sizeof(state));
RandenHwAes::Generate(RandenHwAes::GetKeys(), state);
EXPECT_EQ(0, std::memcmp(state, kGolden, sizeof(state)));
}
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
LOG(INFO) << "ABSL_HAVE_ACCELERATED_AES=" << ABSL_HAVE_ACCELERATED_AES;
LOG(INFO) << "ABSL_RANDOM_INTERNAL_AES_DISPATCH="
<< ABSL_RANDOM_INTERNAL_AES_DISPATCH;
#if defined(ABSL_ARCH_X86_64)
LOG(INFO) << "ABSL_ARCH_X86_64";
#elif defined(ABSL_ARCH_X86_32)
LOG(INFO) << "ABSL_ARCH_X86_32";
#elif defined(ABSL_ARCH_AARCH64)
LOG(INFO) << "ABSL_ARCH_AARCH64";
#elif defined(ABSL_ARCH_ARM)
LOG(INFO) << "ABSL_ARCH_ARM";
#elif defined(ABSL_ARCH_PPC)
LOG(INFO) << "ABSL_ARCH_PPC";
#else
LOG(INFO) << "ARCH Unknown";
#endif
int x = absl::random_internal::HasRandenHwAesImplementation();
LOG(INFO) << "HasRandenHwAesImplementation = " << x;
int y = absl::random_internal::CPUSupportsRandenHwAes();
LOG(INFO) << "CPUSupportsRandenHwAes = " << x;
if (!x || !y) {
LOG(INFO) << "Skipping Randen HWAES tests.";
return 0;
}
return RUN_ALL_TESTS();
} |
2,524 | cpp | abseil/abseil-cpp | chi_square | absl/random/internal/chi_square.cc | absl/random/internal/chi_square_test.cc | #ifndef ABSL_RANDOM_INTERNAL_CHI_SQUARE_H_
#define ABSL_RANDOM_INTERNAL_CHI_SQUARE_H_
#include <cassert>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
constexpr const char kChiSquared[] = "chi-squared";
template <typename Iterator>
double ChiSquareWithExpected(Iterator begin, Iterator end, double expected) {
assert(expected >= 10);
double chi_square = 0;
for (auto it = begin; it != end; it++) {
double d = static_cast<double>(*it) - expected;
chi_square += d * d;
}
chi_square = chi_square / expected;
return chi_square;
}
template <typename Iterator, typename Expected>
double ChiSquare(Iterator it, Iterator end, Expected eit, Expected eend) {
double chi_square = 0;
for (; it != end && eit != eend; ++it, ++eit) {
if (*it > 0) {
assert(*eit > 0);
}
double e = static_cast<double>(*eit);
double d = static_cast<double>(*it - *eit);
if (d != 0) {
assert(e > 0);
chi_square += (d * d) / e;
}
}
assert(it == end && eit == eend);
return chi_square;
}
double ChiSquareValue(int dof, double p);
double ChiSquarePValue(double chi_square, int dof);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/chi_square.h"
#include <cmath>
#include "absl/random/internal/distribution_test_util.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
namespace {
#if defined(__EMSCRIPTEN__)
inline double fma(double x, double y, double z) {
return (x * y) + z;
}
#endif
template <typename T, unsigned N>
inline T EvaluatePolynomial(T x, const T (&poly)[N]) {
#if !defined(__EMSCRIPTEN__)
using std::fma;
#endif
T p = poly[N - 1];
for (unsigned i = 2; i <= N; i++) {
p = fma(p, x, poly[N - i]);
}
return p;
}
static constexpr int kLargeDOF = 150;
double POZ(double z) {
static constexpr double kP1[] = {
0.797884560593, -0.531923007300, 0.319152932694,
-0.151968751364, 0.059054035642, -0.019198292004,
0.005198775019, -0.001075204047, 0.000124818987,
};
static constexpr double kP2[] = {
0.999936657524, 0.000535310849, -0.002141268741, 0.005353579108,
-0.009279453341, 0.011630447319, -0.010557625006, 0.006549791214,
-0.002034254874, -0.000794620820, 0.001390604284, -0.000676904986,
-0.000019538132, 0.000152529290, -0.000045255659,
};
const double kZMax = 6.0;
if (z == 0.0) {
return 0.5;
}
double x;
double y = 0.5 * std::fabs(z);
if (y >= (kZMax * 0.5)) {
x = 1.0;
} else if (y < 1.0) {
double w = y * y;
x = EvaluatePolynomial(w, kP1) * y * 2.0;
} else {
y -= 2.0;
x = EvaluatePolynomial(y, kP2);
}
return z > 0.0 ? ((x + 1.0) * 0.5) : ((1.0 - x) * 0.5);
}
double normal_survival(double z) {
static constexpr double kR[] = {
1.0, 0.196854, 0.115194, 0.000344, 0.019527,
};
double r = EvaluatePolynomial(z, kR);
r *= r;
return 0.5 / (r * r);
}
}
double ChiSquareValue(int dof, double p) {
static constexpr double kChiEpsilon =
0.000001;
static constexpr double kChiMax =
99999.0;
const double p_value = 1.0 - p;
if (dof < 1 || p_value > 1.0) {
return 0.0;
}
if (dof > kLargeDOF) {
const double z = InverseNormalSurvival(p_value);
const double mean = 1 - 2.0 / (9 * dof);
const double variance = 2.0 / (9 * dof);
if (variance != 0) {
double term = z * std::sqrt(variance) + mean;
return dof * (term * term * term);
}
}
if (p_value <= 0.0) return kChiMax;
double min_chisq = 0.0;
double max_chisq = kChiMax;
double current = dof / std::sqrt(p_value);
while ((max_chisq - min_chisq) > kChiEpsilon) {
if (ChiSquarePValue(current, dof) < p_value) {
max_chisq = current;
} else {
min_chisq = current;
}
current = (max_chisq + min_chisq) * 0.5;
}
return current;
}
double ChiSquarePValue(double chi_square, int dof) {
static constexpr double kLogSqrtPi =
0.5723649429247000870717135;
static constexpr double kInverseSqrtPi =
0.5641895835477562869480795;
if (dof > kLargeDOF) {
const double chi_square_scaled = std::pow(chi_square / dof, 1.0 / 3);
const double mean = 1 - 2.0 / (9 * dof);
const double variance = 2.0 / (9 * dof);
if (variance != 0) {
const double z = (chi_square_scaled - mean) / std::sqrt(variance);
if (z > 0) {
return normal_survival(z);
} else if (z < 0) {
return 1.0 - normal_survival(-z);
} else {
return 0.5;
}
}
}
if (chi_square <= 0.0) return 1.0;
if (dof < 1) return 0;
auto capped_exp = [](double x) { return x < -20 ? 0.0 : std::exp(x); };
static constexpr double kBigX = 20;
double a = 0.5 * chi_square;
const bool even = !(dof & 1);
const double y = capped_exp(-a);
double s = even ? y : (2.0 * POZ(-std::sqrt(chi_square)));
if (dof <= 2) {
return s;
}
chi_square = 0.5 * (dof - 1.0);
double z = (even ? 1.0 : 0.5);
if (a > kBigX) {
double e = (even ? 0.0 : kLogSqrtPi);
double c = std::log(a);
while (z <= chi_square) {
e = std::log(z) + e;
s += capped_exp(c * z - a - e);
z += 1.0;
}
return s;
}
double e = (even ? 1.0 : (kInverseSqrtPi / std::sqrt(a)));
double c = 0.0;
while (z <= chi_square) {
e = e * (a / z);
c = c + e;
z += 1.0;
}
return c * y + s;
}
}
ABSL_NAMESPACE_END
} | #include "absl/random/internal/chi_square.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <numeric>
#include <vector>
#include "gtest/gtest.h"
#include "absl/base/macros.h"
using absl::random_internal::ChiSquare;
using absl::random_internal::ChiSquarePValue;
using absl::random_internal::ChiSquareValue;
using absl::random_internal::ChiSquareWithExpected;
namespace {
TEST(ChiSquare, Value) {
struct {
int line;
double chi_square;
int df;
double confidence;
} const specs[] = {
{__LINE__, 0, 0, 0.01},
{__LINE__, 0.00016, 1, 0.01},
{__LINE__, 1.64650, 8, 0.01},
{__LINE__, 5.81221, 16, 0.01},
{__LINE__, 156.4319, 200, 0.01},
{__LINE__, 1121.3784, 1234, 0.01},
{__LINE__, 53557.1629, 54321, 0.01},
{__LINE__, 651662.6647, 654321, 0.01},
{__LINE__, 0, 0, 0.99},
{__LINE__, 6.635, 1, 0.99},
{__LINE__, 20.090, 8, 0.99},
{__LINE__, 32.000, 16, 0.99},
{__LINE__, 249.4456, 200, 0.99},
{__LINE__, 1131.1573, 1023, 0.99},
{__LINE__, 1352.5038, 1234, 0.99},
{__LINE__, 55090.7356, 54321, 0.99},
{__LINE__, 656985.1514, 654321, 0.99},
{__LINE__, 16.2659, 3, 0.999},
{__LINE__, 22.4580, 6, 0.999},
{__LINE__, 267.5409, 200, 0.999},
{__LINE__, 1168.5033, 1023, 0.999},
{__LINE__, 55345.1741, 54321, 0.999},
{__LINE__, 657861.7284, 654321, 0.999},
{__LINE__, 51.1772, 24, 0.999},
{__LINE__, 59.7003, 30, 0.999},
{__LINE__, 37.6984, 15, 0.999},
{__LINE__, 29.5898, 10, 0.999},
{__LINE__, 27.8776, 9, 0.999},
{__LINE__, 0.000157088, 1, 0.01},
{__LINE__, 5.31852, 2, 0.93},
{__LINE__, 1.92256, 4, 0.25},
{__LINE__, 10.7709, 13, 0.37},
{__LINE__, 26.2514, 17, 0.93},
{__LINE__, 36.4799, 29, 0.84},
{__LINE__, 25.818, 31, 0.27},
{__LINE__, 63.3346, 64, 0.50},
{__LINE__, 196.211, 128, 0.9999},
{__LINE__, 215.21, 243, 0.10},
{__LINE__, 285.393, 256, 0.90},
{__LINE__, 984.504, 1024, 0.1923},
{__LINE__, 2043.85, 2048, 0.4783},
{__LINE__, 48004.6, 48273, 0.194},
};
for (const auto& spec : specs) {
SCOPED_TRACE(spec.line);
const double val = ChiSquareValue(spec.df, spec.confidence);
const double err = std::max(5e-6, spec.chi_square / 5e3);
EXPECT_NEAR(spec.chi_square, val, err) << spec.line;
}
EXPECT_NEAR(49.2680, ChiSquareValue(100, 1e-6), 5);
EXPECT_NEAR(123.499, ChiSquareValue(200, 1e-6), 5);
EXPECT_NEAR(149.449, ChiSquareValue(100, 0.999), 0.01);
EXPECT_NEAR(161.318, ChiSquareValue(100, 0.9999), 0.01);
EXPECT_NEAR(172.098, ChiSquareValue(100, 0.99999), 0.01);
EXPECT_NEAR(381.426, ChiSquareValue(300, 0.999), 0.05);
EXPECT_NEAR(399.756, ChiSquareValue(300, 0.9999), 0.1);
EXPECT_NEAR(416.126, ChiSquareValue(300, 0.99999), 0.2);
}
TEST(ChiSquareTest, PValue) {
struct {
int line;
double pval;
double chi_square;
int df;
} static const specs[] = {
{__LINE__, 1, 0, 0},
{__LINE__, 0, 0.001, 0},
{__LINE__, 1.000, 0, 453},
{__LINE__, 0.134471, 7972.52, 7834},
{__LINE__, 0.203922, 28.32, 23},
{__LINE__, 0.737171, 48274, 48472},
{__LINE__, 0.444146, 583.1234, 579},
{__LINE__, 0.294814, 138.2, 130},
{__LINE__, 0.0816532, 12.63, 7},
{__LINE__, 0, 682.32, 67},
{__LINE__, 0.49405, 999, 999},
{__LINE__, 1.000, 0, 9999},
{__LINE__, 0.997477, 0.00001, 1},
{__LINE__, 0, 5823.21, 5040},
};
for (const auto& spec : specs) {
SCOPED_TRACE(spec.line);
const double pval = ChiSquarePValue(spec.chi_square, spec.df);
EXPECT_NEAR(spec.pval, pval, 1e-3);
}
}
TEST(ChiSquareTest, CalcChiSquare) {
struct {
int line;
std::vector<int> expected;
std::vector<int> actual;
} const specs[] = {
{__LINE__,
{56, 234, 76, 1, 546, 1, 87, 345, 1, 234},
{2, 132, 4, 43, 234, 8, 345, 8, 236, 56}},
{__LINE__,
{123, 36, 234, 367, 345, 2, 456, 567, 234, 567},
{123, 56, 2345, 8, 345, 8, 2345, 23, 48, 267}},
{__LINE__,
{123, 234, 345, 456, 567, 678, 789, 890, 98, 76},
{123, 234, 345, 456, 567, 678, 789, 890, 98, 76}},
{__LINE__, {3, 675, 23, 86, 2, 8, 2}, {456, 675, 23, 86, 23, 65, 2}},
{__LINE__, {1}, {23}},
};
for (const auto& spec : specs) {
SCOPED_TRACE(spec.line);
double chi_square = 0;
for (int i = 0; i < spec.expected.size(); ++i) {
const double diff = spec.actual[i] - spec.expected[i];
chi_square += (diff * diff) / spec.expected[i];
}
EXPECT_NEAR(chi_square,
ChiSquare(std::begin(spec.actual), std::end(spec.actual),
std::begin(spec.expected), std::end(spec.expected)),
1e-5);
}
}
TEST(ChiSquareTest, CalcChiSquareInt64) {
const int64_t data[3] = {910293487, 910292491, 910216780};
double sum = std::accumulate(std::begin(data), std::end(data), double{0});
size_t n = std::distance(std::begin(data), std::end(data));
double a = ChiSquareWithExpected(std::begin(data), std::end(data), sum / n);
EXPECT_NEAR(4.254101, a, 1e-6);
double b =
ChiSquareWithExpected(std::begin(data), std::end(data), 910267586.0);
EXPECT_NEAR(4.254101, b, 1e-6);
}
TEST(ChiSquareTest, TableData) {
const double data[100][5] = {
{2.706, 3.841, 5.024, 6.635, 10.828},
{4.605, 5.991, 7.378, 9.210, 13.816},
{6.251, 7.815, 9.348, 11.345, 16.266},
{7.779, 9.488, 11.143, 13.277, 18.467},
{9.236, 11.070, 12.833, 15.086, 20.515},
{10.645, 12.592, 14.449, 16.812, 22.458},
{12.017, 14.067, 16.013, 18.475, 24.322},
{13.362, 15.507, 17.535, 20.090, 26.125},
{14.684, 16.919, 19.023, 21.666, 27.877},
{15.987, 18.307, 20.483, 23.209, 29.588},
{17.275, 19.675, 21.920, 24.725, 31.264},
{18.549, 21.026, 23.337, 26.217, 32.910},
{19.812, 22.362, 24.736, 27.688, 34.528},
{21.064, 23.685, 26.119, 29.141, 36.123},
{22.307, 24.996, 27.488, 30.578, 37.697},
{23.542, 26.296, 28.845, 32.000, 39.252},
{24.769, 27.587, 30.191, 33.409, 40.790},
{25.989, 28.869, 31.526, 34.805, 42.312},
{27.204, 30.144, 32.852, 36.191, 43.820},
{28.412, 31.410, 34.170, 37.566, 45.315},
{29.615, 32.671, 35.479, 38.932, 46.797},
{30.813, 33.924, 36.781, 40.289, 48.268},
{32.007, 35.172, 38.076, 41.638, 49.728},
{33.196, 36.415, 39.364, 42.980, 51.179},
{34.382, 37.652, 40.646, 44.314, 52.620},
{35.563, 38.885, 41.923, 45.642, 54.052},
{36.741, 40.113, 43.195, 46.963, 55.476},
{37.916, 41.337, 44.461, 48.278, 56.892},
{39.087, 42.557, 45.722, 49.588, 58.301},
{40.256, 43.773, 46.979, 50.892, 59.703},
{41.422, 44.985, 48.232, 52.191, 61.098},
{42.585, 46.194, 49.480, 53.486, 62.487},
{43.745, 47.400, 50.725, 54.776, 63.870},
{44.903, 48.602, 51.966, 56.061, 65.247},
{46.059, 49.802, 53.203, 57.342, 66.619},
{47.212, 50.998, 54.437, 58.619, 67.985},
{48.363, 52.192, 55.668, 59.893, 69.347},
{49.513, 53.384, 56.896, 61.162, 70.703},
{50.660, 54.572, 58.120, 62.428, 72.055},
{51.805, 55.758, 59.342, 63.691, 73.402},
{52.949, 56.942, 60.561, 64.950, 74.745},
{54.090, 58.124, 61.777, 66.206, 76.084},
{55.230, 59.304, 62.990, 67.459, 77.419},
{56.369, 60.481, 64.201, 68.710, 78.750},
{57.505, 61.656, 65.410, 69.957, 80.077},
{58.641, 62.830, 66.617, 71.201, 81.400},
{59.774, 64.001, 67.821, 72.443, 82.720},
{60.907, 65.171, 69.023, 73.683, 84.037},
{62.038, 66.339, 70.222, 74.919, 85.351},
{63.167, 67.505, 71.420, 76.154, 86.661},
{64.295, 68.669, 72.616, 77.386, 87.968},
{65.422, 69.832, 73.810, 78.616, 89.272},
{66.548, 70.993, 75.002, 79.843, 90.573},
{67.673, 72.153, 76.192, 81.069, 91.872},
{68.796, 73.311, 77.380, 82.292, 93.168},
{69.919, 74.468, 78.567, 83.513, 94.461},
{71.040, 75.624, 79.752, 84.733, 95.751},
{72.160, 76.778, 80.936, 85.950, 97.039},
{73.279, 77.931, 82.117, 87.166, 98.324},
{74.397, 79.082, 83.298, 88.379, 99.607},
{75.514, 80.232, 84.476, 89.591, 100.888},
{76.630, 81.381, 85.654, 90.802, 102.166},
{77.745, 82.529, 86.830, 92.010, 103.442},
{78.860, 83.675, 88.004, 93.217, 104.716},
{79.973, 84.821, 89.177, 94.422, 105.988},
{81.085, 85.965, 90.349, 95.626, 107.258},
{82.197, 87.108, 91.519, 96.828, 108.526},
{83.308, 88.250, 92.689, 98.028, 109.791},
{84.418, 89.391, 93.856, 99.228, 111.055},
{85.527, 90.531, 95.023, 100.425, 112.317},
{86.635, 91.670, 96.189, 101.621, 113.577},
{87.743, 92.808, 97.353, 102.816, 114.835},
{88.850, 93.945, 98.516, 104.010, 116.092},
{89.956, 95.081, 99.678, 105.202, 117.346},
{91.061, 96.217, 100.839, 106.393, 118.599},
{92.166, 97.351, 101.999, 107.583, 119.850},
{93.270, 98.484, 103.158, 108.771, 121.100},
{94.374, 99.617, 104.316, 109.958, 122.348},
{95.476, 100.749, 105.473, 111.144, 123.594},
{96.578, 101.879, 106.629, 112.329, 124.839},
{97.680, 103.010, 107.783, 113.512, 126.083},
{98.780, 104.139, 108.937, 114.695, 127.324},
{99.880, 105.267, 110.090, 115.876, 128.565},
{100.980, 106.395, 111.242, 117.057, 129.804},
{102.079, 107.522, 112.393, 118.236, 131.041},
{103.177, 108.648, 113.544, 119.414, 132.277},
{104.275, 109.773, 114.693, 120.591, 133.512},
{105.372, 110.898, 115.841, 121.767, 134.746},
{106.469, 112.022, 116.989, 122.942, 135.978},
{107.565, 113.145, 118.136, 124.116, 137.208},
{108.661, 114.268, 119.282, 125.289, 138.438},
{109.756, 115.390, 120.427, 126.462, 139.666},
{110.850, 116.511, 121.571, 127.633, 140.893},
{111.944, 117.632, 122.715, 128.803, 142.119},
{113.038, 118.752, 123.858, 129.973, 143.344},
{114.131, 119.871, 125.000, 131.141, 144.567},
{115.223, 120.990, 126.141, 132.309, 145.789},
{116.315, 122.108, 127.282, 133.476, 147.010},
{117.407, 123.225, 128.422, 134.642, 148.230},
{118.498, 124.342, 129.561, 135.807, 149.449}
};
for (int i = 0; i < ABSL_ARRAYSIZE(data); i++) {
const double E = 0.0001;
EXPECT_NEAR(ChiSquarePValue(data[i][0], i + 1), 0.10, E)
<< i << " " << data[i][0];
EXPECT_NEAR(ChiSquarePValue(data[i][1], i + 1), 0.05, E)
<< i << " " << data[i][1];
EXPECT_NEAR(ChiSquarePValue(data[i][2], i + 1), 0.025, E)
<< i << " " << data[i][2];
EXPECT_NEAR(ChiSquarePValue(data[i][3], i + 1), 0.01, E)
<< i << " " << data[i][3];
EXPECT_NEAR(ChiSquarePValue(data[i][4], i + 1), 0.001, E)
<< i << " " << data[i][4];
const double F = 0.1;
EXPECT_NEAR(ChiSquareValue(i + 1, 0.90), data[i][0], F) << i;
EXPECT_NEAR(ChiSquareValue(i + 1, 0.95), data[i][1], F) << i;
EXPECT_NEAR(ChiSquareValue(i + 1, 0.975), data[i][2], F) << i;
EXPECT_NEAR(ChiSquareValue(i + 1, 0.99), data[i][3], F) << i;
EXPECT_NEAR(ChiSquareValue(i + 1, 0.999), data[i][4], F) << i;
}
}
TEST(ChiSquareTest, ChiSquareTwoIterator) {
const int counts[10] = {6, 6, 18, 33, 38, 38, 28, 21, 9, 3};
const double expected[10] = {4.6, 8.8, 18.4, 30.0, 38.2,
38.2, 30.0, 18.4, 8.8, 4.6};
double chi_square = ChiSquare(std::begin(counts), std::end(counts),
std::begin(expected), std::end(expected));
EXPECT_NEAR(chi_square, 2.69, 0.001);
const int dof = 7;
double p_value_05 = ChiSquarePValue(14.067, dof);
EXPECT_NEAR(p_value_05, 0.05, 0.001);
double p_actual = ChiSquarePValue(chi_square, dof);
EXPECT_GT(p_actual, 0.05);
}
TEST(ChiSquareTest, DiceRolls) {
const int rolls[6] = {22, 11, 17, 14, 20, 18};
double sum = std::accumulate(std::begin(rolls), std::end(rolls), double{0});
size_t n = std::distance(std::begin(rolls), std::end(rolls));
double a = ChiSquareWithExpected(std::begin(rolls), std::end(rolls), sum / n);
EXPECT_NEAR(a, 4.70588, 1e-5);
EXPECT_LT(a, ChiSquareValue(4, 0.95));
double p_a = ChiSquarePValue(a, 4);
EXPECT_NEAR(p_a, 0.318828, 1e-5);
double b = ChiSquareWithExpected(std::begin(rolls), std::end(rolls), 17.0);
EXPECT_NEAR(b, 4.70588, 1e-5);
EXPECT_LT(b, ChiSquareValue(5, 0.95));
double p_b = ChiSquarePValue(b, 5);
EXPECT_NEAR(p_b, 0.4528180, 1e-5);
}
} |
2,525 | cpp | abseil/abseil-cpp | seed_material | absl/random/internal/seed_material.cc | absl/random/internal/seed_material_test.cc | #ifndef ABSL_RANDOM_INTERNAL_SEED_MATERIAL_H_
#define ABSL_RANDOM_INTERNAL_SEED_MATERIAL_H_
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/random/internal/fast_uniform_bits.h"
#include "absl/types/optional.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
constexpr size_t SeedBitsToBlocks(size_t seed_size) {
return (seed_size + 31) / 32;
}
constexpr size_t kEntropyBitsNeeded = 256;
constexpr size_t kEntropyBlocksNeeded =
random_internal::SeedBitsToBlocks(kEntropyBitsNeeded);
static_assert(kEntropyBlocksNeeded > 0,
"Entropy used to seed URBGs must be nonzero.");
ABSL_MUST_USE_RESULT
bool ReadSeedMaterialFromOSEntropy(absl::Span<uint32_t> values);
template <typename URBG>
ABSL_MUST_USE_RESULT bool ReadSeedMaterialFromURBG(
URBG* urbg, absl::Span<uint32_t> values) {
random_internal::FastUniformBits<uint32_t> distr;
assert(urbg != nullptr && values.data() != nullptr);
if (urbg == nullptr || values.data() == nullptr) {
return false;
}
for (uint32_t& seed_value : values) {
seed_value = distr(*urbg);
}
return true;
}
void MixIntoSeedMaterial(absl::Span<const uint32_t> sequence,
absl::Span<uint32_t> seed_material);
absl::optional<uint32_t> GetSaltMaterial();
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/seed_material.h"
#include <fcntl.h>
#ifndef _WIN32
#include <unistd.h>
#else
#include <io.h>
#endif
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include "absl/base/dynamic_annotations.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#if defined(__native_client__)
#include <nacl/nacl_random.h>
#define ABSL_RANDOM_USE_NACL_SECURE_RANDOM 1
#elif defined(_WIN32)
#include <windows.h>
#define ABSL_RANDOM_USE_BCRYPT 1
#pragma comment(lib, "bcrypt.lib")
#elif defined(__Fuchsia__)
#include <zircon/syscalls.h>
#endif
#if defined(__GLIBC__) && \
(__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 25))
#define ABSL_RANDOM_USE_GET_ENTROPY 1
#endif
#if defined(__EMSCRIPTEN__)
#include <sys/random.h>
#define ABSL_RANDOM_USE_GET_ENTROPY 1
#endif
#if defined(ABSL_RANDOM_USE_BCRYPT)
#include <bcrypt.h>
#ifndef BCRYPT_SUCCESS
#define BCRYPT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#endif
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
namespace {
#if defined(ABSL_RANDOM_USE_BCRYPT)
bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
BCRYPT_ALG_HANDLE hProvider;
NTSTATUS ret;
ret = BCryptOpenAlgorithmProvider(&hProvider, BCRYPT_RNG_ALGORITHM,
MS_PRIMITIVE_PROVIDER, 0);
if (!(BCRYPT_SUCCESS(ret))) {
ABSL_RAW_LOG(ERROR, "Failed to open crypto provider.");
return false;
}
ret = BCryptGenRandom(
hProvider,
reinterpret_cast<UCHAR*>(values.data()),
static_cast<ULONG>(sizeof(uint32_t) * values.size()),
0);
BCryptCloseAlgorithmProvider(hProvider, 0);
return BCRYPT_SUCCESS(ret);
}
#elif defined(ABSL_RANDOM_USE_NACL_SECURE_RANDOM)
bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
auto buffer = reinterpret_cast<uint8_t*>(values.data());
size_t buffer_size = sizeof(uint32_t) * values.size();
uint8_t* output_ptr = buffer;
while (buffer_size > 0) {
size_t nread = 0;
const int error = nacl_secure_random(output_ptr, buffer_size, &nread);
if (error != 0 || nread > buffer_size) {
ABSL_RAW_LOG(ERROR, "Failed to read secure_random seed data: %d", error);
return false;
}
output_ptr += nread;
buffer_size -= nread;
}
return true;
}
#elif defined(__Fuchsia__)
bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
auto buffer = reinterpret_cast<uint8_t*>(values.data());
size_t buffer_size = sizeof(uint32_t) * values.size();
zx_cprng_draw(buffer, buffer_size);
return true;
}
#else
#if defined(ABSL_RANDOM_USE_GET_ENTROPY)
bool ReadSeedMaterialFromGetEntropy(absl::Span<uint32_t> values) {
auto buffer = reinterpret_cast<uint8_t*>(values.data());
size_t buffer_size = sizeof(uint32_t) * values.size();
while (buffer_size > 0) {
size_t to_read = std::min<size_t>(buffer_size, 256);
int result = getentropy(buffer, to_read);
if (result < 0) {
return false;
}
ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(buffer, to_read);
buffer += to_read;
buffer_size -= to_read;
}
return true;
}
#endif
bool ReadSeedMaterialFromDevURandom(absl::Span<uint32_t> values) {
const char kEntropyFile[] = "/dev/urandom";
auto buffer = reinterpret_cast<uint8_t*>(values.data());
size_t buffer_size = sizeof(uint32_t) * values.size();
int dev_urandom = open(kEntropyFile, O_RDONLY);
bool success = (-1 != dev_urandom);
if (!success) {
return false;
}
while (success && buffer_size > 0) {
ssize_t bytes_read = read(dev_urandom, buffer, buffer_size);
int read_error = errno;
success = (bytes_read > 0);
if (success) {
buffer += bytes_read;
buffer_size -= static_cast<size_t>(bytes_read);
} else if (bytes_read == -1 && read_error == EINTR) {
success = true;
}
}
close(dev_urandom);
return success;
}
bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) {
#if defined(ABSL_RANDOM_USE_GET_ENTROPY)
if (ReadSeedMaterialFromGetEntropy(values)) {
return true;
}
#endif
return ReadSeedMaterialFromDevURandom(values);
}
#endif
}
bool ReadSeedMaterialFromOSEntropy(absl::Span<uint32_t> values) {
assert(values.data() != nullptr);
if (values.data() == nullptr) {
return false;
}
if (values.empty()) {
return true;
}
return ReadSeedMaterialFromOSEntropyImpl(values);
}
void MixIntoSeedMaterial(absl::Span<const uint32_t> sequence,
absl::Span<uint32_t> seed_material) {
constexpr uint32_t kInitVal = 0x43b0d7e5;
constexpr uint32_t kHashMul = 0x931e8875;
constexpr uint32_t kMixMulL = 0xca01f9dd;
constexpr uint32_t kMixMulR = 0x4973f715;
constexpr uint32_t kShiftSize = sizeof(uint32_t) * 8 / 2;
uint32_t hash_const = kInitVal;
auto hash = [&](uint32_t value) {
value ^= hash_const;
hash_const *= kHashMul;
value *= hash_const;
value ^= value >> kShiftSize;
return value;
};
auto mix = [&](uint32_t x, uint32_t y) {
uint32_t result = kMixMulL * x - kMixMulR * y;
result ^= result >> kShiftSize;
return result;
};
for (const auto& seq_val : sequence) {
for (auto& elem : seed_material) {
elem = mix(elem, hash(seq_val));
}
}
}
absl::optional<uint32_t> GetSaltMaterial() {
static const auto salt_material = []() -> absl::optional<uint32_t> {
uint32_t salt_value = 0;
if (random_internal::ReadSeedMaterialFromOSEntropy(
MakeSpan(&salt_value, 1))) {
return salt_value;
}
return absl::nullopt;
}();
return salt_material;
}
}
ABSL_NAMESPACE_END
} | #include "absl/random/internal/seed_material.h"
#include <bitset>
#include <cstdlib>
#include <cstring>
#include <random>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#ifdef __ANDROID__
#define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH_IF_SUPPORTED(statement, ".*")
#else
#define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH_IF_SUPPORTED(statement, regex)
#endif
namespace {
using testing::Each;
using testing::ElementsAre;
using testing::Eq;
using testing::Ne;
using testing::Pointwise;
TEST(SeedBitsToBlocks, VerifyCases) {
EXPECT_EQ(0, absl::random_internal::SeedBitsToBlocks(0));
EXPECT_EQ(1, absl::random_internal::SeedBitsToBlocks(1));
EXPECT_EQ(1, absl::random_internal::SeedBitsToBlocks(31));
EXPECT_EQ(1, absl::random_internal::SeedBitsToBlocks(32));
EXPECT_EQ(2, absl::random_internal::SeedBitsToBlocks(33));
EXPECT_EQ(4, absl::random_internal::SeedBitsToBlocks(127));
EXPECT_EQ(4, absl::random_internal::SeedBitsToBlocks(128));
EXPECT_EQ(5, absl::random_internal::SeedBitsToBlocks(129));
}
TEST(ReadSeedMaterialFromOSEntropy, SuccessiveReadsAreDistinct) {
constexpr size_t kSeedMaterialSize = 64;
uint32_t seed_material_1[kSeedMaterialSize] = {};
uint32_t seed_material_2[kSeedMaterialSize] = {};
EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromOSEntropy(
absl::Span<uint32_t>(seed_material_1, kSeedMaterialSize)));
EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromOSEntropy(
absl::Span<uint32_t>(seed_material_2, kSeedMaterialSize)));
EXPECT_THAT(seed_material_1, Pointwise(Ne(), seed_material_2));
}
TEST(ReadSeedMaterialFromOSEntropy, ReadZeroBytesIsNoOp) {
uint32_t seed_material[32] = {};
std::memset(seed_material, 0xAA, sizeof(seed_material));
EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromOSEntropy(
absl::Span<uint32_t>(seed_material, 0)));
EXPECT_THAT(seed_material, Each(Eq(0xAAAAAAAA)));
}
TEST(ReadSeedMaterialFromOSEntropy, NullPtrVectorArgument) {
#ifdef NDEBUG
EXPECT_FALSE(absl::random_internal::ReadSeedMaterialFromOSEntropy(
absl::Span<uint32_t>(nullptr, 32)));
#else
bool result;
ABSL_EXPECT_DEATH_IF_SUPPORTED(
result = absl::random_internal::ReadSeedMaterialFromOSEntropy(
absl::Span<uint32_t>(nullptr, 32)),
"!= nullptr");
(void)result;
#endif
}
TEST(ReadSeedMaterialFromURBG, SeedMaterialEqualsVariateSequence) {
std::mt19937 urbg_1;
std::mt19937 urbg_2;
constexpr size_t kSeedMaterialSize = 1024;
uint32_t seed_material[kSeedMaterialSize] = {};
EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromURBG(
&urbg_1, absl::Span<uint32_t>(seed_material, kSeedMaterialSize)));
for (uint32_t seed : seed_material) {
EXPECT_EQ(seed, urbg_2());
}
}
TEST(ReadSeedMaterialFromURBG, ReadZeroBytesIsNoOp) {
std::mt19937_64 urbg;
uint32_t seed_material[32];
std::memset(seed_material, 0xAA, sizeof(seed_material));
EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromURBG(
&urbg, absl::Span<uint32_t>(seed_material, 0)));
EXPECT_THAT(seed_material, Each(Eq(0xAAAAAAAA)));
}
TEST(ReadSeedMaterialFromURBG, NullUrbgArgument) {
constexpr size_t kSeedMaterialSize = 32;
uint32_t seed_material[kSeedMaterialSize];
#ifdef NDEBUG
EXPECT_FALSE(absl::random_internal::ReadSeedMaterialFromURBG<std::mt19937_64>(
nullptr, absl::Span<uint32_t>(seed_material, kSeedMaterialSize)));
#else
bool result;
ABSL_EXPECT_DEATH_IF_SUPPORTED(
result = absl::random_internal::ReadSeedMaterialFromURBG<std::mt19937_64>(
nullptr, absl::Span<uint32_t>(seed_material, kSeedMaterialSize)),
"!= nullptr");
(void)result;
#endif
}
TEST(ReadSeedMaterialFromURBG, NullPtrVectorArgument) {
std::mt19937_64 urbg;
#ifdef NDEBUG
EXPECT_FALSE(absl::random_internal::ReadSeedMaterialFromURBG(
&urbg, absl::Span<uint32_t>(nullptr, 32)));
#else
bool result;
ABSL_EXPECT_DEATH_IF_SUPPORTED(
result = absl::random_internal::ReadSeedMaterialFromURBG(
&urbg, absl::Span<uint32_t>(nullptr, 32)),
"!= nullptr");
(void)result;
#endif
}
TEST(MixSequenceIntoSeedMaterial, AvalancheEffectTestOneBitLong) {
std::vector<uint32_t> seed_material = {1, 2, 3, 4, 5, 6, 7, 8};
for (uint32_t v = 1; v != 0; v <<= 1) {
std::vector<uint32_t> seed_material_copy = seed_material;
absl::random_internal::MixIntoSeedMaterial(
absl::Span<uint32_t>(&v, 1),
absl::Span<uint32_t>(seed_material_copy.data(),
seed_material_copy.size()));
uint32_t changed_bits = 0;
for (size_t i = 0; i < seed_material.size(); i++) {
std::bitset<sizeof(uint32_t) * 8> bitset(seed_material[i] ^
seed_material_copy[i]);
changed_bits += bitset.count();
}
EXPECT_LE(changed_bits, 0.7 * sizeof(uint32_t) * 8 * seed_material.size());
EXPECT_GE(changed_bits, 0.3 * sizeof(uint32_t) * 8 * seed_material.size());
}
}
TEST(MixSequenceIntoSeedMaterial, AvalancheEffectTestOneBitShort) {
std::vector<uint32_t> seed_material = {1};
for (uint32_t v = 1; v != 0; v <<= 1) {
std::vector<uint32_t> seed_material_copy = seed_material;
absl::random_internal::MixIntoSeedMaterial(
absl::Span<uint32_t>(&v, 1),
absl::Span<uint32_t>(seed_material_copy.data(),
seed_material_copy.size()));
uint32_t changed_bits = 0;
for (size_t i = 0; i < seed_material.size(); i++) {
std::bitset<sizeof(uint32_t) * 8> bitset(seed_material[i] ^
seed_material_copy[i]);
changed_bits += bitset.count();
}
EXPECT_LE(changed_bits, 0.7 * sizeof(uint32_t) * 8 * seed_material.size());
EXPECT_GE(changed_bits, 0.3 * sizeof(uint32_t) * 8 * seed_material.size());
}
}
} |
2,526 | cpp | abseil/abseil-cpp | nanobenchmark | absl/random/internal/nanobenchmark.cc | absl/random/internal/nanobenchmark_test.cc | #ifndef ABSL_RANDOM_INTERNAL_NANOBENCHMARK_H_
#define ABSL_RANDOM_INTERNAL_NANOBENCHMARK_H_
#include <stddef.h>
#include <stdint.h>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal_nanobenchmark {
using FuncInput = size_t;
using FuncOutput = uint64_t;
using Func = FuncOutput (*)(const void*, FuncInput);
struct Params {
static constexpr size_t kTimerSamples = 256;
size_t precision_divisor = 1024;
size_t subset_ratio = 2;
double seconds_per_eval = 4E-3;
size_t min_samples_per_eval = 7;
size_t min_mode_samples = 64;
double target_rel_mad = 0.002;
size_t max_evals = 9;
size_t max_measure_retries = 2;
bool verbose = true;
};
struct Result {
FuncInput input;
float ticks;
float variability;
};
void PinThreadToCPU(const int cpu = -1);
double InvariantTicksPerSecond();
size_t Measure(const Func func, const void* arg, const FuncInput* inputs,
const size_t num_inputs, Result* results,
const Params& p = Params());
template <class Closure>
static FuncOutput CallClosure(const void* f, const FuncInput input) {
return (*reinterpret_cast<const Closure*>(f))(input);
}
template <class Closure>
static inline size_t MeasureClosure(const Closure& closure,
const FuncInput* inputs,
const size_t num_inputs, Result* results,
const Params& p = Params()) {
return Measure(reinterpret_cast<Func>(&CallClosure<Closure>),
reinterpret_cast<const void*>(&closure), inputs, num_inputs,
results, p);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/nanobenchmark.h"
#include <sys/types.h>
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/random/internal/platform.h"
#include "absl/random/internal/randen_engine.h"
#if defined(_WIN32) || defined(_WIN64)
#define ABSL_OS_WIN
#include <windows.h>
#elif defined(__ANDROID__)
#define ABSL_OS_ANDROID
#elif defined(__linux__)
#define ABSL_OS_LINUX
#include <sched.h>
#include <sys/syscall.h>
#endif
#if defined(ABSL_ARCH_X86_64) && !defined(ABSL_OS_WIN)
#include <cpuid.h>
#endif
#if defined(ABSL_ARCH_PPC)
#include <sys/platform/ppc.h>
#endif
#if defined(ABSL_ARCH_ARM) || defined(ABSL_ARCH_AARCH64)
#include <time.h>
#endif
#if ABSL_HAVE_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__))
#define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE __attribute__((noinline))
#elif defined(_MSC_VER)
#define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE __declspec(noinline)
#else
#define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal_nanobenchmark {
namespace {
namespace platform {
#if defined(ABSL_ARCH_X86_64)
void Cpuid(const uint32_t level, const uint32_t count,
uint32_t* ABSL_RANDOM_INTERNAL_RESTRICT abcd) {
#if defined(ABSL_OS_WIN)
int regs[4];
__cpuidex(regs, level, count);
for (int i = 0; i < 4; ++i) {
abcd[i] = regs[i];
}
#else
uint32_t a, b, c, d;
__cpuid_count(level, count, a, b, c, d);
abcd[0] = a;
abcd[1] = b;
abcd[2] = c;
abcd[3] = d;
#endif
}
std::string BrandString() {
char brand_string[49];
uint32_t abcd[4];
Cpuid(0x80000000U, 0, abcd);
if (abcd[0] < 0x80000004U) {
return std::string();
}
for (int i = 0; i < 3; ++i) {
Cpuid(0x80000002U + i, 0, abcd);
memcpy(brand_string + i * 16, &abcd, sizeof(abcd));
}
brand_string[48] = 0;
return brand_string;
}
double NominalClockRate() {
const std::string& brand_string = BrandString();
const char* prefixes[3] = {"MHz", "GHz", "THz"};
const double multipliers[3] = {1E6, 1E9, 1E12};
for (size_t i = 0; i < 3; ++i) {
const size_t pos_prefix = brand_string.find(prefixes[i]);
if (pos_prefix != std::string::npos) {
const size_t pos_space = brand_string.rfind(' ', pos_prefix - 1);
if (pos_space != std::string::npos) {
const std::string digits =
brand_string.substr(pos_space + 1, pos_prefix - pos_space - 1);
return std::stod(digits) * multipliers[i];
}
}
}
return 0.0;
}
#endif
}
template <class T>
inline void PreventElision(T&& output) {
#ifndef ABSL_OS_WIN
asm volatile("" : "+r"(output) : : "memory");
#else
static std::atomic<T> dummy(T{});
dummy.store(output, std::memory_order_relaxed);
#endif
}
namespace timer {
inline uint64_t Start64() {
uint64_t t;
#if defined(ABSL_ARCH_PPC)
asm volatile("mfspr %0, %1" : "=r"(t) : "i"(268));
#elif defined(ABSL_ARCH_X86_64)
#if defined(ABSL_OS_WIN)
_ReadWriteBarrier();
_mm_lfence();
_ReadWriteBarrier();
t = __rdtsc();
_ReadWriteBarrier();
_mm_lfence();
_ReadWriteBarrier();
#else
asm volatile(
"lfence\n\t"
"rdtsc\n\t"
"shl $32, %%rdx\n\t"
"or %%rdx, %0\n\t"
"lfence"
: "=a"(t)
:
: "rdx", "memory", "cc");
#endif
#else
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
t = ts.tv_sec * 1000000000LL + ts.tv_nsec;
#endif
return t;
}
inline uint64_t Stop64() {
uint64_t t;
#if defined(ABSL_ARCH_X86_64)
#if defined(ABSL_OS_WIN)
_ReadWriteBarrier();
unsigned aux;
t = __rdtscp(&aux);
_ReadWriteBarrier();
_mm_lfence();
_ReadWriteBarrier();
#else
asm volatile(
"rdtscp\n\t"
"shl $32, %%rdx\n\t"
"or %%rdx, %0\n\t"
"lfence"
: "=a"(t)
:
: "rcx", "rdx", "memory", "cc");
#endif
#else
t = Start64();
#endif
return t;
}
inline uint32_t Start32() {
uint32_t t;
#if defined(ABSL_ARCH_X86_64)
#if defined(ABSL_OS_WIN)
_ReadWriteBarrier();
_mm_lfence();
_ReadWriteBarrier();
t = static_cast<uint32_t>(__rdtsc());
_ReadWriteBarrier();
_mm_lfence();
_ReadWriteBarrier();
#else
asm volatile(
"lfence\n\t"
"rdtsc\n\t"
"lfence"
: "=a"(t)
:
: "rdx", "memory");
#endif
#else
t = static_cast<uint32_t>(Start64());
#endif
return t;
}
inline uint32_t Stop32() {
uint32_t t;
#if defined(ABSL_ARCH_X86_64)
#if defined(ABSL_OS_WIN)
_ReadWriteBarrier();
unsigned aux;
t = static_cast<uint32_t>(__rdtscp(&aux));
_ReadWriteBarrier();
_mm_lfence();
_ReadWriteBarrier();
#else
asm volatile(
"rdtscp\n\t"
"lfence"
: "=a"(t)
:
: "rcx", "rdx", "memory");
#endif
#else
t = static_cast<uint32_t>(Stop64());
#endif
return t;
}
}
namespace robust_statistics {
template <class T>
void CountingSort(T* values, size_t num_values) {
using Unique = std::pair<T, int>;
std::vector<Unique> unique;
for (size_t i = 0; i < num_values; ++i) {
const T value = values[i];
const auto pos =
std::find_if(unique.begin(), unique.end(),
[value](const Unique u) { return u.first == value; });
if (pos == unique.end()) {
unique.push_back(std::make_pair(value, 1));
} else {
++pos->second;
}
}
std::sort(unique.begin(), unique.end());
T* ABSL_RANDOM_INTERNAL_RESTRICT p = values;
for (const auto& value_count : unique) {
std::fill_n(p, value_count.second, value_count.first);
p += value_count.second;
}
ABSL_RAW_CHECK(p == values + num_values, "Did not produce enough output");
}
template <typename T>
size_t MinRange(const T* const ABSL_RANDOM_INTERNAL_RESTRICT sorted,
const size_t idx_begin, const size_t half_count) {
T min_range = (std::numeric_limits<T>::max)();
size_t min_idx = 0;
for (size_t idx = idx_begin; idx < idx_begin + half_count; ++idx) {
ABSL_RAW_CHECK(sorted[idx] <= sorted[idx + half_count], "Not sorted");
const T range = sorted[idx + half_count] - sorted[idx];
if (range < min_range) {
min_range = range;
min_idx = idx;
}
}
return min_idx;
}
template <typename T>
T ModeOfSorted(const T* const ABSL_RANDOM_INTERNAL_RESTRICT sorted,
const size_t num_values) {
size_t idx_begin = 0;
size_t half_count = num_values / 2;
while (half_count > 1) {
idx_begin = MinRange(sorted, idx_begin, half_count);
half_count >>= 1;
}
const T x = sorted[idx_begin + 0];
if (half_count == 0) {
return x;
}
ABSL_RAW_CHECK(half_count == 1, "Should stop at half_count=1");
const T average = (x + sorted[idx_begin + 1] + 1) / 2;
return average;
}
template <typename T>
T Mode(T* values, const size_t num_values) {
CountingSort(values, num_values);
return ModeOfSorted(values, num_values);
}
template <typename T, size_t N>
T Mode(T (&values)[N]) {
return Mode(&values[0], N);
}
template <typename T>
T Median(T* values, const size_t num_values) {
ABSL_RAW_CHECK(num_values != 0, "Empty input");
std::sort(values, values + num_values);
const size_t half = num_values / 2;
if (num_values % 2) {
return values[half];
}
return (values[half] + values[half - 1] + 1) / 2;
}
template <typename T>
T MedianAbsoluteDeviation(const T* values, const size_t num_values,
const T median) {
ABSL_RAW_CHECK(num_values != 0, "Empty input");
std::vector<T> abs_deviations;
abs_deviations.reserve(num_values);
for (size_t i = 0; i < num_values; ++i) {
const int64_t abs = std::abs(int64_t(values[i]) - int64_t(median));
abs_deviations.push_back(static_cast<T>(abs));
}
return Median(abs_deviations.data(), num_values);
}
}
using Ticks = uint32_t;
Ticks TimerResolution() {
Ticks repetitions[Params::kTimerSamples];
for (size_t rep = 0; rep < Params::kTimerSamples; ++rep) {
Ticks samples[Params::kTimerSamples];
for (size_t i = 0; i < Params::kTimerSamples; ++i) {
const Ticks t0 = timer::Start32();
const Ticks t1 = timer::Stop32();
samples[i] = t1 - t0;
}
repetitions[rep] = robust_statistics::Mode(samples);
}
return robust_statistics::Mode(repetitions);
}
static const Ticks timer_resolution = TimerResolution();
template <class Lambda>
Ticks SampleUntilStable(const double max_rel_mad, double* rel_mad,
const Params& p, const Lambda& lambda) {
auto measure_duration = [&lambda]() -> Ticks {
const Ticks t0 = timer::Start32();
lambda();
const Ticks t1 = timer::Stop32();
return t1 - t0;
};
Ticks est = measure_duration();
static const double ticks_per_second = InvariantTicksPerSecond();
const size_t ticks_per_eval = ticks_per_second * p.seconds_per_eval;
size_t samples_per_eval = ticks_per_eval / est;
samples_per_eval = (std::max)(samples_per_eval, p.min_samples_per_eval);
std::vector<Ticks> samples;
samples.reserve(1 + samples_per_eval);
samples.push_back(est);
const Ticks max_abs_mad = (timer_resolution + 99) / 100;
*rel_mad = 0.0;
for (size_t eval = 0; eval < p.max_evals; ++eval, samples_per_eval *= 2) {
samples.reserve(samples.size() + samples_per_eval);
for (size_t i = 0; i < samples_per_eval; ++i) {
const Ticks r = measure_duration();
samples.push_back(r);
}
if (samples.size() >= p.min_mode_samples) {
est = robust_statistics::Mode(samples.data(), samples.size());
} else {
est = robust_statistics::Median(samples.data(), samples.size());
}
ABSL_RAW_CHECK(est != 0, "Estimator returned zero duration");
const Ticks abs_mad = robust_statistics::MedianAbsoluteDeviation(
samples.data(), samples.size(), est);
*rel_mad = static_cast<double>(static_cast<int>(abs_mad)) / est;
if (*rel_mad <= max_rel_mad || abs_mad <= max_abs_mad) {
if (p.verbose) {
ABSL_RAW_LOG(INFO,
"%6zu samples => %5u (abs_mad=%4u, rel_mad=%4.2f%%)\n",
samples.size(), est, abs_mad, *rel_mad * 100.0);
}
return est;
}
}
if (p.verbose) {
ABSL_RAW_LOG(WARNING,
"rel_mad=%4.2f%% still exceeds %4.2f%% after %6zu samples.\n",
*rel_mad * 100.0, max_rel_mad * 100.0, samples.size());
}
return est;
}
using InputVec = std::vector<FuncInput>;
InputVec UniqueInputs(const FuncInput* inputs, const size_t num_inputs) {
InputVec unique(inputs, inputs + num_inputs);
std::sort(unique.begin(), unique.end());
unique.erase(std::unique(unique.begin(), unique.end()), unique.end());
return unique;
}
size_t NumSkip(const Func func, const void* arg, const InputVec& unique,
const Params& p) {
Ticks min_duration = ~0u;
for (const FuncInput input : unique) {
const uint64_t t0 = timer::Start64();
PreventElision(func(arg, input));
const uint64_t t1 = timer::Stop64();
const uint64_t elapsed = t1 - t0;
if (elapsed >= (1ULL << 30)) {
ABSL_RAW_LOG(WARNING,
"Measurement failed: need 64-bit timer for input=%zu\n",
static_cast<size_t>(input));
return 0;
}
double rel_mad;
const Ticks total = SampleUntilStable(
p.target_rel_mad, &rel_mad, p,
[func, arg, input]() { PreventElision(func(arg, input)); });
min_duration = (std::min)(min_duration, total - timer_resolution);
}
const size_t max_skip = p.precision_divisor;
const size_t num_skip =
min_duration == 0 ? 0 : (max_skip + min_duration - 1) / min_duration;
if (p.verbose) {
ABSL_RAW_LOG(INFO, "res=%u max_skip=%zu min_dur=%u num_skip=%zu\n",
timer_resolution, max_skip, min_duration, num_skip);
}
return num_skip;
}
InputVec ReplicateInputs(const FuncInput* inputs, const size_t num_inputs,
const size_t num_unique, const size_t num_skip,
const Params& p) {
InputVec full;
if (num_unique == 1) {
full.assign(p.subset_ratio * num_skip, inputs[0]);
return full;
}
full.reserve(p.subset_ratio * num_skip * num_inputs);
for (size_t i = 0; i < p.subset_ratio * num_skip; ++i) {
full.insert(full.end(), inputs, inputs + num_inputs);
}
absl::random_internal::randen_engine<uint32_t> rng;
std::shuffle(full.begin(), full.end(), rng);
return full;
}
void FillSubset(const InputVec& full, const FuncInput input_to_skip,
const size_t num_skip, InputVec* subset) {
const size_t count = std::count(full.begin(), full.end(), input_to_skip);
std::vector<uint32_t> omit;
omit.reserve(count);
for (size_t i = 0; i < count; ++i) {
omit.push_back(i);
}
absl::random_internal::randen_engine<uint32_t> rng;
std::shuffle(omit.begin(), omit.end(), rng);
omit.resize(num_skip);
std::sort(omit.begin(), omit.end());
uint32_t occurrence = ~0u;
size_t idx_omit = 0;
size_t idx_subset = 0;
for (const FuncInput next : full) {
if (next == input_to_skip) {
++occurrence;
if (idx_omit < num_skip) {
if (occurrence == omit[idx_omit]) {
++idx_omit;
continue;
}
}
}
if (idx_subset < subset->size()) {
(*subset)[idx_subset++] = next;
}
}
ABSL_RAW_CHECK(idx_subset == subset->size(), "idx_subset not at end");
ABSL_RAW_CHECK(idx_omit == omit.size(), "idx_omit not at end");
ABSL_RAW_CHECK(occurrence == count - 1, "occurrence not at end");
}
Ticks TotalDuration(const Func func, const void* arg, const InputVec* inputs,
const Params& p, double* max_rel_mad) {
double rel_mad;
const Ticks duration =
SampleUntilStable(p.target_rel_mad, &rel_mad, p, [func, arg, inputs]() {
for (const FuncInput input : *inputs) {
PreventElision(func(arg, input));
}
});
*max_rel_mad = (std::max)(*max_rel_mad, rel_mad);
return duration;
}
ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE FuncOutput
EmptyFunc(const void* arg, const FuncInput input) {
return input;
}
Ticks Overhead(const void* arg, const InputVec* inputs, const Params& p) {
double rel_mad;
return SampleUntilStable(0.0, &rel_mad, p, [arg, inputs]() {
for (const FuncInput input : *inputs) {
PreventElision(EmptyFunc(arg, input));
}
});
}
}
void PinThreadToCPU(int cpu) {
#if defined(ABSL_OS_WIN)
if (cpu < 0) {
cpu = static_cast<int>(GetCurrentProcessorNumber());
ABSL_RAW_CHECK(cpu >= 0, "PinThreadToCPU detect failed");
if (cpu >= 64) {
ABSL_RAW_LOG(ERROR, "Invalid CPU number: %d", cpu);
return;
}
} else if (cpu >= 64) {
ABSL_RAW_LOG(FATAL, "Invalid CPU number: %d", cpu);
}
const DWORD_PTR prev = SetThreadAffinityMask(GetCurrentThread(), 1ULL << cpu);
ABSL_RAW_CHECK(prev != 0, "SetAffinity failed");
#elif defined(ABSL_OS_LINUX) && !defined(ABSL_OS_ANDROID)
if (cpu < 0) {
cpu = sched_getcpu();
ABSL_RAW_CHECK(cpu >= 0, "PinThreadToCPU detect failed");
}
const pid_t pid = 0;
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
const int err = sched_setaffinity(pid, sizeof(set), &set);
ABSL_RAW_CHECK(err == 0, "SetAffinity failed");
#endif
}
double InvariantTicksPerSecond() {
#if defined(ABSL_ARCH_PPC)
return __ppc_get_timebase_freq();
#elif defined(ABSL_ARCH_X86_64) | #include "absl/random/internal/nanobenchmark.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_format.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal_nanobenchmark {
namespace {
uint64_t Div(const void*, FuncInput in) {
const int64_t d1 = 0xFFFFFFFFFFll / int64_t(in);
return d1;
}
template <size_t N>
void MeasureDiv(const FuncInput (&inputs)[N]) {
Result results[N];
Params params;
params.max_evals = 6;
const size_t num_results = Measure(&Div, nullptr, inputs, N, results, params);
if (num_results == 0) {
LOG(WARNING)
<< "WARNING: Measurement failed, should not happen when using "
"PinThreadToCPU unless the region to measure takes > 1 second.";
return;
}
for (size_t i = 0; i < num_results; ++i) {
LOG(INFO) << absl::StreamFormat("%5u: %6.2f ticks; MAD=%4.2f%%\n",
results[i].input, results[i].ticks,
results[i].variability * 100.0);
CHECK_NE(results[i].ticks, 0.0f) << "Zero duration";
}
}
void RunAll(const int argc, char* argv[]) {
int cpu = -1;
if (argc == 2) {
if (!absl::SimpleAtoi(argv[1], &cpu)) {
LOG(FATAL) << "The optional argument must be a CPU number >= 0.";
}
}
PinThreadToCPU(cpu);
const FuncInput unpredictable = argc != 999;
static const FuncInput inputs[] = {unpredictable * 10, unpredictable * 100};
MeasureDiv(inputs);
}
}
}
ABSL_NAMESPACE_END
}
int main(int argc, char* argv[]) {
absl::random_internal_nanobenchmark::RunAll(argc, argv);
return 0;
} |
2,527 | cpp | abseil/abseil-cpp | pool_urbg | absl/random/internal/pool_urbg.cc | absl/random/internal/pool_urbg_test.cc | #ifndef ABSL_RANDOM_INTERNAL_POOL_URBG_H_
#define ABSL_RANDOM_INTERNAL_POOL_URBG_H_
#include <cinttypes>
#include <limits>
#include "absl/random/internal/traits.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
template <typename T>
class RandenPool {
public:
using result_type = T;
static_assert(std::is_unsigned<result_type>::value,
"RandenPool template argument must be a built-in unsigned "
"integer type");
static constexpr result_type(min)() {
return (std::numeric_limits<result_type>::min)();
}
static constexpr result_type(max)() {
return (std::numeric_limits<result_type>::max)();
}
RandenPool() {}
inline result_type operator()() { return Generate(); }
static void Fill(absl::Span<result_type> data);
protected:
static result_type Generate();
};
extern template class RandenPool<uint8_t>;
extern template class RandenPool<uint16_t>;
extern template class RandenPool<uint32_t>;
extern template class RandenPool<uint64_t>;
template <typename T, size_t kBufferSize>
class PoolURBG {
using unsigned_type = typename make_unsigned_bits<T>::type;
using PoolType = RandenPool<unsigned_type>;
using SpanType = absl::Span<unsigned_type>;
static constexpr size_t kInitialBuffer = kBufferSize + 1;
static constexpr size_t kHalfBuffer = kBufferSize / 2;
public:
using result_type = T;
static_assert(std::is_unsigned<result_type>::value,
"PoolURBG must be parameterized by an unsigned integer type");
static_assert(kBufferSize > 1,
"PoolURBG must be parameterized by a buffer-size > 1");
static_assert(kBufferSize <= 256,
"PoolURBG must be parameterized by a buffer-size <= 256");
static constexpr result_type(min)() {
return (std::numeric_limits<result_type>::min)();
}
static constexpr result_type(max)() {
return (std::numeric_limits<result_type>::max)();
}
PoolURBG() : next_(kInitialBuffer) {}
PoolURBG(const PoolURBG&) : next_(kInitialBuffer) {}
const PoolURBG& operator=(const PoolURBG&) {
next_ = kInitialBuffer;
return *this;
}
PoolURBG(PoolURBG&&) = default;
PoolURBG& operator=(PoolURBG&&) = default;
inline result_type operator()() {
if (next_ >= kBufferSize) {
next_ = (kBufferSize > 2 && next_ > kBufferSize) ? kHalfBuffer : 0;
PoolType::Fill(SpanType(reinterpret_cast<unsigned_type*>(state_ + next_),
kBufferSize - next_));
}
return state_[next_++];
}
private:
size_t next_;
result_type state_[kBufferSize];
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/pool_urbg.h"
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <iterator>
#include "absl/base/attributes.h"
#include "absl/base/call_once.h"
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/spinlock.h"
#include "absl/base/internal/sysinfo.h"
#include "absl/base/internal/unaligned_access.h"
#include "absl/base/optimization.h"
#include "absl/random/internal/randen.h"
#include "absl/random/internal/seed_material.h"
#include "absl/random/seed_gen_exception.h"
using absl::base_internal::SpinLock;
using absl::base_internal::SpinLockHolder;
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
namespace {
class RandenPoolEntry {
public:
static constexpr size_t kState = RandenTraits::kStateBytes / sizeof(uint32_t);
static constexpr size_t kCapacity =
RandenTraits::kCapacityBytes / sizeof(uint32_t);
void Init(absl::Span<const uint32_t> data) {
SpinLockHolder l(&mu_);
std::copy(data.begin(), data.end(), std::begin(state_));
next_ = kState;
}
void Fill(uint8_t* out, size_t bytes) ABSL_LOCKS_EXCLUDED(mu_);
template <typename T>
inline T Generate() ABSL_LOCKS_EXCLUDED(mu_);
inline void MaybeRefill() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
if (next_ >= kState) {
next_ = kCapacity;
impl_.Generate(state_);
}
}
private:
uint32_t state_[kState] ABSL_GUARDED_BY(mu_);
SpinLock mu_;
const Randen impl_;
size_t next_ ABSL_GUARDED_BY(mu_);
};
template <>
inline uint8_t RandenPoolEntry::Generate<uint8_t>() {
SpinLockHolder l(&mu_);
MaybeRefill();
return static_cast<uint8_t>(state_[next_++]);
}
template <>
inline uint16_t RandenPoolEntry::Generate<uint16_t>() {
SpinLockHolder l(&mu_);
MaybeRefill();
return static_cast<uint16_t>(state_[next_++]);
}
template <>
inline uint32_t RandenPoolEntry::Generate<uint32_t>() {
SpinLockHolder l(&mu_);
MaybeRefill();
return state_[next_++];
}
template <>
inline uint64_t RandenPoolEntry::Generate<uint64_t>() {
SpinLockHolder l(&mu_);
if (next_ >= kState - 1) {
next_ = kCapacity;
impl_.Generate(state_);
}
auto p = state_ + next_;
next_ += 2;
uint64_t result;
std::memcpy(&result, p, sizeof(result));
return result;
}
void RandenPoolEntry::Fill(uint8_t* out, size_t bytes) {
SpinLockHolder l(&mu_);
while (bytes > 0) {
MaybeRefill();
size_t remaining = (kState - next_) * sizeof(state_[0]);
size_t to_copy = std::min(bytes, remaining);
std::memcpy(out, &state_[next_], to_copy);
out += to_copy;
bytes -= to_copy;
next_ += (to_copy + sizeof(state_[0]) - 1) / sizeof(state_[0]);
}
}
static constexpr size_t kPoolSize = 8;
static absl::once_flag pool_once;
ABSL_CACHELINE_ALIGNED static RandenPoolEntry* shared_pools[kPoolSize];
size_t GetPoolID() {
static_assert(kPoolSize >= 1,
"At least one urbg instance is required for PoolURBG");
ABSL_CONST_INIT static std::atomic<uint64_t> sequence{0};
#ifdef ABSL_HAVE_THREAD_LOCAL
static thread_local size_t my_pool_id = kPoolSize;
if (ABSL_PREDICT_FALSE(my_pool_id == kPoolSize)) {
my_pool_id = (sequence++ % kPoolSize);
}
return my_pool_id;
#else
static pthread_key_t tid_key = [] {
pthread_key_t tmp_key;
int err = pthread_key_create(&tmp_key, nullptr);
if (err) {
ABSL_RAW_LOG(FATAL, "pthread_key_create failed with %d", err);
}
return tmp_key;
}();
uintptr_t my_pool_id =
reinterpret_cast<uintptr_t>(pthread_getspecific(tid_key));
if (ABSL_PREDICT_FALSE(my_pool_id == 0)) {
my_pool_id = (sequence++ % kPoolSize) + 1;
int err = pthread_setspecific(tid_key, reinterpret_cast<void*>(my_pool_id));
if (err) {
ABSL_RAW_LOG(FATAL, "pthread_setspecific failed with %d", err);
}
}
return my_pool_id - 1;
#endif
}
RandenPoolEntry* PoolAlignedAlloc() {
constexpr size_t kAlignment =
ABSL_CACHELINE_SIZE > 32 ? ABSL_CACHELINE_SIZE : 32;
uintptr_t x = reinterpret_cast<uintptr_t>(
new char[sizeof(RandenPoolEntry) + kAlignment]);
auto y = x % kAlignment;
void* aligned = reinterpret_cast<void*>(y == 0 ? x : (x + kAlignment - y));
return new (aligned) RandenPoolEntry();
}
void InitPoolURBG() {
static constexpr size_t kSeedSize =
RandenTraits::kStateBytes / sizeof(uint32_t);
uint32_t seed_material[kPoolSize * kSeedSize];
if (!random_internal::ReadSeedMaterialFromOSEntropy(
absl::MakeSpan(seed_material))) {
random_internal::ThrowSeedGenException();
}
for (size_t i = 0; i < kPoolSize; i++) {
shared_pools[i] = PoolAlignedAlloc();
shared_pools[i]->Init(
absl::MakeSpan(&seed_material[i * kSeedSize], kSeedSize));
}
}
RandenPoolEntry* GetPoolForCurrentThread() {
absl::call_once(pool_once, InitPoolURBG);
return shared_pools[GetPoolID()];
}
}
template <typename T>
typename RandenPool<T>::result_type RandenPool<T>::Generate() {
auto* pool = GetPoolForCurrentThread();
return pool->Generate<T>();
}
template <typename T>
void RandenPool<T>::Fill(absl::Span<result_type> data) {
auto* pool = GetPoolForCurrentThread();
pool->Fill(reinterpret_cast<uint8_t*>(data.data()),
data.size() * sizeof(result_type));
}
template class RandenPool<uint8_t>;
template class RandenPool<uint16_t>;
template class RandenPool<uint32_t>;
template class RandenPool<uint64_t>;
}
ABSL_NAMESPACE_END
} | #include "absl/random/internal/pool_urbg.h"
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdint>
#include <iterator>
#include "gtest/gtest.h"
#include "absl/meta/type_traits.h"
#include "absl/types/span.h"
using absl::random_internal::PoolURBG;
using absl::random_internal::RandenPool;
namespace {
template <typename T>
using is_randen_pool = typename absl::disjunction<
std::is_same<T, RandenPool<uint8_t>>,
std::is_same<T, RandenPool<uint16_t>>,
std::is_same<T, RandenPool<uint32_t>>,
std::is_same<T, RandenPool<uint64_t>>>;
template <typename T, typename V>
typename absl::enable_if_t<absl::negation<is_randen_pool<T>>::value, void>
MyFill(T& rng, absl::Span<V> data) {
std::generate(std::begin(data), std::end(data), rng);
}
template <typename T, typename V>
typename absl::enable_if_t<is_randen_pool<T>::value, void>
MyFill(T& rng, absl::Span<V> data) {
rng.Fill(data);
}
template <typename EngineType>
class PoolURBGTypedTest : public ::testing::Test {};
using EngineTypes = ::testing::Types<
RandenPool<uint8_t>,
RandenPool<uint16_t>,
RandenPool<uint32_t>,
RandenPool<uint64_t>,
PoolURBG<uint8_t, 2>,
PoolURBG<uint16_t, 2>,
PoolURBG<uint32_t, 2>,
PoolURBG<uint64_t, 2>,
PoolURBG<unsigned int, 8>,
PoolURBG<unsigned long, 8>,
PoolURBG<unsigned long int, 4>,
PoolURBG<unsigned long long, 4>>;
TYPED_TEST_SUITE(PoolURBGTypedTest, EngineTypes);
TYPED_TEST(PoolURBGTypedTest, URBGInterface) {
using E = TypeParam;
using T = typename E::result_type;
static_assert(std::is_copy_constructible<E>::value,
"engine must be copy constructible");
static_assert(absl::is_copy_assignable<E>::value,
"engine must be copy assignable");
E e;
const E x;
e();
static_assert(std::is_same<decltype(e()), T>::value,
"return type of operator() must be result_type");
E u0(x);
u0();
E u1 = e;
u1();
}
TYPED_TEST(PoolURBGTypedTest, VerifySequences) {
using E = TypeParam;
using result_type = typename E::result_type;
E rng;
(void)rng();
constexpr int kNumOutputs = 64;
result_type a[kNumOutputs];
result_type b[kNumOutputs];
std::fill(std::begin(b), std::end(b), 0);
{
E x = rng;
MyFill(x, absl::MakeSpan(a));
}
{
E x = rng;
std::generate(std::begin(b), std::end(b), x);
}
size_t changed_bits = 0;
size_t unchanged_bits = 0;
size_t total_set = 0;
size_t total_bits = 0;
size_t equal_count = 0;
for (size_t i = 0; i < kNumOutputs; ++i) {
equal_count += (a[i] == b[i]) ? 1 : 0;
std::bitset<sizeof(result_type) * 8> bitset(a[i] ^ b[i]);
changed_bits += bitset.count();
unchanged_bits += bitset.size() - bitset.count();
std::bitset<sizeof(result_type) * 8> a_set(a[i]);
std::bitset<sizeof(result_type) * 8> b_set(b[i]);
total_set += a_set.count() + b_set.count();
total_bits += 2 * 8 * sizeof(result_type);
}
EXPECT_LE(changed_bits, 0.60 * (changed_bits + unchanged_bits));
EXPECT_GE(changed_bits, 0.40 * (changed_bits + unchanged_bits));
EXPECT_NEAR(total_set, total_bits * 0.5, 4 * std::sqrt(total_bits))
<< "@" << total_set / static_cast<double>(total_bits);
const double kExpected = kNumOutputs / (1.0 * sizeof(result_type) * 8);
EXPECT_LE(equal_count, 1.0 + kExpected);
}
} |
2,528 | cpp | abseil/abseil-cpp | randen_slow | absl/random/internal/randen_slow.cc | absl/random/internal/randen_slow_test.cc | #ifndef ABSL_RANDOM_INTERNAL_RANDEN_SLOW_H_
#define ABSL_RANDOM_INTERNAL_RANDEN_SLOW_H_
#include <cstddef>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
class RandenSlow {
public:
static void Generate(const void* keys, void* state_void);
static void Absorb(const void* seed_void, void* state_void);
static const void* GetKeys();
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/randen_slow.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include "absl/base/attributes.h"
#include "absl/base/internal/endian.h"
#include "absl/numeric/int128.h"
#include "absl/random/internal/platform.h"
#include "absl/random/internal/randen_traits.h"
#if ABSL_HAVE_ATTRIBUTE(always_inline) || \
(defined(__GNUC__) && !defined(__clang__))
#define ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE \
__attribute__((always_inline))
#elif defined(_MSC_VER)
#define ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE __forceinline
#else
#define ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE
#endif
namespace {
constexpr uint32_t te0[256] = {
0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6,
0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56,
0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f,
0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb,
0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453,
0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c,
0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551,
0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a,
0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637,
0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df,
0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d,
0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b,
0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd,
0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1,
0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d,
0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85,
0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a,
0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe,
0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d,
0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1,
0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5,
0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3,
0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755,
0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6,
0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54,
0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428,
0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264,
0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8,
0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531,
0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda,
0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac,
0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810,
0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657,
0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e,
0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c,
0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c,
0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199,
0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122,
0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c,
0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7,
0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e,
0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c,
};
constexpr uint32_t te1[256] = {
0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd,
0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d,
0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d,
0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b,
0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7,
0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a,
0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4,
0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f,
0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1,
0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d,
0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e,
0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb,
0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e,
0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c,
0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46,
0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a,
0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7,
0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81,
0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe,
0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104,
0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a,
0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f,
0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2,
0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695,
0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e,
0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c,
0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456,
0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4,
0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4,
0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7,
0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa,
0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018,
0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1,
0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21,
0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42,
0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12,
0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958,
0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233,
0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22,
0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a,
0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731,
0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11,
0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a,
};
constexpr uint32_t te2[256] = {
0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b,
0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b,
0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82,
0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0,
0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4,
0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26,
0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5,
0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15,
0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196,
0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2,
0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83,
0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0,
0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3,
0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced,
0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb,
0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf,
0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d,
0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f,
0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3,
0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5,
0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff,
0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec,
0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7,
0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573,
0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a,
0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14,
0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632,
0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c,
0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495,
0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d,
0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56,
0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808,
0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6,
0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f,
0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e,
0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e,
0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1,
0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311,
0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e,
0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf,
0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6,
0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f,
0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16,
};
constexpr uint32_t te3[256] = {
0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b,
0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b,
0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282,
0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0,
0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4,
0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626,
0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5,
0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515,
0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696,
0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2,
0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383,
0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0,
0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3,
0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded,
0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb,
0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf,
0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d,
0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f,
0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3,
0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5,
0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff,
0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec,
0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7,
0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373,
0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a,
0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414,
0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232,
0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c,
0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595,
0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d,
0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656,
0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808,
0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6,
0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f,
0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e,
0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e,
0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1,
0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111,
0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e,
0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf,
0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6,
0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f,
0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616,
};
struct alignas(16) Vector128 {
uint32_t s[4];
};
inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE Vector128
Vector128Load(const void* from) {
Vector128 result;
std::memcpy(result.s, from, sizeof(Vector128));
return result;
}
inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void Vector128Store(
const Vector128& v, void* to) {
std::memcpy(to, v.s, sizeof(Vector128));
}
inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE Vector128
AesRound(const Vector128& state, const Vector128& round_key) {
Vector128 result;
#ifdef ABSL_IS_LITTLE_ENDIAN
result.s[0] = round_key.s[0] ^
te0[uint8_t(state.s[0])] ^
te1[uint8_t(state.s[1] >> 8)] ^
te2[uint8_t(state.s[2] >> 16)] ^
te3[uint8_t(state.s[3] >> 24)];
result.s[1] = round_key.s[1] ^
te0[uint8_t(state.s[1])] ^
te1[uint8_t(state.s[2] >> 8)] ^
te2[uint8_t(state.s[3] >> 16)] ^
te3[uint8_t(state.s[0] >> 24)];
result.s[2] = round_key.s[2] ^
te0[uint8_t(state.s[2])] ^
te1[uint8_t(state.s[3] >> 8)] ^
te2[uint8_t(state.s[0] >> 16)] ^
te3[uint8_t(state.s[1] >> 24)];
result.s[3] = round_key.s[3] ^
te0[uint8_t(state.s[3])] ^
te1[uint8_t(state.s[0] >> 8)] ^
te2[uint8_t(state.s[1] >> 16)] ^
te3[uint8_t(state.s[2] >> 24)];
#else
result.s[0] = round_key.s[0] ^
te0[uint8_t(state.s[0])] ^
te1[uint8_t(state.s[3] >> 8)] ^
te2[uint8_t(state.s[2] >> 16)] ^
te3[uint8_t(state.s[1] >> 24)];
result.s[1] = round_key.s[1] ^
te0[uint8_t(state.s[1])] ^
te1[uint8_t(state.s[0] >> 8)] ^
te2[uint8_t(state.s[3] >> 16)] ^
te3[uint8_t(state.s[2] >> 24)];
result.s[2] = round_key.s[2] ^
te0[uint8_t(state.s[2])] ^
te1[uint8_t(state.s[1] >> 8)] ^
te2[uint8_t(state.s[0] >> 16)] ^
te3[uint8_t(state.s[3] >> 24)];
result.s[3] = round_key.s[3] ^
te0[uint8_t(state.s[3])] ^
te1[uint8_t(state.s[2] >> 8)] ^
te2[uint8_t(state.s[1] >> 16)] ^
te3[uint8_t(state.s[0] >> 24)];
#endif
return result;
}
using ::absl::random_internal::RandenTraits;
inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void BlockShuffle(
absl::uint128* state) {
static_assert(RandenTraits::kFeistelBlocks == 16,
"Feistel block shuffle only works for 16 blocks.");
constexpr size_t shuffle[RandenTraits::kFeistelBlocks] = {
7, 2, 13, 4, 11, 8, 3, 6, 15, 0, 9, 10, 1, 14, 5, 12};
#if 0
absl::uint128 source[RandenTraits::kFeistelBlocks];
std::memcpy(source, state, sizeof(source));
for (size_t i = 0; i < RandenTraits::kFeistelBlocks; i++) {
const absl::uint128 v0 = source[shuffle[i]];
state[i] = v0;
}
return;
#endif
const absl::uint128 v0 = state[shuffle[0]];
const absl::uint128 v1 = state[shuffle[1]];
const absl::uint128 v2 = state[shuffle[2]];
const absl::uint128 v3 = state[shuffle[3]];
const absl::uint128 v4 = state[shuffle[4]];
const absl::uint128 v5 = state[shuffle[5]];
const absl::uint128 v6 = state[shuffle[6]];
const absl::uint128 v7 = state[shuffle[7]];
const absl::uint128 w0 = state[shuffle[8]];
const absl::uint128 w1 = state[shuffle[9]];
const absl::uint128 w2 = state[shuffle[10]];
const absl::uint128 w3 = state[shuffle[11]];
const absl::uint128 w4 = state[shuffle[12]];
const absl::uint128 w5 = state[shuffle[13]];
const absl::uint128 w6 = state[shuffle[14]];
const absl::uint128 w7 = state[shuffle[15]];
state[0] = v0;
state[1] = v1;
state[2] = v2;
state[3] = v3;
state[4] = v4;
state[5] = v5;
state[6] = v6;
state[7] = v7;
state[8] = w0;
state[9] = w1;
state[10] = w2;
state[11] = w3;
state[12] = w4;
state[13] = w5;
state[14] = w6;
state[15] = w7;
}
inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE const absl::uint128*
FeistelRound(absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT state,
const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) {
for (size_t branch = 0; branch < RandenTraits::kFeistelBlocks; branch += 4) {
const Vector128 s0 = Vector128Load(state + branch);
const Vector128 s1 = Vector128Load(state + branch + 1);
const Vector128 f0 = AesRound(s0, Vector128Load(keys));
keys++;
const Vector128 o1 = AesRound(f0, s1);
Vector128Store(o1, state + branch + 1);
const Vector128 s2 = Vector128Load(state + branch + 2);
const Vector128 s3 = Vector128Load(state + branch + 3);
const Vector128 f2 = AesRound(s2, Vector128Load(keys));
keys++;
const Vector128 o3 = AesRound(f2, s3);
Vector128Store(o3, state + branch + 3);
}
return keys;
}
inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void Permute(
absl::uint128* state,
const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) {
for (size_t round = 0; round < RandenTraits::kFeistelRounds; ++round) {
keys = FeistelRound(state, keys);
BlockShuffle(state);
}
}
inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void SwapEndian(
absl::uint128* state) {
#ifdef ABSL_IS_BIG_ENDIAN
for (uint32_t block = 0; block < RandenTraits::kFeistelBlocks; ++block) {
uint64_t new_lo = absl::little_endian::ToHost64(
static_cast<uint64_t>(state[block] >> 64));
uint64_t new_hi = absl::little_endian::ToHost64(
static_cast<uint64_t>((state[block] << 64) >> 64));
state[block] = (static_cast<absl::uint128>(new_hi) << 64) | new_lo;
}
#else
(void)state;
#endif
}
}
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
const void* RandenSlow::GetKeys() {
#ifdef ABSL_IS_LITTLE_ENDIAN
return kRandenRoundKeys;
#else
return kRandenRoundKeysBE;
#endif
}
void RandenSlow::Absorb(const void* seed_void, void* state_void) {
auto* state =
reinterpret_cast<uint64_t * ABSL_RANDOM_INTERNAL_RESTRICT>(state_void);
const auto* seed =
reinterpret_cast<const uint64_t * ABSL_RANDOM_INTERNAL_RESTRICT>(
seed_void);
constexpr size_t kCapacityBlocks =
RandenTraits::kCapacityBytes / sizeof(uint64_t);
static_assert(
kCapacityBlocks * sizeof(uint64_t) == RandenTraits::kCapacityBytes,
"Not i*V");
for (size_t i = kCapacityBlocks;
i < RandenTraits::kStateBytes / sizeof(uint64_t); ++i) {
state[i] ^= seed[i - kCapacityBlocks];
}
}
void RandenSlow::Generate(const void* keys_void, void* state_void) {
static_assert(RandenTraits::kCapacityBytes == sizeof(absl::uint128),
"Capacity mismatch");
auto* state = reinterpret_cast<absl::uint128*>(state_void);
const auto* keys = reinterpret_cast<const absl::uint128*>(keys_void);
const absl::uint128 prev_inner = state[0];
SwapEndian(state);
Permute(state, keys);
SwapEndian(state);
*state ^= prev_inner;
}
}
ABSL_NAMESPACE_END
} | #include "absl/random/internal/randen_slow.h"
#include <cstring>
#include "gtest/gtest.h"
#include "absl/base/internal/endian.h"
#include "absl/random/internal/randen_traits.h"
namespace {
using absl::random_internal::RandenSlow;
using absl::random_internal::RandenTraits;
TEST(RandenSlowTest, Default) {
constexpr uint8_t kGolden[] = {
0xee, 0xd3, 0xe6, 0x0e, 0x09, 0x34, 0x65, 0x6c, 0xc6, 0x33, 0x53, 0x9d,
0x9b, 0x2b, 0x4e, 0x04, 0x77, 0x39, 0x43, 0x4e, 0x13, 0x4f, 0xc1, 0xc3,
0xee, 0x10, 0x04, 0xd9, 0x7c, 0xf4, 0xa9, 0xdd, 0x10, 0xca, 0xd8, 0x7f,
0x08, 0xf3, 0x7b, 0x88, 0x12, 0x29, 0xc7, 0x45, 0xf5, 0x80, 0xb7, 0xf0,
0x9f, 0x59, 0x96, 0x76, 0xd3, 0xb1, 0xdb, 0x15, 0x59, 0x6d, 0x3c, 0xff,
0xba, 0x63, 0xec, 0x30, 0xa6, 0x20, 0x7f, 0x6f, 0x60, 0x73, 0x9f, 0xb2,
0x4c, 0xa5, 0x49, 0x6f, 0x31, 0x8a, 0x80, 0x02, 0x0e, 0xe5, 0xc8, 0xd5,
0xf9, 0xea, 0x8f, 0x3b, 0x8a, 0xde, 0xd9, 0x3f, 0x5e, 0x60, 0xbf, 0x9c,
0xbb, 0x3b, 0x18, 0x78, 0x1a, 0xae, 0x70, 0xc9, 0xd5, 0x1e, 0x30, 0x56,
0xd3, 0xff, 0xb2, 0xd8, 0x37, 0x3c, 0xc7, 0x0f, 0xfe, 0x27, 0xb3, 0xf4,
0x19, 0x9a, 0x8f, 0xeb, 0x76, 0x8d, 0xfd, 0xcd, 0x9d, 0x0c, 0x42, 0x91,
0xeb, 0x06, 0xa5, 0xc3, 0x56, 0x95, 0xff, 0x3e, 0xdd, 0x05, 0xaf, 0xd5,
0xa1, 0xc4, 0x83, 0x8f, 0xb7, 0x1b, 0xdb, 0x48, 0x8c, 0xfe, 0x6b, 0x0d,
0x0e, 0x92, 0x23, 0x70, 0x42, 0x6d, 0x95, 0x34, 0x58, 0x57, 0xd3, 0x58,
0x40, 0xb8, 0x87, 0x6b, 0xc2, 0xf4, 0x1e, 0xed, 0xf3, 0x2d, 0x0b, 0x3e,
0xa2, 0x32, 0xef, 0x8e, 0xfc, 0x54, 0x11, 0x43, 0xf3, 0xab, 0x7c, 0x49,
0x8b, 0x9a, 0x02, 0x70, 0x05, 0x37, 0x24, 0x4e, 0xea, 0xe5, 0x90, 0xf0,
0x49, 0x57, 0x8b, 0xd8, 0x2f, 0x69, 0x70, 0xa9, 0x82, 0xa5, 0x51, 0xc6,
0xf5, 0x42, 0x63, 0xbb, 0x2c, 0xec, 0xfc, 0x78, 0xdb, 0x55, 0x2f, 0x61,
0x45, 0xb7, 0x3c, 0x46, 0xe3, 0xaf, 0x16, 0x18, 0xad, 0xe4, 0x2e, 0x35,
0x7e, 0xda, 0x01, 0xc1, 0x74, 0xf3, 0x6f, 0x02, 0x51, 0xe8, 0x3d, 0x1c,
0x82, 0xf0, 0x1e, 0x81,
};
alignas(16) uint8_t state[RandenTraits::kStateBytes];
std::memset(state, 0, sizeof(state));
RandenSlow::Generate(RandenSlow::GetKeys(), state);
EXPECT_EQ(0, std::memcmp(state, kGolden, sizeof(state)));
}
} |
2,529 | cpp | abseil/abseil-cpp | distribution_test_util | absl/random/internal/distribution_test_util.cc | absl/random/internal/distribution_test_util_test.cc | #ifndef ABSL_RANDOM_INTERNAL_DISTRIBUTION_TEST_UTIL_H_
#define ABSL_RANDOM_INTERNAL_DISTRIBUTION_TEST_UTIL_H_
#include <cstddef>
#include <iostream>
#include <vector>
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
struct DistributionMoments {
size_t n = 0;
double mean = 0.0;
double variance = 0.0;
double skewness = 0.0;
double kurtosis = 0.0;
};
DistributionMoments ComputeDistributionMoments(
absl::Span<const double> data_points);
std::ostream& operator<<(std::ostream& os, const DistributionMoments& moments);
double ZScore(double expected_mean, const DistributionMoments& moments);
double RequiredSuccessProbability(double p_fail, int num_trials);
double MaxErrorTolerance(double acceptance_probability);
double erfinv(double x);
double beta(double p, double q);
double InverseNormalSurvival(double x);
bool Near(absl::string_view msg, double actual, double expected, double bound);
double BetaIncomplete(double x, double p, double q);
double BetaIncompleteInv(double p, double q, double alpha);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/distribution_test_util.h"
#include <cassert>
#include <cmath>
#include <string>
#include <vector>
#include "absl/base/internal/raw_logging.h"
#include "absl/base/macros.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
namespace {
#if defined(__EMSCRIPTEN__)
inline double fma(double x, double y, double z) { return (x * y) + z; }
#endif
}
DistributionMoments ComputeDistributionMoments(
absl::Span<const double> data_points) {
DistributionMoments result;
for (double x : data_points) {
result.n++;
result.mean += x;
}
result.mean /= static_cast<double>(result.n);
for (double x : data_points) {
double v = x - result.mean;
result.variance += v * v;
result.skewness += v * v * v;
result.kurtosis += v * v * v * v;
}
result.variance /= static_cast<double>(result.n - 1);
result.skewness /= static_cast<double>(result.n);
result.skewness /= std::pow(result.variance, 1.5);
result.kurtosis /= static_cast<double>(result.n);
result.kurtosis /= std::pow(result.variance, 2.0);
return result;
}
std::ostream& operator<<(std::ostream& os, const DistributionMoments& moments) {
return os << absl::StrFormat("mean=%f, stddev=%f, skewness=%f, kurtosis=%f",
moments.mean, std::sqrt(moments.variance),
moments.skewness, moments.kurtosis);
}
double InverseNormalSurvival(double x) {
static constexpr double kSqrt2 = 1.4142135623730950488;
return -kSqrt2 * absl::random_internal::erfinv(2 * x - 1.0);
}
bool Near(absl::string_view msg, double actual, double expected, double bound) {
assert(bound > 0.0);
double delta = fabs(expected - actual);
if (delta < bound) {
return true;
}
std::string formatted = absl::StrCat(
msg, " actual=", actual, " expected=", expected, " err=", delta / bound);
ABSL_RAW_LOG(INFO, "%s", formatted.c_str());
return false;
}
double beta(double p, double q) {
double lbeta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q);
return std::exp(lbeta);
}
double erfinv(double x) {
#if !defined(__EMSCRIPTEN__)
using std::fma;
#endif
double w = 0.0;
double p = 0.0;
w = -std::log((1.0 - x) * (1.0 + x));
if (w < 6.250000) {
w = w - 3.125000;
p = -3.6444120640178196996e-21;
p = fma(p, w, -1.685059138182016589e-19);
p = fma(p, w, 1.2858480715256400167e-18);
p = fma(p, w, 1.115787767802518096e-17);
p = fma(p, w, -1.333171662854620906e-16);
p = fma(p, w, 2.0972767875968561637e-17);
p = fma(p, w, 6.6376381343583238325e-15);
p = fma(p, w, -4.0545662729752068639e-14);
p = fma(p, w, -8.1519341976054721522e-14);
p = fma(p, w, 2.6335093153082322977e-12);
p = fma(p, w, -1.2975133253453532498e-11);
p = fma(p, w, -5.4154120542946279317e-11);
p = fma(p, w, 1.051212273321532285e-09);
p = fma(p, w, -4.1126339803469836976e-09);
p = fma(p, w, -2.9070369957882005086e-08);
p = fma(p, w, 4.2347877827932403518e-07);
p = fma(p, w, -1.3654692000834678645e-06);
p = fma(p, w, -1.3882523362786468719e-05);
p = fma(p, w, 0.0001867342080340571352);
p = fma(p, w, -0.00074070253416626697512);
p = fma(p, w, -0.0060336708714301490533);
p = fma(p, w, 0.24015818242558961693);
p = fma(p, w, 1.6536545626831027356);
} else if (w < 16.000000) {
w = std::sqrt(w) - 3.250000;
p = 2.2137376921775787049e-09;
p = fma(p, w, 9.0756561938885390979e-08);
p = fma(p, w, -2.7517406297064545428e-07);
p = fma(p, w, 1.8239629214389227755e-08);
p = fma(p, w, 1.5027403968909827627e-06);
p = fma(p, w, -4.013867526981545969e-06);
p = fma(p, w, 2.9234449089955446044e-06);
p = fma(p, w, 1.2475304481671778723e-05);
p = fma(p, w, -4.7318229009055733981e-05);
p = fma(p, w, 6.8284851459573175448e-05);
p = fma(p, w, 2.4031110387097893999e-05);
p = fma(p, w, -0.0003550375203628474796);
p = fma(p, w, 0.00095328937973738049703);
p = fma(p, w, -0.0016882755560235047313);
p = fma(p, w, 0.0024914420961078508066);
p = fma(p, w, -0.0037512085075692412107);
p = fma(p, w, 0.005370914553590063617);
p = fma(p, w, 1.0052589676941592334);
p = fma(p, w, 3.0838856104922207635);
} else {
w = std::sqrt(w) - 5.000000;
p = -2.7109920616438573243e-11;
p = fma(p, w, -2.5556418169965252055e-10);
p = fma(p, w, 1.5076572693500548083e-09);
p = fma(p, w, -3.7894654401267369937e-09);
p = fma(p, w, 7.6157012080783393804e-09);
p = fma(p, w, -1.4960026627149240478e-08);
p = fma(p, w, 2.9147953450901080826e-08);
p = fma(p, w, -6.7711997758452339498e-08);
p = fma(p, w, 2.2900482228026654717e-07);
p = fma(p, w, -9.9298272942317002539e-07);
p = fma(p, w, 4.5260625972231537039e-06);
p = fma(p, w, -1.9681778105531670567e-05);
p = fma(p, w, 7.5995277030017761139e-05);
p = fma(p, w, -0.00021503011930044477347);
p = fma(p, w, -0.00013871931833623122026);
p = fma(p, w, 1.0103004648645343977);
p = fma(p, w, 4.8499064014085844221);
}
return p * x;
}
namespace {
double BetaIncompleteImpl(const double x, const double p, const double q,
const double beta) {
if (p < (p + q) * x) {
return 1. - BetaIncompleteImpl(1.0 - x, q, p, beta);
}
double psq = p + q;
const double kErr = 1e-14;
const double xc = 1. - x;
const double pre =
std::exp(p * std::log(x) + (q - 1.) * std::log(xc) - beta) / p;
double term = 1.;
double ai = 1.;
double result = 1.;
int ns = static_cast<int>(q + xc * psq);
double rx = (ns == 0) ? x : x / xc;
double temp = q - ai;
for (;;) {
term = term * temp * rx / (p + ai);
result = result + term;
temp = std::fabs(term);
if (temp < kErr && temp < kErr * result) {
return result * pre;
}
ai = ai + 1.;
--ns;
if (ns >= 0) {
temp = q - ai;
if (ns == 0) {
rx = x;
}
} else {
temp = psq;
psq = psq + 1.;
}
}
}
double BetaIncompleteInvImpl(const double p, const double q, const double beta,
const double alpha) {
if (alpha < 0.5) {
return 1. - BetaIncompleteInvImpl(q, p, beta, 1. - alpha);
}
const double kErr = 1e-14;
double value = kErr;
{
double r = std::sqrt(-std::log(alpha * alpha));
double y =
r - fma(r, 0.27061, 2.30753) / fma(r, fma(r, 0.04481, 0.99229), 1.0);
if (p > 1. && q > 1.) {
r = (y * y - 3.) / 6.;
double s = 1. / (p + p - 1.);
double t = 1. / (q + q - 1.);
double h = 2. / s + t;
double w =
y * std::sqrt(h + r) / h - (t - s) * (r + 5. / 6. - t / (3. * h));
value = p / (p + q * std::exp(w + w));
} else {
r = q + q;
double t = 1.0 / (9. * q);
double u = 1.0 - t + y * std::sqrt(t);
t = r * (u * u * u);
if (t <= 0) {
value = 1.0 - std::exp((std::log((1.0 - alpha) * q) + beta) / q);
} else {
t = (4.0 * p + r - 2.0) / t;
if (t <= 1) {
value = std::exp((std::log(alpha * p) + beta) / p);
} else {
value = 1.0 - 2.0 / (t + 1.0);
}
}
}
}
{
value = std::max(value, kErr);
value = std::min(value, 1.0 - kErr);
const double r = 1.0 - p;
const double t = 1.0 - q;
double y;
double yprev = 0;
double sq = 1;
double prev = 1;
for (;;) {
if (value < 0 || value > 1.0) {
return std::numeric_limits<double>::infinity();
} else if (value == 0 || value == 1) {
y = value;
} else {
y = BetaIncompleteImpl(value, p, q, beta);
if (!std::isfinite(y)) {
return y;
}
}
y = (y - alpha) *
std::exp(beta + r * std::log(value) + t * std::log(1.0 - value));
if (y * yprev <= 0) {
prev = std::max(sq, std::numeric_limits<double>::min());
}
double g = 1.0;
for (;;) {
const double adj = g * y;
const double adj_sq = adj * adj;
if (adj_sq >= prev) {
g = g / 3.0;
continue;
}
const double tx = value - adj;
if (tx < 0 || tx > 1) {
g = g / 3.0;
continue;
}
if (prev < kErr) {
return value;
}
if (y * y < kErr) {
return value;
}
if (tx == value) {
return value;
}
if (tx == 0 || tx == 1) {
g = g / 3.0;
continue;
}
value = tx;
yprev = y;
break;
}
}
}
}
}
double BetaIncomplete(const double x, const double p, const double q) {
if (p < 0 || q < 0 || x < 0 || x > 1.0) {
return std::numeric_limits<double>::infinity();
}
if (x == 0 || x == 1) {
return x;
}
double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q);
return BetaIncompleteImpl(x, p, q, beta);
}
double BetaIncompleteInv(const double p, const double q, const double alpha) {
if (p < 0 || q < 0 || alpha < 0 || alpha > 1.0) {
return std::numeric_limits<double>::infinity();
}
if (alpha == 0 || alpha == 1) {
return alpha;
}
double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q);
return BetaIncompleteInvImpl(p, q, beta, alpha);
}
double RequiredSuccessProbability(const double p_fail, const int num_trials) {
double p = std::exp(std::log(1.0 - p_fail) / static_cast<double>(num_trials));
ABSL_ASSERT(p > 0);
return p;
}
double ZScore(double expected_mean, const DistributionMoments& moments) {
return (moments.mean - expected_mean) /
(std::sqrt(moments.variance) /
std::sqrt(static_cast<double>(moments.n)));
}
double MaxErrorTolerance(double acceptance_probability) {
double one_sided_pvalue = 0.5 * (1.0 - acceptance_probability);
const double max_err = InverseNormalSurvival(one_sided_pvalue);
ABSL_ASSERT(max_err > 0);
return max_err;
}
}
ABSL_NAMESPACE_END
} | #include "absl/random/internal/distribution_test_util.h"
#include "gtest/gtest.h"
namespace {
TEST(TestUtil, InverseErf) {
const struct {
const double z;
const double value;
} kErfInvTable[] = {
{0.0000001, 8.86227e-8},
{0.00001, 8.86227e-6},
{0.5, 0.4769362762044},
{0.6, 0.5951160814499},
{0.99999, 3.1234132743},
{0.9999999, 3.7665625816},
{0.999999944, 3.8403850690566985},
{0.999999999, 4.3200053849134452},
};
for (const auto& data : kErfInvTable) {
auto value = absl::random_internal::erfinv(data.z);
EXPECT_NEAR(value, data.value, 1e-8)
<< " InverseErf[" << data.z << "] (expected=" << data.value << ") -> "
<< value;
}
}
const struct {
const double p;
const double q;
const double x;
const double alpha;
} kBetaTable[] = {
{0.5, 0.5, 0.01, 0.06376856085851985},
{0.5, 0.5, 0.1, 0.2048327646991335},
{0.5, 0.5, 1, 1},
{1, 0.5, 0, 0},
{1, 0.5, 0.01, 0.005012562893380045},
{1, 0.5, 0.1, 0.0513167019494862},
{1, 0.5, 0.5, 0.2928932188134525},
{1, 1, 0.5, 0.5},
{2, 2, 0.1, 0.028},
{2, 2, 0.2, 0.104},
{2, 2, 0.3, 0.216},
{2, 2, 0.4, 0.352},
{2, 2, 0.5, 0.5},
{2, 2, 0.6, 0.648},
{2, 2, 0.7, 0.784},
{2, 2, 0.8, 0.896},
{2, 2, 0.9, 0.972},
{5.5, 5, 0.5, 0.4361908850559777},
{10, 0.5, 0.9, 0.1516409096346979},
{10, 5, 0.5, 0.08978271484375},
{10, 5, 1, 1},
{10, 10, 0.5, 0.5},
{20, 5, 0.8, 0.4598773297575791},
{20, 10, 0.6, 0.2146816102371739},
{20, 10, 0.8, 0.9507364826957875},
{20, 20, 0.5, 0.5},
{20, 20, 0.6, 0.8979413687105918},
{30, 10, 0.7, 0.2241297491808366},
{30, 10, 0.8, 0.7586405487192086},
{40, 20, 0.7, 0.7001783247477069},
{1, 0.5, 0.1, 0.0513167019494862},
{1, 0.5, 0.2, 0.1055728090000841},
{1, 0.5, 0.3, 0.1633399734659245},
{1, 0.5, 0.4, 0.2254033307585166},
{1, 2, 0.2, 0.36},
{1, 3, 0.2, 0.488},
{1, 4, 0.2, 0.5904},
{1, 5, 0.2, 0.67232},
{2, 2, 0.3, 0.216},
{3, 2, 0.3, 0.0837},
{4, 2, 0.3, 0.03078},
{5, 2, 0.3, 0.010935},
{1e-5, 1e-5, 1e-5, 0.4999424388184638311},
{1e-5, 1e-5, (1.0 - 1e-8), 0.5000920948389232964},
{1e-5, 1e5, 1e-6, 0.9999817708130066936},
{1e-5, 1e5, (1.0 - 1e-7), 1.0},
{1e5, 1e-5, 1e-6, 0},
{1e5, 1e-5, (1.0 - 1e-6), 1.8229186993306369e-5},
};
TEST(BetaTest, BetaIncomplete) {
for (const auto& data : kBetaTable) {
auto value = absl::random_internal::BetaIncomplete(data.x, data.p, data.q);
EXPECT_NEAR(value, data.alpha, 1e-12)
<< " BetaRegularized[" << data.x << ", " << data.p << ", " << data.q
<< "] (expected=" << data.alpha << ") -> " << value;
}
}
TEST(BetaTest, BetaIncompleteInv) {
for (const auto& data : kBetaTable) {
auto value =
absl::random_internal::BetaIncompleteInv(data.p, data.q, data.alpha);
EXPECT_NEAR(value, data.x, 1e-6)
<< " InverseBetaRegularized[" << data.alpha << ", " << data.p << ", "
<< data.q << "] (expected=" << data.x << ") -> " << value;
}
}
TEST(MaxErrorTolerance, MaxErrorTolerance) {
std::vector<std::pair<double, double>> cases = {
{0.0000001, 8.86227e-8 * 1.41421356237},
{0.00001, 8.86227e-6 * 1.41421356237},
{0.5, 0.4769362762044 * 1.41421356237},
{0.6, 0.5951160814499 * 1.41421356237},
{0.99999, 3.1234132743 * 1.41421356237},
{0.9999999, 3.7665625816 * 1.41421356237},
{0.999999944, 3.8403850690566985 * 1.41421356237},
{0.999999999, 4.3200053849134452 * 1.41421356237}};
for (auto entry : cases) {
EXPECT_NEAR(absl::random_internal::MaxErrorTolerance(entry.first),
entry.second, 1e-8);
}
}
TEST(ZScore, WithSameMean) {
absl::random_internal::DistributionMoments m;
m.n = 100;
m.mean = 5;
m.variance = 1;
EXPECT_NEAR(absl::random_internal::ZScore(5, m), 0, 1e-12);
m.n = 1;
m.mean = 0;
m.variance = 1;
EXPECT_NEAR(absl::random_internal::ZScore(0, m), 0, 1e-12);
m.n = 10000;
m.mean = -5;
m.variance = 100;
EXPECT_NEAR(absl::random_internal::ZScore(-5, m), 0, 1e-12);
}
TEST(ZScore, DifferentMean) {
absl::random_internal::DistributionMoments m;
m.n = 100;
m.mean = 5;
m.variance = 1;
EXPECT_NEAR(absl::random_internal::ZScore(4, m), 10, 1e-12);
m.n = 1;
m.mean = 0;
m.variance = 1;
EXPECT_NEAR(absl::random_internal::ZScore(-1, m), 1, 1e-12);
m.n = 10000;
m.mean = -5;
m.variance = 100;
EXPECT_NEAR(absl::random_internal::ZScore(-4, m), -10, 1e-12);
}
} |
2,530 | cpp | abseil/abseil-cpp | randen | absl/random/internal/randen.cc | absl/random/internal/randen_test.cc | #ifndef ABSL_RANDOM_INTERNAL_RANDEN_H_
#define ABSL_RANDOM_INTERNAL_RANDEN_H_
#include <cstddef>
#include "absl/random/internal/platform.h"
#include "absl/random/internal/randen_hwaes.h"
#include "absl/random/internal/randen_slow.h"
#include "absl/random/internal/randen_traits.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
class Randen {
public:
static constexpr size_t kStateBytes = RandenTraits::kStateBytes;
static constexpr size_t kCapacityBytes = RandenTraits::kCapacityBytes;
static constexpr size_t kSeedBytes = RandenTraits::kSeedBytes;
~Randen() = default;
Randen();
inline void Generate(void* state) const {
#if ABSL_RANDOM_INTERNAL_AES_DISPATCH
if (has_crypto_) {
RandenHwAes::Generate(keys_, state);
} else {
RandenSlow::Generate(keys_, state);
}
#elif ABSL_HAVE_ACCELERATED_AES
RandenHwAes::Generate(keys_, state);
#else
RandenSlow::Generate(keys_, state);
#endif
}
inline void Absorb(const void* seed, void* state) const {
#if ABSL_RANDOM_INTERNAL_AES_DISPATCH
if (has_crypto_) {
RandenHwAes::Absorb(seed, state);
} else {
RandenSlow::Absorb(seed, state);
}
#elif ABSL_HAVE_ACCELERATED_AES
RandenHwAes::Absorb(seed, state);
#else
RandenSlow::Absorb(seed, state);
#endif
}
private:
const void* keys_;
#if ABSL_RANDOM_INTERNAL_AES_DISPATCH
bool has_crypto_;
#endif
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/random/internal/randen.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/random/internal/randen_detect.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace random_internal {
namespace {
struct RandenState {
const void* keys;
bool has_crypto;
};
RandenState GetRandenState() {
static const RandenState state = []() {
RandenState tmp;
#if ABSL_RANDOM_INTERNAL_AES_DISPATCH
if (HasRandenHwAesImplementation() && CPUSupportsRandenHwAes()) {
tmp.has_crypto = true;
tmp.keys = RandenHwAes::GetKeys();
} else {
tmp.has_crypto = false;
tmp.keys = RandenSlow::GetKeys();
}
#elif ABSL_HAVE_ACCELERATED_AES
tmp.has_crypto = true;
tmp.keys = RandenHwAes::GetKeys();
#else
tmp.has_crypto = false;
tmp.keys = RandenSlow::GetKeys();
#endif
return tmp;
}();
return state;
}
}
Randen::Randen() {
auto tmp = GetRandenState();
keys_ = tmp.keys;
#if ABSL_RANDOM_INTERNAL_AES_DISPATCH
has_crypto_ = tmp.has_crypto;
#endif
}
}
ABSL_NAMESPACE_END
} | #include "absl/random/internal/randen.h"
#include <cstring>
#include "gtest/gtest.h"
#include "absl/meta/type_traits.h"
namespace {
using absl::random_internal::Randen;
TEST(RandenTest, CopyAndMove) {
static_assert(std::is_copy_constructible<Randen>::value,
"Randen must be copy constructible");
static_assert(absl::is_copy_assignable<Randen>::value,
"Randen must be copy assignable");
static_assert(std::is_move_constructible<Randen>::value,
"Randen must be move constructible");
static_assert(absl::is_move_assignable<Randen>::value,
"Randen must be move assignable");
}
TEST(RandenTest, Default) {
constexpr uint8_t kGolden[] = {
0xee, 0xd3, 0xe6, 0x0e, 0x09, 0x34, 0x65, 0x6c, 0xc6, 0x33, 0x53, 0x9d,
0x9b, 0x2b, 0x4e, 0x04, 0x77, 0x39, 0x43, 0x4e, 0x13, 0x4f, 0xc1, 0xc3,
0xee, 0x10, 0x04, 0xd9, 0x7c, 0xf4, 0xa9, 0xdd, 0x10, 0xca, 0xd8, 0x7f,
0x08, 0xf3, 0x7b, 0x88, 0x12, 0x29, 0xc7, 0x45, 0xf5, 0x80, 0xb7, 0xf0,
0x9f, 0x59, 0x96, 0x76, 0xd3, 0xb1, 0xdb, 0x15, 0x59, 0x6d, 0x3c, 0xff,
0xba, 0x63, 0xec, 0x30, 0xa6, 0x20, 0x7f, 0x6f, 0x60, 0x73, 0x9f, 0xb2,
0x4c, 0xa5, 0x49, 0x6f, 0x31, 0x8a, 0x80, 0x02, 0x0e, 0xe5, 0xc8, 0xd5,
0xf9, 0xea, 0x8f, 0x3b, 0x8a, 0xde, 0xd9, 0x3f, 0x5e, 0x60, 0xbf, 0x9c,
0xbb, 0x3b, 0x18, 0x78, 0x1a, 0xae, 0x70, 0xc9, 0xd5, 0x1e, 0x30, 0x56,
0xd3, 0xff, 0xb2, 0xd8, 0x37, 0x3c, 0xc7, 0x0f, 0xfe, 0x27, 0xb3, 0xf4,
0x19, 0x9a, 0x8f, 0xeb, 0x76, 0x8d, 0xfd, 0xcd, 0x9d, 0x0c, 0x42, 0x91,
0xeb, 0x06, 0xa5, 0xc3, 0x56, 0x95, 0xff, 0x3e, 0xdd, 0x05, 0xaf, 0xd5,
0xa1, 0xc4, 0x83, 0x8f, 0xb7, 0x1b, 0xdb, 0x48, 0x8c, 0xfe, 0x6b, 0x0d,
0x0e, 0x92, 0x23, 0x70, 0x42, 0x6d, 0x95, 0x34, 0x58, 0x57, 0xd3, 0x58,
0x40, 0xb8, 0x87, 0x6b, 0xc2, 0xf4, 0x1e, 0xed, 0xf3, 0x2d, 0x0b, 0x3e,
0xa2, 0x32, 0xef, 0x8e, 0xfc, 0x54, 0x11, 0x43, 0xf3, 0xab, 0x7c, 0x49,
0x8b, 0x9a, 0x02, 0x70, 0x05, 0x37, 0x24, 0x4e, 0xea, 0xe5, 0x90, 0xf0,
0x49, 0x57, 0x8b, 0xd8, 0x2f, 0x69, 0x70, 0xa9, 0x82, 0xa5, 0x51, 0xc6,
0xf5, 0x42, 0x63, 0xbb, 0x2c, 0xec, 0xfc, 0x78, 0xdb, 0x55, 0x2f, 0x61,
0x45, 0xb7, 0x3c, 0x46, 0xe3, 0xaf, 0x16, 0x18, 0xad, 0xe4, 0x2e, 0x35,
0x7e, 0xda, 0x01, 0xc1, 0x74, 0xf3, 0x6f, 0x02, 0x51, 0xe8, 0x3d, 0x1c,
0x82, 0xf0, 0x1e, 0x81,
};
alignas(16) uint8_t state[Randen::kStateBytes];
std::memset(state, 0, sizeof(state));
Randen r;
r.Generate(state);
EXPECT_EQ(0, std::memcmp(state, kGolden, sizeof(state)));
}
} |
2,531 | cpp | abseil/abseil-cpp | crc32c | absl/crc/crc32c.cc | absl/crc/crc32c_test.cc | #ifndef ABSL_CRC_INTERNAL_CRC32C_H_
#define ABSL_CRC_INTERNAL_CRC32C_H_
#include "absl/base/config.h"
#include "absl/crc/crc32c.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace crc_internal {
crc32c_t UnextendCrc32cByZeroes(crc32c_t initial_crc, size_t length);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/crc/crc32c.h"
#include <cstdint>
#include "absl/crc/internal/crc.h"
#include "absl/crc/internal/crc32c.h"
#include "absl/crc/internal/crc_memcpy.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
const crc_internal::CRC* CrcEngine() {
static const crc_internal::CRC* engine = crc_internal::CRC::Crc32c();
return engine;
}
constexpr uint32_t kCRC32Xor = 0xffffffffU;
}
namespace crc_internal {
crc32c_t UnextendCrc32cByZeroes(crc32c_t initial_crc, size_t length) {
uint32_t crc = static_cast<uint32_t>(initial_crc) ^ kCRC32Xor;
CrcEngine()->UnextendByZeroes(&crc, length);
return static_cast<crc32c_t>(crc ^ kCRC32Xor);
}
crc32c_t ExtendCrc32cInternal(crc32c_t initial_crc,
absl::string_view buf_to_add) {
uint32_t crc = static_cast<uint32_t>(initial_crc) ^ kCRC32Xor;
CrcEngine()->Extend(&crc, buf_to_add.data(), buf_to_add.size());
return static_cast<crc32c_t>(crc ^ kCRC32Xor);
}
}
crc32c_t ComputeCrc32c(absl::string_view buf) {
return ExtendCrc32c(crc32c_t{0}, buf);
}
crc32c_t ExtendCrc32cByZeroes(crc32c_t initial_crc, size_t length) {
uint32_t crc = static_cast<uint32_t>(initial_crc) ^ kCRC32Xor;
CrcEngine()->ExtendByZeroes(&crc, length);
return static_cast<crc32c_t>(crc ^ kCRC32Xor);
}
crc32c_t ConcatCrc32c(crc32c_t lhs_crc, crc32c_t rhs_crc, size_t rhs_len) {
uint32_t result = static_cast<uint32_t>(lhs_crc);
CrcEngine()->ExtendByZeroes(&result, rhs_len);
return crc32c_t{result ^ static_cast<uint32_t>(rhs_crc)};
}
crc32c_t RemoveCrc32cPrefix(crc32c_t crc_a, crc32c_t crc_ab, size_t length_b) {
return ConcatCrc32c(crc_a, crc_ab, length_b);
}
crc32c_t MemcpyCrc32c(void* dest, const void* src, size_t count,
crc32c_t initial_crc) {
return static_cast<crc32c_t>(
crc_internal::Crc32CAndCopy(dest, src, count, initial_crc, false));
}
crc32c_t RemoveCrc32cSuffix(crc32c_t full_string_crc, crc32c_t suffix_crc,
size_t suffix_len) {
uint32_t result = static_cast<uint32_t>(full_string_crc) ^
static_cast<uint32_t>(suffix_crc);
CrcEngine()->UnextendByZeroes(&result, suffix_len);
return crc32c_t{result};
}
ABSL_NAMESPACE_END
} | #include "absl/crc/crc32c.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
#include "absl/crc/internal/crc32c.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
namespace {
TEST(CRC32C, RFC3720) {
char data[32];
memset(data, 0, sizeof(data));
EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))),
absl::crc32c_t{0x8a9136aa});
memset(data, 0xff, sizeof(data));
EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))),
absl::crc32c_t{0x62a8ab43});
for (int i = 0; i < 32; ++i) data[i] = static_cast<char>(i);
EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))),
absl::crc32c_t{0x46dd794e});
for (int i = 0; i < 32; ++i) data[i] = static_cast<char>(31 - i);
EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))),
absl::crc32c_t{0x113fdb5c});
constexpr uint8_t cmd[48] = {
0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(
reinterpret_cast<const char*>(cmd), sizeof(cmd))),
absl::crc32c_t{0xd9963a56});
}
std::string TestString(size_t len) {
std::string result;
result.reserve(len);
for (size_t i = 0; i < len; ++i) {
result.push_back(static_cast<char>(i % 256));
}
return result;
}
TEST(CRC32C, Compute) {
EXPECT_EQ(absl::ComputeCrc32c(""), absl::crc32c_t{0});
EXPECT_EQ(absl::ComputeCrc32c("hello world"), absl::crc32c_t{0xc99465aa});
}
TEST(CRC32C, Extend) {
uint32_t base = 0xC99465AA;
std::string extension = "Extension String";
EXPECT_EQ(
absl::ExtendCrc32c(absl::crc32c_t{base}, extension),
absl::crc32c_t{0xD2F65090});
}
TEST(CRC32C, ExtendByZeroes) {
std::string base = "hello world";
absl::crc32c_t base_crc = absl::crc32c_t{0xc99465aa};
constexpr size_t kExtendByValues[] = {100, 10000, 100000};
for (const size_t extend_by : kExtendByValues) {
SCOPED_TRACE(extend_by);
absl::crc32c_t crc2 = absl::ExtendCrc32cByZeroes(base_crc, extend_by);
EXPECT_EQ(crc2, absl::ComputeCrc32c(base + std::string(extend_by, '\0')));
}
}
TEST(CRC32C, UnextendByZeroes) {
constexpr size_t kExtendByValues[] = {2, 200, 20000, 200000, 20000000};
constexpr size_t kUnextendByValues[] = {0, 100, 10000, 100000, 10000000};
for (auto seed_crc : {absl::crc32c_t{0}, absl::crc32c_t{0xc99465aa}}) {
SCOPED_TRACE(seed_crc);
for (const size_t size_1 : kExtendByValues) {
for (const size_t size_2 : kUnextendByValues) {
size_t extend_size = std::max(size_1, size_2);
size_t unextend_size = std::min(size_1, size_2);
SCOPED_TRACE(extend_size);
SCOPED_TRACE(unextend_size);
absl::crc32c_t crc1 = seed_crc;
crc1 = absl::ExtendCrc32cByZeroes(crc1, extend_size);
crc1 = absl::crc_internal::UnextendCrc32cByZeroes(crc1, unextend_size);
absl::crc32c_t crc2 = seed_crc;
crc2 = absl::ExtendCrc32cByZeroes(crc2, extend_size - unextend_size);
EXPECT_EQ(crc1, crc2);
}
}
}
constexpr size_t kSizes[] = {0, 1, 100, 10000};
for (const size_t size : kSizes) {
SCOPED_TRACE(size);
std::string string_before = TestString(size);
std::string string_after = string_before + std::string(size, '\0');
absl::crc32c_t crc_before = absl::ComputeCrc32c(string_before);
absl::crc32c_t crc_after = absl::ComputeCrc32c(string_after);
EXPECT_EQ(crc_before,
absl::crc_internal::UnextendCrc32cByZeroes(crc_after, size));
}
}
TEST(CRC32C, Concat) {
std::string hello = "Hello, ";
std::string world = "world!";
std::string hello_world = absl::StrCat(hello, world);
absl::crc32c_t crc_a = absl::ComputeCrc32c(hello);
absl::crc32c_t crc_b = absl::ComputeCrc32c(world);
absl::crc32c_t crc_ab = absl::ComputeCrc32c(hello_world);
EXPECT_EQ(absl::ConcatCrc32c(crc_a, crc_b, world.size()), crc_ab);
}
TEST(CRC32C, Memcpy) {
constexpr size_t kBytesSize[] = {0, 1, 20, 500, 100000};
for (size_t bytes : kBytesSize) {
SCOPED_TRACE(bytes);
std::string sample_string = TestString(bytes);
std::string target_buffer = std::string(bytes, '\0');
absl::crc32c_t memcpy_crc =
absl::MemcpyCrc32c(&(target_buffer[0]), sample_string.data(), bytes);
absl::crc32c_t compute_crc = absl::ComputeCrc32c(sample_string);
EXPECT_EQ(memcpy_crc, compute_crc);
EXPECT_EQ(sample_string, target_buffer);
}
}
TEST(CRC32C, RemovePrefix) {
std::string hello = "Hello, ";
std::string world = "world!";
std::string hello_world = absl::StrCat(hello, world);
absl::crc32c_t crc_a = absl::ComputeCrc32c(hello);
absl::crc32c_t crc_b = absl::ComputeCrc32c(world);
absl::crc32c_t crc_ab = absl::ComputeCrc32c(hello_world);
EXPECT_EQ(absl::RemoveCrc32cPrefix(crc_a, crc_ab, world.size()), crc_b);
}
TEST(CRC32C, RemoveSuffix) {
std::string hello = "Hello, ";
std::string world = "world!";
std::string hello_world = absl::StrCat(hello, world);
absl::crc32c_t crc_a = absl::ComputeCrc32c(hello);
absl::crc32c_t crc_b = absl::ComputeCrc32c(world);
absl::crc32c_t crc_ab = absl::ComputeCrc32c(hello_world);
EXPECT_EQ(absl::RemoveCrc32cSuffix(crc_ab, crc_b, world.size()), crc_a);
}
TEST(CRC32C, InsertionOperator) {
{
std::ostringstream buf;
buf << absl::crc32c_t{0xc99465aa};
EXPECT_EQ(buf.str(), "c99465aa");
}
{
std::ostringstream buf;
buf << absl::crc32c_t{0};
EXPECT_EQ(buf.str(), "00000000");
}
{
std::ostringstream buf;
buf << absl::crc32c_t{17};
EXPECT_EQ(buf.str(), "00000011");
}
}
TEST(CRC32C, AbslStringify) {
EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{0xc99465aa}), "c99465aa");
EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{0}), "00000000");
EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{17}), "00000011");
EXPECT_EQ(absl::StrCat(absl::crc32c_t{0xc99465aa}), "c99465aa");
EXPECT_EQ(absl::StrCat(absl::crc32c_t{0}), "00000000");
EXPECT_EQ(absl::StrCat(absl::crc32c_t{17}), "00000011");
}
} |
2,532 | cpp | abseil/abseil-cpp | crc_cord_state | absl/crc/internal/crc_cord_state.cc | absl/crc/internal/crc_cord_state_test.cc | #ifndef ABSL_CRC_INTERNAL_CRC_CORD_STATE_H_
#define ABSL_CRC_INTERNAL_CRC_CORD_STATE_H_
#include <atomic>
#include <cstddef>
#include <deque>
#include "absl/base/config.h"
#include "absl/crc/crc32c.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace crc_internal {
class CrcCordState {
public:
CrcCordState();
CrcCordState(const CrcCordState&);
CrcCordState(CrcCordState&&);
~CrcCordState();
CrcCordState& operator=(const CrcCordState&);
CrcCordState& operator=(CrcCordState&&);
struct PrefixCrc {
PrefixCrc() = default;
PrefixCrc(size_t length_arg, absl::crc32c_t crc_arg)
: length(length_arg), crc(crc_arg) {}
size_t length = 0;
absl::crc32c_t crc = absl::crc32c_t{0};
};
struct Rep {
PrefixCrc removed_prefix;
std::deque<PrefixCrc> prefix_crc;
};
const Rep& rep() const { return refcounted_rep_->rep; }
Rep* mutable_rep() {
if (refcounted_rep_->count.load(std::memory_order_acquire) != 1) {
RefcountedRep* copy = new RefcountedRep;
copy->rep = refcounted_rep_->rep;
Unref(refcounted_rep_);
refcounted_rep_ = copy;
}
return &refcounted_rep_->rep;
}
absl::crc32c_t Checksum() const;
bool IsNormalized() const { return rep().removed_prefix.length == 0; }
void Normalize();
size_t NumChunks() const { return rep().prefix_crc.size(); }
PrefixCrc NormalizedPrefixCrcAtNthChunk(size_t n) const;
void Poison();
private:
struct RefcountedRep {
std::atomic<int32_t> count{1};
Rep rep;
};
static RefcountedRep* RefSharedEmptyRep();
static void Ref(RefcountedRep* r) {
assert(r != nullptr);
r->count.fetch_add(1, std::memory_order_relaxed);
}
static void Unref(RefcountedRep* r) {
assert(r != nullptr);
if (r->count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
delete r;
}
}
RefcountedRep* refcounted_rep_;
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/crc/internal/crc_cord_state.h"
#include <cassert>
#include "absl/base/config.h"
#include "absl/base/no_destructor.h"
#include "absl/numeric/bits.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace crc_internal {
CrcCordState::RefcountedRep* CrcCordState::RefSharedEmptyRep() {
static absl::NoDestructor<CrcCordState::RefcountedRep> empty;
assert(empty->count.load(std::memory_order_relaxed) >= 1);
assert(empty->rep.removed_prefix.length == 0);
assert(empty->rep.prefix_crc.empty());
Ref(empty.get());
return empty.get();
}
CrcCordState::CrcCordState() : refcounted_rep_(new RefcountedRep) {}
CrcCordState::CrcCordState(const CrcCordState& other)
: refcounted_rep_(other.refcounted_rep_) {
Ref(refcounted_rep_);
}
CrcCordState::CrcCordState(CrcCordState&& other)
: refcounted_rep_(other.refcounted_rep_) {
other.refcounted_rep_ = RefSharedEmptyRep();
}
CrcCordState& CrcCordState::operator=(const CrcCordState& other) {
if (this != &other) {
Unref(refcounted_rep_);
refcounted_rep_ = other.refcounted_rep_;
Ref(refcounted_rep_);
}
return *this;
}
CrcCordState& CrcCordState::operator=(CrcCordState&& other) {
if (this != &other) {
Unref(refcounted_rep_);
refcounted_rep_ = other.refcounted_rep_;
other.refcounted_rep_ = RefSharedEmptyRep();
}
return *this;
}
CrcCordState::~CrcCordState() {
Unref(refcounted_rep_);
}
crc32c_t CrcCordState::Checksum() const {
if (rep().prefix_crc.empty()) {
return absl::crc32c_t{0};
}
if (IsNormalized()) {
return rep().prefix_crc.back().crc;
}
return absl::RemoveCrc32cPrefix(
rep().removed_prefix.crc, rep().prefix_crc.back().crc,
rep().prefix_crc.back().length - rep().removed_prefix.length);
}
CrcCordState::PrefixCrc CrcCordState::NormalizedPrefixCrcAtNthChunk(
size_t n) const {
assert(n < NumChunks());
if (IsNormalized()) {
return rep().prefix_crc[n];
}
size_t length = rep().prefix_crc[n].length - rep().removed_prefix.length;
return PrefixCrc(length,
absl::RemoveCrc32cPrefix(rep().removed_prefix.crc,
rep().prefix_crc[n].crc, length));
}
void CrcCordState::Normalize() {
if (IsNormalized() || rep().prefix_crc.empty()) {
return;
}
Rep* r = mutable_rep();
for (auto& prefix_crc : r->prefix_crc) {
size_t remaining = prefix_crc.length - r->removed_prefix.length;
prefix_crc.crc = absl::RemoveCrc32cPrefix(r->removed_prefix.crc,
prefix_crc.crc, remaining);
prefix_crc.length = remaining;
}
r->removed_prefix = PrefixCrc();
}
void CrcCordState::Poison() {
Rep* rep = mutable_rep();
if (NumChunks() > 0) {
for (auto& prefix_crc : rep->prefix_crc) {
uint32_t crc = static_cast<uint32_t>(prefix_crc.crc);
crc += 0x2e76e41b;
crc = absl::rotr(crc, 17);
prefix_crc.crc = crc32c_t{crc};
}
} else {
rep->prefix_crc.emplace_back(0, crc32c_t{1});
}
}
}
ABSL_NAMESPACE_END
} | #include "absl/crc/internal/crc_cord_state.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "absl/crc/crc32c.h"
namespace {
TEST(CrcCordState, Default) {
absl::crc_internal::CrcCordState state;
EXPECT_TRUE(state.IsNormalized());
EXPECT_EQ(state.Checksum(), absl::crc32c_t{0});
state.Normalize();
EXPECT_EQ(state.Checksum(), absl::crc32c_t{0});
}
TEST(CrcCordState, Normalize) {
absl::crc_internal::CrcCordState state;
auto* rep = state.mutable_rep();
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000}));
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(2000, absl::crc32c_t{2000}));
rep->removed_prefix =
absl::crc_internal::CrcCordState::PrefixCrc(500, absl::crc32c_t{500});
EXPECT_FALSE(state.IsNormalized());
absl::crc32c_t crc = state.Checksum();
state.Normalize();
EXPECT_TRUE(state.IsNormalized());
EXPECT_EQ(state.Checksum(), crc);
EXPECT_EQ(rep->removed_prefix.length, 0);
}
TEST(CrcCordState, Copy) {
absl::crc_internal::CrcCordState state;
auto* rep = state.mutable_rep();
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000}));
absl::crc_internal::CrcCordState copy = state;
EXPECT_EQ(state.Checksum(), absl::crc32c_t{1000});
EXPECT_EQ(copy.Checksum(), absl::crc32c_t{1000});
}
TEST(CrcCordState, UnsharedSelfCopy) {
absl::crc_internal::CrcCordState state;
auto* rep = state.mutable_rep();
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000}));
const absl::crc_internal::CrcCordState& ref = state;
state = ref;
EXPECT_EQ(state.Checksum(), absl::crc32c_t{1000});
}
TEST(CrcCordState, Move) {
absl::crc_internal::CrcCordState state;
auto* rep = state.mutable_rep();
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000}));
absl::crc_internal::CrcCordState moved = std::move(state);
EXPECT_EQ(moved.Checksum(), absl::crc32c_t{1000});
}
TEST(CrcCordState, UnsharedSelfMove) {
absl::crc_internal::CrcCordState state;
auto* rep = state.mutable_rep();
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000}));
absl::crc_internal::CrcCordState& ref = state;
state = std::move(ref);
EXPECT_EQ(state.Checksum(), absl::crc32c_t{1000});
}
TEST(CrcCordState, PoisonDefault) {
absl::crc_internal::CrcCordState state;
state.Poison();
EXPECT_NE(state.Checksum(), absl::crc32c_t{0});
}
TEST(CrcCordState, PoisonData) {
absl::crc_internal::CrcCordState state;
auto* rep = state.mutable_rep();
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000}));
rep->prefix_crc.push_back(
absl::crc_internal::CrcCordState::PrefixCrc(2000, absl::crc32c_t{2000}));
rep->removed_prefix =
absl::crc_internal::CrcCordState::PrefixCrc(500, absl::crc32c_t{500});
absl::crc32c_t crc = state.Checksum();
state.Poison();
EXPECT_NE(state.Checksum(), crc);
}
} |
2,533 | cpp | abseil/abseil-cpp | die_if_null | absl/log/die_if_null.cc | absl/log/die_if_null_test.cc | #ifndef ABSL_LOG_DIE_IF_NULL_H_
#define ABSL_LOG_DIE_IF_NULL_H_
#include <stdint.h>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#define ABSL_DIE_IF_NULL(val) \
::absl::log_internal::DieIfNull(__FILE__, __LINE__, #val, (val))
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
ABSL_ATTRIBUTE_NORETURN ABSL_ATTRIBUTE_NOINLINE void DieBecauseNull(
const char* file, int line, const char* exprtext);
template <typename T>
ABSL_MUST_USE_RESULT T DieIfNull(const char* file, int line,
const char* exprtext, T&& t) {
if (ABSL_PREDICT_FALSE(t == nullptr)) {
DieBecauseNull(file, line, exprtext);
}
return std::forward<T>(t);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/die_if_null.h"
#include "absl/base/config.h"
#include "absl/log/log.h"
#include "absl/strings/str_cat.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
void DieBecauseNull(const char* file, int line, const char* exprtext) {
LOG(FATAL).AtLocation(file, line)
<< absl::StrCat("Check failed: '", exprtext, "' Must be non-null");
}
}
ABSL_NAMESPACE_END
} | #include "absl/log/die_if_null.h"
#include <stdint.h>
#include <memory>
#include <utility>
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/log/internal/test_helpers.h"
namespace {
auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment(
new absl::log_internal::LogTestEnvironment);
TEST(AbslDieIfNull, Simple) {
int64_t t;
void* ptr = static_cast<void*>(&t);
void* ref = ABSL_DIE_IF_NULL(ptr);
ASSERT_EQ(ptr, ref);
char* t_as_char;
t_as_char = ABSL_DIE_IF_NULL(reinterpret_cast<char*>(&t));
(void)t_as_char;
unsigned char* t_as_uchar;
t_as_uchar = ABSL_DIE_IF_NULL(reinterpret_cast<unsigned char*>(&t));
(void)t_as_uchar;
int* t_as_int;
t_as_int = ABSL_DIE_IF_NULL(reinterpret_cast<int*>(&t));
(void)t_as_int;
int64_t* t_as_int64_t;
t_as_int64_t = ABSL_DIE_IF_NULL(reinterpret_cast<int64_t*>(&t));
(void)t_as_int64_t;
std::unique_ptr<int64_t> sptr(new int64_t);
EXPECT_EQ(sptr.get(), ABSL_DIE_IF_NULL(sptr).get());
ABSL_DIE_IF_NULL(sptr).reset();
int64_t* int_ptr = new int64_t();
EXPECT_EQ(int_ptr, ABSL_DIE_IF_NULL(std::unique_ptr<int64_t>(int_ptr)).get());
}
#if GTEST_HAS_DEATH_TEST
TEST(DeathCheckAbslDieIfNull, Simple) {
void* ptr;
ASSERT_DEATH({ ptr = ABSL_DIE_IF_NULL(nullptr); }, "");
(void)ptr;
std::unique_ptr<int64_t> sptr;
ASSERT_DEATH(ptr = ABSL_DIE_IF_NULL(sptr).get(), "");
}
#endif
TEST(AbslDieIfNull, DoesNotCompareSmartPointerToNULL) {
std::unique_ptr<int> up(new int);
EXPECT_EQ(&up, &ABSL_DIE_IF_NULL(up));
ABSL_DIE_IF_NULL(up).reset();
std::shared_ptr<int> sp(new int);
EXPECT_EQ(&sp, &ABSL_DIE_IF_NULL(sp));
ABSL_DIE_IF_NULL(sp).reset();
}
TEST(AbslDieIfNull, PreservesRValues) {
int64_t* ptr = new int64_t();
auto uptr = ABSL_DIE_IF_NULL(std::unique_ptr<int64_t>(ptr));
EXPECT_EQ(ptr, uptr.get());
}
TEST(AbslDieIfNull, PreservesLValues) {
int64_t array[2] = {0};
int64_t* a = array + 0;
int64_t* b = array + 1;
using std::swap;
swap(ABSL_DIE_IF_NULL(a), ABSL_DIE_IF_NULL(b));
EXPECT_EQ(array + 1, a);
EXPECT_EQ(array + 0, b);
}
} |
2,534 | cpp | abseil/abseil-cpp | log_entry | absl/log/log_entry.cc | absl/log/log_entry_test.cc | #ifndef ABSL_LOG_LOG_ENTRY_H_
#define ABSL_LOG_LOG_ENTRY_H_
#include <cstddef>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/log_severity.h"
#include "absl/log/internal/config.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
class LogEntryTestPeer;
class LogMessage;
}
class LogEntry final {
public:
using tid_t = log_internal::Tid;
static constexpr int kNoVerbosityLevel = -1;
static constexpr int kNoVerboseLevel = -1;
LogEntry(const LogEntry&) = delete;
LogEntry& operator=(const LogEntry&) = delete;
absl::string_view source_filename() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return full_filename_;
}
absl::string_view source_basename() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return base_filename_;
}
int source_line() const { return line_; }
bool prefix() const { return prefix_; }
absl::LogSeverity log_severity() const { return severity_; }
int verbosity() const { return verbose_level_; }
absl::Time timestamp() const { return timestamp_; }
tid_t tid() const { return tid_; }
absl::string_view text_message_with_prefix_and_newline() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return absl::string_view(
text_message_with_prefix_and_newline_and_nul_.data(),
text_message_with_prefix_and_newline_and_nul_.size() - 1);
}
absl::string_view text_message_with_prefix() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return absl::string_view(
text_message_with_prefix_and_newline_and_nul_.data(),
text_message_with_prefix_and_newline_and_nul_.size() - 2);
}
absl::string_view text_message_with_newline() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return absl::string_view(
text_message_with_prefix_and_newline_and_nul_.data() + prefix_len_,
text_message_with_prefix_and_newline_and_nul_.size() - prefix_len_ - 1);
}
absl::string_view text_message() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return absl::string_view(
text_message_with_prefix_and_newline_and_nul_.data() + prefix_len_,
text_message_with_prefix_and_newline_and_nul_.size() - prefix_len_ - 2);
}
const char* text_message_with_prefix_and_newline_c_str() const
ABSL_ATTRIBUTE_LIFETIME_BOUND {
return text_message_with_prefix_and_newline_and_nul_.data();
}
absl::string_view encoded_message() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return encoding_;
}
absl::string_view stacktrace() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
return stacktrace_;
}
private:
LogEntry() = default;
absl::string_view full_filename_;
absl::string_view base_filename_;
int line_;
bool prefix_;
absl::LogSeverity severity_;
int verbose_level_;
absl::Time timestamp_;
tid_t tid_;
absl::Span<const char> text_message_with_prefix_and_newline_and_nul_;
size_t prefix_len_;
absl::string_view encoding_;
std::string stacktrace_;
friend class log_internal::LogEntryTestPeer;
friend class log_internal::LogMessage;
};
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/log_entry.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr int LogEntry::kNoVerbosityLevel;
constexpr int LogEntry::kNoVerboseLevel;
#endif
#ifdef __APPLE__
namespace log_internal {
extern const char kAvoidEmptyLogEntryLibraryWarning;
const char kAvoidEmptyLogEntryLibraryWarning = 0;
}
#endif
ABSL_NAMESPACE_END
} | #include "absl/log/log_entry.h"
#include <stddef.h>
#include <stdint.h>
#include <cstring>
#include <limits>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/log_severity.h"
#include "absl/log/internal/append_truncated.h"
#include "absl/log/internal/log_format.h"
#include "absl/log/internal/test_helpers.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/time/civil_time.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
namespace {
using ::absl::log_internal::LogEntryTestPeer;
using ::testing::Eq;
using ::testing::IsTrue;
using ::testing::StartsWith;
using ::testing::StrEq;
auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment(
new absl::log_internal::LogTestEnvironment);
}
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
class LogEntryTestPeer {
public:
LogEntryTestPeer(absl::string_view base_filename, int line, bool prefix,
absl::LogSeverity severity, absl::string_view timestamp,
absl::LogEntry::tid_t tid, PrefixFormat format,
absl::string_view text_message)
: format_{format}, buf_(15000, '\0') {
entry_.base_filename_ = base_filename;
entry_.line_ = line;
entry_.prefix_ = prefix;
entry_.severity_ = severity;
std::string time_err;
EXPECT_THAT(
absl::ParseTime("%Y-%m-%d%ET%H:%M:%E*S", timestamp,
absl::LocalTimeZone(), &entry_.timestamp_, &time_err),
IsTrue())
<< "Failed to parse time " << timestamp << ": " << time_err;
entry_.tid_ = tid;
std::pair<absl::string_view, std::string> timestamp_bits =
absl::StrSplit(timestamp, absl::ByChar('.'));
EXPECT_THAT(absl::ParseCivilTime(timestamp_bits.first, &ci_.cs), IsTrue())
<< "Failed to parse time " << timestamp_bits.first;
timestamp_bits.second.resize(9, '0');
int64_t nanos = 0;
EXPECT_THAT(absl::SimpleAtoi(timestamp_bits.second, &nanos), IsTrue())
<< "Failed to parse time " << timestamp_bits.first;
ci_.subsecond = absl::Nanoseconds(nanos);
absl::Span<char> view = absl::MakeSpan(buf_);
view.remove_suffix(2);
entry_.prefix_len_ =
entry_.prefix_
? log_internal::FormatLogPrefix(
entry_.log_severity(), entry_.timestamp(), entry_.tid(),
entry_.source_basename(), entry_.source_line(), format_, view)
: 0;
EXPECT_THAT(entry_.prefix_len_,
Eq(static_cast<size_t>(view.data() - buf_.data())));
log_internal::AppendTruncated(text_message, view);
view = absl::Span<char>(view.data(), view.size() + 2);
view[0] = '\n';
view[1] = '\0';
view.remove_prefix(2);
buf_.resize(static_cast<size_t>(view.data() - buf_.data()));
entry_.text_message_with_prefix_and_newline_and_nul_ = absl::MakeSpan(buf_);
}
LogEntryTestPeer(const LogEntryTestPeer&) = delete;
LogEntryTestPeer& operator=(const LogEntryTestPeer&) = delete;
std::string FormatLogMessage() const {
return log_internal::FormatLogMessage(
entry_.log_severity(), ci_.cs, ci_.subsecond, entry_.tid(),
entry_.source_basename(), entry_.source_line(), format_,
entry_.text_message());
}
std::string FormatPrefixIntoSizedBuffer(size_t sz) {
std::string str(sz, '\0');
absl::Span<char> buf(&str[0], str.size());
const size_t prefix_size = log_internal::FormatLogPrefix(
entry_.log_severity(), entry_.timestamp(), entry_.tid(),
entry_.source_basename(), entry_.source_line(), format_, buf);
EXPECT_THAT(prefix_size, Eq(static_cast<size_t>(buf.data() - str.data())));
str.resize(prefix_size);
return str;
}
const absl::LogEntry& entry() const { return entry_; }
private:
absl::LogEntry entry_;
PrefixFormat format_;
absl::TimeZone::CivilInfo ci_;
std::vector<char> buf_;
};
}
ABSL_NAMESPACE_END
}
namespace {
constexpr bool kUsePrefix = true, kNoPrefix = false;
TEST(LogEntryTest, Baseline) {
LogEntryTestPeer entry("foo.cc", 1234, kUsePrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05.6789", 451,
absl::log_internal::PrefixFormat::kNotRaw,
"hello world");
EXPECT_THAT(entry.FormatLogMessage(),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world"));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] "));
for (size_t sz = strlen("I0102 03:04:05.678900 451 foo.cc:1234] ") + 20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:1234] ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.678900 451 foo.cc:1234] hello world\n"));
EXPECT_THAT(entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world"));
EXPECT_THAT(entry.entry().text_message(), Eq("hello world"));
}
TEST(LogEntryTest, NoPrefix) {
LogEntryTestPeer entry("foo.cc", 1234, kNoPrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05.6789", 451,
absl::log_internal::PrefixFormat::kNotRaw,
"hello world");
EXPECT_THAT(entry.FormatLogMessage(),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world"));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] "));
for (size_t sz = strlen("I0102 03:04:05.678900 451 foo.cc:1234] ") + 20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:1234] ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(),
Eq("hello world\n"));
EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("hello world\n"));
EXPECT_THAT(entry.entry().text_message_with_prefix(), Eq("hello world"));
EXPECT_THAT(entry.entry().text_message(), Eq("hello world"));
}
TEST(LogEntryTest, EmptyFields) {
LogEntryTestPeer entry("", 0, kUsePrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05", 0,
absl::log_internal::PrefixFormat::kNotRaw, "");
const std::string format_message = entry.FormatLogMessage();
EXPECT_THAT(format_message, Eq("I0102 03:04:05.000000 0 :0] "));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq(format_message));
for (size_t sz = format_message.size() + 20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT(format_message,
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.000000 0 :0] \n"));
EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.000000 0 :0] \n"));
EXPECT_THAT(entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.000000 0 :0] "));
EXPECT_THAT(entry.entry().text_message(), Eq(""));
}
TEST(LogEntryTest, NegativeFields) {
if (std::is_signed<absl::LogEntry::tid_t>::value) {
LogEntryTestPeer entry(
"foo.cc", -1234, kUsePrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05.6789", static_cast<absl::LogEntry::tid_t>(-451),
absl::log_internal::PrefixFormat::kNotRaw, "hello world");
EXPECT_THAT(entry.FormatLogMessage(),
Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world"));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] "));
for (size_t sz =
strlen("I0102 03:04:05.678900 -451 foo.cc:-1234] ") + 20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT("I0102 03:04:05.678900 -451 foo.cc:-1234] ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world\n"));
EXPECT_THAT(entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world"));
EXPECT_THAT(entry.entry().text_message(), Eq("hello world"));
} else {
LogEntryTestPeer entry("foo.cc", -1234, kUsePrefix,
absl::LogSeverity::kInfo, "2020-01-02T03:04:05.6789",
451, absl::log_internal::PrefixFormat::kNotRaw,
"hello world");
EXPECT_THAT(entry.FormatLogMessage(),
Eq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world"));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678900 451 foo.cc:-1234] "));
for (size_t sz =
strlen("I0102 03:04:05.678900 451 foo.cc:-1234] ") + 20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:-1234] ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world\n"));
EXPECT_THAT(entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world"));
EXPECT_THAT(entry.entry().text_message(), Eq("hello world"));
}
}
TEST(LogEntryTest, LongFields) {
LogEntryTestPeer entry(
"I am the very model of a modern Major-General / "
"I've information vegetable, animal, and mineral.",
2147483647, kUsePrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05.678967896789", 2147483647,
absl::log_internal::PrefixFormat::kNotRaw,
"I know the kings of England, and I quote the fights historical / "
"From Marathon to Waterloo, in order categorical.");
EXPECT_THAT(entry.FormatLogMessage(),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical."));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:2147483647] "));
for (size_t sz =
strlen("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:2147483647] ") +
20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT(
"I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:2147483647] ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical.\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical.\n"));
EXPECT_THAT(entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical."));
EXPECT_THAT(
entry.entry().text_message(),
Eq("I know the kings of England, and I quote the fights historical / "
"From Marathon to Waterloo, in order categorical."));
}
TEST(LogEntryTest, LongNegativeFields) {
if (std::is_signed<absl::LogEntry::tid_t>::value) {
LogEntryTestPeer entry(
"I am the very model of a modern Major-General / "
"I've information vegetable, animal, and mineral.",
-2147483647, kUsePrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05.678967896789",
static_cast<absl::LogEntry::tid_t>(-2147483647),
absl::log_internal::PrefixFormat::kNotRaw,
"I know the kings of England, and I quote the fights historical / "
"From Marathon to Waterloo, in order categorical.");
EXPECT_THAT(
entry.FormatLogMessage(),
Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical."));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] "));
for (size_t sz =
strlen(
"I0102 03:04:05.678967 -2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] ") +
20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT(
"I0102 03:04:05.678967 -2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical.\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.678967 -2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical.\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical."));
EXPECT_THAT(
entry.entry().text_message(),
Eq("I know the kings of England, and I quote the fights historical / "
"From Marathon to Waterloo, in order categorical."));
} else {
LogEntryTestPeer entry(
"I am the very model of a modern Major-General / "
"I've information vegetable, animal, and mineral.",
-2147483647, kUsePrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05.678967896789", 2147483647,
absl::log_internal::PrefixFormat::kNotRaw,
"I know the kings of England, and I quote the fights historical / "
"From Marathon to Waterloo, in order categorical.");
EXPECT_THAT(
entry.FormatLogMessage(),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical."));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] "));
for (size_t sz =
strlen(
"I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] ") +
20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT(
"I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical.\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical.\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.678967 2147483647 I am the very model of a "
"modern Major-General / I've information vegetable, animal, "
"and mineral.:-2147483647] I know the kings of England, and I "
"quote the fights historical / From Marathon to Waterloo, in "
"order categorical."));
EXPECT_THAT(
entry.entry().text_message(),
Eq("I know the kings of England, and I quote the fights historical / "
"From Marathon to Waterloo, in order categorical."));
}
}
TEST(LogEntryTest, Raw) {
LogEntryTestPeer entry("foo.cc", 1234, kUsePrefix, absl::LogSeverity::kInfo,
"2020-01-02T03:04:05.6789", 451,
absl::log_internal::PrefixFormat::kRaw, "hello world");
EXPECT_THAT(
entry.FormatLogMessage(),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world"));
EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: "));
for (size_t sz =
strlen("I0102 03:04:05.678900 451 foo.cc:1234] RAW: ") + 20;
sz != std::numeric_limits<size_t>::max(); sz--)
EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:1234] RAW: ",
StartsWith(entry.FormatPrefixIntoSizedBuffer(sz)));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline(),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix_and_newline_c_str(),
StrEq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world\n"));
EXPECT_THAT(
entry.entry().text_message_with_prefix(),
Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world"));
EXPECT_THAT(entry.entry().text_message(), Eq("hello world"));
}
} |
2,535 | cpp | abseil/abseil-cpp | globals | absl/log/internal/globals.cc | absl/log/globals_test.cc | #ifndef ABSL_LOG_INTERNAL_GLOBALS_H_
#define ABSL_LOG_INTERNAL_GLOBALS_H_
#include "absl/base/config.h"
#include "absl/base/log_severity.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
bool IsInitialized();
void SetInitialized();
void WriteToStderr(absl::string_view message, absl::LogSeverity severity);
void SetTimeZone(absl::TimeZone tz);
const absl::TimeZone* TimeZone();
bool ShouldSymbolizeLogStackTrace();
void EnableSymbolizeLogStackTrace(bool on_off);
int MaxFramesInLogStackTrace();
void SetMaxFramesInLogStackTrace(int max_num_frames);
bool ExitOnDFatal();
void SetExitOnDFatal(bool on_off);
bool SuppressSigabortTrace();
bool SetSuppressSigabortTrace(bool on_off);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/internal/globals.h"
#include <atomic>
#include <cstdio>
#if defined(__EMSCRIPTEN__)
#include <emscripten/console.h>
#endif
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/log_severity.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
namespace {
ABSL_CONST_INIT std::atomic<bool> logging_initialized(false);
ABSL_CONST_INIT std::atomic<absl::TimeZone*> timezone_ptr{nullptr};
ABSL_CONST_INIT std::atomic<bool> symbolize_stack_trace(true);
ABSL_CONST_INIT std::atomic<int> max_frames_in_stack_trace(64);
ABSL_CONST_INIT std::atomic<bool> exit_on_dfatal(true);
ABSL_CONST_INIT std::atomic<bool> suppress_sigabort_trace(false);
}
bool IsInitialized() {
return logging_initialized.load(std::memory_order_acquire);
}
void SetInitialized() {
logging_initialized.store(true, std::memory_order_release);
}
void WriteToStderr(absl::string_view message, absl::LogSeverity severity) {
if (message.empty()) return;
#if defined(__EMSCRIPTEN__)
const auto message_minus_newline = absl::StripSuffix(message, "\n");
#if ABSL_INTERNAL_EMSCRIPTEN_VERSION >= 3001043
emscripten_errn(message_minus_newline.data(), message_minus_newline.size());
#else
std::string null_terminated_message(message_minus_newline);
_emscripten_err(null_terminated_message.c_str());
#endif
#else
std::fwrite(message.data(), message.size(), 1, stderr);
#endif
#if defined(_WIN64) || defined(_WIN32) || defined(_WIN16)
if (severity >= absl::LogSeverity::kWarning) {
std::fflush(stderr);
}
#else
(void)severity;
#endif
}
void SetTimeZone(absl::TimeZone tz) {
absl::TimeZone* expected = nullptr;
absl::TimeZone* new_tz = new absl::TimeZone(tz);
if (!timezone_ptr.compare_exchange_strong(expected, new_tz,
std::memory_order_release,
std::memory_order_relaxed)) {
ABSL_RAW_LOG(FATAL,
"absl::log_internal::SetTimeZone() has already been called");
}
}
const absl::TimeZone* TimeZone() {
return timezone_ptr.load(std::memory_order_acquire);
}
bool ShouldSymbolizeLogStackTrace() {
return symbolize_stack_trace.load(std::memory_order_acquire);
}
void EnableSymbolizeLogStackTrace(bool on_off) {
symbolize_stack_trace.store(on_off, std::memory_order_release);
}
int MaxFramesInLogStackTrace() {
return max_frames_in_stack_trace.load(std::memory_order_acquire);
}
void SetMaxFramesInLogStackTrace(int max_num_frames) {
max_frames_in_stack_trace.store(max_num_frames, std::memory_order_release);
}
bool ExitOnDFatal() { return exit_on_dfatal.load(std::memory_order_acquire); }
void SetExitOnDFatal(bool on_off) {
exit_on_dfatal.store(on_off, std::memory_order_release);
}
bool SuppressSigabortTrace() {
return suppress_sigabort_trace.load(std::memory_order_acquire);
}
bool SetSuppressSigabortTrace(bool on_off) {
return suppress_sigabort_trace.exchange(on_off);
}
}
ABSL_NAMESPACE_END
} | #include "absl/log/globals.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/log_severity.h"
#include "absl/log/internal/globals.h"
#include "absl/log/internal/test_helpers.h"
#include "absl/log/log.h"
#include "absl/log/scoped_mock_log.h"
namespace {
using ::testing::_;
using ::testing::StrEq;
auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment(
new absl::log_internal::LogTestEnvironment);
constexpr static absl::LogSeverityAtLeast DefaultMinLogLevel() {
return absl::LogSeverityAtLeast::kInfo;
}
constexpr static absl::LogSeverityAtLeast DefaultStderrThreshold() {
return absl::LogSeverityAtLeast::kError;
}
TEST(TestGlobals, MinLogLevel) {
EXPECT_EQ(absl::MinLogLevel(), DefaultMinLogLevel());
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kError);
EXPECT_EQ(absl::MinLogLevel(), absl::LogSeverityAtLeast::kError);
absl::SetMinLogLevel(DefaultMinLogLevel());
}
TEST(TestGlobals, ScopedMinLogLevel) {
EXPECT_EQ(absl::MinLogLevel(), DefaultMinLogLevel());
{
absl::log_internal::ScopedMinLogLevel scoped_stderr_threshold(
absl::LogSeverityAtLeast::kError);
EXPECT_EQ(absl::MinLogLevel(), absl::LogSeverityAtLeast::kError);
}
EXPECT_EQ(absl::MinLogLevel(), DefaultMinLogLevel());
}
TEST(TestGlobals, StderrThreshold) {
EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold());
absl::SetStderrThreshold(absl::LogSeverityAtLeast::kError);
EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kError);
absl::SetStderrThreshold(DefaultStderrThreshold());
}
TEST(TestGlobals, ScopedStderrThreshold) {
EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold());
{
absl::ScopedStderrThreshold scoped_stderr_threshold(
absl::LogSeverityAtLeast::kError);
EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kError);
}
EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold());
}
TEST(TestGlobals, LogBacktraceAt) {
EXPECT_FALSE(absl::log_internal::ShouldLogBacktraceAt("some_file.cc", 111));
absl::SetLogBacktraceLocation("some_file.cc", 111);
EXPECT_TRUE(absl::log_internal::ShouldLogBacktraceAt("some_file.cc", 111));
EXPECT_FALSE(
absl::log_internal::ShouldLogBacktraceAt("another_file.cc", 222));
}
TEST(TestGlobals, LogPrefix) {
EXPECT_TRUE(absl::ShouldPrependLogPrefix());
absl::EnableLogPrefix(false);
EXPECT_FALSE(absl::ShouldPrependLogPrefix());
absl::EnableLogPrefix(true);
EXPECT_TRUE(absl::ShouldPrependLogPrefix());
}
TEST(TestGlobals, SetGlobalVLogLevel) {
EXPECT_EQ(absl::SetGlobalVLogLevel(42), 0);
EXPECT_EQ(absl::SetGlobalVLogLevel(1337), 42);
EXPECT_EQ(absl::SetGlobalVLogLevel(0), 1337);
}
TEST(TestGlobals, SetVLogLevel) {
EXPECT_EQ(absl::SetVLogLevel("setvloglevel", 42), 0);
EXPECT_EQ(absl::SetVLogLevel("setvloglevel", 1337), 42);
EXPECT_EQ(absl::SetVLogLevel("othersetvloglevel", 50), 0);
}
TEST(TestGlobals, AndroidLogTag) {
EXPECT_DEATH_IF_SUPPORTED(absl::SetAndroidNativeTag(nullptr), ".*");
EXPECT_THAT(absl::log_internal::GetAndroidNativeTag(), StrEq("native"));
absl::SetAndroidNativeTag("test_tag");
EXPECT_THAT(absl::log_internal::GetAndroidNativeTag(), StrEq("test_tag"));
EXPECT_DEATH_IF_SUPPORTED(absl::SetAndroidNativeTag("test_tag_fail"), ".*");
}
TEST(TestExitOnDFatal, OffTest) {
absl::log_internal::SetExitOnDFatal(false);
EXPECT_FALSE(absl::log_internal::ExitOnDFatal());
{
absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(log, Log(absl::kLogDebugFatal, _, "This should not be fatal"));
log.StartCapturingLogs();
LOG(DFATAL) << "This should not be fatal";
}
}
#if GTEST_HAS_DEATH_TEST
TEST(TestDeathWhileExitOnDFatal, OnTest) {
absl::log_internal::SetExitOnDFatal(true);
EXPECT_TRUE(absl::log_internal::ExitOnDFatal());
EXPECT_DEBUG_DEATH({ LOG(DFATAL) << "This should be fatal in debug mode"; },
"This should be fatal in debug mode");
}
#endif
} |
2,536 | cpp | abseil/abseil-cpp | flags | absl/log/flags.cc | absl/log/flags_test.cc | #ifndef ABSL_LOG_INTERNAL_FLAGS_H_
#define ABSL_LOG_INTERNAL_FLAGS_H_
#include <string>
#include "absl/flags/declare.h"
ABSL_DECLARE_FLAG(int, stderrthreshold);
ABSL_DECLARE_FLAG(int, minloglevel);
ABSL_DECLARE_FLAG(std::string, log_backtrace_at);
ABSL_DECLARE_FLAG(bool, log_prefix);
ABSL_DECLARE_FLAG(int, v);
ABSL_DECLARE_FLAG(std::string, vmodule);
#endif
#include "absl/log/internal/flags.h"
#include <stddef.h>
#include <algorithm>
#include <cstdlib>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/log_severity.h"
#include "absl/flags/flag.h"
#include "absl/flags/marshalling.h"
#include "absl/log/globals.h"
#include "absl/log/internal/config.h"
#include "absl/log/internal/vlog_config.h"
#include "absl/strings/numbers.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
namespace {
void SyncLoggingFlags() {
absl::SetFlag(&FLAGS_minloglevel, static_cast<int>(absl::MinLogLevel()));
absl::SetFlag(&FLAGS_log_prefix, absl::ShouldPrependLogPrefix());
}
bool RegisterSyncLoggingFlags() {
log_internal::SetLoggingGlobalsListener(&SyncLoggingFlags);
return true;
}
ABSL_ATTRIBUTE_UNUSED const bool unused = RegisterSyncLoggingFlags();
template <typename T>
T GetFromEnv(const char* varname, T dflt) {
const char* val = ::getenv(varname);
if (val != nullptr) {
std::string err;
ABSL_INTERNAL_CHECK(absl::ParseFlag(val, &dflt, &err), err.c_str());
}
return dflt;
}
constexpr absl::LogSeverityAtLeast StderrThresholdDefault() {
return absl::LogSeverityAtLeast::kError;
}
}
}
ABSL_NAMESPACE_END
}
ABSL_FLAG(int, stderrthreshold,
static_cast<int>(absl::log_internal::StderrThresholdDefault()),
"Log messages at or above this threshold level are copied to stderr.")
.OnUpdate([] {
absl::log_internal::RawSetStderrThreshold(
static_cast<absl::LogSeverityAtLeast>(
absl::GetFlag(FLAGS_stderrthreshold)));
});
ABSL_FLAG(int, minloglevel, static_cast<int>(absl::LogSeverityAtLeast::kInfo),
"Messages logged at a lower level than this don't actually "
"get logged anywhere")
.OnUpdate([] {
absl::log_internal::RawSetMinLogLevel(
static_cast<absl::LogSeverityAtLeast>(
absl::GetFlag(FLAGS_minloglevel)));
});
ABSL_FLAG(std::string, log_backtrace_at, "",
"Emit a backtrace when logging at file:linenum.")
.OnUpdate([] {
const std::string log_backtrace_at =
absl::GetFlag(FLAGS_log_backtrace_at);
if (log_backtrace_at.empty()) {
absl::ClearLogBacktraceLocation();
return;
}
const size_t last_colon = log_backtrace_at.rfind(':');
if (last_colon == log_backtrace_at.npos) {
absl::ClearLogBacktraceLocation();
return;
}
const absl::string_view file =
absl::string_view(log_backtrace_at).substr(0, last_colon);
int line;
if (!absl::SimpleAtoi(
absl::string_view(log_backtrace_at).substr(last_colon + 1),
&line)) {
absl::ClearLogBacktraceLocation();
return;
}
absl::SetLogBacktraceLocation(file, line);
});
ABSL_FLAG(bool, log_prefix, true,
"Prepend the log prefix to the start of each log line")
.OnUpdate([] {
absl::log_internal::RawEnableLogPrefix(absl::GetFlag(FLAGS_log_prefix));
});
ABSL_FLAG(int, v, 0,
"Show all VLOG(m) messages for m <= this. Overridable by --vmodule.")
.OnUpdate([] {
absl::log_internal::UpdateGlobalVLogLevel(absl::GetFlag(FLAGS_v));
});
ABSL_FLAG(
std::string, vmodule, "",
"per-module log verbosity level."
" Argument is a comma-separated list of <module name>=<log level>."
" <module name> is a glob pattern, matched against the filename base"
" (that is, name ignoring .cc/.h./-inl.h)."
" A pattern without slashes matches just the file name portion, otherwise"
" the whole file path below the workspace root"
" (still without .cc/.h./-inl.h) is matched."
" ? and * in the glob pattern match any single or sequence of characters"
" respectively including slashes."
" <log level> overrides any value given by --v.")
.OnUpdate([] {
absl::log_internal::UpdateVModule(absl::GetFlag(FLAGS_vmodule));
}); | #include "absl/log/internal/flags.h"
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/log_severity.h"
#include "absl/flags/flag.h"
#include "absl/flags/reflection.h"
#include "absl/log/globals.h"
#include "absl/log/internal/test_helpers.h"
#include "absl/log/internal/test_matchers.h"
#include "absl/log/log.h"
#include "absl/log/scoped_mock_log.h"
#include "absl/strings/str_cat.h"
namespace {
using ::absl::log_internal::TextMessage;
using ::testing::HasSubstr;
using ::testing::Not;
auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment(
new absl::log_internal::LogTestEnvironment);
constexpr static absl::LogSeverityAtLeast DefaultStderrThreshold() {
return absl::LogSeverityAtLeast::kError;
}
class LogFlagsTest : public ::testing::Test {
protected:
absl::FlagSaver flag_saver_;
};
TEST_F(LogFlagsTest, DISABLED_StderrKnobsDefault) {
EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold());
}
TEST_F(LogFlagsTest, SetStderrThreshold) {
absl::SetFlag(&FLAGS_stderrthreshold,
static_cast<int>(absl::LogSeverityAtLeast::kInfo));
EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kInfo);
absl::SetFlag(&FLAGS_stderrthreshold,
static_cast<int>(absl::LogSeverityAtLeast::kError));
EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kError);
}
TEST_F(LogFlagsTest, SetMinLogLevel) {
absl::SetFlag(&FLAGS_minloglevel,
static_cast<int>(absl::LogSeverityAtLeast::kError));
EXPECT_EQ(absl::MinLogLevel(), absl::LogSeverityAtLeast::kError);
absl::log_internal::ScopedMinLogLevel scoped_min_log_level(
absl::LogSeverityAtLeast::kWarning);
EXPECT_EQ(absl::GetFlag(FLAGS_minloglevel),
static_cast<int>(absl::LogSeverityAtLeast::kWarning));
}
TEST_F(LogFlagsTest, PrependLogPrefix) {
absl::SetFlag(&FLAGS_log_prefix, false);
EXPECT_EQ(absl::ShouldPrependLogPrefix(), false);
absl::EnableLogPrefix(true);
EXPECT_EQ(absl::GetFlag(FLAGS_log_prefix), true);
}
TEST_F(LogFlagsTest, EmptyBacktraceAtFlag) {
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo);
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:")))));
test_sink.StartCapturingLogs();
absl::SetFlag(&FLAGS_log_backtrace_at, "");
LOG(INFO) << "hello world";
}
TEST_F(LogFlagsTest, BacktraceAtNonsense) {
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo);
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:")))));
test_sink.StartCapturingLogs();
absl::SetFlag(&FLAGS_log_backtrace_at, "gibberish");
LOG(INFO) << "hello world";
}
TEST_F(LogFlagsTest, BacktraceAtWrongFile) {
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo);
const int log_line = __LINE__ + 1;
auto do_log = [] { LOG(INFO) << "hello world"; };
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:")))));
test_sink.StartCapturingLogs();
absl::SetFlag(&FLAGS_log_backtrace_at,
absl::StrCat("some_other_file.cc:", log_line));
do_log();
}
TEST_F(LogFlagsTest, BacktraceAtWrongLine) {
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo);
const int log_line = __LINE__ + 1;
auto do_log = [] { LOG(INFO) << "hello world"; };
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:")))));
test_sink.StartCapturingLogs();
absl::SetFlag(&FLAGS_log_backtrace_at,
absl::StrCat("flags_test.cc:", log_line + 1));
do_log();
}
TEST_F(LogFlagsTest, BacktraceAtWholeFilename) {
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo);
const int log_line = __LINE__ + 1;
auto do_log = [] { LOG(INFO) << "hello world"; };
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:")))));
test_sink.StartCapturingLogs();
absl::SetFlag(&FLAGS_log_backtrace_at, absl::StrCat(__FILE__, ":", log_line));
do_log();
}
TEST_F(LogFlagsTest, BacktraceAtNonmatchingSuffix) {
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo);
const int log_line = __LINE__ + 1;
auto do_log = [] { LOG(INFO) << "hello world"; };
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:")))));
test_sink.StartCapturingLogs();
absl::SetFlag(&FLAGS_log_backtrace_at,
absl::StrCat("flags_test.cc:", log_line, "gibberish"));
do_log();
}
TEST_F(LogFlagsTest, LogsBacktrace) {
absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo);
const int log_line = __LINE__ + 1;
auto do_log = [] { LOG(INFO) << "hello world"; };
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
testing::InSequence seq;
EXPECT_CALL(test_sink, Send(TextMessage(HasSubstr("(stacktrace:"))));
EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:")))));
test_sink.StartCapturingLogs();
absl::SetFlag(&FLAGS_log_backtrace_at,
absl::StrCat("flags_test.cc:", log_line));
do_log();
absl::SetFlag(&FLAGS_log_backtrace_at, "");
do_log();
}
} |
2,537 | cpp | abseil/abseil-cpp | scoped_mock_log | absl/log/scoped_mock_log.cc | absl/log/scoped_mock_log_test.cc | #ifndef ABSL_LOG_SCOPED_MOCK_LOG_H_
#define ABSL_LOG_SCOPED_MOCK_LOG_H_
#include <atomic>
#include <string>
#include "gmock/gmock.h"
#include "absl/base/config.h"
#include "absl/base/log_severity.h"
#include "absl/log/log_entry.h"
#include "absl/log/log_sink.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
enum class MockLogDefault { kIgnoreUnexpected, kDisallowUnexpected };
class ScopedMockLog final {
public:
explicit ScopedMockLog(
MockLogDefault default_exp = MockLogDefault::kIgnoreUnexpected);
ScopedMockLog(const ScopedMockLog&) = delete;
ScopedMockLog& operator=(const ScopedMockLog&) = delete;
~ScopedMockLog();
void StartCapturingLogs();
void StopCapturingLogs();
absl::LogSink& UseAsLocalSink();
MOCK_METHOD(void, Log,
(absl::LogSeverity severity, const std::string& file_path,
const std::string& message));
MOCK_METHOD(void, Send, (const absl::LogEntry&));
MOCK_METHOD(void, Flush, ());
private:
class ForwardingSink final : public absl::LogSink {
public:
explicit ForwardingSink(ScopedMockLog* sml) : sml_(sml) {}
ForwardingSink(const ForwardingSink&) = delete;
ForwardingSink& operator=(const ForwardingSink&) = delete;
void Send(const absl::LogEntry& entry) override { sml_->Send(entry); }
void Flush() override { sml_->Flush(); }
private:
ScopedMockLog* sml_;
};
ForwardingSink sink_;
bool is_capturing_logs_;
std::atomic<bool> is_triggered_;
};
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/scoped_mock_log.h"
#include <atomic>
#include <string>
#include "gmock/gmock.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/log/log_entry.h"
#include "absl/log/log_sink.h"
#include "absl/log/log_sink_registry.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
ScopedMockLog::ScopedMockLog(MockLogDefault default_exp)
: sink_(this), is_capturing_logs_(false), is_triggered_(false) {
if (default_exp == MockLogDefault::kIgnoreUnexpected) {
EXPECT_CALL(*this, Log).Times(::testing::AnyNumber());
} else {
EXPECT_CALL(*this, Log).Times(0);
}
EXPECT_CALL(*this, Send)
.Times(::testing::AnyNumber())
.WillRepeatedly([this](const absl::LogEntry& entry) {
is_triggered_.store(true, std::memory_order_relaxed);
Log(entry.log_severity(), std::string(entry.source_filename()),
std::string(entry.text_message()));
});
EXPECT_CALL(*this, Flush).Times(::testing::AnyNumber());
}
ScopedMockLog::~ScopedMockLog() {
ABSL_RAW_CHECK(is_triggered_.load(std::memory_order_relaxed),
"Did you forget to call StartCapturingLogs()?");
if (is_capturing_logs_) StopCapturingLogs();
}
void ScopedMockLog::StartCapturingLogs() {
ABSL_RAW_CHECK(!is_capturing_logs_,
"StartCapturingLogs() can be called only when the "
"absl::ScopedMockLog object is not capturing logs.");
is_capturing_logs_ = true;
is_triggered_.store(true, std::memory_order_relaxed);
absl::AddLogSink(&sink_);
}
void ScopedMockLog::StopCapturingLogs() {
ABSL_RAW_CHECK(is_capturing_logs_,
"StopCapturingLogs() can be called only when the "
"absl::ScopedMockLog object is capturing logs.");
is_capturing_logs_ = false;
absl::RemoveLogSink(&sink_);
}
absl::LogSink& ScopedMockLog::UseAsLocalSink() {
is_triggered_.store(true, std::memory_order_relaxed);
return sink_;
}
ABSL_NAMESPACE_END
} | #include "absl/log/scoped_mock_log.h"
#include <memory>
#include <thread>
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/log_severity.h"
#include "absl/log/globals.h"
#include "absl/log/internal/test_helpers.h"
#include "absl/log/internal/test_matchers.h"
#include "absl/log/log.h"
#include "absl/memory/memory.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/barrier.h"
#include "absl/synchronization/notification.h"
namespace {
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::InSequence;
using ::testing::Lt;
using ::testing::Truly;
using absl::log_internal::SourceBasename;
using absl::log_internal::SourceFilename;
using absl::log_internal::SourceLine;
using absl::log_internal::TextMessageWithPrefix;
using absl::log_internal::ThreadID;
auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment(
new absl::log_internal::LogTestEnvironment);
#if GTEST_HAS_DEATH_TEST
TEST(ScopedMockLogDeathTest,
StartCapturingLogsCannotBeCalledWhenAlreadyCapturing) {
EXPECT_DEATH(
{
absl::ScopedMockLog log;
log.StartCapturingLogs();
log.StartCapturingLogs();
},
"StartCapturingLogs");
}
TEST(ScopedMockLogDeathTest, StopCapturingLogsCannotBeCalledWhenNotCapturing) {
EXPECT_DEATH(
{
absl::ScopedMockLog log;
log.StopCapturingLogs();
},
"StopCapturingLogs");
}
TEST(ScopedMockLogDeathTest, FailsCheckIfStartCapturingLogsIsNeverCalled) {
EXPECT_DEATH({ absl::ScopedMockLog log; },
"Did you forget to call StartCapturingLogs");
}
#endif
TEST(ScopedMockLogTest, LogMockCatchAndMatchStrictExpectations) {
absl::ScopedMockLog log;
InSequence s;
EXPECT_CALL(log,
Log(absl::LogSeverity::kWarning, HasSubstr(__FILE__), "Danger."));
EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Working...")).Times(2);
EXPECT_CALL(log, Log(absl::LogSeverity::kError, _, "Bad!!"));
log.StartCapturingLogs();
LOG(WARNING) << "Danger.";
LOG(INFO) << "Working...";
LOG(INFO) << "Working...";
LOG(ERROR) << "Bad!!";
}
TEST(ScopedMockLogTest, LogMockCatchAndMatchSendExpectations) {
absl::ScopedMockLog log;
EXPECT_CALL(
log,
Send(AllOf(SourceFilename(Eq("/my/very/very/very_long_source_file.cc")),
SourceBasename(Eq("very_long_source_file.cc")),
SourceLine(Eq(777)), ThreadID(Eq(absl::LogEntry::tid_t{1234})),
TextMessageWithPrefix(Truly([](absl::string_view msg) {
return absl::EndsWith(
msg, " very_long_source_file.cc:777] Info message");
})))));
log.StartCapturingLogs();
LOG(INFO)
.AtLocation("/my/very/very/very_long_source_file.cc", 777)
.WithThreadID(1234)
<< "Info message";
}
TEST(ScopedMockLogTest, ScopedMockLogCanBeNice) {
absl::ScopedMockLog log;
InSequence s;
EXPECT_CALL(log,
Log(absl::LogSeverity::kWarning, HasSubstr(__FILE__), "Danger."));
EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Working...")).Times(2);
EXPECT_CALL(log, Log(absl::LogSeverity::kError, _, "Bad!!"));
log.StartCapturingLogs();
LOG(INFO) << "Info message.";
LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger ";
LOG(WARNING) << "Danger.";
LOG(INFO) << "Info message.";
LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger ";
LOG(INFO) << "Working...";
LOG(INFO) << "Info message.";
LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger ";
LOG(INFO) << "Working...";
LOG(INFO) << "Info message.";
LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger ";
LOG(ERROR) << "Bad!!";
LOG(INFO) << "Info message.";
LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger ";
}
TEST(ScopedMockLogTest, RejectsUnexpectedLogs) {
EXPECT_NONFATAL_FAILURE(
{
absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(log, Log(Lt(absl::LogSeverity::kError), _, _))
.Times(AnyNumber());
log.StartCapturingLogs();
LOG(INFO) << "Ignored";
LOG(WARNING) << "Ignored";
LOG(ERROR) << "Should not be ignored";
},
"Should not be ignored");
}
TEST(ScopedMockLogTest, CapturesLogsAfterStartCapturingLogs) {
absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfinity);
absl::ScopedMockLog log;
LOG(INFO) << "Ignored info";
LOG(WARNING) << "Ignored warning";
LOG(ERROR) << "Ignored error";
EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Expected info"));
log.StartCapturingLogs();
LOG(INFO) << "Expected info";
}
TEST(ScopedMockLogTest, DoesNotCaptureLogsAfterStopCapturingLogs) {
absl::ScopedMockLog log;
EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Expected info"));
log.StartCapturingLogs();
LOG(INFO) << "Expected info";
log.StopCapturingLogs();
LOG(INFO) << "Ignored info";
LOG(WARNING) << "Ignored warning";
LOG(ERROR) << "Ignored error";
}
TEST(ScopedMockLogTest, LogFromMultipleThreads) {
absl::ScopedMockLog log;
EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, __FILE__, "Thread 1"));
EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, __FILE__, "Thread 2"));
log.StartCapturingLogs();
absl::Barrier barrier(2);
std::thread thread1([&barrier]() {
barrier.Block();
LOG(INFO) << "Thread 1";
});
std::thread thread2([&barrier]() {
barrier.Block();
LOG(INFO) << "Thread 2";
});
thread1.join();
thread2.join();
}
TEST(ScopedMockLogTest, NoSequenceWithMultipleThreads) {
absl::ScopedMockLog log;
absl::Barrier barrier(2);
EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, _))
.Times(2)
.WillRepeatedly([&barrier]() { barrier.Block(); });
log.StartCapturingLogs();
std::thread thread1([]() { LOG(INFO) << "Thread 1"; });
std::thread thread2([]() { LOG(INFO) << "Thread 2"; });
thread1.join();
thread2.join();
}
TEST(ScopedMockLogTsanTest,
ScopedMockLogCanBeDeletedWhenAnotherThreadIsLogging) {
auto log = absl::make_unique<absl::ScopedMockLog>();
EXPECT_CALL(*log, Log(absl::LogSeverity::kInfo, __FILE__, "Thread log"))
.Times(AnyNumber());
log->StartCapturingLogs();
absl::Notification logging_started;
std::thread thread([&logging_started]() {
for (int i = 0; i < 100; ++i) {
if (i == 50) logging_started.Notify();
LOG(INFO) << "Thread log";
}
});
logging_started.WaitForNotification();
log.reset();
thread.join();
}
TEST(ScopedMockLogTest, AsLocalSink) {
absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(log, Log(_, _, "two"));
EXPECT_CALL(log, Log(_, _, "three"));
LOG(INFO) << "one";
LOG(INFO).ToSinkOnly(&log.UseAsLocalSink()) << "two";
LOG(INFO).ToSinkAlso(&log.UseAsLocalSink()) << "three";
}
} |
2,538 | cpp | abseil/abseil-cpp | log_sink | absl/log/log_sink.cc | absl/log/log_sink_test.cc | #ifndef ABSL_LOG_LOG_SINK_H_
#define ABSL_LOG_LOG_SINK_H_
#include "absl/base/config.h"
#include "absl/log/log_entry.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class LogSink {
public:
virtual ~LogSink() = default;
virtual void Send(const absl::LogEntry& entry) = 0;
virtual void Flush() {}
protected:
LogSink() = default;
LogSink(const LogSink&) = default;
LogSink& operator=(const LogSink&) = default;
private:
virtual void KeyFunction() const final;
};
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/log_sink.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
void LogSink::KeyFunction() const {}
ABSL_NAMESPACE_END
} | #include "absl/log/log_sink.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/log/internal/test_actions.h"
#include "absl/log/internal/test_helpers.h"
#include "absl/log/internal/test_matchers.h"
#include "absl/log/log.h"
#include "absl/log/log_sink_registry.h"
#include "absl/log/scoped_mock_log.h"
#include "absl/strings/string_view.h"
namespace {
using ::absl::log_internal::DeathTestExpectedLogging;
using ::absl::log_internal::DeathTestUnexpectedLogging;
using ::absl::log_internal::DeathTestValidateExpectations;
using ::absl::log_internal::DiedOfFatal;
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::HasSubstr;
using ::testing::InSequence;
auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment(
new absl::log_internal::LogTestEnvironment);
TEST(LogSinkRegistryTest, AddLogSink) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
InSequence s;
EXPECT_CALL(test_sink, Log(_, _, "hello world")).Times(0);
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, __FILE__, "Test : 42"));
EXPECT_CALL(test_sink,
Log(absl::LogSeverity::kWarning, __FILE__, "Danger ahead"));
EXPECT_CALL(test_sink,
Log(absl::LogSeverity::kError, __FILE__, "This is an error"));
LOG(INFO) << "hello world";
test_sink.StartCapturingLogs();
LOG(INFO) << "Test : " << 42;
LOG(WARNING) << "Danger" << ' ' << "ahead";
LOG(ERROR) << "This is an error";
test_sink.StopCapturingLogs();
LOG(INFO) << "Goodby world";
}
TEST(LogSinkRegistryTest, MultipleLogSinks) {
absl::ScopedMockLog test_sink1(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog test_sink2(absl::MockLogDefault::kDisallowUnexpected);
::testing::InSequence seq;
EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "First")).Times(1);
EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "First")).Times(0);
EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "Second")).Times(1);
EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "Second")).Times(1);
EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "Third")).Times(0);
EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "Third")).Times(1);
LOG(INFO) << "Before first";
test_sink1.StartCapturingLogs();
LOG(INFO) << "First";
test_sink2.StartCapturingLogs();
LOG(INFO) << "Second";
test_sink1.StopCapturingLogs();
LOG(INFO) << "Third";
test_sink2.StopCapturingLogs();
LOG(INFO) << "Fourth";
}
TEST(LogSinkRegistrationDeathTest, DuplicateSinkRegistration) {
ASSERT_DEATH_IF_SUPPORTED(
{
absl::ScopedMockLog sink;
sink.StartCapturingLogs();
absl::AddLogSink(&sink.UseAsLocalSink());
},
HasSubstr("Duplicate log sinks"));
}
TEST(LogSinkRegistrationDeathTest, MismatchSinkRemoval) {
ASSERT_DEATH_IF_SUPPORTED(
{
absl::ScopedMockLog sink;
absl::RemoveLogSink(&sink.UseAsLocalSink());
},
HasSubstr("Mismatched log sink"));
}
TEST(LogSinkTest, FlushSinks) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Flush()).Times(2);
test_sink.StartCapturingLogs();
absl::FlushLogSinks();
absl::FlushLogSinks();
}
TEST(LogSinkDeathTest, DeathInSend) {
class FatalSendSink : public absl::LogSink {
public:
void Send(const absl::LogEntry&) override { LOG(FATAL) << "goodbye world"; }
};
FatalSendSink sink;
EXPECT_EXIT({ LOG(INFO).ToSinkAlso(&sink) << "hello world"; }, DiedOfFatal,
_);
}
TEST(LogSinkTest, ToSinkAlso) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog another_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
EXPECT_CALL(another_sink, Log(_, _, "hello world"));
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkAlso(&another_sink.UseAsLocalSink()) << "hello world";
}
TEST(LogSinkTest, ToSinkOnly) {
absl::ScopedMockLog another_sink(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(another_sink, Log(_, _, "hello world"));
LOG(INFO).ToSinkOnly(&another_sink.UseAsLocalSink()) << "hello world";
}
TEST(LogSinkTest, ToManySinks) {
absl::ScopedMockLog sink1(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink2(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink3(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink4(absl::MockLogDefault::kDisallowUnexpected);
absl::ScopedMockLog sink5(absl::MockLogDefault::kDisallowUnexpected);
EXPECT_CALL(sink3, Log(_, _, "hello world"));
EXPECT_CALL(sink4, Log(_, _, "hello world"));
EXPECT_CALL(sink5, Log(_, _, "hello world"));
LOG(INFO)
.ToSinkAlso(&sink1.UseAsLocalSink())
.ToSinkAlso(&sink2.UseAsLocalSink())
.ToSinkOnly(&sink3.UseAsLocalSink())
.ToSinkAlso(&sink4.UseAsLocalSink())
.ToSinkAlso(&sink5.UseAsLocalSink())
<< "hello world";
}
class ReentrancyTest : public ::testing::Test {
protected:
ReentrancyTest() = default;
enum class LogMode : int { kNormal, kToSinkAlso, kToSinkOnly };
class ReentrantSendLogSink : public absl::LogSink {
public:
explicit ReentrantSendLogSink(absl::LogSeverity severity,
absl::LogSink* sink, LogMode mode)
: severity_(severity), sink_(sink), mode_(mode) {}
explicit ReentrantSendLogSink(absl::LogSeverity severity)
: ReentrantSendLogSink(severity, nullptr, LogMode::kNormal) {}
void Send(const absl::LogEntry&) override {
switch (mode_) {
case LogMode::kNormal:
LOG(LEVEL(severity_)) << "The log is coming from *inside the sink*.";
break;
case LogMode::kToSinkAlso:
LOG(LEVEL(severity_)).ToSinkAlso(sink_)
<< "The log is coming from *inside the sink*.";
break;
case LogMode::kToSinkOnly:
LOG(LEVEL(severity_)).ToSinkOnly(sink_)
<< "The log is coming from *inside the sink*.";
break;
default:
LOG(FATAL) << "Invalid mode " << static_cast<int>(mode_);
}
}
private:
absl::LogSeverity severity_;
absl::LogSink* sink_;
LogMode mode_;
};
static absl::string_view LogAndReturn(absl::LogSeverity severity,
absl::string_view to_log,
absl::string_view to_return) {
LOG(LEVEL(severity)) << to_log;
return to_return;
}
};
TEST_F(ReentrancyTest, LogFunctionThatLogs) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
InSequence seq;
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "hello"));
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "world"));
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kWarning, _, "danger"));
EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "here"));
test_sink.StartCapturingLogs();
LOG(INFO) << LogAndReturn(absl::LogSeverity::kInfo, "hello", "world");
LOG(INFO) << LogAndReturn(absl::LogSeverity::kWarning, "danger", "here");
}
TEST_F(ReentrancyTest, RegisteredLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink renentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
test_sink.StartCapturingLogs();
absl::AddLogSink(&renentrant_sink);
LOG(INFO) << "hello world";
absl::RemoveLogSink(&renentrant_sink);
}
TEST_F(ReentrancyTest, AlsoLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
}
TEST_F(ReentrancyTest, RegisteredAlsoLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink, Log(_, _, "hello world"));
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
absl::RemoveLogSink(&reentrant_sink);
}
TEST_F(ReentrancyTest, OnlyLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
}
TEST_F(ReentrancyTest, RegisteredOnlyLogSinkThatLogsInSend) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo);
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."));
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
absl::RemoveLogSink(&reentrant_sink);
}
using ReentrancyDeathTest = ReentrancyTest;
TEST_F(ReentrancyDeathTest, LogFunctionThatLogsFatal) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello"))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
LOG(INFO) << LogAndReturn(absl::LogSeverity::kFatal, "hello", "world");
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, RegisteredLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello world"))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, AlsoLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello world"))
.WillOnce(DeathTestExpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, RegisteredAlsoLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink, Log(_, _, "hello world"))
.WillOnce(DeathTestExpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, OnlyLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
TEST_F(ReentrancyDeathTest, RegisteredOnlyLogSinkThatLogsFatalInSend) {
EXPECT_EXIT(
{
absl::ScopedMockLog test_sink;
ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal);
EXPECT_CALL(test_sink, Log)
.Times(AnyNumber())
.WillRepeatedly(DeathTestUnexpectedLogging());
EXPECT_CALL(test_sink,
Log(_, _, "The log is coming from *inside the sink*."))
.WillOnce(DeathTestExpectedLogging());
test_sink.StartCapturingLogs();
absl::AddLogSink(&reentrant_sink);
LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world";
},
DiedOfFatal, DeathTestValidateExpectations());
}
} |
2,539 | cpp | abseil/abseil-cpp | fnmatch | absl/log/internal/fnmatch.cc | absl/log/internal/fnmatch_test.cc | #ifndef ABSL_LOG_INTERNAL_FNMATCH_H_
#define ABSL_LOG_INTERNAL_FNMATCH_H_
#include "absl/base/config.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
bool FNMatch(absl::string_view pattern, absl::string_view str);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/internal/fnmatch.h"
#include <cstddef>
#include "absl/base/config.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
bool FNMatch(absl::string_view pattern, absl::string_view str) {
bool in_wildcard_match = false;
while (true) {
if (pattern.empty()) {
return in_wildcard_match || str.empty();
}
if (str.empty()) {
return pattern.find_first_not_of('*') == pattern.npos;
}
switch (pattern.front()) {
case '*':
pattern.remove_prefix(1);
in_wildcard_match = true;
break;
case '?':
pattern.remove_prefix(1);
str.remove_prefix(1);
break;
default:
if (in_wildcard_match) {
absl::string_view fixed_portion = pattern;
const size_t end = fixed_portion.find_first_of("*?");
if (end != fixed_portion.npos) {
fixed_portion = fixed_portion.substr(0, end);
}
const size_t match = str.find(fixed_portion);
if (match == str.npos) {
return false;
}
pattern.remove_prefix(fixed_portion.size());
str.remove_prefix(match + fixed_portion.size());
in_wildcard_match = false;
} else {
if (pattern.front() != str.front()) {
return false;
}
pattern.remove_prefix(1);
str.remove_prefix(1);
}
break;
}
}
}
}
ABSL_NAMESPACE_END
} | #include "absl/log/internal/fnmatch.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace {
using ::testing::IsFalse;
using ::testing::IsTrue;
TEST(FNMatchTest, Works) {
using absl::log_internal::FNMatch;
EXPECT_THAT(FNMatch("foo", "foo"), IsTrue());
EXPECT_THAT(FNMatch("foo", "bar"), IsFalse());
EXPECT_THAT(FNMatch("foo", "fo"), IsFalse());
EXPECT_THAT(FNMatch("foo", "foo2"), IsFalse());
EXPECT_THAT(FNMatch("bar/foo.ext", "bar/foo.ext"), IsTrue());
EXPECT_THAT(FNMatch("*ba*r/fo*o.ext*", "bar/foo.ext"), IsTrue());
EXPECT_THAT(FNMatch("bar/foo.ext", "bar/baz.ext"), IsFalse());
EXPECT_THAT(FNMatch("bar/foo.ext", "bar/foo"), IsFalse());
EXPECT_THAT(FNMatch("bar/foo.ext", "bar/foo.ext.zip"), IsFalse());
EXPECT_THAT(FNMatch("ba?/*.ext", "bar/foo.ext"), IsTrue());
EXPECT_THAT(FNMatch("ba?/*.ext", "baZ/FOO.ext"), IsTrue());
EXPECT_THAT(FNMatch("ba?/*.ext", "barr/foo.ext"), IsFalse());
EXPECT_THAT(FNMatch("ba?/*.ext", "bar/foo.ext2"), IsFalse());
EXPECT_THAT(FNMatch("ba?/*", "bar/foo.ext2"), IsTrue());
EXPECT_THAT(FNMatch("ba?/*", "bar/"), IsTrue());
EXPECT_THAT(FNMatch("ba?/?", "bar/"), IsFalse());
EXPECT_THAT(FNMatch("ba?/*", "bar"), IsFalse());
EXPECT_THAT(FNMatch("?x", "zx"), IsTrue());
EXPECT_THAT(FNMatch("*b", "aab"), IsTrue());
EXPECT_THAT(FNMatch("a*b", "aXb"), IsTrue());
EXPECT_THAT(FNMatch("", ""), IsTrue());
EXPECT_THAT(FNMatch("", "a"), IsFalse());
EXPECT_THAT(FNMatch("ab*", "ab"), IsTrue());
EXPECT_THAT(FNMatch("ab**", "ab"), IsTrue());
EXPECT_THAT(FNMatch("ab*?", "ab"), IsFalse());
EXPECT_THAT(FNMatch("*", "bbb"), IsTrue());
EXPECT_THAT(FNMatch("*", ""), IsTrue());
EXPECT_THAT(FNMatch("?", ""), IsFalse());
EXPECT_THAT(FNMatch("***", "**p"), IsTrue());
EXPECT_THAT(FNMatch("**", "*"), IsTrue());
EXPECT_THAT(FNMatch("*?", "*"), IsTrue());
}
} |
2,540 | cpp | abseil/abseil-cpp | log_format | absl/log/internal/log_format.cc | absl/log/log_format_test.cc | #ifndef ABSL_LOG_INTERNAL_LOG_FORMAT_H_
#define ABSL_LOG_INTERNAL_LOG_FORMAT_H_
#include <stddef.h>
#include <string>
#include "absl/base/config.h"
#include "absl/base/log_severity.h"
#include "absl/log/internal/config.h"
#include "absl/strings/string_view.h"
#include "absl/time/civil_time.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
enum class PrefixFormat {
kNotRaw,
kRaw,
};
std::string FormatLogMessage(absl::LogSeverity severity,
absl::CivilSecond civil_second,
absl::Duration subsecond, log_internal::Tid tid,
absl::string_view basename, int line,
PrefixFormat format, absl::string_view message);
size_t FormatLogPrefix(absl::LogSeverity severity, absl::Time timestamp,
log_internal::Tid tid, absl::string_view basename,
int line, PrefixFormat format, absl::Span<char>& buf);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/log/internal/log_format.h"
#include <string.h>
#ifdef _MSC_VER
#include <winsock2.h>
#else
#include <sys/time.h>
#endif
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <type_traits>
#include "absl/base/config.h"
#include "absl/base/log_severity.h"
#include "absl/base/optimization.h"
#include "absl/log/internal/append_truncated.h"
#include "absl/log/internal/config.h"
#include "absl/log/internal/globals.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/time/civil_time.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace log_internal {
namespace {
template <typename T>
inline std::enable_if_t<!std::is_signed<T>::value>
PutLeadingWhitespace(T tid, char*& p) {
if (tid < 10) *p++ = ' ';
if (tid < 100) *p++ = ' ';
if (tid < 1000) *p++ = ' ';
if (tid < 10000) *p++ = ' ';
if (tid < 100000) *p++ = ' ';
if (tid < 1000000) *p++ = ' ';
}
template <typename T>
inline std::enable_if_t<std::is_signed<T>::value>
PutLeadingWhitespace(T tid, char*& p) {
if (tid >= 0 && tid < 10) *p++ = ' ';
if (tid > -10 && tid < 100) *p++ = ' ';
if (tid > -100 && tid < 1000) *p++ = ' ';
if (tid > -1000 && tid < 10000) *p++ = ' ';
if (tid > -10000 && tid < 100000) *p++ = ' ';
if (tid > -100000 && tid < 1000000) *p++ = ' ';
}
size_t FormatBoundedFields(absl::LogSeverity severity, absl::Time timestamp,
log_internal::Tid tid, absl::Span<char>& buf) {
constexpr size_t kBoundedFieldsMaxLen =
sizeof("SMMDD HH:MM:SS.NNNNNN ") +
(1 + std::numeric_limits<log_internal::Tid>::digits10 + 1) - sizeof("");
if (ABSL_PREDICT_FALSE(buf.size() < kBoundedFieldsMaxLen)) {
buf.remove_suffix(buf.size());
return 0;
}
const absl::TimeZone* tz = absl::log_internal::TimeZone();
if (ABSL_PREDICT_FALSE(tz == nullptr)) {
auto tv = absl::ToTimeval(timestamp);
int snprintf_result = absl::SNPrintF(
buf.data(), buf.size(), "%c0000 00:00:%02d.%06d %7d ",
absl::LogSeverityName(severity)[0], static_cast<int>(tv.tv_sec),
static_cast<int>(tv.tv_usec), static_cast<int>(tid));
if (snprintf_result >= 0) {
buf.remove_prefix(static_cast<size_t>(snprintf_result));
return static_cast<size_t>(snprintf_result);
}
return 0;
}
char* p = buf.data();
*p++ = absl::LogSeverityName(severity)[0];
const absl::TimeZone::CivilInfo ci = tz->At(timestamp);
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.month()), p);
p += 2;
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.day()), p);
p += 2;
*p++ = ' ';
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.hour()), p);
p += 2;
*p++ = ':';
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.minute()),
p);
p += 2;
*p++ = ':';
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.second()),
p);
p += 2;
*p++ = '.';
const int64_t usecs = absl::ToInt64Microseconds(ci.subsecond);
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(usecs / 10000), p);
p += 2;
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(usecs / 100 % 100),
p);
p += 2;
absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(usecs % 100), p);
p += 2;
*p++ = ' ';
PutLeadingWhitespace(tid, p);
p = absl::numbers_internal::FastIntToBuffer(tid, p);
*p++ = ' ';
const size_t bytes_formatted = static_cast<size_t>(p - buf.data());
buf.remove_prefix(bytes_formatted);
return bytes_formatted;
}
size_t FormatLineNumber(int line, absl::Span<char>& buf) {
constexpr size_t kLineFieldMaxLen =
sizeof(":] ") + (1 + std::numeric_limits<int>::digits10 + 1) - sizeof("");
if (ABSL_PREDICT_FALSE(buf.size() < kLineFieldMaxLen)) {
buf.remove_suffix(buf.size());
return 0;
}
char* p = buf.data();
*p++ = ':';
p = absl::numbers_internal::FastIntToBuffer(line, p);
*p++ = ']';
*p++ = ' ';
const size_t bytes_formatted = static_cast<size_t>(p - buf.data());
buf.remove_prefix(bytes_formatted);
return bytes_formatted;
}
}
std::string FormatLogMessage(absl::LogSeverity severity,
absl::CivilSecond civil_second,
absl::Duration subsecond, log_internal::Tid tid,
absl::string_view basename, int line,
PrefixFormat format, absl::string_view message) {
return absl::StrFormat(
"%c%02d%02d %02d:%02d:%02d.%06d %7d %s:%d] %s%s",
absl::LogSeverityName(severity)[0], civil_second.month(),
civil_second.day(), civil_second.hour(), civil_second.minute(),
civil_second.second(), absl::ToInt64Microseconds(subsecond), tid,
basename, line, format == PrefixFormat::kRaw ? "RAW: " : "", message);
}
size_t FormatLogPrefix(absl::LogSeverity severity, absl::Time timestamp,
log_internal::Tid tid, absl::string_view basename,
int line, PrefixFormat format, absl::Span<char>& buf) {
auto prefix_size = FormatBoundedFields(severity, timestamp, tid, buf);
prefix_size += log_internal::AppendTruncated(basename, buf);
prefix_size += FormatLineNumber(line, buf);
if (format == PrefixFormat::kRaw)
prefix_size += log_internal::AppendTruncated("RAW: ", buf);
return prefix_size;
}
}
ABSL_NAMESPACE_END
} | #include <math.h>
#include <iomanip>
#include <ios>
#include <limits>
#include <ostream>
#include <sstream>
#include <string>
#include <type_traits>
#ifdef __ANDROID__
#include <android/api-level.h>
#endif
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/log/check.h"
#include "absl/log/internal/test_matchers.h"
#include "absl/log/log.h"
#include "absl/log/scoped_mock_log.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace {
using ::absl::log_internal::AsString;
using ::absl::log_internal::MatchesOstream;
using ::absl::log_internal::RawEncodedMessage;
using ::absl::log_internal::TextMessage;
using ::absl::log_internal::TextPrefix;
using ::testing::AllOf;
using ::testing::AnyOf;
using ::testing::Each;
using ::testing::EndsWith;
using ::testing::Eq;
using ::testing::Ge;
using ::testing::IsEmpty;
using ::testing::Le;
using ::testing::SizeIs;
using ::testing::Types;
std::ostringstream ComparisonStream() {
std::ostringstream str;
str.setf(std::ios_base::showbase | std::ios_base::boolalpha |
std::ios_base::internal);
return str;
}
TEST(LogFormatTest, NoMessage) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const int log_line = __LINE__ + 1;
auto do_log = [] { LOG(INFO); };
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(ComparisonStream())),
TextPrefix(AsString(EndsWith(absl::StrCat(
" log_format_test.cc:", log_line, "] ")))),
TextMessage(IsEmpty()),
ENCODED_MESSAGE(EqualsProto(R"pb()pb")))));
test_sink.StartCapturingLogs();
do_log();
}
template <typename T>
class CharLogFormatTest : public testing::Test {};
using CharTypes = Types<char, signed char, unsigned char>;
TYPED_TEST_SUITE(CharLogFormatTest, CharTypes);
TYPED_TEST(CharLogFormatTest, Printable) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = 'x';
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("x")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "x" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(CharLogFormatTest, Unprintable) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
constexpr auto value = static_cast<TypeParam>(0xeeu);
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("\xee")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "\xee"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
template <typename T>
class UnsignedIntLogFormatTest : public testing::Test {};
using UnsignedIntTypes = Types<unsigned short, unsigned int,
unsigned long, unsigned long long>;
TYPED_TEST_SUITE(UnsignedIntLogFormatTest, UnsignedIntTypes);
TYPED_TEST(UnsignedIntLogFormatTest, Positive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = 224;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("224")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "224" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(UnsignedIntLogFormatTest, BitfieldPositive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const struct {
TypeParam bits : 6;
} value{42};
auto comparison_stream = ComparisonStream();
comparison_stream << value.bits;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("42")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "42" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value.bits;
}
template <typename T>
class SignedIntLogFormatTest : public testing::Test {};
using SignedIntTypes =
Types<signed short, signed int, signed long, signed long long>;
TYPED_TEST_SUITE(SignedIntLogFormatTest, SignedIntTypes);
TYPED_TEST(SignedIntLogFormatTest, Positive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = 224;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("224")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "224" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(SignedIntLogFormatTest, Negative) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = -112;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("-112")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "-112"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(SignedIntLogFormatTest, BitfieldPositive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const struct {
TypeParam bits : 6;
} value{21};
auto comparison_stream = ComparisonStream();
comparison_stream << value.bits;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("21")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "21" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value.bits;
}
TYPED_TEST(SignedIntLogFormatTest, BitfieldNegative) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const struct {
TypeParam bits : 6;
} value{-21};
auto comparison_stream = ComparisonStream();
comparison_stream << value.bits;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("-21")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "-21" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value.bits;
}
#if !defined(__GNUC__) || defined(__clang__)
enum MyUnsignedEnum {
MyUnsignedEnum_ZERO = 0,
MyUnsignedEnum_FORTY_TWO = 42,
MyUnsignedEnum_TWO_HUNDRED_TWENTY_FOUR = 224,
};
enum MyUnsignedIntEnum : unsigned int {
MyUnsignedIntEnum_ZERO = 0,
MyUnsignedIntEnum_FORTY_TWO = 42,
MyUnsignedIntEnum_TWO_HUNDRED_TWENTY_FOUR = 224,
};
template <typename T>
class UnsignedEnumLogFormatTest : public testing::Test {};
using UnsignedEnumTypes = std::conditional<
std::is_signed<std::underlying_type<MyUnsignedEnum>::type>::value,
Types<MyUnsignedIntEnum>, Types<MyUnsignedEnum, MyUnsignedIntEnum>>::type;
TYPED_TEST_SUITE(UnsignedEnumLogFormatTest, UnsignedEnumTypes);
TYPED_TEST(UnsignedEnumLogFormatTest, Positive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = static_cast<TypeParam>(224);
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("224")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "224" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(UnsignedEnumLogFormatTest, BitfieldPositive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const struct {
TypeParam bits : 6;
} value{static_cast<TypeParam>(42)};
auto comparison_stream = ComparisonStream();
comparison_stream << value.bits;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("42")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "42" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value.bits;
}
enum MySignedEnum {
MySignedEnum_NEGATIVE_ONE_HUNDRED_TWELVE = -112,
MySignedEnum_NEGATIVE_TWENTY_ONE = -21,
MySignedEnum_ZERO = 0,
MySignedEnum_TWENTY_ONE = 21,
MySignedEnum_TWO_HUNDRED_TWENTY_FOUR = 224,
};
enum MySignedIntEnum : signed int {
MySignedIntEnum_NEGATIVE_ONE_HUNDRED_TWELVE = -112,
MySignedIntEnum_NEGATIVE_TWENTY_ONE = -21,
MySignedIntEnum_ZERO = 0,
MySignedIntEnum_TWENTY_ONE = 21,
MySignedIntEnum_TWO_HUNDRED_TWENTY_FOUR = 224,
};
template <typename T>
class SignedEnumLogFormatTest : public testing::Test {};
using SignedEnumTypes = std::conditional<
std::is_signed<std::underlying_type<MyUnsignedEnum>::type>::value,
Types<MyUnsignedEnum, MySignedEnum, MySignedIntEnum>,
Types<MySignedEnum, MySignedIntEnum>>::type;
TYPED_TEST_SUITE(SignedEnumLogFormatTest, SignedEnumTypes);
TYPED_TEST(SignedEnumLogFormatTest, Positive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = static_cast<TypeParam>(224);
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("224")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "224" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(SignedEnumLogFormatTest, Negative) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = static_cast<TypeParam>(-112);
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("-112")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "-112"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(SignedEnumLogFormatTest, BitfieldPositive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const struct {
TypeParam bits : 6;
} value{static_cast<TypeParam>(21)};
auto comparison_stream = ComparisonStream();
comparison_stream << value.bits;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("21")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "21" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value.bits;
}
TYPED_TEST(SignedEnumLogFormatTest, BitfieldNegative) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const struct {
TypeParam bits : 6;
} value{static_cast<TypeParam>(-21)};
auto comparison_stream = ComparisonStream();
comparison_stream << value.bits;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("-21")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "-21" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value.bits;
}
#endif
TEST(FloatLogFormatTest, Positive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const float value = 6.02e23f;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("6.02e+23")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "6.02e+23"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(FloatLogFormatTest, Negative) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const float value = -6.02e23f;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("-6.02e+23")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "-6.02e+23"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(FloatLogFormatTest, NegativeExponent) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const float value = 6.02e-23f;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("6.02e-23")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "6.02e-23"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(DoubleLogFormatTest, Positive) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const double value = 6.02e23;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("6.02e+23")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "6.02e+23"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(DoubleLogFormatTest, Negative) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const double value = -6.02e23;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("-6.02e+23")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "-6.02e+23"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(DoubleLogFormatTest, NegativeExponent) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const double value = 6.02e-23;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("6.02e-23")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "6.02e-23"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
template <typename T>
class FloatingPointLogFormatTest : public testing::Test {};
using FloatingPointTypes = Types<float, double>;
TYPED_TEST_SUITE(FloatingPointLogFormatTest, FloatingPointTypes);
TYPED_TEST(FloatingPointLogFormatTest, Zero) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = 0.0;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("0")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "0" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(FloatingPointLogFormatTest, Integer) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = 1.0;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("1")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "1" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(FloatingPointLogFormatTest, Infinity) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = std::numeric_limits<TypeParam>::infinity();
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(AnyOf(Eq("inf"), Eq("Inf"))),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "inf" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(FloatingPointLogFormatTest, NegativeInfinity) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = -std::numeric_limits<TypeParam>::infinity();
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(AnyOf(Eq("-inf"), Eq("-Inf"))),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "-inf"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(FloatingPointLogFormatTest, NaN) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = std::numeric_limits<TypeParam>::quiet_NaN();
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(AnyOf(Eq("nan"), Eq("NaN"))),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "nan" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(FloatingPointLogFormatTest, NegativeNaN) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value =
std::copysign(std::numeric_limits<TypeParam>::quiet_NaN(), -1.0);
auto comparison_stream = ComparisonStream();
comparison_stream << value;
#ifdef __riscv
EXPECT_CALL(
test_sink,
Send(AllOf(
TextMessage(AnyOf(Eq("-nan"), Eq("nan"), Eq("NaN"), Eq("-nan(ind)"))),
ENCODED_MESSAGE(
AnyOf(EqualsProto(R"pb(value { str: "-nan" })pb"),
EqualsProto(R"pb(value { str: "nan" })pb"),
EqualsProto(R"pb(value { str: "-nan(ind)" })pb"))))));
#else
EXPECT_CALL(
test_sink,
Send(AllOf(
TextMessage(MatchesOstream(comparison_stream)),
TextMessage(AnyOf(Eq("-nan"), Eq("nan"), Eq("NaN"), Eq("-nan(ind)"))),
ENCODED_MESSAGE(
AnyOf(EqualsProto(R"pb(value { str: "-nan" })pb"),
EqualsProto(R"pb(value { str: "nan" })pb"),
EqualsProto(R"pb(value { str: "-nan(ind)" })pb"))))));
#endif
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
template <typename T>
class VoidPtrLogFormatTest : public testing::Test {};
using VoidPtrTypes = Types<void *, const void *>;
TYPED_TEST_SUITE(VoidPtrLogFormatTest, VoidPtrTypes);
TYPED_TEST(VoidPtrLogFormatTest, Null) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = nullptr;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(AnyOf(Eq("(nil)"), Eq("0"), Eq("0x0"),
Eq("00000000"), Eq("0000000000000000"))))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(VoidPtrLogFormatTest, NonNull) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = reinterpret_cast<TypeParam>(0xdeadbeefULL);
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(
TextMessage(MatchesOstream(comparison_stream)),
TextMessage(
AnyOf(Eq("0xdeadbeef"), Eq("DEADBEEF"), Eq("00000000DEADBEEF"))),
ENCODED_MESSAGE(AnyOf(
EqualsProto(R"pb(value { str: "0xdeadbeef" })pb"),
EqualsProto(R"pb(value { str: "00000000DEADBEEF" })pb"))))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
template <typename T>
class VolatilePtrLogFormatTest : public testing::Test {};
using VolatilePtrTypes =
Types<volatile void*, const volatile void*, volatile char*,
const volatile char*, volatile signed char*,
const volatile signed char*, volatile unsigned char*,
const volatile unsigned char*>;
TYPED_TEST_SUITE(VolatilePtrLogFormatTest, VolatilePtrTypes);
TYPED_TEST(VolatilePtrLogFormatTest, Null) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = nullptr;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("false")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "false"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(VolatilePtrLogFormatTest, NonNull) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const TypeParam value = reinterpret_cast<TypeParam>(0xdeadbeefLL);
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("true")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "true"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
template <typename T>
class CharPtrLogFormatTest : public testing::Test {};
using CharPtrTypes = Types<char, const char, signed char, const signed char,
unsigned char, const unsigned char>;
TYPED_TEST_SUITE(CharPtrLogFormatTest, CharPtrTypes);
TYPED_TEST(CharPtrLogFormatTest, Null) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
TypeParam* const value = nullptr;
EXPECT_CALL(
test_sink,
Send(AllOf(
TextMessage(Eq("(null)")),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "(null)" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TYPED_TEST(CharPtrLogFormatTest, NonNull) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
TypeParam data[] = {'v', 'a', 'l', 'u', 'e', '\0'};
TypeParam* const value = data;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("value")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "value"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(BoolLogFormatTest, True) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const bool value = true;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("true")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "true"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(BoolLogFormatTest, False) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
const bool value = false;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("false")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "false"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
TEST(LogFormatTest, StringLiteral) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
auto comparison_stream = ComparisonStream();
comparison_stream << "value";
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("value")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
literal: "value"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << "value";
}
TEST(LogFormatTest, CharArray) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
char value[] = "value";
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("value")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "value"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
class CustomClass {};
std::ostream& operator<<(std::ostream& os, const CustomClass&) {
return os << "CustomClass{}";
}
TEST(LogFormatTest, Custom) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
CustomClass value;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("CustomClass{}")),
ENCODED_MESSAGE(EqualsProto(R"pb(value {
str: "CustomClass{}"
})pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
class CustomClassNonCopyable {
public:
CustomClassNonCopyable() = default;
CustomClassNonCopyable(const CustomClassNonCopyable&) = delete;
CustomClassNonCopyable& operator=(const CustomClassNonCopyable&) = delete;
};
std::ostream& operator<<(std::ostream& os, const CustomClassNonCopyable&) {
return os << "CustomClassNonCopyable{}";
}
TEST(LogFormatTest, CustomNonCopyable) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
CustomClassNonCopyable value;
auto comparison_stream = ComparisonStream();
comparison_stream << value;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(MatchesOstream(comparison_stream)),
TextMessage(Eq("CustomClassNonCopyable{}")),
ENCODED_MESSAGE(EqualsProto(
R"pb(value { str: "CustomClassNonCopyable{}" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << value;
}
struct Point {
template <typename Sink>
friend void AbslStringify(Sink& sink, const Point& p) {
absl::Format(&sink, "(%d, %d)", p.x, p.y);
}
int x = 10;
int y = 20;
};
TEST(LogFormatTest, AbslStringifyExample) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
Point p;
EXPECT_CALL(
test_sink,
Send(AllOf(
TextMessage(Eq("(10, 20)")), TextMessage(Eq(absl::StrCat(p))),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "(10, 20)" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << p;
}
struct PointWithAbslStringifiyAndOstream {
template <typename Sink>
friend void AbslStringify(Sink& sink,
const PointWithAbslStringifiyAndOstream& p) {
absl::Format(&sink, "(%d, %d)", p.x, p.y);
}
int x = 10;
int y = 20;
};
ABSL_ATTRIBUTE_UNUSED std::ostream& operator<<(
std::ostream& os, const PointWithAbslStringifiyAndOstream&) {
return os << "Default to AbslStringify()";
}
TEST(LogFormatTest, CustomWithAbslStringifyAndOstream) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
PointWithAbslStringifiyAndOstream p;
EXPECT_CALL(
test_sink,
Send(AllOf(
TextMessage(Eq("(10, 20)")), TextMessage(Eq(absl::StrCat(p))),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "(10, 20)" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << p;
}
struct PointStreamsNothing {
template <typename Sink>
friend void AbslStringify(Sink&, const PointStreamsNothing&) {}
int x = 10;
int y = 20;
};
TEST(LogFormatTest, AbslStringifyStreamsNothing) {
absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected);
PointStreamsNothing p;
EXPECT_CALL(
test_sink,
Send(AllOf(TextMessage(Eq("77")), TextMessage(Eq(absl::StrCat(p, 77))),
ENCODED_MESSAGE(EqualsProto(R"pb(value { str: "77" })pb")))));
test_sink.StartCapturingLogs();
LOG(INFO) << p << 77;
}
struct PointMultipleAppend |
2,541 | cpp | abseil/abseil-cpp | cord | absl/strings/cord.cc | absl/strings/cord_test.cc | #ifndef ABSL_STRINGS_CORD_H_
#define ABSL_STRINGS_CORD_H_
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iosfwd>
#include <iterator>
#include <string>
#include <type_traits>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/internal/per_thread_tls.h"
#include "absl/base/macros.h"
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
#include "absl/base/port.h"
#include "absl/container/inlined_vector.h"
#include "absl/crc/internal/crc_cord_state.h"
#include "absl/functional/function_ref.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/cord_analysis.h"
#include "absl/strings/cord_buffer.h"
#include "absl/strings/internal/cord_data_edge.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_btree_reader.h"
#include "absl/strings/internal/cord_rep_crc.h"
#include "absl/strings/internal/cordz_functions.h"
#include "absl/strings/internal/cordz_info.h"
#include "absl/strings/internal/cordz_statistics.h"
#include "absl/strings/internal/cordz_update_scope.h"
#include "absl/strings/internal/cordz_update_tracker.h"
#include "absl/strings/internal/resize_uninitialized.h"
#include "absl/strings/internal/string_constant.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Cord;
class CordTestPeer;
template <typename Releaser>
Cord MakeCordFromExternal(absl::string_view, Releaser&&);
void CopyCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
void AppendCordToString(const Cord& src, absl::Nonnull<std::string*> dst);
enum class CordMemoryAccounting {
kTotal,
kTotalMorePrecise,
kFairShare,
};
class Cord {
private:
template <typename T>
using EnableIfString =
absl::enable_if_t<std::is_same<T, std::string>::value, int>;
public:
constexpr Cord() noexcept;
Cord(const Cord& src);
Cord(Cord&& src) noexcept;
Cord& operator=(const Cord& x);
Cord& operator=(Cord&& x) noexcept;
explicit Cord(absl::string_view src);
Cord& operator=(absl::string_view src);
template <typename T, EnableIfString<T> = 0>
explicit Cord(T&& src);
template <typename T, EnableIfString<T> = 0>
Cord& operator=(T&& src);
~Cord() {
if (contents_.is_tree()) DestroyCordSlow();
}
template <typename Releaser>
friend Cord MakeCordFromExternal(absl::string_view data, Releaser&& releaser);
ABSL_ATTRIBUTE_REINITIALIZES void Clear();
void Append(const Cord& src);
void Append(Cord&& src);
void Append(absl::string_view src);
template <typename T, EnableIfString<T> = 0>
void Append(T&& src);
void Append(CordBuffer buffer);
CordBuffer GetAppendBuffer(size_t capacity, size_t min_capacity = 16);
CordBuffer GetCustomAppendBuffer(size_t block_size, size_t capacity,
size_t min_capacity = 16);
void Prepend(const Cord& src);
void Prepend(absl::string_view src);
template <typename T, EnableIfString<T> = 0>
void Prepend(T&& src);
void Prepend(CordBuffer buffer);
void RemovePrefix(size_t n);
void RemoveSuffix(size_t n);
Cord Subcord(size_t pos, size_t new_size) const;
void swap(Cord& other) noexcept;
friend void swap(Cord& x, Cord& y) noexcept { x.swap(y); }
size_t size() const;
bool empty() const;
size_t EstimatedMemoryUsage(CordMemoryAccounting accounting_method =
CordMemoryAccounting::kTotal) const;
int Compare(absl::string_view rhs) const;
int Compare(const Cord& rhs) const;
bool StartsWith(const Cord& rhs) const;
bool StartsWith(absl::string_view rhs) const;
bool EndsWith(absl::string_view rhs) const;
bool EndsWith(const Cord& rhs) const;
bool Contains(absl::string_view rhs) const;
bool Contains(const Cord& rhs) const;
explicit operator std::string() const;
friend void CopyCordToString(const Cord& src,
absl::Nonnull<std::string*> dst);
friend void AppendCordToString(const Cord& src,
absl::Nonnull<std::string*> dst);
class CharIterator;
class ChunkIterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = absl::string_view;
using difference_type = ptrdiff_t;
using pointer = absl::Nonnull<const value_type*>;
using reference = value_type;
ChunkIterator() = default;
ChunkIterator& operator++();
ChunkIterator operator++(int);
bool operator==(const ChunkIterator& other) const;
bool operator!=(const ChunkIterator& other) const;
reference operator*() const;
pointer operator->() const;
friend class Cord;
friend class CharIterator;
private:
using CordRep = absl::cord_internal::CordRep;
using CordRepBtree = absl::cord_internal::CordRepBtree;
using CordRepBtreeReader = absl::cord_internal::CordRepBtreeReader;
explicit ChunkIterator(absl::Nonnull<cord_internal::CordRep*> tree);
explicit ChunkIterator(absl::Nonnull<const Cord*> cord);
void InitTree(absl::Nonnull<cord_internal::CordRep*> tree);
void RemoveChunkPrefix(size_t n);
Cord AdvanceAndReadBytes(size_t n);
void AdvanceBytes(size_t n);
ChunkIterator& AdvanceBtree();
void AdvanceBytesBtree(size_t n);
absl::string_view current_chunk_;
absl::Nullable<absl::cord_internal::CordRep*> current_leaf_ = nullptr;
size_t bytes_remaining_ = 0;
CordRepBtreeReader btree_reader_;
};
ChunkIterator chunk_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
ChunkIterator chunk_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
class ChunkRange {
public:
using value_type = absl::string_view;
using reference = value_type&;
using const_reference = const value_type&;
using iterator = ChunkIterator;
using const_iterator = ChunkIterator;
explicit ChunkRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
ChunkIterator begin() const;
ChunkIterator end() const;
private:
absl::Nonnull<const Cord*> cord_;
};
ChunkRange Chunks() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
class CharIterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = char;
using difference_type = ptrdiff_t;
using pointer = absl::Nonnull<const char*>;
using reference = const char&;
CharIterator() = default;
CharIterator& operator++();
CharIterator operator++(int);
bool operator==(const CharIterator& other) const;
bool operator!=(const CharIterator& other) const;
reference operator*() const;
pointer operator->() const;
friend Cord;
private:
explicit CharIterator(absl::Nonnull<const Cord*> cord)
: chunk_iterator_(cord) {}
ChunkIterator chunk_iterator_;
};
static Cord AdvanceAndRead(absl::Nonnull<CharIterator*> it, size_t n_bytes);
static void Advance(absl::Nonnull<CharIterator*> it, size_t n_bytes);
static absl::string_view ChunkRemaining(const CharIterator& it);
CharIterator char_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
CharIterator char_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
class CharRange {
public:
using value_type = char;
using reference = value_type&;
using const_reference = const value_type&;
using iterator = CharIterator;
using const_iterator = CharIterator;
explicit CharRange(absl::Nonnull<const Cord*> cord) : cord_(cord) {}
CharIterator begin() const;
CharIterator end() const;
private:
absl::Nonnull<const Cord*> cord_;
};
CharRange Chars() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
char operator[](size_t i) const;
absl::optional<absl::string_view> TryFlat() const
ABSL_ATTRIBUTE_LIFETIME_BOUND;
absl::string_view Flatten() ABSL_ATTRIBUTE_LIFETIME_BOUND;
CharIterator Find(absl::string_view needle) const;
CharIterator Find(const absl::Cord& needle) const;
friend void AbslFormatFlush(absl::Nonnull<absl::Cord*> cord,
absl::string_view part) {
cord->Append(part);
}
template <typename Sink>
friend void AbslStringify(Sink& sink, const absl::Cord& cord) {
for (absl::string_view chunk : cord.Chunks()) {
sink.Append(chunk);
}
} | #include "absl/strings/cord.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <iterator>
#include <limits>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/macros.h"
#include "absl/base/no_destructor.h"
#include "absl/base/options.h"
#include "absl/container/fixed_array.h"
#include "absl/functional/function_ref.h"
#include "absl/hash/hash.h"
#include "absl/hash/hash_testing.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/random/random.h"
#include "absl/strings/cord_buffer.h"
#include "absl/strings/cord_test_helpers.h"
#include "absl/strings/cordz_test_helpers.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_crc.h"
#include "absl/strings/internal/cord_rep_flat.h"
#include "absl/strings/internal/cordz_statistics.h"
#include "absl/strings/internal/cordz_update_tracker.h"
#include "absl/strings/internal/string_constant.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
static constexpr auto FLAT = absl::cord_internal::FLAT;
static constexpr auto MAX_FLAT_TAG = absl::cord_internal::MAX_FLAT_TAG;
typedef std::mt19937_64 RandomEngine;
using absl::cord_internal::CordRep;
using absl::cord_internal::CordRepBtree;
using absl::cord_internal::CordRepConcat;
using absl::cord_internal::CordRepCrc;
using absl::cord_internal::CordRepExternal;
using absl::cord_internal::CordRepFlat;
using absl::cord_internal::CordRepSubstring;
using absl::cord_internal::CordzUpdateTracker;
using absl::cord_internal::kFlatOverhead;
using absl::cord_internal::kMaxFlatLength;
using ::testing::ElementsAre;
using ::testing::Le;
static std::string RandomLowercaseString(RandomEngine* rng);
static std::string RandomLowercaseString(RandomEngine* rng, size_t length);
static int GetUniformRandomUpTo(RandomEngine* rng, int upper_bound) {
if (upper_bound > 0) {
std::uniform_int_distribution<int> uniform(0, upper_bound - 1);
return uniform(*rng);
} else {
return 0;
}
}
static size_t GetUniformRandomUpTo(RandomEngine* rng, size_t upper_bound) {
if (upper_bound > 0) {
std::uniform_int_distribution<size_t> uniform(0, upper_bound - 1);
return uniform(*rng);
} else {
return 0;
}
}
static int32_t GenerateSkewedRandom(RandomEngine* rng, int max_log) {
const uint32_t base = (*rng)() % (max_log + 1);
const uint32_t mask = ((base < 32) ? (1u << base) : 0u) - 1u;
return (*rng)() & mask;
}
static std::string RandomLowercaseString(RandomEngine* rng) {
int length;
std::bernoulli_distribution one_in_1k(0.001);
std::bernoulli_distribution one_in_10k(0.0001);
if (one_in_10k(*rng)) {
length = GetUniformRandomUpTo(rng, 1048576);
} else if (one_in_1k(*rng)) {
length = GetUniformRandomUpTo(rng, 10000);
} else {
length = GenerateSkewedRandom(rng, 10);
}
return RandomLowercaseString(rng, length);
}
static std::string RandomLowercaseString(RandomEngine* rng, size_t length) {
std::string result(length, '\0');
std::uniform_int_distribution<int> chars('a', 'z');
std::generate(result.begin(), result.end(),
[&]() { return static_cast<char>(chars(*rng)); });
return result;
}
static void DoNothing(absl::string_view , void* ) {}
static void DeleteExternalString(absl::string_view data, void* arg) {
std::string* s = reinterpret_cast<std::string*>(arg);
EXPECT_EQ(data, *s);
delete s;
}
static void AddExternalMemory(absl::string_view s, absl::Cord* dst) {
std::string* str = new std::string(s.data(), s.size());
dst->Append(absl::MakeCordFromExternal(*str, [str](absl::string_view data) {
DeleteExternalString(data, str);
}));
}
static void DumpGrowth() {
absl::Cord str;
for (int i = 0; i < 1000; i++) {
char c = 'a' + i % 26;
str.Append(absl::string_view(&c, 1));
}
}
static size_t AppendWithFragments(const std::string& s, RandomEngine* rng,
absl::Cord* cord) {
size_t j = 0;
const size_t max_size = s.size() / 5;
size_t min_size = max_size;
while (j < s.size()) {
size_t N = 1 + GetUniformRandomUpTo(rng, max_size);
if (N > (s.size() - j)) {
N = s.size() - j;
}
if (N < min_size) {
min_size = N;
}
std::bernoulli_distribution coin_flip(0.5);
if (coin_flip(*rng)) {
AddExternalMemory(absl::string_view(s.data() + j, N), cord);
} else {
cord->Append(absl::string_view(s.data() + j, N));
}
j += N;
}
return min_size;
}
static void AddNewStringBlock(const std::string& str, absl::Cord* dst) {
char* data = new char[str.size()];
memcpy(data, str.data(), str.size());
dst->Append(absl::MakeCordFromExternal(
absl::string_view(data, str.size()),
[](absl::string_view s) { delete[] s.data(); }));
}
static absl::Cord MakeComposite() {
absl::Cord cord;
cord.Append("the");
AddExternalMemory(" quick brown", &cord);
AddExternalMemory(" fox jumped", &cord);
absl::Cord full(" over");
AddExternalMemory(" the lazy", &full);
AddNewStringBlock(" dog slept the whole day away", &full);
absl::Cord substring = full.Subcord(0, 18);
substring.Append(std::string(1000, '.'));
cord.Append(substring);
cord = cord.Subcord(0, cord.size() - 998);
return cord;
}
namespace absl {
ABSL_NAMESPACE_BEGIN
class CordTestPeer {
public:
static void ForEachChunk(
const Cord& c, absl::FunctionRef<void(absl::string_view)> callback) {
c.ForEachChunk(callback);
}
static bool IsTree(const Cord& c) { return c.contents_.is_tree(); }
static CordRep* Tree(const Cord& c) { return c.contents_.tree(); }
static cord_internal::CordzInfo* GetCordzInfo(const Cord& c) {
return c.contents_.cordz_info();
}
static Cord MakeSubstring(Cord src, size_t offset, size_t length) {
CHECK(src.contents_.is_tree()) << "Can not be inlined";
CHECK(!src.ExpectedChecksum().has_value()) << "Can not be hardened";
Cord cord;
auto* tree = cord_internal::SkipCrcNode(src.contents_.tree());
auto* rep = CordRepSubstring::Create(CordRep::Ref(tree), offset, length);
cord.contents_.EmplaceTree(rep, CordzUpdateTracker::kSubCord);
return cord;
}
};
ABSL_NAMESPACE_END
}
class CordTest : public testing::TestWithParam<bool > {
public:
bool UseCrc() const { return GetParam(); }
void MaybeHarden(absl::Cord& c) {
if (UseCrc()) {
c.SetExpectedChecksum(1);
}
}
absl::Cord MaybeHardened(absl::Cord c) {
MaybeHarden(c);
return c;
}
static std::string ToString(testing::TestParamInfo<bool> useCrc) {
if (useCrc.param) {
return "BtreeHardened";
} else {
return "Btree";
}
}
};
INSTANTIATE_TEST_SUITE_P(WithParam, CordTest, testing::Bool(),
CordTest::ToString);
TEST(CordRepFlat, AllFlatCapacities) {
static_assert(absl::cord_internal::kFlatOverhead < 32, "");
static_assert(absl::cord_internal::kMinFlatSize == 32, "");
static_assert(absl::cord_internal::kMaxLargeFlatSize == 256 << 10, "");
EXPECT_EQ(absl::cord_internal::TagToAllocatedSize(FLAT), 32);
EXPECT_EQ(absl::cord_internal::TagToAllocatedSize(MAX_FLAT_TAG), 256 << 10);
size_t last_size = 0;
for (int tag = FLAT; tag <= MAX_FLAT_TAG; ++tag) {
size_t size = absl::cord_internal::TagToAllocatedSize(tag);
ASSERT_GT(size, last_size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
last_size = size;
}
for (size_t size = 32; size <= 512; size += 8) {
ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size);
uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
}
for (size_t size = 512; size <= 8192; size += 64) {
ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size);
uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
}
for (size_t size = 8192; size <= 256 * 1024; size += 4 * 1024) {
ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size);
uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
}
}
TEST(CordRepFlat, MaxFlatSize) {
CordRepFlat* flat = CordRepFlat::New(kMaxFlatLength);
EXPECT_EQ(flat->Capacity(), kMaxFlatLength);
CordRep::Unref(flat);
flat = CordRepFlat::New(kMaxFlatLength * 4);
EXPECT_EQ(flat->Capacity(), kMaxFlatLength);
CordRep::Unref(flat);
}
TEST(CordRepFlat, MaxLargeFlatSize) {
const size_t size = 256 * 1024 - kFlatOverhead;
CordRepFlat* flat = CordRepFlat::New(CordRepFlat::Large(), size);
EXPECT_GE(flat->Capacity(), size);
CordRep::Unref(flat);
}
TEST(CordRepFlat, AllFlatSizes) {
const size_t kMaxSize = 256 * 1024;
for (size_t size = 32; size <= kMaxSize; size *=2) {
const size_t length = size - kFlatOverhead - 1;
CordRepFlat* flat = CordRepFlat::New(CordRepFlat::Large(), length);
EXPECT_GE(flat->Capacity(), length);
memset(flat->Data(), 0xCD, flat->Capacity());
CordRep::Unref(flat);
}
}
TEST_P(CordTest, AllFlatSizes) {
using absl::strings_internal::CordTestAccess;
for (size_t s = 0; s < CordTestAccess::MaxFlatLength(); s++) {
std::string src;
while (src.size() < s) {
src.push_back('a' + (src.size() % 26));
}
absl::Cord dst(src);
MaybeHarden(dst);
EXPECT_EQ(std::string(dst), src) << s;
}
}
TEST_P(CordTest, GigabyteCordFromExternal) {
const size_t one_gig = 1024U * 1024U * 1024U;
size_t max_size = 2 * one_gig;
if (sizeof(max_size) > 4) max_size = 128 * one_gig;
size_t length = 128 * 1024;
char* data = new char[length];
absl::Cord from = absl::MakeCordFromExternal(
absl::string_view(data, length),
[](absl::string_view sv) { delete[] sv.data(); });
absl::Cord c;
c.Append(from);
while (c.size() < max_size) {
c.Append(c);
c.Append(from);
c.Append(from);
c.Append(from);
c.Append(from);
MaybeHarden(c);
}
for (int i = 0; i < 1024; ++i) {
c.Append(from);
}
LOG(INFO) << "Made a Cord with " << c.size() << " bytes!";
}
static absl::Cord MakeExternalCord(int size) {
char* buffer = new char[size];
memset(buffer, 'x', size);
absl::Cord cord;
cord.Append(absl::MakeCordFromExternal(
absl::string_view(buffer, size),
[](absl::string_view s) { delete[] s.data(); }));
return cord;
}
extern bool my_unique_true_boolean;
bool my_unique_true_boolean = true;
TEST_P(CordTest, Assignment) {
absl::Cord x(absl::string_view("hi there"));
absl::Cord y(x);
MaybeHarden(y);
ASSERT_EQ(x.ExpectedChecksum(), absl::nullopt);
ASSERT_EQ(std::string(x), "hi there");
ASSERT_EQ(std::string(y), "hi there");
ASSERT_TRUE(x == y);
ASSERT_TRUE(x <= y);
ASSERT_TRUE(y <= x);
x = absl::string_view("foo");
ASSERT_EQ(std::string(x), "foo");
ASSERT_EQ(std::string(y), "hi there");
ASSERT_TRUE(x < y);
ASSERT_TRUE(y > x);
ASSERT_TRUE(x != y);
ASSERT_TRUE(x <= y);
ASSERT_TRUE(y >= x);
x = "foo";
ASSERT_EQ(x, "foo");
std::vector<std::pair<absl::string_view, absl::string_view>>
test_string_pairs = {{"hi there", "foo"},
{"loooooong coooooord", "short cord"},
{"short cord", "loooooong coooooord"},
{"loooooong coooooord1", "loooooong coooooord2"}};
for (std::pair<absl::string_view, absl::string_view> test_strings :
test_string_pairs) {
absl::Cord tmp(test_strings.first);
absl::Cord z(std::move(tmp));
ASSERT_EQ(std::string(z), test_strings.first);
tmp = test_strings.second;
z = std::move(tmp);
ASSERT_EQ(std::string(z), test_strings.second);
}
{
absl::Cord my_small_cord("foo");
absl::Cord my_big_cord("loooooong coooooord");
absl::Cord* my_small_alias =
my_unique_true_boolean ? &my_small_cord : &my_big_cord;
absl::Cord* my_big_alias =
!my_unique_true_boolean ? &my_small_cord : &my_big_cord;
*my_small_alias = std::move(my_small_cord);
*my_big_alias = std::move(my_big_cord);
}
}
TEST_P(CordTest, StartsEndsWith) {
absl::Cord x(absl::string_view("abcde"));
MaybeHarden(x);
absl::Cord empty("");
ASSERT_TRUE(x.StartsWith(absl::Cord("abcde")));
ASSERT_TRUE(x.StartsWith(absl::Cord("abc")));
ASSERT_TRUE(x.StartsWith(absl::Cord("")));
ASSERT_TRUE(empty.StartsWith(absl::Cord("")));
ASSERT_TRUE(x.EndsWith(absl::Cord("abcde")));
ASSERT_TRUE(x.EndsWith(absl::Cord("cde")));
ASSERT_TRUE(x.EndsWith(absl::Cord("")));
ASSERT_TRUE(empty.EndsWith(absl::Cord("")));
ASSERT_TRUE(!x.StartsWith(absl::Cord("xyz")));
ASSERT_TRUE(!empty.StartsWith(absl::Cord("xyz")));
ASSERT_TRUE(!x.EndsWith(absl::Cord("xyz")));
ASSERT_TRUE(!empty.EndsWith(absl::Cord("xyz")));
ASSERT_TRUE(x.StartsWith("abcde"));
ASSERT_TRUE(x.StartsWith("abc"));
ASSERT_TRUE(x.StartsWith(""));
ASSERT_TRUE(empty.StartsWith(""));
ASSERT_TRUE(x.EndsWith("abcde"));
ASSERT_TRUE(x.EndsWith("cde"));
ASSERT_TRUE(x.EndsWith(""));
ASSERT_TRUE(empty.EndsWith(""));
ASSERT_TRUE(!x.StartsWith("xyz"));
ASSERT_TRUE(!empty.StartsWith("xyz"));
ASSERT_TRUE(!x.EndsWith("xyz"));
ASSERT_TRUE(!empty.EndsWith("xyz"));
}
TEST_P(CordTest, Contains) {
auto flat_haystack = absl::Cord("this is a flat cord");
auto fragmented_haystack = absl::MakeFragmentedCord(
{"this", " ", "is", " ", "a", " ", "fragmented", " ", "cord"});
EXPECT_TRUE(flat_haystack.Contains(""));
EXPECT_TRUE(fragmented_haystack.Contains(""));
EXPECT_TRUE(flat_haystack.Contains(absl::Cord("")));
EXPECT_TRUE(fragmented_haystack.Contains(absl::Cord("")));
EXPECT_TRUE(absl::Cord("").Contains(""));
EXPECT_TRUE(absl::Cord("").Contains(absl::Cord("")));
EXPECT_FALSE(absl::Cord("").Contains(flat_haystack));
EXPECT_FALSE(absl::Cord("").Contains(fragmented_haystack));
EXPECT_FALSE(flat_haystack.Contains("z"));
EXPECT_FALSE(fragmented_haystack.Contains("z"));
EXPECT_FALSE(flat_haystack.Contains(absl::Cord("z")));
EXPECT_FALSE(fragmented_haystack.Contains(absl::Cord("z")));
EXPECT_FALSE(flat_haystack.Contains("is an"));
EXPECT_FALSE(fragmented_haystack.Contains("is an"));
EXPECT_FALSE(flat_haystack.Contains(absl::Cord("is an")));
EXPECT_FALSE(fragmented_haystack.Contains(absl::Cord("is an")));
EXPECT_FALSE(
flat_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "an"})));
EXPECT_FALSE(fragmented_haystack.Contains(
absl::MakeFragmentedCord({"is", " ", "an"})));
EXPECT_TRUE(flat_haystack.Contains("is a"));
EXPECT_TRUE(fragmented_haystack.Contains("is a"));
EXPECT_TRUE(flat_haystack.Contains(absl::Cord("is a")));
EXPECT_TRUE(fragmented_haystack.Contains(absl::Cord("is a")));
EXPECT_TRUE(
flat_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "a"})));
EXPECT_TRUE(
fragmented_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "a"})));
}
TEST_P(CordTest, Find) {
auto flat_haystack = absl::Cord("this is a flat cord");
auto fragmented_haystack = absl::MakeFragmentedCord(
{"this", " ", "is", " ", "a", " ", "fragmented", " ", "cord"});
auto empty_haystack = absl::Cord("");
EXPECT_EQ(flat_haystack.Find(""), flat_haystack.char_begin());
EXPECT_EQ(fragmented_haystack.Find(""), fragmented_haystack.char_begin());
EXPECT_EQ(flat_haystack.Find(absl::Cord("")), flat_haystack.char_begin());
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("")),
fragmented_haystack.char_begin());
EXPECT_EQ(empty_haystack.Find(""), empty_haystack.char_begin());
EXPECT_EQ(empty_haystack.Find(absl::Cord("")), empty_haystack.char_begin());
EXPECT_EQ(empty_haystack.Find(flat_haystack), empty_haystack.char_end());
EXPECT_EQ(empty_haystack.Find(fragmented_haystack),
empty_haystack.char_end());
EXPECT_EQ(flat_haystack.Find("z"), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find("z"), fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find(absl::Cord("z")), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("z")),
fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find("is an"), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find("is an"), fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find(absl::Cord("is an")), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("is an")),
fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find(absl::MakeFragmentedCord({"is", " ", "an"})),
flat_haystack.char_end());
EXPECT_EQ(
fragmented_haystack.Find(absl::MakeFragmentedCord({"is", " ", "an"})),
fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find("is a"),
std::next(flat_haystack.char_begin(), 5));
EXPECT_EQ(fragmented_haystack.Find("is a"),
std::next(fragmented_haystack.char_begin(), 5));
EXPECT_EQ(flat_haystack.Find(absl::Cord("is a")),
std::next(flat_haystack.char_begin(), 5));
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("is a")),
std::next(fragmented_haystack.char_begin(), 5));
EXPECT_EQ(flat_haystack.Find(absl::MakeFragmentedCord({"is", " ", "a"})),
std::next(flat_haystack.char_begin(), 5));
EXPECT_EQ(
fragmented_haystack.Find(absl::MakeFragmentedCord({"is", " ", "a"})),
std::next(fragmented_haystack.char_begin(), 5));
}
TEST_P(CordTest, Subcord) {
RandomEngine rng(GTEST_FLAG_GET(random_seed));
const std::string s = RandomLowercaseString(&rng, 1024);
absl::Cord a;
AppendWithFragments(s, &rng, &a);
MaybeHarden(a);
ASSERT_EQ(s, std::string(a));
std::set<size_t> positions;
for (int i = 0; i <= 32; ++i) {
positions.insert(i);
positions.insert(i * 32 - 1);
positions.insert(i * 32);
positions.insert(i * 32 + 1);
positions.insert(a.size() - i);
}
positions.insert(237);
positions.insert(732);
for (size_t pos : positions) {
if (pos > a.size()) continue;
for (size_t end_pos : positions) {
if (end_pos < pos || end_pos > a.size()) continue;
absl::Cord sa = a.Subcord(pos, end_pos - pos);
ASSERT_EQ(absl::string_view(s).substr(pos, end_pos - pos),
std::string(sa))
<< a;
if (pos != 0 || end_pos != a.size()) {
ASSERT_EQ(sa.ExpectedChecksum(), absl::nullopt);
}
}
}
const std::string sh = "short";
absl::Cord c(sh);
for (size_t pos = 0; pos <= sh.size(); ++pos) {
for (size_t n = 0; n <= sh.size() - pos; ++n) {
absl::Cord sc = c.Subcord(pos, n);
ASSERT_EQ(sh.substr(pos, n), std::string(sc)) << c;
}
}
absl::Cord sa = a.Subcord(0, a.size());
std::string ss = s.substr(0, s.size());
while (sa.size() > 1) {
sa = sa.Subcord(1, sa.size() - 2);
ss = ss.substr(1, ss.size() - 2);
ASSERT_EQ(ss, std::string(sa)) << a;
if (HasFailure()) break;
}
sa = a.Subcord(0, a.size() + 1);
EXPECT_EQ(s, std::string(sa));
sa = a.Subcord(a.size() + 1, 0);
EXPECT_TRUE(sa.empty());
sa = a.Subcord(a.size() + 1, 1);
EXPECT_TRUE(sa.empty());
}
TEST_P(CordTest, Swap) {
absl::string_view a("Dexter");
absl::string_view b("Mandark");
absl::Cord x(a);
absl::Cord y(b);
MaybeHarden(x);
swap(x, y);
if (UseCrc()) {
ASSERT_EQ(x.ExpectedChecksum(), absl::nullopt);
ASSERT_EQ(y.ExpectedChecksum(), 1);
}
ASSERT_EQ(x, absl::Cord(b));
ASSERT_EQ(y, absl::Cord(a));
x.swap(y);
if (UseCrc()) {
ASSERT_EQ(x.ExpectedChecksum(), 1);
ASSERT_EQ(y.ExpectedChecksum(), absl::nullopt);
}
ASSERT_EQ(x, absl::Cord(a));
ASSERT_EQ(y, absl::Cord(b));
}
static void VerifyCopyToString(const absl::Cord& cord) {
std::string initially_empty;
absl::CopyCordToString(cord, &initially_empty);
EXPECT_EQ(initially_empty, cord);
constexpr size_t kInitialLength = 1024;
std::string has_initial_contents(kInitialLength, 'x');
const char* address_before_copy = has_initial_contents.data();
absl::CopyCordToString(cord, &has_initial_contents);
EXPECT_EQ(has_initial_contents, cord);
if (cord.size() <= kInitialLength) {
EXPECT_EQ(has_initial_contents.data(), address_before_copy)
<< "CopyCordToString allocated new string storage; "
"has_initial_contents = \""
<< has_initial_contents << "\"";
}
}
TEST_P(CordTest, CopyToString) {
VerifyCopyToString(absl::Cord());
VerifyCopyToString(MaybeHardened(absl::Cord("small cord")));
VerifyCopyToString(MaybeHardened(
absl::MakeFragmentedCord({"fragmented ", "cord ", "to ", "test ",
"copying ", "to ", "a ", "string."})));
}
static void VerifyAppendCordToString(const absl::Cord& cord) {
std::string initially_empty;
absl::AppendCordToString(cord, &initially_empty);
EXPECT_EQ(initially_empty, cord);
const absl::string_view kInitialContents = "initial contents.";
std::string expected_after_append =
absl::StrCat(kInitialContents, std::string(cord));
std::string no_reserve(kInitialContents);
absl::AppendCordToString(cord, &no_reserve);
EXPECT_EQ(no_reserve, expected_after_append);
std::string has_reserved_capacity(kInitialContents);
has_reserved_capacity.reserve(has_reserved_capacity.size() + cord.size());
const char* address_before_copy = has_reserved_capacity.data();
absl::AppendCordToString(cord, &has_reserved_capacity);
EXPECT_EQ(has_reserved_capacity, expected_after_append);
EXPECT_EQ(has_reserved_capacity.data(), address_before_copy)
<< "AppendCordToString allocated new string storage; "
"has_reserved_capacity = \""
<< has_reserved_capacity << "\"";
}
TEST_P(CordTest, AppendToString) {
VerifyAppendCordToString(absl::Cord());
VerifyAppendCordToString(MaybeHardened(absl::Cord("small cord")));
VerifyAppendCordToString(MaybeHardened(
absl::MakeFragmentedCord({"fragmented ", "cord ", "to ", "test ",
"appending ", "to ", "a ", "string."})));
}
TEST_P(CordTest, AppendEmptyBuffer) {
absl::Cord cord;
cord.Append(absl::CordBuffer());
cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000));
}
TEST_P(CordTest, AppendEmptyBufferToFlat) {
absl::Cord cord(std::string(2000, 'x'));
cord.Append(absl::CordBuffer());
cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000));
}
TEST_P(CordTest, AppendEmptyBufferToTree) {
absl::Cord cord(std::string(2000, 'x'));
cord.Append(std::string(2000, 'y'));
cord.Append(absl::CordBuffer());
cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000));
}
TEST_P(CordTest, AppendSmallBuffer) {
absl::Cord cord;
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
ASSERT_THAT(buffer.capacity(), Le(15));
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "defgh", 5);
buffer.SetLength(5);
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
EXPECT_THAT(cord.Chunks(), ElementsAre("Abcdefgh"));
}
TEST_P(CordTest, AppendAndPrependBufferArePrecise) {
std::string test_data(absl::cord_internal::kMaxFlatLength * 10, 'x');
absl::Cord cord1(test_data);
absl::Cord cord2(test_data);
const size_t size1 = cord1.EstimatedMemoryUsage();
const size_t size2 = cord2.EstimatedMemoryUsage();
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord1.Append(std::move(buffer));
buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord2.Prepend(std::move(buffer));
#ifndef NDEBUG
constexpr size_t kMaxDelta = 128 + 32;
#else
constexpr size_t kMaxDelta = 128 + 32 + 256;
#endif
EXPECT_LE(cord1.EstimatedMemoryUsage() - size1, kMaxDelta);
EXPECT_LE(cord2.EstimatedMemoryUsage() - size2, kMaxDelta);
EXPECT_EQ(cord1, absl::StrCat(test_data, "Abc"));
EXPECT_EQ(cord2, absl::StrCat("Abc", test_data));
}
TEST_P(CordTest, PrependSmallBuffer) {
absl::Cord cord;
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
ASSERT_THAT(buffer.capacity(), Le(15));
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "defgh", 5);
buffer.SetLength(5);
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
EXPECT_THAT(cord.Chunks(), ElementsAre("defghAbc"));
}
TEST_P(CordTest, AppendLargeBuffer) {
absl::Cord cord;
std::string s1(700, '1');
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(s1.size());
memcpy(buffer.data(), s1.data(), s1.size());
buffer.SetLength(s1.size());
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
std::string s2(1000, '2');
buffer = absl::CordBuffer::CreateWithDefaultLimit(s2.size());
memcpy(buffer.data(), s2.data(), s2.size());
buffer.SetLength(s2.size());
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
EXPECT_THAT(cord.Chunks(), ElementsAre(s1, s2));
}
TEST_P(CordTest, PrependLargeBuffer) {
absl::Cord cord;
std::string s1(700, '1');
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(s1.size());
memcpy(buffer.data(), s1.data(), s1.size());
buffer.SetLength(s1.size());
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
std::string s2(1000, '2');
buffer = absl::CordBuffer::CreateWithDefaultLimit(s2.size());
memcpy(buffer.data(), s2.data(), s2.size());
buffer.SetLength(s2.size());
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0);
EXPECT_GT(buffer.capacity(), 0);
EXPECT_THAT(cord.Chunks(), ElementsAre(s2, s1));
}
class CordAppendBufferTest : public testing::TestWithParam<bool> {
public:
size_t is_default() const { return GetParam(); }
static std::string ToString(testing::TestParamInfo<bool> param) {
return param.param ? "DefaultLimit" : "CustomLimit";
}
size_t limit() const {
return is_default() ? absl::CordBuffer::kDefaultLimit
: absl::CordBuffer::kCustomLimit;
}
size_t maximum_payload() const {
return is_default() ? absl::CordBuffer::MaximumPayload()
: absl::CordBuffer::MaximumPayload(limit());
}
absl::CordBuffer GetAppendBuffer(absl::Cord& cord, size_t capacity,
size_t min_capacity = 16) {
return is_default()
? cord.GetAppendBuffer(capacity, min_capacity)
: cord.GetCustomAppendBuffer(limit(), capacity, min_capacity);
}
};
INSTANTIATE_TEST_SUITE_P(WithParam, CordAppendBufferTest, testing::Bool(),
CordAppendBufferTest::ToString);
TEST_P(CordAppendBufferTest, GetAppendBufferOnEmptyCord) {
absl::Cord cord;
absl::CordBuffer buffer = GetAppendBuffer(cord, 1000);
EXPECT_GE(buffer.capacity(), 1000);
EXPECT_EQ(buffer.length(), 0);
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnInlinedCord) {
static constexpr int kInlinedSize = sizeof(absl::CordBuffer) - 1;
for (int size : {6, kInlinedSize - 3, kInlinedSize - 2, 1000}) {
absl::Cord cord("Abc");
absl::CordBuffer buffer = GetAppendBuffer(cord, size, 1);
EXPECT_GE(buffer.capacity(), 3 + size);
EXPECT_EQ(buffer.length(), 3);
EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc");
EXPECT_TRUE(cord.empty());
}
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnInlinedCordCapacityCloseToMax) {
for (size_t dist_from_max = 0; dist_from_max <= 4; ++dist_from_max) {
absl::Cord cord("Abc");
size_t size = std::numeric_limits<size_t>::max() - dist_from_max;
absl::CordBuffer buffer = GetAppendBuffer(cord, size, 1);
EXPECT_GE(buffer.capacity(), maximum_payload());
EXPECT_EQ(buffer.length(), 3);
EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc");
EXPECT_TRUE(cord.empty());
}
}
TEST_P(CordAppendBufferTest, GetAppend |
2,542 | cpp | abseil/abseil-cpp | substitute | absl/strings/substitute.cc | absl/strings/substitute_test.cc | #ifndef ABSL_STRINGS_SUBSTITUTE_H_
#define ABSL_STRINGS_SUBSTITUTE_H_
#include <cstring>
#include <string>
#include <type_traits>
#include <vector>
#include "absl/base/macros.h"
#include "absl/base/nullability.h"
#include "absl/base/port.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/internal/stringify_sink.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace substitute_internal {
class Arg {
public:
Arg(absl::Nullable<const char*> value)
: piece_(absl::NullSafeStringView(value)) {}
template <typename Allocator>
Arg(
const std::basic_string<char, std::char_traits<char>, Allocator>&
value) noexcept
: piece_(value) {}
Arg(absl::string_view value)
: piece_(value) {}
Arg(char value)
: piece_(scratch_, 1) {
scratch_[0] = value;
}
Arg(short value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(unsigned short value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(int value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(unsigned int value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(long value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(unsigned long value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(long long value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(unsigned long long value)
: piece_(scratch_,
static_cast<size_t>(
numbers_internal::FastIntToBuffer(value, scratch_) -
scratch_)) {}
Arg(float value)
: piece_(scratch_, numbers_internal::SixDigitsToBuffer(value, scratch_)) {
}
Arg(double value)
: piece_(scratch_, numbers_internal::SixDigitsToBuffer(value, scratch_)) {
}
Arg(bool value)
: piece_(value ? "true" : "false") {}
template <typename T, typename = typename std::enable_if<
HasAbslStringify<T>::value>::type>
Arg(
const T& v, strings_internal::StringifySink&& sink = {})
: piece_(strings_internal::ExtractStringification(sink, v)) {}
Arg(Hex hex);
Arg(Dec dec);
template <typename T,
absl::enable_if_t<
std::is_class<T>::value &&
(std::is_same<T, std::vector<bool>::reference>::value ||
std::is_same<T, std::vector<bool>::const_reference>::value)>* =
nullptr>
Arg(T value)
: Arg(static_cast<bool>(value)) {}
Arg(
absl::Nullable<const void*> value);
template <typename T,
typename = typename std::enable_if<
std::is_enum<T>{} && !std::is_convertible<T, int>{} &&
!HasAbslStringify<T>::value>::type>
Arg(T value)
: Arg(static_cast<typename std::underlying_type<T>::type>(value)) {}
Arg(const Arg&) = delete;
Arg& operator=(const Arg&) = delete;
absl::string_view piece() const { return piece_; }
private:
absl::string_view piece_;
char scratch_[numbers_internal::kFastToBufferSize];
};
void SubstituteAndAppendArray(
absl::Nonnull<std::string*> output, absl::string_view format,
absl::Nullable<const absl::string_view*> args_array, size_t num_args);
#if defined(ABSL_BAD_CALL_IF)
constexpr int CalculateOneBit(absl::Nonnull<const char*> format) {
return (*format < '0' || *format > '9') ? (*format == '$' ? 0 : -1)
: (1 << (*format - '0'));
}
constexpr const char* SkipNumber(absl::Nonnull<const char*> format) {
return !*format ? format : (format + 1);
}
constexpr int PlaceholderBitmask(absl::Nonnull<const char*> format) {
return !*format
? 0
: *format != '$' ? PlaceholderBitmask(format + 1)
: (CalculateOneBit(format + 1) |
PlaceholderBitmask(SkipNumber(format + 1)));
}
#endif
}
inline void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::string_view format) {
substitute_internal::SubstituteAndAppendArray(output, format, nullptr, 0);
}
inline void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::string_view format,
const substitute_internal::Arg& a0) {
const absl::string_view args[] = {a0.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::string_view format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1) {
const absl::string_view args[] = {a0.piece(), a1.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::string_view format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2) {
const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::string_view format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3) {
const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(),
a3.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::string_view format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4) {
const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(),
a3.piece(), a4.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::string_view format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5) {
const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(),
a3.piece(), a4.piece(), a5.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::string_view format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6) {
const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(),
a3.piece(), a4.piece(), a5.piece(),
a6.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::string_view format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6, const substitute_internal::Arg& a7) {
const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(),
a3.piece(), a4.piece(), a5.piece(),
a6.piece(), a7.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::string_view format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6, const substitute_internal::Arg& a7,
const substitute_internal::Arg& a8) {
const absl::string_view args[] = {a0.piece(), a1.piece(), a2.piece(),
a3.piece(), a4.piece(), a5.piece(),
a6.piece(), a7.piece(), a8.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
inline void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::string_view format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6, const substitute_internal::Arg& a7,
const substitute_internal::Arg& a8, const substitute_internal::Arg& a9) {
const absl::string_view args[] = {
a0.piece(), a1.piece(), a2.piece(), a3.piece(), a4.piece(),
a5.piece(), a6.piece(), a7.piece(), a8.piece(), a9.piece()};
substitute_internal::SubstituteAndAppendArray(output, format, args,
ABSL_ARRAYSIZE(args));
}
#if defined(ABSL_BAD_CALL_IF)
void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::Nonnull<const char*> format)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 0,
"There were no substitution arguments "
"but this format string either has a $[0-9] in it or contains "
"an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0)
ABSL_BAD_CALL_IF(substitute_internal::PlaceholderBitmask(format) != 1,
"There was 1 substitution argument given, but "
"this format string is missing its $0, contains "
"one of $1-$9, or contains an unescaped $ character (use "
"$$ instead)");
void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 3,
"There were 2 substitution arguments given, but this format string is "
"missing its $0/$1, contains one of $2-$9, or contains an "
"unescaped $ character (use $$ instead)");
void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 7,
"There were 3 substitution arguments given, but "
"this format string is missing its $0/$1/$2, contains one of "
"$3-$9, or contains an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 15,
"There were 4 substitution arguments given, but "
"this format string is missing its $0-$3, contains one of "
"$4-$9, or contains an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(absl::Nonnull<std::string*> output,
absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 31,
"There were 5 substitution arguments given, but "
"this format string is missing its $0-$4, contains one of "
"$5-$9, or contains an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 63,
"There were 6 substitution arguments given, but "
"this format string is missing its $0-$5, contains one of "
"$6-$9, or contains an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 127,
"There were 7 substitution arguments given, but "
"this format string is missing its $0-$6, contains one of "
"$7-$9, or contains an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6, const substitute_internal::Arg& a7)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 255,
"There were 8 substitution arguments given, but "
"this format string is missing its $0-$7, contains one of "
"$8-$9, or contains an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6, const substitute_internal::Arg& a7,
const substitute_internal::Arg& a8)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 511,
"There were 9 substitution arguments given, but "
"this format string is missing its $0-$8, contains a $9, or "
"contains an unescaped $ character (use $$ instead)");
void SubstituteAndAppend(
absl::Nonnull<std::string*> output, absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0, const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2, const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4, const substitute_internal::Arg& a5,
const substitute_internal::Arg& a6, const substitute_internal::Arg& a7,
const substitute_internal::Arg& a8, const substitute_internal::Arg& a9)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 1023,
"There were 10 substitution arguments given, but this "
"format string either doesn't contain all of $0 through $9 or "
"contains an unescaped $ character (use $$ instead)");
#endif
ABSL_MUST_USE_RESULT inline std::string Substitute(absl::string_view format) {
std::string result;
SubstituteAndAppend(&result, format);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0) {
std::string result;
SubstituteAndAppend(&result, format, a0);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2, a3);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3, const substitute_internal::Arg& a4) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3, const substitute_internal::Arg& a4,
const substitute_internal::Arg& a5) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3, const substitute_internal::Arg& a4,
const substitute_internal::Arg& a5, const substitute_internal::Arg& a6) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3, const substitute_internal::Arg& a4,
const substitute_internal::Arg& a5, const substitute_internal::Arg& a6,
const substitute_internal::Arg& a7) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6, a7);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3, const substitute_internal::Arg& a4,
const substitute_internal::Arg& a5, const substitute_internal::Arg& a6,
const substitute_internal::Arg& a7, const substitute_internal::Arg& a8) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6, a7, a8);
return result;
}
ABSL_MUST_USE_RESULT inline std::string Substitute(
absl::string_view format, const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1, const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3, const substitute_internal::Arg& a4,
const substitute_internal::Arg& a5, const substitute_internal::Arg& a6,
const substitute_internal::Arg& a7, const substitute_internal::Arg& a8,
const substitute_internal::Arg& a9) {
std::string result;
SubstituteAndAppend(&result, format, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
return result;
}
#if defined(ABSL_BAD_CALL_IF)
std::string Substitute(absl::Nonnull<const char*> format)
ABSL_BAD_CALL_IF(substitute_internal::PlaceholderBitmask(format) != 0,
"There were no substitution arguments "
"but this format string either has a $[0-9] in it or "
"contains an unescaped $ character (use $$ instead)");
std::string Substitute(absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 1,
"There was 1 substitution argument given, but "
"this format string is missing its $0, contains one of $1-$9, "
"or contains an unescaped $ character (use $$ instead)");
std::string Substitute(absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 3,
"There were 2 substitution arguments given, but "
"this format string is missing its $0/$1, contains one of "
"$2-$9, or contains an unescaped $ character (use $$ instead)");
std::string Substitute(absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 7,
"There were 3 substitution arguments given, but "
"this format string is missing its $0/$1/$2, contains one of "
"$3-$9, or contains an unescaped $ character (use $$ instead)");
std::string Substitute(absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 15,
"There were 4 substitution arguments given, but "
"this format string is missing its $0-$3, contains one of "
"$4-$9, or contains an unescaped $ character (use $$ instead)");
std::string Substitute(absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4)
ABSL_BAD_CALL_IF(
substitute_internal::PlaceholderBitmask(format) != 31,
"There were 5 substitution arguments given, but "
"this format string is missing its $0-$4, contains one of "
"$5-$9, or contains an unescaped $ character (use $$ instead)");
std::string Substitute(absl::Nonnull<const char*> format,
const substitute_internal::Arg& a0,
const substitute_internal::Arg& a1,
const substitute_internal::Arg& a2,
const substitute_internal::Arg& a3,
const substitute_internal::Arg& a4,
const substitute_internal::Arg& a5)
ABSL_BAD_CALL_IF(
substitute_ | #include "absl/strings/substitute.h"
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace {
struct MyStruct {
template <typename Sink>
friend void AbslStringify(Sink& sink, const MyStruct& s) {
sink.Append("MyStruct{.value = ");
sink.Append(absl::StrCat(s.value));
sink.Append("}");
}
int value;
};
TEST(SubstituteTest, Substitute) {
EXPECT_EQ("Hello, world!", absl::Substitute("$0, $1!", "Hello", "world"));
EXPECT_EQ("123 0.2 0.1 foo true false x",
absl::Substitute("$0 $1 $2 $3 $4 $5 $6", 123, 0.2, 0.1f,
std::string("foo"), true, false, 'x'));
EXPECT_EQ(
"-32767 65535 "
"-1234567890 3234567890 "
"-1234567890 3234567890 "
"-1234567890123456789 9234567890123456789",
absl::Substitute(
"$0 $1 $2 $3 $4 $5 $6 $7",
static_cast<short>(-32767),
static_cast<unsigned short>(65535),
-1234567890, 3234567890U, -1234567890L, 3234567890UL,
-int64_t{1234567890123456789}, uint64_t{9234567890123456789u}));
EXPECT_EQ("0 1 f ffff0ffff 0123456789abcdef",
absl::Substitute("$0$1$2$3$4 $5",
absl::Hex(0), absl::Hex(1, absl::kSpacePad2),
absl::Hex(0xf, absl::kSpacePad2),
absl::Hex(int16_t{-1}, absl::kSpacePad5),
absl::Hex(int16_t{-1}, absl::kZeroPad5),
absl::Hex(0x123456789abcdef, absl::kZeroPad16)));
EXPECT_EQ("0 115 -1-0001 81985529216486895",
absl::Substitute("$0$1$2$3$4 $5",
absl::Dec(0), absl::Dec(1, absl::kSpacePad2),
absl::Dec(0xf, absl::kSpacePad2),
absl::Dec(int16_t{-1}, absl::kSpacePad5),
absl::Dec(int16_t{-1}, absl::kZeroPad5),
absl::Dec(0x123456789abcdef, absl::kZeroPad16)));
const int* int_p = reinterpret_cast<const int*>(0x12345);
std::string str = absl::Substitute("$0", int_p);
EXPECT_EQ(absl::StrCat("0x", absl::Hex(int_p)), str);
volatile int vol = 237;
volatile int* volatile volptr = &vol;
str = absl::Substitute("$0", volptr);
EXPECT_EQ("true", str);
const uint64_t* null_p = nullptr;
str = absl::Substitute("$0", null_p);
EXPECT_EQ("NULL", str);
const char* char_p = "print me";
str = absl::Substitute("$0", char_p);
EXPECT_EQ("print me", str);
char char_buf[16];
strncpy(char_buf, "print me too", sizeof(char_buf));
str = absl::Substitute("$0", char_buf);
EXPECT_EQ("print me too", str);
char_p = nullptr;
str = absl::Substitute("$0", char_p);
EXPECT_EQ("", str);
EXPECT_EQ("b, a, c, b", absl::Substitute("$1, $0, $2, $1", "a", "b", "c"));
EXPECT_EQ("$", absl::Substitute("$$"));
EXPECT_EQ("$1", absl::Substitute("$$1"));
EXPECT_EQ("a", absl::Substitute("$0", "a"));
EXPECT_EQ("a b", absl::Substitute("$0 $1", "a", "b"));
EXPECT_EQ("a b c", absl::Substitute("$0 $1 $2", "a", "b", "c"));
EXPECT_EQ("a b c d", absl::Substitute("$0 $1 $2 $3", "a", "b", "c", "d"));
EXPECT_EQ("a b c d e",
absl::Substitute("$0 $1 $2 $3 $4", "a", "b", "c", "d", "e"));
EXPECT_EQ("a b c d e f", absl::Substitute("$0 $1 $2 $3 $4 $5", "a", "b", "c",
"d", "e", "f"));
EXPECT_EQ("a b c d e f g", absl::Substitute("$0 $1 $2 $3 $4 $5 $6", "a", "b",
"c", "d", "e", "f", "g"));
EXPECT_EQ("a b c d e f g h",
absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7", "a", "b", "c", "d", "e",
"f", "g", "h"));
EXPECT_EQ("a b c d e f g h i",
absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7 $8", "a", "b", "c", "d",
"e", "f", "g", "h", "i"));
EXPECT_EQ("a b c d e f g h i j",
absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7 $8 $9", "a", "b", "c",
"d", "e", "f", "g", "h", "i", "j"));
EXPECT_EQ("a b c d e f g h i j b0",
absl::Substitute("$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10", "a", "b", "c",
"d", "e", "f", "g", "h", "i", "j"));
const char* null_cstring = nullptr;
EXPECT_EQ("Text: ''", absl::Substitute("Text: '$0'", null_cstring));
MyStruct s1 = MyStruct{17};
MyStruct s2 = MyStruct{1043};
EXPECT_EQ("MyStruct{.value = 17}, MyStruct{.value = 1043}",
absl::Substitute("$0, $1", s1, s2));
}
TEST(SubstituteTest, SubstituteAndAppend) {
std::string str = "Hello";
absl::SubstituteAndAppend(&str, ", $0!", "world");
EXPECT_EQ("Hello, world!", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0", "a");
EXPECT_EQ("a", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1", "a", "b");
EXPECT_EQ("a b", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2", "a", "b", "c");
EXPECT_EQ("a b c", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3", "a", "b", "c", "d");
EXPECT_EQ("a b c d", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4", "a", "b", "c", "d", "e");
EXPECT_EQ("a b c d e", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5", "a", "b", "c", "d", "e",
"f");
EXPECT_EQ("a b c d e f", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6", "a", "b", "c", "d",
"e", "f", "g");
EXPECT_EQ("a b c d e f g", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6 $7", "a", "b", "c", "d",
"e", "f", "g", "h");
EXPECT_EQ("a b c d e f g h", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6 $7 $8", "a", "b", "c",
"d", "e", "f", "g", "h", "i");
EXPECT_EQ("a b c d e f g h i", str);
str.clear();
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3 $4 $5 $6 $7 $8 $9", "a", "b",
"c", "d", "e", "f", "g", "h", "i", "j");
EXPECT_EQ("a b c d e f g h i j", str);
str.clear();
MyStruct s1 = MyStruct{17};
MyStruct s2 = MyStruct{1043};
absl::SubstituteAndAppend(&str, "$0, $1", s1, s2);
EXPECT_EQ("MyStruct{.value = 17}, MyStruct{.value = 1043}", str);
}
TEST(SubstituteTest, VectorBoolRef) {
std::vector<bool> v = {true, false};
const auto& cv = v;
EXPECT_EQ("true false true false",
absl::Substitute("$0 $1 $2 $3", v[0], v[1], cv[0], cv[1]));
std::string str = "Logic be like: ";
absl::SubstituteAndAppend(&str, "$0 $1 $2 $3", v[0], v[1], cv[0], cv[1]);
EXPECT_EQ("Logic be like: true false true false", str);
}
TEST(SubstituteTest, Enums) {
enum UnscopedEnum { kEnum0 = 0, kEnum1 = 1 };
EXPECT_EQ("0 1", absl::Substitute("$0 $1", UnscopedEnum::kEnum0,
UnscopedEnum::kEnum1));
enum class ScopedEnum { kEnum0 = 0, kEnum1 = 1 };
EXPECT_EQ("0 1",
absl::Substitute("$0 $1", ScopedEnum::kEnum0, ScopedEnum::kEnum1));
enum class ScopedEnumInt32 : int32_t { kEnum0 = 989, kEnum1 = INT32_MIN };
EXPECT_EQ("989 -2147483648",
absl::Substitute("$0 $1", ScopedEnumInt32::kEnum0,
ScopedEnumInt32::kEnum1));
enum class ScopedEnumUInt32 : uint32_t { kEnum0 = 1, kEnum1 = UINT32_MAX };
EXPECT_EQ("1 4294967295", absl::Substitute("$0 $1", ScopedEnumUInt32::kEnum0,
ScopedEnumUInt32::kEnum1));
enum class ScopedEnumInt64 : int64_t { kEnum0 = -1, kEnum1 = 42949672950 };
EXPECT_EQ("-1 42949672950", absl::Substitute("$0 $1", ScopedEnumInt64::kEnum0,
ScopedEnumInt64::kEnum1));
enum class ScopedEnumUInt64 : uint64_t { kEnum0 = 1, kEnum1 = 42949672950 };
EXPECT_EQ("1 42949672950", absl::Substitute("$0 $1", ScopedEnumUInt64::kEnum0,
ScopedEnumUInt64::kEnum1));
enum class ScopedEnumChar : signed char { kEnum0 = -1, kEnum1 = 1 };
EXPECT_EQ("-1 1", absl::Substitute("$0 $1", ScopedEnumChar::kEnum0,
ScopedEnumChar::kEnum1));
enum class ScopedEnumUChar : unsigned char {
kEnum0 = 0,
kEnum1 = 1,
kEnumMax = 255
};
EXPECT_EQ("0 1 255", absl::Substitute("$0 $1 $2", ScopedEnumUChar::kEnum0,
ScopedEnumUChar::kEnum1,
ScopedEnumUChar::kEnumMax));
enum class ScopedEnumInt16 : int16_t { kEnum0 = -100, kEnum1 = 10000 };
EXPECT_EQ("-100 10000", absl::Substitute("$0 $1", ScopedEnumInt16::kEnum0,
ScopedEnumInt16::kEnum1));
enum class ScopedEnumUInt16 : uint16_t { kEnum0 = 0, kEnum1 = 10000 };
EXPECT_EQ("0 10000", absl::Substitute("$0 $1", ScopedEnumUInt16::kEnum0,
ScopedEnumUInt16::kEnum1));
}
enum class EnumWithStringify { Many = 0, Choices = 1 };
template <typename Sink>
void AbslStringify(Sink& sink, EnumWithStringify e) {
sink.Append(e == EnumWithStringify::Many ? "Many" : "Choices");
}
TEST(SubstituteTest, AbslStringifyWithEnum) {
const auto e = EnumWithStringify::Choices;
EXPECT_EQ(absl::Substitute("$0", e), "Choices");
}
#if GTEST_HAS_DEATH_TEST
TEST(SubstituteDeathTest, SubstituteDeath) {
EXPECT_DEBUG_DEATH(
static_cast<void>(absl::Substitute(absl::string_view("-$2"), "a", "b")),
"Invalid absl::Substitute\\(\\) format string: asked for \"\\$2\", "
"but only 2 args were given.");
EXPECT_DEBUG_DEATH(
static_cast<void>(absl::Substitute(absl::string_view("-$z-"))),
"Invalid absl::Substitute\\(\\) format string: \"-\\$z-\"");
EXPECT_DEBUG_DEATH(
static_cast<void>(absl::Substitute(absl::string_view("-$"))),
"Invalid absl::Substitute\\(\\) format string: \"-\\$\"");
}
#endif
} |
2,543 | cpp | abseil/abseil-cpp | match | absl/strings/match.cc | absl/strings/match_test.cc | #ifndef ABSL_STRINGS_MATCH_H_
#define ABSL_STRINGS_MATCH_H_
#include <cstring>
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
inline bool StrContains(absl::string_view haystack,
absl::string_view needle) noexcept {
return haystack.find(needle, 0) != haystack.npos;
}
inline bool StrContains(absl::string_view haystack, char needle) noexcept {
return haystack.find(needle) != haystack.npos;
}
inline bool StartsWith(absl::string_view text,
absl::string_view prefix) noexcept {
return prefix.empty() ||
(text.size() >= prefix.size() &&
memcmp(text.data(), prefix.data(), prefix.size()) == 0);
}
inline bool EndsWith(absl::string_view text,
absl::string_view suffix) noexcept {
return suffix.empty() ||
(text.size() >= suffix.size() &&
memcmp(text.data() + (text.size() - suffix.size()), suffix.data(),
suffix.size()) == 0);
}
bool StrContainsIgnoreCase(absl::string_view haystack,
absl::string_view needle) noexcept;
bool StrContainsIgnoreCase(absl::string_view haystack,
char needle) noexcept;
bool EqualsIgnoreCase(absl::string_view piece1,
absl::string_view piece2) noexcept;
bool StartsWithIgnoreCase(absl::string_view text,
absl::string_view prefix) noexcept;
bool EndsWithIgnoreCase(absl::string_view text,
absl::string_view suffix) noexcept;
absl::string_view FindLongestCommonPrefix(absl::string_view a,
absl::string_view b);
absl::string_view FindLongestCommonSuffix(absl::string_view a,
absl::string_view b);
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/match.h"
#include <algorithm>
#include <cstdint>
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/optimization.h"
#include "absl/numeric/bits.h"
#include "absl/strings/ascii.h"
#include "absl/strings/internal/memutil.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
bool EqualsIgnoreCase(absl::string_view piece1,
absl::string_view piece2) noexcept {
return (piece1.size() == piece2.size() &&
0 == absl::strings_internal::memcasecmp(piece1.data(), piece2.data(),
piece1.size()));
}
bool StrContainsIgnoreCase(absl::string_view haystack,
absl::string_view needle) noexcept {
while (haystack.size() >= needle.size()) {
if (StartsWithIgnoreCase(haystack, needle)) return true;
haystack.remove_prefix(1);
}
return false;
}
bool StrContainsIgnoreCase(absl::string_view haystack,
char needle) noexcept {
char upper_needle = absl::ascii_toupper(static_cast<unsigned char>(needle));
char lower_needle = absl::ascii_tolower(static_cast<unsigned char>(needle));
if (upper_needle == lower_needle) {
return StrContains(haystack, needle);
} else {
const char both_cstr[3] = {lower_needle, upper_needle, '\0'};
return haystack.find_first_of(both_cstr) != absl::string_view::npos;
}
}
bool StartsWithIgnoreCase(absl::string_view text,
absl::string_view prefix) noexcept {
return (text.size() >= prefix.size()) &&
EqualsIgnoreCase(text.substr(0, prefix.size()), prefix);
}
bool EndsWithIgnoreCase(absl::string_view text,
absl::string_view suffix) noexcept {
return (text.size() >= suffix.size()) &&
EqualsIgnoreCase(text.substr(text.size() - suffix.size()), suffix);
}
absl::string_view FindLongestCommonPrefix(absl::string_view a,
absl::string_view b) {
const absl::string_view::size_type limit = std::min(a.size(), b.size());
const char* const pa = a.data();
const char* const pb = b.data();
absl::string_view::size_type count = (unsigned) 0;
if (ABSL_PREDICT_FALSE(limit < 8)) {
while (ABSL_PREDICT_TRUE(count + 2 <= limit)) {
uint16_t xor_bytes = absl::little_endian::Load16(pa + count) ^
absl::little_endian::Load16(pb + count);
if (ABSL_PREDICT_FALSE(xor_bytes != 0)) {
if (ABSL_PREDICT_TRUE((xor_bytes & 0xff) == 0)) ++count;
return absl::string_view(pa, count);
}
count += 2;
}
if (ABSL_PREDICT_TRUE(count != limit)) {
if (ABSL_PREDICT_TRUE(pa[count] == pb[count])) ++count;
}
return absl::string_view(pa, count);
}
do {
uint64_t xor_bytes = absl::little_endian::Load64(pa + count) ^
absl::little_endian::Load64(pb + count);
if (ABSL_PREDICT_FALSE(xor_bytes != 0)) {
count += static_cast<uint64_t>(absl::countr_zero(xor_bytes) >> 3);
return absl::string_view(pa, count);
}
count += 8;
} while (ABSL_PREDICT_TRUE(count + 8 < limit));
count = limit - 8;
uint64_t xor_bytes = absl::little_endian::Load64(pa + count) ^
absl::little_endian::Load64(pb + count);
if (ABSL_PREDICT_TRUE(xor_bytes != 0)) {
count += static_cast<uint64_t>(absl::countr_zero(xor_bytes) >> 3);
return absl::string_view(pa, count);
}
return absl::string_view(pa, limit);
}
absl::string_view FindLongestCommonSuffix(absl::string_view a,
absl::string_view b) {
const absl::string_view::size_type limit = std::min(a.size(), b.size());
if (limit == 0) return absl::string_view();
const char* pa = a.data() + a.size() - 1;
const char* pb = b.data() + b.size() - 1;
absl::string_view::size_type count = (unsigned) 0;
while (count < limit && *pa == *pb) {
--pa;
--pb;
++count;
}
return absl::string_view(++pa, count);
}
ABSL_NAMESPACE_END
} | #include "absl/strings/match.h"
#include <string>
#include "gtest/gtest.h"
#include "absl/strings/string_view.h"
namespace {
TEST(MatchTest, StartsWith) {
const std::string s1("123\0abc", 7);
const absl::string_view a("foobar");
const absl::string_view b(s1);
const absl::string_view e;
EXPECT_TRUE(absl::StartsWith(a, a));
EXPECT_TRUE(absl::StartsWith(a, "foo"));
EXPECT_TRUE(absl::StartsWith(a, e));
EXPECT_TRUE(absl::StartsWith(b, s1));
EXPECT_TRUE(absl::StartsWith(b, b));
EXPECT_TRUE(absl::StartsWith(b, e));
EXPECT_TRUE(absl::StartsWith(e, ""));
EXPECT_FALSE(absl::StartsWith(a, b));
EXPECT_FALSE(absl::StartsWith(b, a));
EXPECT_FALSE(absl::StartsWith(e, a));
}
TEST(MatchTest, EndsWith) {
const std::string s1("123\0abc", 7);
const absl::string_view a("foobar");
const absl::string_view b(s1);
const absl::string_view e;
EXPECT_TRUE(absl::EndsWith(a, a));
EXPECT_TRUE(absl::EndsWith(a, "bar"));
EXPECT_TRUE(absl::EndsWith(a, e));
EXPECT_TRUE(absl::EndsWith(b, s1));
EXPECT_TRUE(absl::EndsWith(b, b));
EXPECT_TRUE(absl::EndsWith(b, e));
EXPECT_TRUE(absl::EndsWith(e, ""));
EXPECT_FALSE(absl::EndsWith(a, b));
EXPECT_FALSE(absl::EndsWith(b, a));
EXPECT_FALSE(absl::EndsWith(e, a));
}
TEST(MatchTest, Contains) {
absl::string_view a("abcdefg");
absl::string_view b("abcd");
absl::string_view c("efg");
absl::string_view d("gh");
EXPECT_TRUE(absl::StrContains(a, a));
EXPECT_TRUE(absl::StrContains(a, b));
EXPECT_TRUE(absl::StrContains(a, c));
EXPECT_FALSE(absl::StrContains(a, d));
EXPECT_TRUE(absl::StrContains("", ""));
EXPECT_TRUE(absl::StrContains("abc", ""));
EXPECT_FALSE(absl::StrContains("", "a"));
}
TEST(MatchTest, ContainsChar) {
absl::string_view a("abcdefg");
absl::string_view b("abcd");
EXPECT_TRUE(absl::StrContains(a, 'a'));
EXPECT_TRUE(absl::StrContains(a, 'b'));
EXPECT_TRUE(absl::StrContains(a, 'e'));
EXPECT_FALSE(absl::StrContains(a, 'h'));
EXPECT_TRUE(absl::StrContains(b, 'a'));
EXPECT_TRUE(absl::StrContains(b, 'b'));
EXPECT_FALSE(absl::StrContains(b, 'e'));
EXPECT_FALSE(absl::StrContains(b, 'h'));
EXPECT_FALSE(absl::StrContains("", 'a'));
EXPECT_FALSE(absl::StrContains("", 'a'));
}
TEST(MatchTest, ContainsNull) {
const std::string s = "foo";
const char* cs = "foo";
const absl::string_view sv("foo");
const absl::string_view sv2("foo\0bar", 4);
EXPECT_EQ(s, "foo");
EXPECT_EQ(sv, "foo");
EXPECT_NE(sv2, "foo");
EXPECT_TRUE(absl::EndsWith(s, sv));
EXPECT_TRUE(absl::StartsWith(cs, sv));
EXPECT_TRUE(absl::StrContains(cs, sv));
EXPECT_FALSE(absl::StrContains(cs, sv2));
}
TEST(MatchTest, EqualsIgnoreCase) {
std::string text = "the";
absl::string_view data(text);
EXPECT_TRUE(absl::EqualsIgnoreCase(data, "The"));
EXPECT_TRUE(absl::EqualsIgnoreCase(data, "THE"));
EXPECT_TRUE(absl::EqualsIgnoreCase(data, "the"));
EXPECT_FALSE(absl::EqualsIgnoreCase(data, "Quick"));
EXPECT_FALSE(absl::EqualsIgnoreCase(data, "then"));
}
TEST(MatchTest, StartsWithIgnoreCase) {
EXPECT_TRUE(absl::StartsWithIgnoreCase("foo", "foo"));
EXPECT_TRUE(absl::StartsWithIgnoreCase("foo", "Fo"));
EXPECT_TRUE(absl::StartsWithIgnoreCase("foo", ""));
EXPECT_FALSE(absl::StartsWithIgnoreCase("foo", "fooo"));
EXPECT_FALSE(absl::StartsWithIgnoreCase("", "fo"));
}
TEST(MatchTest, EndsWithIgnoreCase) {
EXPECT_TRUE(absl::EndsWithIgnoreCase("foo", "foo"));
EXPECT_TRUE(absl::EndsWithIgnoreCase("foo", "Oo"));
EXPECT_TRUE(absl::EndsWithIgnoreCase("foo", ""));
EXPECT_FALSE(absl::EndsWithIgnoreCase("foo", "fooo"));
EXPECT_FALSE(absl::EndsWithIgnoreCase("", "fo"));
}
TEST(MatchTest, ContainsIgnoreCase) {
EXPECT_TRUE(absl::StrContainsIgnoreCase("foo", "foo"));
EXPECT_TRUE(absl::StrContainsIgnoreCase("FOO", "Foo"));
EXPECT_TRUE(absl::StrContainsIgnoreCase("--FOO", "Foo"));
EXPECT_TRUE(absl::StrContainsIgnoreCase("FOO--", "Foo"));
EXPECT_FALSE(absl::StrContainsIgnoreCase("BAR", "Foo"));
EXPECT_FALSE(absl::StrContainsIgnoreCase("BAR", "Foo"));
EXPECT_TRUE(absl::StrContainsIgnoreCase("123456", "123456"));
EXPECT_TRUE(absl::StrContainsIgnoreCase("123456", "234"));
EXPECT_TRUE(absl::StrContainsIgnoreCase("", ""));
EXPECT_TRUE(absl::StrContainsIgnoreCase("abc", ""));
EXPECT_FALSE(absl::StrContainsIgnoreCase("", "a"));
}
TEST(MatchTest, ContainsCharIgnoreCase) {
absl::string_view a("AaBCdefg!");
absl::string_view b("AaBCd!");
EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'a'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'A'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'b'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'B'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'e'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(a, 'E'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(a, 'h'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(a, 'H'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(a, '!'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(a, '?'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'a'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'A'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'b'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(b, 'B'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'e'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'E'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'h'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(b, 'H'));
EXPECT_TRUE(absl::StrContainsIgnoreCase(b, '!'));
EXPECT_FALSE(absl::StrContainsIgnoreCase(b, '?'));
EXPECT_FALSE(absl::StrContainsIgnoreCase("", 'a'));
EXPECT_FALSE(absl::StrContainsIgnoreCase("", 'A'));
EXPECT_FALSE(absl::StrContainsIgnoreCase("", '0'));
}
TEST(MatchTest, FindLongestCommonPrefix) {
EXPECT_EQ(absl::FindLongestCommonPrefix("", ""), "");
EXPECT_EQ(absl::FindLongestCommonPrefix("", "abc"), "");
EXPECT_EQ(absl::FindLongestCommonPrefix("abc", ""), "");
EXPECT_EQ(absl::FindLongestCommonPrefix("ab", "abc"), "ab");
EXPECT_EQ(absl::FindLongestCommonPrefix("abc", "ab"), "ab");
EXPECT_EQ(absl::FindLongestCommonPrefix("abc", "abd"), "ab");
EXPECT_EQ(absl::FindLongestCommonPrefix("abc", "abcd"), "abc");
EXPECT_EQ(absl::FindLongestCommonPrefix("abcd", "abcd"), "abcd");
EXPECT_EQ(absl::FindLongestCommonPrefix("abcd", "efgh"), "");
EXPECT_EQ(absl::FindLongestCommonPrefix(
absl::string_view("1234 abcdef").substr(5, 5),
absl::string_view("5678 abcdef").substr(5, 3)),
"abc");
}
TEST(MatchTest, FindLongestCommonPrefixLoad16Mismatch) {
const std::string x1 = "abcdefgh";
const std::string x2 = "abcde_";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcde");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcde");
}
TEST(MatchTest, FindLongestCommonPrefixLoad16MatchesNoLast) {
const std::string x1 = "abcdef";
const std::string x2 = "abcdef";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcdef");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcdef");
}
TEST(MatchTest, FindLongestCommonPrefixLoad16MatchesLastCharMismatches) {
const std::string x1 = "abcdefg";
const std::string x2 = "abcdef_h";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcdef");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcdef");
}
TEST(MatchTest, FindLongestCommonPrefixLoad16MatchesLastMatches) {
const std::string x1 = "abcde";
const std::string x2 = "abcdefgh";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcde");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcde");
}
TEST(MatchTest, FindLongestCommonPrefixSize8Load64Mismatches) {
const std::string x1 = "abcdefghijk";
const std::string x2 = "abcde_g_";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcde");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcde");
}
TEST(MatchTest, FindLongestCommonPrefixSize8Load64Matches) {
const std::string x1 = "abcdefgh";
const std::string x2 = "abcdefgh";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "abcdefgh");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "abcdefgh");
}
TEST(MatchTest, FindLongestCommonPrefixSize15Load64Mismatches) {
const std::string x1 = "012345670123456";
const std::string x2 = "0123456701_34_6";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "0123456701");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "0123456701");
}
TEST(MatchTest, FindLongestCommonPrefixSize15Load64Matches) {
const std::string x1 = "012345670123456";
const std::string x2 = "0123456701234567";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "012345670123456");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "012345670123456");
}
TEST(MatchTest, FindLongestCommonPrefixSizeFirstByteOfLast8BytesMismatch) {
const std::string x1 = "012345670123456701234567";
const std::string x2 = "0123456701234567_1234567";
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), "0123456701234567");
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), "0123456701234567");
}
TEST(MatchTest, FindLongestCommonPrefixLargeLastCharMismatches) {
const std::string x1(300, 'x');
std::string x2 = x1;
x2.back() = '#';
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), std::string(299, 'x'));
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), std::string(299, 'x'));
}
TEST(MatchTest, FindLongestCommonPrefixLargeFullMatch) {
const std::string x1(300, 'x');
const std::string x2 = x1;
EXPECT_EQ(absl::FindLongestCommonPrefix(x1, x2), std::string(300, 'x'));
EXPECT_EQ(absl::FindLongestCommonPrefix(x2, x1), std::string(300, 'x'));
}
TEST(MatchTest, FindLongestCommonSuffix) {
EXPECT_EQ(absl::FindLongestCommonSuffix("", ""), "");
EXPECT_EQ(absl::FindLongestCommonSuffix("", "abc"), "");
EXPECT_EQ(absl::FindLongestCommonSuffix("abc", ""), "");
EXPECT_EQ(absl::FindLongestCommonSuffix("bc", "abc"), "bc");
EXPECT_EQ(absl::FindLongestCommonSuffix("abc", "bc"), "bc");
EXPECT_EQ(absl::FindLongestCommonSuffix("abc", "dbc"), "bc");
EXPECT_EQ(absl::FindLongestCommonSuffix("bcd", "abcd"), "bcd");
EXPECT_EQ(absl::FindLongestCommonSuffix("abcd", "abcd"), "abcd");
EXPECT_EQ(absl::FindLongestCommonSuffix("abcd", "efgh"), "");
EXPECT_EQ(absl::FindLongestCommonSuffix(
absl::string_view("1234 abcdef").substr(5, 5),
absl::string_view("5678 abcdef").substr(7, 3)),
"cde");
}
} |
2,544 | cpp | abseil/abseil-cpp | charconv | absl/strings/charconv.cc | absl/strings/charconv_test.cc | #ifndef ABSL_STRINGS_CHARCONV_H_
#define ABSL_STRINGS_CHARCONV_H_
#include <system_error>
#include "absl/base/config.h"
#include "absl/base/nullability.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
enum class chars_format {
scientific = 1,
fixed = 2,
hex = 4,
general = fixed | scientific,
};
struct from_chars_result {
absl::Nonnull<const char*> ptr;
std::errc ec;
};
absl::from_chars_result from_chars(absl::Nonnull<const char*> first,
absl::Nonnull<const char*> last,
double& value,
chars_format fmt = chars_format::general);
absl::from_chars_result from_chars(absl::Nonnull<const char*> first,
absl::Nonnull<const char*> last,
float& value,
chars_format fmt = chars_format::general);
inline constexpr chars_format operator&(chars_format lhs, chars_format rhs) {
return static_cast<chars_format>(static_cast<int>(lhs) &
static_cast<int>(rhs));
}
inline constexpr chars_format operator|(chars_format lhs, chars_format rhs) {
return static_cast<chars_format>(static_cast<int>(lhs) |
static_cast<int>(rhs));
}
inline constexpr chars_format operator^(chars_format lhs, chars_format rhs) {
return static_cast<chars_format>(static_cast<int>(lhs) ^
static_cast<int>(rhs));
}
inline constexpr chars_format operator~(chars_format arg) {
return static_cast<chars_format>(~static_cast<int>(arg));
}
inline chars_format& operator&=(chars_format& lhs, chars_format rhs) {
lhs = lhs & rhs;
return lhs;
}
inline chars_format& operator|=(chars_format& lhs, chars_format rhs) {
lhs = lhs | rhs;
return lhs;
}
inline chars_format& operator^=(chars_format& lhs, chars_format rhs) {
lhs = lhs ^ rhs;
return lhs;
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/charconv.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <system_error>
#include "absl/base/casts.h"
#include "absl/base/config.h"
#include "absl/base/nullability.h"
#include "absl/numeric/bits.h"
#include "absl/numeric/int128.h"
#include "absl/strings/internal/charconv_bigint.h"
#include "absl/strings/internal/charconv_parse.h"
#ifdef ABSL_BIT_PACK_FLOATS
#error ABSL_BIT_PACK_FLOATS cannot be directly set
#elif defined(__x86_64__) || defined(_M_X64)
#define ABSL_BIT_PACK_FLOATS 1
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
template <typename FloatType>
struct FloatTraits;
template <>
struct FloatTraits<double> {
using mantissa_t = uint64_t;
static constexpr int kTargetBits = 64;
static constexpr int kTargetExponentBits = 11;
static constexpr int kTargetMantissaBits = 53;
static constexpr int kMaxExponent = 971;
static constexpr int kMinNormalExponent = -1074;
static constexpr int kExponentBias = 1023;
static constexpr int kEiselLemireShift = 9;
static constexpr uint64_t kEiselLemireMask = uint64_t{0x1FF};
static constexpr int kEiselLemireMinInclusiveExp10 = -324 - 18;
static constexpr int kEiselLemireMaxExclusiveExp10 = 309;
static double MakeNan(absl::Nonnull<const char*> tagp) {
#if ABSL_HAVE_BUILTIN(__builtin_nan)
return __builtin_nan(tagp);
#else
using namespace std;
return nan(tagp);
#endif
}
static double Make(mantissa_t mantissa, int exponent, bool sign) {
#ifndef ABSL_BIT_PACK_FLOATS
using namespace std;
return sign ? -ldexp(mantissa, exponent) : ldexp(mantissa, exponent);
#else
constexpr uint64_t kMantissaMask =
(uint64_t{1} << (kTargetMantissaBits - 1)) - 1;
uint64_t dbl = static_cast<uint64_t>(sign) << 63;
if (mantissa > kMantissaMask) {
dbl += static_cast<uint64_t>(exponent + 1023 + kTargetMantissaBits - 1)
<< 52;
mantissa &= kMantissaMask;
} else {
assert(exponent == kMinNormalExponent);
}
dbl += mantissa;
return absl::bit_cast<double>(dbl);
#endif
}
};
template <>
struct FloatTraits<float> {
using mantissa_t = uint32_t;
static constexpr int kTargetBits = 32;
static constexpr int kTargetExponentBits = 8;
static constexpr int kTargetMantissaBits = 24;
static constexpr int kMaxExponent = 104;
static constexpr int kMinNormalExponent = -149;
static constexpr int kExponentBias = 127;
static constexpr int kEiselLemireShift = 38;
static constexpr uint64_t kEiselLemireMask = uint64_t{0x3FFFFFFFFF};
static constexpr int kEiselLemireMinInclusiveExp10 = -46 - 18;
static constexpr int kEiselLemireMaxExclusiveExp10 = 39;
static float MakeNan(absl::Nonnull<const char*> tagp) {
#if ABSL_HAVE_BUILTIN(__builtin_nanf)
return __builtin_nanf(tagp);
#else
using namespace std;
return std::nanf(tagp);
#endif
}
static float Make(mantissa_t mantissa, int exponent, bool sign) {
#ifndef ABSL_BIT_PACK_FLOATS
using namespace std;
return sign ? -ldexpf(mantissa, exponent) : ldexpf(mantissa, exponent);
#else
constexpr uint32_t kMantissaMask =
(uint32_t{1} << (kTargetMantissaBits - 1)) - 1;
uint32_t flt = static_cast<uint32_t>(sign) << 31;
if (mantissa > kMantissaMask) {
flt += static_cast<uint32_t>(exponent + 127 + kTargetMantissaBits - 1)
<< 23;
mantissa &= kMantissaMask;
} else {
assert(exponent == kMinNormalExponent);
}
flt += mantissa;
return absl::bit_cast<float>(flt);
#endif
}
};
extern const uint64_t kPower10MantissaHighTable[];
extern const uint64_t kPower10MantissaLowTable[];
constexpr int kPower10TableMinInclusive = -342;
constexpr int kPower10TableMaxExclusive = 309;
uint64_t Power10Mantissa(int n) {
return kPower10MantissaHighTable[n - kPower10TableMinInclusive];
}
int Power10Exponent(int n) {
return (217706 * n >> 16) - 63;
}
bool Power10Overflow(int n) { return n >= kPower10TableMaxExclusive; }
bool Power10Underflow(int n) { return n < kPower10TableMinInclusive; }
bool Power10Exact(int n) { return n >= 0 && n <= 27; }
constexpr int kOverflow = 99999;
constexpr int kUnderflow = -99999;
struct CalculatedFloat {
uint64_t mantissa = 0;
int exponent = 0;
};
int BitWidth(uint128 value) {
if (Uint128High64(value) == 0) {
return static_cast<int>(bit_width(Uint128Low64(value)));
}
return 128 - countl_zero(Uint128High64(value));
}
template <typename FloatType>
int NormalizedShiftSize(int mantissa_width, int binary_exponent) {
const int normal_shift =
mantissa_width - FloatTraits<FloatType>::kTargetMantissaBits;
const int minimum_shift =
FloatTraits<FloatType>::kMinNormalExponent - binary_exponent;
return std::max(normal_shift, minimum_shift);
}
int TruncateToBitWidth(int bit_width, absl::Nonnull<uint128*> value) {
const int current_bit_width = BitWidth(*value);
const int shift = current_bit_width - bit_width;
*value >>= shift;
return shift;
}
template <typename FloatType>
bool HandleEdgeCase(const strings_internal::ParsedFloat& input, bool negative,
absl::Nonnull<FloatType*> value) {
if (input.type == strings_internal::FloatType::kNan) {
constexpr ptrdiff_t kNanBufferSize = 128;
#if (defined(__GNUC__) && !defined(__clang__)) || \
(defined(__clang__) && __clang_major__ < 7)
volatile char n_char_sequence[kNanBufferSize];
#else
char n_char_sequence[kNanBufferSize];
#endif
if (input.subrange_begin == nullptr) {
n_char_sequence[0] = '\0';
} else {
ptrdiff_t nan_size = input.subrange_end - input.subrange_begin;
nan_size = std::min(nan_size, kNanBufferSize - 1);
std::copy_n(input.subrange_begin, nan_size, n_char_sequence);
n_char_sequence[nan_size] = '\0';
}
char* nan_argument = const_cast<char*>(n_char_sequence);
*value = negative ? -FloatTraits<FloatType>::MakeNan(nan_argument)
: FloatTraits<FloatType>::MakeNan(nan_argument);
return true;
}
if (input.type == strings_internal::FloatType::kInfinity) {
*value = negative ? -std::numeric_limits<FloatType>::infinity()
: std::numeric_limits<FloatType>::infinity();
return true;
}
if (input.mantissa == 0) {
*value = negative ? -0.0 : 0.0;
return true;
}
return false;
}
template <typename FloatType>
void EncodeResult(const CalculatedFloat& calculated, bool negative,
absl::Nonnull<absl::from_chars_result*> result,
absl::Nonnull<FloatType*> value) {
if (calculated.exponent == kOverflow) {
result->ec = std::errc::result_out_of_range;
*value = negative ? -std::numeric_limits<FloatType>::max()
: std::numeric_limits<FloatType>::max();
return;
} else if (calculated.mantissa == 0 || calculated.exponent == kUnderflow) {
result->ec = std::errc::result_out_of_range;
*value = negative ? -0.0 : 0.0;
return;
}
*value = FloatTraits<FloatType>::Make(
static_cast<typename FloatTraits<FloatType>::mantissa_t>(
calculated.mantissa),
calculated.exponent, negative);
}
uint64_t ShiftRightAndRound(uint128 value, int shift, bool input_exact,
absl::Nonnull<bool*> output_exact) {
if (shift <= 0) {
*output_exact = input_exact;
return static_cast<uint64_t>(value << -shift);
}
if (shift >= 128) {
*output_exact = true;
return 0;
}
*output_exact = true;
const uint128 shift_mask = (uint128(1) << shift) - 1;
const uint128 halfway_point = uint128(1) << (shift - 1);
const uint128 shifted_bits = value & shift_mask;
value >>= shift;
if (shifted_bits > halfway_point) {
return static_cast<uint64_t>(value + 1);
}
if (shifted_bits == halfway_point) {
if ((value & 1) == 1 || !input_exact) {
++value;
}
return static_cast<uint64_t>(value);
}
if (!input_exact && shifted_bits == halfway_point - 1) {
*output_exact = false;
}
return static_cast<uint64_t>(value);
}
bool MustRoundUp(uint64_t guess_mantissa, int guess_exponent,
const strings_internal::ParsedFloat& parsed_decimal) {
absl::strings_internal::BigUnsigned<84> exact_mantissa;
int exact_exponent = exact_mantissa.ReadFloatMantissa(parsed_decimal, 768);
guess_mantissa = guess_mantissa * 2 + 1;
guess_exponent -= 1;
absl::strings_internal::BigUnsigned<84>& lhs = exact_mantissa;
int comparison;
if (exact_exponent >= 0) {
lhs.MultiplyByFiveToTheNth(exact_exponent);
absl::strings_internal::BigUnsigned<84> rhs(guess_mantissa);
if (exact_exponent > guess_exponent) {
lhs.ShiftLeft(exact_exponent - guess_exponent);
} else {
rhs.ShiftLeft(guess_exponent - exact_exponent);
}
comparison = Compare(lhs, rhs);
} else {
absl::strings_internal::BigUnsigned<84> rhs =
absl::strings_internal::BigUnsigned<84>::FiveToTheNth(-exact_exponent);
rhs.MultiplyBy(guess_mantissa);
if (exact_exponent > guess_exponent) {
lhs.ShiftLeft(exact_exponent - guess_exponent);
} else {
rhs.ShiftLeft(guess_exponent - exact_exponent);
}
comparison = Compare(lhs, rhs);
}
if (comparison < 0) {
return false;
} else if (comparison > 0) {
return true;
} else {
return (guess_mantissa & 2) == 2;
}
}
template <typename FloatType>
CalculatedFloat CalculatedFloatFromRawValues(uint64_t mantissa, int exponent) {
CalculatedFloat result;
if (mantissa == uint64_t{1} << FloatTraits<FloatType>::kTargetMantissaBits) {
mantissa >>= 1;
exponent += 1;
}
if (exponent > FloatTraits<FloatType>::kMaxExponent) {
result.exponent = kOverflow;
} else if (mantissa == 0) {
result.exponent = kUnderflow;
} else {
result.exponent = exponent;
result.mantissa = mantissa;
}
return result;
}
template <typename FloatType>
CalculatedFloat CalculateFromParsedHexadecimal(
const strings_internal::ParsedFloat& parsed_hex) {
uint64_t mantissa = parsed_hex.mantissa;
int exponent = parsed_hex.exponent;
int mantissa_width = static_cast<int>(bit_width(mantissa));
const int shift = NormalizedShiftSize<FloatType>(mantissa_width, exponent);
bool result_exact;
exponent += shift;
mantissa = ShiftRightAndRound(mantissa, shift,
true, &result_exact);
return CalculatedFloatFromRawValues<FloatType>(mantissa, exponent);
}
template <typename FloatType>
CalculatedFloat CalculateFromParsedDecimal(
const strings_internal::ParsedFloat& parsed_decimal) {
CalculatedFloat result;
if (Power10Underflow(parsed_decimal.exponent)) {
result.exponent = kUnderflow;
return result;
} else if (Power10Overflow(parsed_decimal.exponent)) {
result.exponent = kOverflow;
return result;
}
uint128 wide_binary_mantissa = parsed_decimal.mantissa;
wide_binary_mantissa *= Power10Mantissa(parsed_decimal.exponent);
int binary_exponent = Power10Exponent(parsed_decimal.exponent);
bool mantissa_exact;
int mantissa_width;
if (parsed_decimal.subrange_begin) {
mantissa_width = 58;
mantissa_exact = false;
binary_exponent +=
TruncateToBitWidth(mantissa_width, &wide_binary_mantissa);
} else if (!Power10Exact(parsed_decimal.exponent)) {
mantissa_width = 63;
mantissa_exact = false;
binary_exponent +=
TruncateToBitWidth(mantissa_width, &wide_binary_mantissa);
} else {
mantissa_width = BitWidth(wide_binary_mantissa);
mantissa_exact = true;
}
const int shift =
NormalizedShiftSize<FloatType>(mantissa_width, binary_exponent);
bool result_exact;
binary_exponent += shift;
uint64_t binary_mantissa = ShiftRightAndRound(wide_binary_mantissa, shift,
mantissa_exact, &result_exact);
if (!result_exact) { | #include "absl/strings/charconv.h"
#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <limits>
#include <string>
#include <system_error>
#include "gtest/gtest.h"
#include "absl/strings/internal/pow10_helper.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#ifdef _MSC_FULL_VER
#define ABSL_COMPILER_DOES_EXACT_ROUNDING 0
#define ABSL_STRTOD_HANDLES_NAN_CORRECTLY 0
#else
#define ABSL_COMPILER_DOES_EXACT_ROUNDING 1
#define ABSL_STRTOD_HANDLES_NAN_CORRECTLY 1
#endif
namespace {
using absl::strings_internal::Pow10;
#if ABSL_COMPILER_DOES_EXACT_ROUNDING
void TestDoubleParse(absl::string_view str, double expected_number) {
SCOPED_TRACE(str);
double actual_number = 0.0;
absl::from_chars_result result =
absl::from_chars(str.data(), str.data() + str.length(), actual_number);
EXPECT_EQ(result.ec, std::errc());
EXPECT_EQ(result.ptr, str.data() + str.length());
EXPECT_EQ(actual_number, expected_number);
}
void TestFloatParse(absl::string_view str, float expected_number) {
SCOPED_TRACE(str);
float actual_number = 0.0;
absl::from_chars_result result =
absl::from_chars(str.data(), str.data() + str.length(), actual_number);
EXPECT_EQ(result.ec, std::errc());
EXPECT_EQ(result.ptr, str.data() + str.length());
EXPECT_EQ(actual_number, expected_number);
}
#define FROM_CHARS_TEST_DOUBLE(number) \
{ \
TestDoubleParse(#number, number); \
TestDoubleParse("-" #number, -number); \
}
#define FROM_CHARS_TEST_FLOAT(number) \
{ \
TestFloatParse(#number, number##f); \
TestFloatParse("-" #number, -number##f); \
}
TEST(FromChars, NearRoundingCases) {
FROM_CHARS_TEST_DOUBLE(5.e125);
FROM_CHARS_TEST_DOUBLE(69.e267);
FROM_CHARS_TEST_DOUBLE(999.e-026);
FROM_CHARS_TEST_DOUBLE(7861.e-034);
FROM_CHARS_TEST_DOUBLE(75569.e-254);
FROM_CHARS_TEST_DOUBLE(928609.e-261);
FROM_CHARS_TEST_DOUBLE(9210917.e080);
FROM_CHARS_TEST_DOUBLE(84863171.e114);
FROM_CHARS_TEST_DOUBLE(653777767.e273);
FROM_CHARS_TEST_DOUBLE(5232604057.e-298);
FROM_CHARS_TEST_DOUBLE(27235667517.e-109);
FROM_CHARS_TEST_DOUBLE(653532977297.e-123);
FROM_CHARS_TEST_DOUBLE(3142213164987.e-294);
FROM_CHARS_TEST_DOUBLE(46202199371337.e-072);
FROM_CHARS_TEST_DOUBLE(231010996856685.e-073);
FROM_CHARS_TEST_DOUBLE(9324754620109615.e212);
FROM_CHARS_TEST_DOUBLE(78459735791271921.e049);
FROM_CHARS_TEST_DOUBLE(272104041512242479.e200);
FROM_CHARS_TEST_DOUBLE(6802601037806061975.e198);
FROM_CHARS_TEST_DOUBLE(20505426358836677347.e-221);
FROM_CHARS_TEST_DOUBLE(836168422905420598437.e-234);
FROM_CHARS_TEST_DOUBLE(4891559871276714924261.e222);
FROM_CHARS_TEST_FLOAT(5.e-20);
FROM_CHARS_TEST_FLOAT(67.e14);
FROM_CHARS_TEST_FLOAT(985.e15);
FROM_CHARS_TEST_FLOAT(7693.e-42);
FROM_CHARS_TEST_FLOAT(55895.e-16);
FROM_CHARS_TEST_FLOAT(996622.e-44);
FROM_CHARS_TEST_FLOAT(7038531.e-32);
FROM_CHARS_TEST_FLOAT(60419369.e-46);
FROM_CHARS_TEST_FLOAT(702990899.e-20);
FROM_CHARS_TEST_FLOAT(6930161142.e-48);
FROM_CHARS_TEST_FLOAT(25933168707.e-13);
FROM_CHARS_TEST_FLOAT(596428896559.e20);
FROM_CHARS_TEST_DOUBLE(9.e-265);
FROM_CHARS_TEST_DOUBLE(85.e-037);
FROM_CHARS_TEST_DOUBLE(623.e100);
FROM_CHARS_TEST_DOUBLE(3571.e263);
FROM_CHARS_TEST_DOUBLE(81661.e153);
FROM_CHARS_TEST_DOUBLE(920657.e-023);
FROM_CHARS_TEST_DOUBLE(4603285.e-024);
FROM_CHARS_TEST_DOUBLE(87575437.e-309);
FROM_CHARS_TEST_DOUBLE(245540327.e122);
FROM_CHARS_TEST_DOUBLE(6138508175.e120);
FROM_CHARS_TEST_DOUBLE(83356057653.e193);
FROM_CHARS_TEST_DOUBLE(619534293513.e124);
FROM_CHARS_TEST_DOUBLE(2335141086879.e218);
FROM_CHARS_TEST_DOUBLE(36167929443327.e-159);
FROM_CHARS_TEST_DOUBLE(609610927149051.e-255);
FROM_CHARS_TEST_DOUBLE(3743626360493413.e-165);
FROM_CHARS_TEST_DOUBLE(94080055902682397.e-242);
FROM_CHARS_TEST_DOUBLE(899810892172646163.e283);
FROM_CHARS_TEST_DOUBLE(7120190517612959703.e120);
FROM_CHARS_TEST_DOUBLE(25188282901709339043.e-252);
FROM_CHARS_TEST_DOUBLE(308984926168550152811.e-052);
FROM_CHARS_TEST_DOUBLE(6372891218502368041059.e064);
FROM_CHARS_TEST_FLOAT(3.e-23);
FROM_CHARS_TEST_FLOAT(57.e18);
FROM_CHARS_TEST_FLOAT(789.e-35);
FROM_CHARS_TEST_FLOAT(2539.e-18);
FROM_CHARS_TEST_FLOAT(76173.e28);
FROM_CHARS_TEST_FLOAT(887745.e-11);
FROM_CHARS_TEST_FLOAT(5382571.e-37);
FROM_CHARS_TEST_FLOAT(82381273.e-35);
FROM_CHARS_TEST_FLOAT(750486563.e-38);
FROM_CHARS_TEST_FLOAT(3752432815.e-39);
FROM_CHARS_TEST_FLOAT(75224575729.e-45);
FROM_CHARS_TEST_FLOAT(459926601011.e15);
}
#undef FROM_CHARS_TEST_DOUBLE
#undef FROM_CHARS_TEST_FLOAT
#endif
float ToFloat(absl::string_view s) {
float f;
absl::from_chars(s.data(), s.data() + s.size(), f);
return f;
}
double ToDouble(absl::string_view s) {
double d;
absl::from_chars(s.data(), s.data() + s.size(), d);
return d;
}
TEST(FromChars, NearRoundingCasesExplicit) {
EXPECT_EQ(ToDouble("5.e125"), ldexp(6653062250012735, 365));
EXPECT_EQ(ToDouble("69.e267"), ldexp(4705683757438170, 841));
EXPECT_EQ(ToDouble("999.e-026"), ldexp(6798841691080350, -129));
EXPECT_EQ(ToDouble("7861.e-034"), ldexp(8975675289889240, -153));
EXPECT_EQ(ToDouble("75569.e-254"), ldexp(6091718967192243, -880));
EXPECT_EQ(ToDouble("928609.e-261"), ldexp(7849264900213743, -900));
EXPECT_EQ(ToDouble("9210917.e080"), ldexp(8341110837370930, 236));
EXPECT_EQ(ToDouble("84863171.e114"), ldexp(4625202867375927, 353));
EXPECT_EQ(ToDouble("653777767.e273"), ldexp(5068902999763073, 884));
EXPECT_EQ(ToDouble("5232604057.e-298"), ldexp(5741343011915040, -1010));
EXPECT_EQ(ToDouble("27235667517.e-109"), ldexp(6707124626673586, -380));
EXPECT_EQ(ToDouble("653532977297.e-123"), ldexp(7078246407265384, -422));
EXPECT_EQ(ToDouble("3142213164987.e-294"), ldexp(8219991337640559, -988));
EXPECT_EQ(ToDouble("46202199371337.e-072"), ldexp(5224462102115359, -246));
EXPECT_EQ(ToDouble("231010996856685.e-073"), ldexp(5224462102115359, -247));
EXPECT_EQ(ToDouble("9324754620109615.e212"), ldexp(5539753864394442, 705));
EXPECT_EQ(ToDouble("78459735791271921.e049"), ldexp(8388176519442766, 166));
EXPECT_EQ(ToDouble("272104041512242479.e200"), ldexp(5554409530847367, 670));
EXPECT_EQ(ToDouble("6802601037806061975.e198"), ldexp(5554409530847367, 668));
EXPECT_EQ(ToDouble("20505426358836677347.e-221"),
ldexp(4524032052079546, -722));
EXPECT_EQ(ToDouble("836168422905420598437.e-234"),
ldexp(5070963299887562, -760));
EXPECT_EQ(ToDouble("4891559871276714924261.e222"),
ldexp(6452687840519111, 757));
EXPECT_EQ(ToFloat("5.e-20"), ldexpf(15474250, -88));
EXPECT_EQ(ToFloat("67.e14"), ldexpf(12479722, 29));
EXPECT_EQ(ToFloat("985.e15"), ldexpf(14333636, 36));
EXPECT_EQ(ToFloat("7693.e-42"), ldexpf(10979816, -150));
EXPECT_EQ(ToFloat("55895.e-16"), ldexpf(12888509, -61));
EXPECT_EQ(ToFloat("996622.e-44"), ldexpf(14224264, -150));
EXPECT_EQ(ToFloat("7038531.e-32"), ldexpf(11420669, -107));
EXPECT_EQ(ToFloat("60419369.e-46"), ldexpf(8623340, -150));
EXPECT_EQ(ToFloat("702990899.e-20"), ldexpf(16209866, -61));
EXPECT_EQ(ToFloat("6930161142.e-48"), ldexpf(9891056, -150));
EXPECT_EQ(ToFloat("25933168707.e-13"), ldexpf(11138211, -32));
EXPECT_EQ(ToFloat("596428896559.e20"), ldexpf(12333860, 82));
EXPECT_EQ(ToDouble("9.e-265"), ldexp(8168427841980010, -930));
EXPECT_EQ(ToDouble("85.e-037"), ldexp(6360455125664090, -169));
EXPECT_EQ(ToDouble("623.e100"), ldexp(6263531988747231, 289));
EXPECT_EQ(ToDouble("3571.e263"), ldexp(6234526311072170, 833));
EXPECT_EQ(ToDouble("81661.e153"), ldexp(6696636728760206, 472));
EXPECT_EQ(ToDouble("920657.e-023"), ldexp(5975405561110124, -109));
EXPECT_EQ(ToDouble("4603285.e-024"), ldexp(5975405561110124, -110));
EXPECT_EQ(ToDouble("87575437.e-309"), ldexp(8452160731874668, -1053));
EXPECT_EQ(ToDouble("245540327.e122"), ldexp(4985336549131723, 381));
EXPECT_EQ(ToDouble("6138508175.e120"), ldexp(4985336549131723, 379));
EXPECT_EQ(ToDouble("83356057653.e193"), ldexp(5986732817132056, 625));
EXPECT_EQ(ToDouble("619534293513.e124"), ldexp(4798406992060657, 399));
EXPECT_EQ(ToDouble("2335141086879.e218"), ldexp(5419088166961646, 713));
EXPECT_EQ(ToDouble("36167929443327.e-159"), ldexp(8135819834632444, -536));
EXPECT_EQ(ToDouble("609610927149051.e-255"), ldexp(4576664294594737, -850));
EXPECT_EQ(ToDouble("3743626360493413.e-165"), ldexp(6898586531774201, -549));
EXPECT_EQ(ToDouble("94080055902682397.e-242"), ldexp(6273271706052298, -800));
EXPECT_EQ(ToDouble("899810892172646163.e283"), ldexp(7563892574477827, 947));
EXPECT_EQ(ToDouble("7120190517612959703.e120"), ldexp(5385467232557565, 409));
EXPECT_EQ(ToDouble("25188282901709339043.e-252"),
ldexp(5635662608542340, -825));
EXPECT_EQ(ToDouble("308984926168550152811.e-052"),
ldexp(5644774693823803, -157));
EXPECT_EQ(ToDouble("6372891218502368041059.e064"),
ldexp(4616868614322430, 233));
EXPECT_EQ(ToFloat("3.e-23"), ldexpf(9507380, -98));
EXPECT_EQ(ToFloat("57.e18"), ldexpf(12960300, 42));
EXPECT_EQ(ToFloat("789.e-35"), ldexpf(10739312, -130));
EXPECT_EQ(ToFloat("2539.e-18"), ldexpf(11990089, -72));
EXPECT_EQ(ToFloat("76173.e28"), ldexpf(9845130, 86));
EXPECT_EQ(ToFloat("887745.e-11"), ldexpf(9760860, -40));
EXPECT_EQ(ToFloat("5382571.e-37"), ldexpf(11447463, -124));
EXPECT_EQ(ToFloat("82381273.e-35"), ldexpf(8554961, -113));
EXPECT_EQ(ToFloat("750486563.e-38"), ldexpf(9975678, -120));
EXPECT_EQ(ToFloat("3752432815.e-39"), ldexpf(9975678, -121));
EXPECT_EQ(ToFloat("75224575729.e-45"), ldexpf(13105970, -137));
EXPECT_EQ(ToFloat("459926601011.e15"), ldexpf(12466336, 65));
}
template <typename FloatType>
void TestHalfwayValue(const std::string& mantissa, int exponent,
FloatType expected_low, FloatType expected_high,
FloatType expected_half) {
std::string low_rep = mantissa;
low_rep[low_rep.size() - 1] -= 1;
absl::StrAppend(&low_rep, std::string(1000, '9'), "e", exponent);
FloatType actual_low = 0;
absl::from_chars(low_rep.data(), low_rep.data() + low_rep.size(), actual_low);
EXPECT_EQ(expected_low, actual_low);
std::string high_rep =
absl::StrCat(mantissa, std::string(1000, '0'), "1e", exponent);
FloatType actual_high = 0;
absl::from_chars(high_rep.data(), high_rep.data() + high_rep.size(),
actual_high);
EXPECT_EQ(expected_high, actual_high);
std::string halfway_rep = absl::StrCat(mantissa, "e", exponent);
FloatType actual_half = 0;
absl::from_chars(halfway_rep.data(), halfway_rep.data() + halfway_rep.size(),
actual_half);
EXPECT_EQ(expected_half, actual_half);
}
TEST(FromChars, DoubleRounding) {
const double zero = 0.0;
const double first_subnormal = nextafter(zero, 1.0);
const double second_subnormal = nextafter(first_subnormal, 1.0);
const double first_normal = DBL_MIN;
const double last_subnormal = nextafter(first_normal, 0.0);
const double second_normal = nextafter(first_normal, 1.0);
const double last_normal = DBL_MAX;
const double penultimate_normal = nextafter(last_normal, 0.0);
TestHalfwayValue(
"2."
"470328229206232720882843964341106861825299013071623822127928412503377536"
"351043759326499181808179961898982823477228588654633283551779698981993873"
"980053909390631503565951557022639229085839244910518443593180284993653615"
"250031937045767824921936562366986365848075700158576926990370631192827955"
"855133292783433840935197801553124659726357957462276646527282722005637400"
"648549997709659947045402082816622623785739345073633900796776193057750674"
"017632467360096895134053553745851666113422376667860416215968046191446729"
"184030053005753084904876539171138659164623952491262365388187963623937328"
"042389101867234849766823508986338858792562830275599565752445550725518931"
"369083625477918694866799496832404970582102851318545139621383772282614543"
"7693412532098591327667236328125",
-324, zero, first_subnormal, zero);
TestHalfwayValue(
"7."
"410984687618698162648531893023320585475897039214871466383785237510132609"
"053131277979497545424539885696948470431685765963899850655339096945981621"
"940161728171894510697854671067917687257517734731555330779540854980960845"
"750095811137303474765809687100959097544227100475730780971111893578483867"
"565399878350301522805593404659373979179073872386829939581848166016912201"
"945649993128979841136206248449867871357218035220901702390328579173252022"
"052897402080290685402160661237554998340267130003581248647904138574340187"
"552090159017259254714629617513415977493871857473787096164563890871811984"
"127167305601704549300470526959016576377688490826798697257336652176556794"
"107250876433756084600398490497214911746308553955635418864151316847843631"
"3080237596295773983001708984375",
-324, first_subnormal, second_subnormal, second_subnormal);
TestHalfwayValue(
"2."
"225073858507201136057409796709131975934819546351645648023426109724822222"
"021076945516529523908135087914149158913039621106870086438694594645527657"
"207407820621743379988141063267329253552286881372149012981122451451889849"
"057222307285255133155755015914397476397983411801999323962548289017107081"
"850690630666655994938275772572015763062690663332647565300009245888316433"
"037779791869612049497390377829704905051080609940730262937128958950003583"
"799967207254304360284078895771796150945516748243471030702609144621572289"
"880258182545180325707018860872113128079512233426288368622321503775666622"
"503982534335974568884423900265498198385487948292206894721689831099698365"
"846814022854243330660339850886445804001034933970427567186443383770486037"
"86162277173854562306587467901408672332763671875",
-308, last_subnormal, first_normal, first_normal);
TestHalfwayValue(
"2."
"225073858507201630123055637955676152503612414573018013083228724049586647"
"606759446192036794116886953213985520549032000903434781884412325572184367"
"563347617020518175998922941393629966742598285899994830148971433555578567"
"693279306015978183162142425067962460785295885199272493577688320732492479"
"924816869232247165964934329258783950102250973957579510571600738343645738"
"494324192997092179207389919761694314131497173265255020084997973676783743"
"155205818804439163810572367791175177756227497413804253387084478193655533"
"073867420834526162513029462022730109054820067654020201547112002028139700"
"141575259123440177362244273712468151750189745559978653234255886219611516"
"335924167958029604477064946470184777360934300451421683607013647479513962"
"13837722826145437693412532098591327667236328125",
-308, first_normal, second_normal, first_normal);
TestHalfwayValue(
"1."
"797693134862315608353258760581052985162070023416521662616611746258695532"
"672923265745300992879465492467506314903358770175220871059269879629062776"
"047355692132901909191523941804762171253349609463563872612866401980290377"
"995141836029815117562837277714038305214839639239356331336428021390916694"
"57927874464075218944",
308, penultimate_normal, last_normal, penultimate_normal);
}
TEST(FromChars, FloatRounding) {
const float zero = 0.0;
const float first_subnormal = nextafterf(zero, 1.0);
const float second_subnormal = nextafterf(first_subnormal, 1.0);
const float first_normal = FLT_MIN;
const float last_subnormal = nextafterf(first_normal, 0.0);
const float second_normal = nextafterf(first_normal, 1.0);
const float last_normal = FLT_MAX;
const float penultimate_normal = nextafterf(last_normal, 0.0);
TestHalfwayValue(
"7."
"006492321624085354618647916449580656401309709382578858785341419448955413"
"42930300743319094181060791015625",
-46, zero, first_subnormal, zero);
TestHalfwayValue(
"2."
"101947696487225606385594374934874196920392912814773657635602425834686624"
"028790902229957282543182373046875",
-45, first_subnormal, second_subnormal, second_subnormal);
TestHalfwayValue(
"1."
"175494280757364291727882991035766513322858992758990427682963118425003064"
"9651730385585324256680905818939208984375",
-38, last_subnormal, first_normal, first_normal);
TestHalfwayValue(
"1."
"175494420887210724209590083408724842314472120785184615334540294131831453"
"9442813071445925743319094181060791015625",
-38, first_normal, second_normal, first_normal);
TestHalfwayValue("3.40282336497324057985868971510891282432", 38,
penultimate_normal, last_normal, penultimate_normal);
}
TEST(FromChars, Underflow) {
double d;
float f;
absl::from_chars_result result;
std::string negative_underflow = "-1e-1000";
const char* begin = negative_underflow.data();
const char* end = begin + negative_underflow.size();
d = 100.0;
result = absl::from_chars(begin, end, d);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_TRUE(std::signbit(d));
EXPECT_GE(d, -std::numeric_limits<double>::min());
f = 100.0;
result = absl::from_chars(begin, end, f);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_TRUE(std::signbit(f));
EXPECT_GE(f, -std::numeric_limits<float>::min());
std::string positive_underflow = "1e-1000";
begin = positive_underflow.data();
end = begin + positive_underflow.size();
d = -100.0;
result = absl::from_chars(begin, end, d);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_FALSE(std::signbit(d));
EXPECT_LE(d, std::numeric_limits<double>::min());
f = -100.0;
result = absl::from_chars(begin, end, f);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_FALSE(std::signbit(f));
EXPECT_LE(f, std::numeric_limits<float>::min());
}
TEST(FromChars, Overflow) {
double d;
float f;
absl::from_chars_result result;
std::string negative_overflow = "-1e1000";
const char* begin = negative_overflow.data();
const char* end = begin + negative_overflow.size();
d = 100.0;
result = absl::from_chars(begin, end, d);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_TRUE(std::signbit(d));
EXPECT_EQ(d, -std::numeric_limits<double>::max());
f = 100.0;
result = absl::from_chars(begin, end, f);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_TRUE(std::signbit(f));
EXPECT_EQ(f, -std::numeric_limits<float>::max());
std::string positive_overflow = "1e1000";
begin = positive_overflow.data();
end = begin + positive_overflow.size();
d = -100.0;
result = absl::from_chars(begin, end, d);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_FALSE(std::signbit(d));
EXPECT_EQ(d, std::numeric_limits<double>::max());
f = -100.0;
result = absl::from_chars(begin, end, f);
EXPECT_EQ(result.ptr, end);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_FALSE(std::signbit(f));
EXPECT_EQ(f, std::numeric_limits<float>::max());
}
TEST(FromChars, RegressionTestsFromFuzzer) {
absl::string_view src = "0x21900000p00000000099";
float f;
auto result = absl::from_chars(src.data(), src.data() + src.size(), f);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
}
TEST(FromChars, ReturnValuePtr) {
double d;
absl::from_chars_result result;
std::string normal = "3.14@#$%@#$%";
result = absl::from_chars(normal.data(), normal.data() + normal.size(), d);
EXPECT_EQ(result.ec, std::errc());
EXPECT_EQ(result.ptr - normal.data(), 4);
std::string overflow = "1e1000@#$%@#$%";
result = absl::from_chars(overflow.data(),
overflow.data() + overflow.size(), d);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_EQ(result.ptr - overflow.data(), 6);
std::string garbage = "#$%@#$%";
result = absl::from_chars(garbage.data(),
garbage.data() + garbage.size(), d);
EXPECT_EQ(result.ec, std::errc::invalid_argument);
EXPECT_EQ(result.ptr - garbage.data(), 0);
}
TEST(FromChars, TestVersusStrtod) {
for (int mantissa = 1000000; mantissa <= 9999999; mantissa += 501) {
for (int exponent = -300; exponent < 300; ++exponent) {
std::string candidate = absl::StrCat(mantissa, "e", exponent);
double strtod_value = strtod(candidate.c_str(), nullptr);
double absl_value = 0;
absl::from_chars(candidate.data(), candidate.data() + candidate.size(),
absl_value);
ASSERT_EQ(strtod_value, absl_value) << candidate;
}
}
}
TEST(FromChars, TestVersusStrtof) {
for (int mantissa = 1000000; mantissa <= 9999999; mantissa += 501) {
for (int exponent = -43; exponent < 32; ++exponent) {
std::string candidate = absl::StrCat(mantissa, "e", exponent);
float strtod_value = strtof(candidate.c_str(), nullptr);
float absl_value = 0;
absl::from_chars(candidate.data(), candidate.data() + candidate.size(),
absl_value);
ASSERT_EQ(strtod_value, absl_value) << candidate;
}
}
}
template <typename Float>
bool Identical(Float a, Float b) {
return 0 == memcmp(&a, &b, sizeof(Float));
}
TEST(FromChars, NaNDoubles) {
for (std::string n_char_sequence :
{"", "1", "2", "3", "fff", "FFF", "200000", "400000", "4000000000000",
"8000000000000", "abc123", "legal_but_unexpected",
"99999999999999999999999", "_"}) {
std::string input = absl::StrCat("nan(", n_char_sequence, ")");
SCOPED_TRACE(input);
double from_chars_double;
absl::from_chars(input.data(), input.data() + input.size(),
from_chars_double);
double std_nan_double = std::nan(n_char_sequence.c_str());
EXPECT_TRUE(Identical(from_chars_double, std_nan_double));
#if ABSL_STRTOD_HANDLES_NAN_CORRECTLY
double strtod_double = strtod(input.c_str(), nullptr);
EXPECT_TRUE(Identical(from_chars_double, strtod_double));
#endif
std::string negative_input = "-" + input;
double negative_from_chars_double;
absl::from_chars(negative_input.data(),
negative_input.data() + negative_input.size(),
negative_from_chars_double);
EXPECT_TRUE(std::signbit(negative_from_chars_double));
EXPECT_FALSE(Identical(negative_from_chars_double, from_chars_double));
from_chars_double = std::copysign(from_chars_double, -1.0);
EXPECT_TRUE(Identical(negative_from_chars_double, from_chars_double));
}
}
TEST(FromChars, NaNFloats) {
for (std::string n_char_sequence :
{"", "1", "2", "3", "fff", "FFF", "200000", "400000", "4000000000000",
"8000000000000", "abc123", "legal_but_unexpected",
"99999999999999999999999", "_"}) {
std::string input = absl::StrCat("nan(", n_char_sequence, ")");
SCOPED_TRACE(input);
float from_chars_float;
absl::from_chars(input.data(), input.data() + input.size(),
from_chars_float);
float std_nan_float = std::nanf(n_char_sequence.c_str());
EXPECT_TRUE(Identical(from_chars_float, std_nan_float));
#if ABSL_STRTOD_HANDLES_NAN_CORRECTLY
float strtof_float = strtof(input.c_str(), nullptr);
EXPECT_TRUE(Identical(from_chars_float, strtof_float));
#endif
std::string negative_input = "-" + input;
float negative_from_chars_float;
absl::from_chars(negative_input.data(),
negative_input.data() + negative_input.size(),
negative_from_chars_float);
EXPECT_TRUE(std::signbit(negative_from_chars_float));
EXPECT_FALSE(Identical(negative_from_chars_float, from_chars_float));
from_chars_float = std::copysign(from_chars_float, -1.0f);
EXPECT_TRUE(Identical(negative_from_chars_float, from_chars_float));
}
}
int NextStep(int step) {
return step + (step >> 2) + 1;
}
template <typename Float>
void TestOverflowAndUnderflow(
const std::function<std::string(int)>& input_generator,
const std::function<Float(int)>& expected_generator, int lower_bound,
int upper_bound) {
int index, step;
for (index = lower_bound, step = 1; index < upper_bound;
index += step, step = NextStep(step)) {
std::string input = input_generator(index);
SCOPED_TRACE(input);
Float expected = expected_generator(index);
Float actual;
auto result =
absl::from_chars(input.data(), input.data() + input.size(), actual);
EXPECT_EQ(result.ec, std::errc());
EXPECT_EQ(expected, actual)
<< absl::StrFormat("%a vs %a", expected, actual);
}
for (index = upper_bound, step = 1; index > lower_bound;
index -= step, step = NextStep(step)) {
std::string input = input_generator(index);
SCOPED_TRACE(input);
Float expected = expected_generator(index);
Float actual;
auto result =
absl::from_chars(input.data(), input.data() + input.size(), actual);
EXPECT_EQ(result.ec, std::errc());
EXPECT_EQ(expected, actual)
<< absl::StrFormat("%a vs %a", expected, actual);
}
for (index = lower_bound - 1, step = 1; index > -1000000;
index -= step, step = NextStep(step)) {
std::string input = input_generator(index);
SCOPED_TRACE(input);
Float actual;
auto result =
absl::from_chars(input.data(), input.data() + input.size(), actual);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_LT(actual, 1.0);
}
for (index = upper_bound + 1, step = 1; index < 1000000;
index += step, step = NextStep(step)) {
std::string input = input_generator(index);
SCOPED_TRACE(input);
Float actual;
auto result =
absl::from_chars(input.data(), input.data() + input.size(), actual);
EXPECT_EQ(result.ec, std::errc::result_out_of_range);
EXPECT_GT(actual, 1.0);
}
}
TEST(FromChars, HexdecimalDoubleLimits) {
auto input_gen = [](int index) { return absl::StrCat("0x1.0p", index); };
auto expected_gen = [](int index) { return std::ldexp(1.0, index); };
TestOverflowAndUnderflow<doub |
2,545 | cpp | abseil/abseil-cpp | ascii | absl/strings/ascii.cc | absl/strings/ascii_test.cc | #ifndef ABSL_STRINGS_ASCII_H_
#define ABSL_STRINGS_ASCII_H_
#include <algorithm>
#include <cstddef>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/nullability.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace ascii_internal {
ABSL_DLL extern const unsigned char kPropertyBits[256];
ABSL_DLL extern const char kToUpper[256];
ABSL_DLL extern const char kToLower[256];
}
inline bool ascii_isalpha(unsigned char c) {
return (ascii_internal::kPropertyBits[c] & 0x01) != 0;
}
inline bool ascii_isalnum(unsigned char c) {
return (ascii_internal::kPropertyBits[c] & 0x04) != 0;
}
inline bool ascii_isspace(unsigned char c) {
return (ascii_internal::kPropertyBits[c] & 0x08) != 0;
}
inline bool ascii_ispunct(unsigned char c) {
return (ascii_internal::kPropertyBits[c] & 0x10) != 0;
}
inline bool ascii_isblank(unsigned char c) {
return (ascii_internal::kPropertyBits[c] & 0x20) != 0;
}
inline bool ascii_iscntrl(unsigned char c) {
return (ascii_internal::kPropertyBits[c] & 0x40) != 0;
}
inline bool ascii_isxdigit(unsigned char c) {
return (ascii_internal::kPropertyBits[c] & 0x80) != 0;
}
inline bool ascii_isdigit(unsigned char c) { return c >= '0' && c <= '9'; }
inline bool ascii_isprint(unsigned char c) { return c >= 32 && c < 127; }
inline bool ascii_isgraph(unsigned char c) { return c > 32 && c < 127; }
inline bool ascii_isupper(unsigned char c) { return c >= 'A' && c <= 'Z'; }
inline bool ascii_islower(unsigned char c) { return c >= 'a' && c <= 'z'; }
inline bool ascii_isascii(unsigned char c) { return c < 128; }
inline char ascii_tolower(unsigned char c) {
return ascii_internal::kToLower[c];
}
void AsciiStrToLower(absl::Nonnull<std::string*> s);
ABSL_MUST_USE_RESULT inline std::string AsciiStrToLower(absl::string_view s) {
std::string result(s);
absl::AsciiStrToLower(&result);
return result;
}
inline char ascii_toupper(unsigned char c) {
return ascii_internal::kToUpper[c];
}
void AsciiStrToUpper(absl::Nonnull<std::string*> s);
ABSL_MUST_USE_RESULT inline std::string AsciiStrToUpper(absl::string_view s) {
std::string result(s);
absl::AsciiStrToUpper(&result);
return result;
}
ABSL_MUST_USE_RESULT inline absl::string_view StripLeadingAsciiWhitespace(
absl::string_view str) {
auto it = std::find_if_not(str.begin(), str.end(), absl::ascii_isspace);
return str.substr(static_cast<size_t>(it - str.begin()));
}
inline void StripLeadingAsciiWhitespace(absl::Nonnull<std::string*> str) {
auto it = std::find_if_not(str->begin(), str->end(), absl::ascii_isspace);
str->erase(str->begin(), it);
}
ABSL_MUST_USE_RESULT inline absl::string_view StripTrailingAsciiWhitespace(
absl::string_view str) {
auto it = std::find_if_not(str.rbegin(), str.rend(), absl::ascii_isspace);
return str.substr(0, static_cast<size_t>(str.rend() - it));
}
inline void StripTrailingAsciiWhitespace(absl::Nonnull<std::string*> str) {
auto it = std::find_if_not(str->rbegin(), str->rend(), absl::ascii_isspace);
str->erase(static_cast<size_t>(str->rend() - it));
}
ABSL_MUST_USE_RESULT inline absl::string_view StripAsciiWhitespace(
absl::string_view str) {
return StripTrailingAsciiWhitespace(StripLeadingAsciiWhitespace(str));
}
inline void StripAsciiWhitespace(absl::Nonnull<std::string*> str) {
StripTrailingAsciiWhitespace(str);
StripLeadingAsciiWhitespace(str);
}
void RemoveExtraAsciiWhitespace(absl::Nonnull<std::string*> str);
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/ascii.h"
#include <climits>
#include <cstddef>
#include <cstring>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace ascii_internal {
ABSL_DLL const unsigned char kPropertyBits[256] = {
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x68, 0x48, 0x48, 0x48, 0x48, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,
0x28, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84,
0x84, 0x84, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x85, 0x85, 0x85, 0x85, 0x85, 0x85, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
0x05, 0x05, 0x05, 0x10, 0x10, 0x10, 0x10, 0x40,
};
ABSL_DLL const char kToLower[256] = {
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
'\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
'\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
'\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
'\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
'\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
'\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
'\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
'\x40', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
'\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
'\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
'\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
'\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f',
'\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87',
'\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e', '\x8f',
'\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97',
'\x98', '\x99', '\x9a', '\x9b', '\x9c', '\x9d', '\x9e', '\x9f',
'\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7',
'\xa8', '\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf',
'\xb0', '\xb1', '\xb2', '\xb3', '\xb4', '\xb5', '\xb6', '\xb7',
'\xb8', '\xb9', '\xba', '\xbb', '\xbc', '\xbd', '\xbe', '\xbf',
'\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7',
'\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf',
'\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7',
'\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf',
'\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7',
'\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef',
'\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7',
'\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff',
};
ABSL_DLL const char kToUpper[256] = {
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
'\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
'\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
'\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
'\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
'\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
'\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
'\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
'\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47',
'\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f',
'\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57',
'\x58', '\x59', '\x5a', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
'\x60', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f',
'\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87',
'\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e', '\x8f',
'\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97',
'\x98', '\x99', '\x9a', '\x9b', '\x9c', '\x9d', '\x9e', '\x9f',
'\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7',
'\xa8', '\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf',
'\xb0', '\xb1', '\xb2', '\xb3', '\xb4', '\xb5', '\xb6', '\xb7',
'\xb8', '\xb9', '\xba', '\xbb', '\xbc', '\xbd', '\xbe', '\xbf',
'\xc0', '\xc1', '\xc2', '\xc3', '\xc4', '\xc5', '\xc6', '\xc7',
'\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf',
'\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7',
'\xd8', '\xd9', '\xda', '\xdb', '\xdc', '\xdd', '\xde', '\xdf',
'\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7',
'\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef',
'\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6', '\xf7',
'\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff',
};
template <bool ToUpper>
constexpr bool AsciiInAZRange(unsigned char c) {
constexpr unsigned char sub = (ToUpper ? 'a' : 'A') - SCHAR_MIN;
constexpr signed char threshold = SCHAR_MIN + 26;
unsigned char u = c - sub;
return static_cast<signed char>(u) < threshold;
}
template <bool ToUpper>
ABSL_ATTRIBUTE_ALWAYS_INLINE inline constexpr void AsciiStrCaseFoldImpl(
absl::Nonnull<char*> p, size_t size) {
constexpr unsigned char kAsciiCaseBitFlip = 'a' ^ 'A';
for (size_t i = 0; i < size; ++i) {
unsigned char v = static_cast<unsigned char>(p[i]);
v ^= AsciiInAZRange<ToUpper>(v) ? kAsciiCaseBitFlip : 0;
p[i] = static_cast<char>(v);
}
}
constexpr size_t kCaseFoldThreshold = 16;
template <bool ToUpper>
ABSL_ATTRIBUTE_NOINLINE constexpr void AsciiStrCaseFoldLong(
absl::Nonnull<char*> p, size_t size) {
ABSL_ASSUME(size >= kCaseFoldThreshold);
AsciiStrCaseFoldImpl<ToUpper>(p, size);
}
template <bool ToUpper>
constexpr void AsciiStrCaseFold(absl::Nonnull<char*> p, size_t size) {
size < kCaseFoldThreshold ? AsciiStrCaseFoldImpl<ToUpper>(p, size)
: AsciiStrCaseFoldLong<ToUpper>(p, size);
}
static constexpr size_t ValidateAsciiCasefold() {
constexpr size_t num_chars = 1 + CHAR_MAX - CHAR_MIN;
size_t incorrect_index = 0;
char lowered[num_chars] = {};
char uppered[num_chars] = {};
for (unsigned int i = 0; i < num_chars; ++i) {
uppered[i] = lowered[i] = static_cast<char>(i);
}
AsciiStrCaseFold<false>(&lowered[0], num_chars);
AsciiStrCaseFold<true>(&uppered[0], num_chars);
for (size_t i = 0; i < num_chars; ++i) {
const char ch = static_cast<char>(i),
ch_upper = ('a' <= ch && ch <= 'z' ? 'A' + (ch - 'a') : ch),
ch_lower = ('A' <= ch && ch <= 'Z' ? 'a' + (ch - 'A') : ch);
if (uppered[i] != ch_upper || lowered[i] != ch_lower) {
incorrect_index = i > 0 ? i : num_chars;
break;
}
}
return incorrect_index;
}
static_assert(ValidateAsciiCasefold() == 0, "error in case conversion");
}
void AsciiStrToLower(absl::Nonnull<std::string*> s) {
return ascii_internal::AsciiStrCaseFold<false>(&(*s)[0], s->size());
}
void AsciiStrToUpper(absl::Nonnull<std::string*> s) {
return ascii_internal::AsciiStrCaseFold<true>(&(*s)[0], s->size());
}
void RemoveExtraAsciiWhitespace(absl::Nonnull<std::string*> str) {
auto stripped = StripAsciiWhitespace(*str);
if (stripped.empty()) {
str->clear();
return;
}
auto input_it = stripped.begin();
auto input_end = stripped.end();
auto output_it = &(*str)[0];
bool is_ws = false;
for (; input_it < input_end; ++input_it) {
if (is_ws) {
is_ws = absl::ascii_isspace(static_cast<unsigned char>(*input_it));
if (is_ws) --output_it;
} else {
is_ws = absl::ascii_isspace(static_cast<unsigned char>(*input_it));
}
*output_it = *input_it;
++output_it;
}
str->erase(static_cast<size_t>(output_it - &(*str)[0]));
}
ABSL_NAMESPACE_END
} | #include "absl/strings/ascii.h"
#include <algorithm>
#include <cctype>
#include <clocale>
#include <cstring>
#include <string>
#include "gtest/gtest.h"
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
namespace {
TEST(AsciiIsFoo, All) {
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
EXPECT_TRUE(absl::ascii_isalpha(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isalpha(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if ((c >= '0' && c <= '9'))
EXPECT_TRUE(absl::ascii_isdigit(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isdigit(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (absl::ascii_isalpha(c) || absl::ascii_isdigit(c))
EXPECT_TRUE(absl::ascii_isalnum(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isalnum(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (i != '\0' && strchr(" \r\n\t\v\f", i))
EXPECT_TRUE(absl::ascii_isspace(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isspace(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (i >= 32 && i < 127)
EXPECT_TRUE(absl::ascii_isprint(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isprint(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (absl::ascii_isprint(c) && !absl::ascii_isspace(c) &&
!absl::ascii_isalnum(c)) {
EXPECT_TRUE(absl::ascii_ispunct(c)) << ": failed on " << c;
} else {
EXPECT_TRUE(!absl::ascii_ispunct(c)) << ": failed on " << c;
}
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (i == ' ' || i == '\t')
EXPECT_TRUE(absl::ascii_isblank(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isblank(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (i < 32 || i == 127)
EXPECT_TRUE(absl::ascii_iscntrl(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_iscntrl(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (absl::ascii_isdigit(c) || (i >= 'A' && i <= 'F') ||
(i >= 'a' && i <= 'f')) {
EXPECT_TRUE(absl::ascii_isxdigit(c)) << ": failed on " << c;
} else {
EXPECT_TRUE(!absl::ascii_isxdigit(c)) << ": failed on " << c;
}
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (i > 32 && i < 127)
EXPECT_TRUE(absl::ascii_isgraph(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isgraph(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (i >= 'A' && i <= 'Z')
EXPECT_TRUE(absl::ascii_isupper(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_isupper(c)) << ": failed on " << c;
}
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (i >= 'a' && i <= 'z')
EXPECT_TRUE(absl::ascii_islower(c)) << ": failed on " << c;
else
EXPECT_TRUE(!absl::ascii_islower(c)) << ": failed on " << c;
}
for (unsigned char c = 0; c < 128; c++) {
EXPECT_TRUE(absl::ascii_isascii(c)) << ": failed on " << c;
}
for (int i = 128; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
EXPECT_TRUE(!absl::ascii_isascii(c)) << ": failed on " << c;
}
}
TEST(AsciiIsFoo, SameAsIsFoo) {
#ifndef __ANDROID__
const char* old_locale = setlocale(LC_CTYPE, "C");
ASSERT_TRUE(old_locale != nullptr);
#endif
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
EXPECT_EQ(isalpha(c) != 0, absl::ascii_isalpha(c)) << c;
EXPECT_EQ(isdigit(c) != 0, absl::ascii_isdigit(c)) << c;
EXPECT_EQ(isalnum(c) != 0, absl::ascii_isalnum(c)) << c;
EXPECT_EQ(isspace(c) != 0, absl::ascii_isspace(c)) << c;
EXPECT_EQ(ispunct(c) != 0, absl::ascii_ispunct(c)) << c;
EXPECT_EQ(isblank(c) != 0, absl::ascii_isblank(c)) << c;
EXPECT_EQ(iscntrl(c) != 0, absl::ascii_iscntrl(c)) << c;
EXPECT_EQ(isxdigit(c) != 0, absl::ascii_isxdigit(c)) << c;
EXPECT_EQ(isprint(c) != 0, absl::ascii_isprint(c)) << c;
EXPECT_EQ(isgraph(c) != 0, absl::ascii_isgraph(c)) << c;
EXPECT_EQ(isupper(c) != 0, absl::ascii_isupper(c)) << c;
EXPECT_EQ(islower(c) != 0, absl::ascii_islower(c)) << c;
EXPECT_EQ(isascii(c) != 0, absl::ascii_isascii(c)) << c;
}
#ifndef __ANDROID__
ASSERT_TRUE(setlocale(LC_CTYPE, old_locale));
#endif
}
TEST(AsciiToFoo, All) {
#ifndef __ANDROID__
const char* old_locale = setlocale(LC_CTYPE, "C");
ASSERT_TRUE(old_locale != nullptr);
#endif
for (int i = 0; i < 256; i++) {
const auto c = static_cast<unsigned char>(i);
if (absl::ascii_islower(c))
EXPECT_EQ(absl::ascii_toupper(c), 'A' + (i - 'a')) << c;
else
EXPECT_EQ(absl::ascii_toupper(c), static_cast<char>(i)) << c;
if (absl::ascii_isupper(c))
EXPECT_EQ(absl::ascii_tolower(c), 'a' + (i - 'A')) << c;
else
EXPECT_EQ(absl::ascii_tolower(c), static_cast<char>(i)) << c;
EXPECT_EQ(static_cast<char>(tolower(i)), absl::ascii_tolower(c)) << c;
EXPECT_EQ(static_cast<char>(toupper(i)), absl::ascii_toupper(c)) << c;
}
#ifndef __ANDROID__
ASSERT_TRUE(setlocale(LC_CTYPE, old_locale));
#endif
}
TEST(AsciiStrTo, Lower) {
const char buf[] = "ABCDEF";
const std::string str("GHIJKL");
const std::string str2("MNOPQR");
const absl::string_view sp(str2);
const std::string long_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ1!a");
std::string mutable_str("_`?@[{AMNOPQRSTUVWXYZ");
EXPECT_EQ("abcdef", absl::AsciiStrToLower(buf));
EXPECT_EQ("ghijkl", absl::AsciiStrToLower(str));
EXPECT_EQ("mnopqr", absl::AsciiStrToLower(sp));
EXPECT_EQ("abcdefghijklmnopqrstuvwxyz1!a", absl::AsciiStrToLower(long_str));
absl::AsciiStrToLower(&mutable_str);
EXPECT_EQ("_`?@[{amnopqrstuvwxyz", mutable_str);
char mutable_buf[] = "Mutable";
std::transform(mutable_buf, mutable_buf + strlen(mutable_buf),
mutable_buf, absl::ascii_tolower);
EXPECT_STREQ("mutable", mutable_buf);
}
TEST(AsciiStrTo, Upper) {
const char buf[] = "abcdef";
const std::string str("ghijkl");
const std::string str2("_`?@[{amnopqrstuvwxyz");
const absl::string_view sp(str2);
const std::string long_str("abcdefghijklmnopqrstuvwxyz1!A");
EXPECT_EQ("ABCDEF", absl::AsciiStrToUpper(buf));
EXPECT_EQ("GHIJKL", absl::AsciiStrToUpper(str));
EXPECT_EQ("_`?@[{AMNOPQRSTUVWXYZ", absl::AsciiStrToUpper(sp));
EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1!A", absl::AsciiStrToUpper(long_str));
char mutable_buf[] = "Mutable";
std::transform(mutable_buf, mutable_buf + strlen(mutable_buf),
mutable_buf, absl::ascii_toupper);
EXPECT_STREQ("MUTABLE", mutable_buf);
}
TEST(StripLeadingAsciiWhitespace, FromStringView) {
EXPECT_EQ(absl::string_view{},
absl::StripLeadingAsciiWhitespace(absl::string_view{}));
EXPECT_EQ("foo", absl::StripLeadingAsciiWhitespace({"foo"}));
EXPECT_EQ("foo", absl::StripLeadingAsciiWhitespace({"\t \n\f\r\n\vfoo"}));
EXPECT_EQ("foo foo\n ",
absl::StripLeadingAsciiWhitespace({"\t \n\f\r\n\vfoo foo\n "}));
EXPECT_EQ(absl::string_view{}, absl::StripLeadingAsciiWhitespace(
{"\t \n\f\r\v\n\t \n\f\r\v\n"}));
}
TEST(StripLeadingAsciiWhitespace, InPlace) {
std::string str;
absl::StripLeadingAsciiWhitespace(&str);
EXPECT_EQ("", str);
str = "foo";
absl::StripLeadingAsciiWhitespace(&str);
EXPECT_EQ("foo", str);
str = "\t \n\f\r\n\vfoo";
absl::StripLeadingAsciiWhitespace(&str);
EXPECT_EQ("foo", str);
str = "\t \n\f\r\n\vfoo foo\n ";
absl::StripLeadingAsciiWhitespace(&str);
EXPECT_EQ("foo foo\n ", str);
str = "\t \n\f\r\v\n\t \n\f\r\v\n";
absl::StripLeadingAsciiWhitespace(&str);
EXPECT_EQ(absl::string_view{}, str);
}
TEST(StripTrailingAsciiWhitespace, FromStringView) {
EXPECT_EQ(absl::string_view{},
absl::StripTrailingAsciiWhitespace(absl::string_view{}));
EXPECT_EQ("foo", absl::StripTrailingAsciiWhitespace({"foo"}));
EXPECT_EQ("foo", absl::StripTrailingAsciiWhitespace({"foo\t \n\f\r\n\v"}));
EXPECT_EQ(" \nfoo foo",
absl::StripTrailingAsciiWhitespace({" \nfoo foo\t \n\f\r\n\v"}));
EXPECT_EQ(absl::string_view{}, absl::StripTrailingAsciiWhitespace(
{"\t \n\f\r\v\n\t \n\f\r\v\n"}));
}
TEST(StripTrailingAsciiWhitespace, InPlace) {
std::string str;
absl::StripTrailingAsciiWhitespace(&str);
EXPECT_EQ("", str);
str = "foo";
absl::StripTrailingAsciiWhitespace(&str);
EXPECT_EQ("foo", str);
str = "foo\t \n\f\r\n\v";
absl::StripTrailingAsciiWhitespace(&str);
EXPECT_EQ("foo", str);
str = " \nfoo foo\t \n\f\r\n\v";
absl::StripTrailingAsciiWhitespace(&str);
EXPECT_EQ(" \nfoo foo", str);
str = "\t \n\f\r\v\n\t \n\f\r\v\n";
absl::StripTrailingAsciiWhitespace(&str);
EXPECT_EQ(absl::string_view{}, str);
}
TEST(StripAsciiWhitespace, FromStringView) {
EXPECT_EQ(absl::string_view{},
absl::StripAsciiWhitespace(absl::string_view{}));
EXPECT_EQ("foo", absl::StripAsciiWhitespace({"foo"}));
EXPECT_EQ("foo",
absl::StripAsciiWhitespace({"\t \n\f\r\n\vfoo\t \n\f\r\n\v"}));
EXPECT_EQ("foo foo", absl::StripAsciiWhitespace(
{"\t \n\f\r\n\vfoo foo\t \n\f\r\n\v"}));
EXPECT_EQ(absl::string_view{},
absl::StripAsciiWhitespace({"\t \n\f\r\v\n\t \n\f\r\v\n"}));
}
TEST(StripAsciiWhitespace, InPlace) {
std::string str;
absl::StripAsciiWhitespace(&str);
EXPECT_EQ("", str);
str = "foo";
absl::StripAsciiWhitespace(&str);
EXPECT_EQ("foo", str);
str = "\t \n\f\r\n\vfoo\t \n\f\r\n\v";
absl::StripAsciiWhitespace(&str);
EXPECT_EQ("foo", str);
str = "\t \n\f\r\n\vfoo foo\t \n\f\r\n\v";
absl::StripAsciiWhitespace(&str);
EXPECT_EQ("foo foo", str);
str = "\t \n\f\r\v\n\t \n\f\r\v\n";
absl::StripAsciiWhitespace(&str);
EXPECT_EQ(absl::string_view{}, str);
}
TEST(RemoveExtraAsciiWhitespace, InPlace) {
const char* inputs[] = {"No extra space",
" Leading whitespace",
"Trailing whitespace ",
" Leading and trailing ",
" Whitespace \t in\v middle ",
"'Eeeeep! \n Newlines!\n",
"nospaces",
"",
"\n\t a\t\n\nb \t\n"};
const char* outputs[] = {
"No extra space",
"Leading whitespace",
"Trailing whitespace",
"Leading and trailing",
"Whitespace in middle",
"'Eeeeep! Newlines!",
"nospaces",
"",
"a\nb",
};
const int NUM_TESTS = ABSL_ARRAYSIZE(inputs);
for (int i = 0; i < NUM_TESTS; i++) {
std::string s(inputs[i]);
absl::RemoveExtraAsciiWhitespace(&s);
EXPECT_EQ(outputs[i], s);
}
}
} |
2,546 | cpp | abseil/abseil-cpp | escaping | absl/strings/internal/escaping.cc | absl/strings/escaping_test.cc | #ifndef ABSL_STRINGS_INTERNAL_ESCAPING_H_
#define ABSL_STRINGS_INTERNAL_ESCAPING_H_
#include <cassert>
#include "absl/strings/internal/resize_uninitialized.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
ABSL_CONST_INIT extern const char kBase64Chars[];
ABSL_CONST_INIT extern const char kWebSafeBase64Chars[];
size_t CalculateBase64EscapedLenInternal(size_t input_len, bool do_padding);
size_t Base64EscapeInternal(const unsigned char* src, size_t szsrc, char* dest,
size_t szdest, const char* base64, bool do_padding);
template <typename String>
void Base64EscapeInternal(const unsigned char* src, size_t szsrc, String* dest,
bool do_padding, const char* base64_chars) {
const size_t calc_escaped_size =
CalculateBase64EscapedLenInternal(szsrc, do_padding);
STLStringResizeUninitialized(dest, calc_escaped_size);
const size_t escaped_len = Base64EscapeInternal(
src, szsrc, &(*dest)[0], dest->size(), base64_chars, do_padding);
assert(calc_escaped_size == escaped_len);
dest->erase(escaped_len);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/escaping.h"
#include <limits>
#include "absl/base/internal/endian.h"
#include "absl/base/internal/raw_logging.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
ABSL_CONST_INIT const char kBase64Chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
ABSL_CONST_INIT const char kWebSafeBase64Chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
size_t CalculateBase64EscapedLenInternal(size_t input_len, bool do_padding) {
constexpr size_t kMaxSize = (std::numeric_limits<size_t>::max() - 1) / 4 * 3;
ABSL_INTERNAL_CHECK(input_len <= kMaxSize,
"CalculateBase64EscapedLenInternal() overflow");
size_t len = (input_len / 3) * 4;
if (input_len % 3 == 0) {
} else if (input_len % 3 == 1) {
len += 2;
if (do_padding) {
len += 2;
}
} else {
len += 3;
if (do_padding) {
len += 1;
}
}
return len;
}
size_t Base64EscapeInternal(const unsigned char* src, size_t szsrc, char* dest,
size_t szdest, const char* base64,
bool do_padding) {
static const char kPad64 = '=';
if (szsrc * 4 > szdest * 3) return 0;
char* cur_dest = dest;
const unsigned char* cur_src = src;
char* const limit_dest = dest + szdest;
const unsigned char* const limit_src = src + szsrc;
if (szsrc >= 3) {
while (cur_src < limit_src - 3) {
uint32_t in = absl::big_endian::Load32(cur_src) >> 8;
cur_dest[0] = base64[in >> 18];
in &= 0x3FFFF;
cur_dest[1] = base64[in >> 12];
in &= 0xFFF;
cur_dest[2] = base64[in >> 6];
in &= 0x3F;
cur_dest[3] = base64[in];
cur_dest += 4;
cur_src += 3;
}
}
szdest = static_cast<size_t>(limit_dest - cur_dest);
szsrc = static_cast<size_t>(limit_src - cur_src);
switch (szsrc) {
case 0:
break;
case 1: {
if (szdest < 2) return 0;
uint32_t in = cur_src[0];
cur_dest[0] = base64[in >> 2];
in &= 0x3;
cur_dest[1] = base64[in << 4];
cur_dest += 2;
szdest -= 2;
if (do_padding) {
if (szdest < 2) return 0;
cur_dest[0] = kPad64;
cur_dest[1] = kPad64;
cur_dest += 2;
szdest -= 2;
}
break;
}
case 2: {
if (szdest < 3) return 0;
uint32_t in = absl::big_endian::Load16(cur_src);
cur_dest[0] = base64[in >> 10];
in &= 0x3FF;
cur_dest[1] = base64[in >> 4];
in &= 0x00F;
cur_dest[2] = base64[in << 2];
cur_dest += 3;
szdest -= 3;
if (do_padding) {
if (szdest < 1) return 0;
cur_dest[0] = kPad64;
cur_dest += 1;
szdest -= 1;
}
break;
}
case 3: {
if (szdest < 4) return 0;
uint32_t in =
(uint32_t{cur_src[0]} << 16) + absl::big_endian::Load16(cur_src + 1);
cur_dest[0] = base64[in >> 18];
in &= 0x3FFFF;
cur_dest[1] = base64[in >> 12];
in &= 0xFFF;
cur_dest[2] = base64[in >> 6];
in &= 0x3F;
cur_dest[3] = base64[in];
cur_dest += 4;
szdest -= 4;
break;
}
default:
ABSL_RAW_LOG(FATAL, "Logic problem? szsrc = %zu", szsrc);
break;
}
return static_cast<size_t>(cur_dest - dest);
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/escaping.h"
#include <array>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#include <memory>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "absl/log/check.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/internal/escaping_test_common.h"
#include "absl/strings/string_view.h"
namespace {
struct epair {
std::string escaped;
std::string unescaped;
};
TEST(CEscape, EscapeAndUnescape) {
const std::string inputs[] = {
std::string("foo\nxx\r\b\0023"),
std::string(""),
std::string("abc"),
std::string("\1chad_rules"),
std::string("\1arnar_drools"),
std::string("xxxx\r\t'\"\\"),
std::string("\0xx\0", 4),
std::string("\x01\x31"),
std::string("abc\xb\x42\141bc"),
std::string("123\1\x31\x32\x33"),
std::string("\xc1\xca\x1b\x62\x19o\xcc\x04"),
std::string(
"\\\"\xe8\xb0\xb7\xe6\xad\x8c\\\" is Google\\\'s Chinese name"),
};
for (int kind = 0; kind < 4; kind++) {
for (const std::string& original : inputs) {
std::string escaped;
switch (kind) {
case 0:
escaped = absl::CEscape(original);
break;
case 1:
escaped = absl::CHexEscape(original);
break;
case 2:
escaped = absl::Utf8SafeCEscape(original);
break;
case 3:
escaped = absl::Utf8SafeCHexEscape(original);
break;
}
std::string unescaped_str;
EXPECT_TRUE(absl::CUnescape(escaped, &unescaped_str));
EXPECT_EQ(unescaped_str, original);
unescaped_str.erase();
std::string error;
EXPECT_TRUE(absl::CUnescape(escaped, &unescaped_str, &error));
EXPECT_EQ(error, "");
std::string s = escaped;
EXPECT_TRUE(absl::CUnescape(s, &s));
ASSERT_EQ(s, original);
}
}
for (int char0 = 0; char0 < 256; char0++) {
for (int char1 = 0; char1 < 256; char1++) {
char chars[2];
chars[0] = char0;
chars[1] = char1;
std::string s(chars, 2);
std::string escaped = absl::CHexEscape(s);
std::string unescaped;
EXPECT_TRUE(absl::CUnescape(escaped, &unescaped));
EXPECT_EQ(s, unescaped);
}
}
}
TEST(CEscape, BasicEscaping) {
epair oct_values[] = {
{"foo\\rbar\\nbaz\\t", "foo\rbar\nbaz\t"},
{"\\'full of \\\"sound\\\" and \\\"fury\\\"\\'",
"'full of \"sound\" and \"fury\"'"},
{"signi\\\\fying\\\\ nothing\\\\", "signi\\fying\\ nothing\\"},
{"\\010\\t\\n\\013\\014\\r", "\010\011\012\013\014\015"}
};
epair hex_values[] = {
{"ubik\\rubik\\nubik\\t", "ubik\rubik\nubik\t"},
{"I\\\'ve just seen a \\\"face\\\"",
"I've just seen a \"face\""},
{"hel\\\\ter\\\\skel\\\\ter\\\\", "hel\\ter\\skel\\ter\\"},
{"\\x08\\t\\n\\x0b\\x0c\\r", "\010\011\012\013\014\015"}
};
epair utf8_oct_values[] = {
{"\xe8\xb0\xb7\xe6\xad\x8c\\r\xe8\xb0\xb7\xe6\xad\x8c\\nbaz\\t",
"\xe8\xb0\xb7\xe6\xad\x8c\r\xe8\xb0\xb7\xe6\xad\x8c\nbaz\t"},
{"\\\"\xe8\xb0\xb7\xe6\xad\x8c\\\" is Google\\\'s Chinese name",
"\"\xe8\xb0\xb7\xe6\xad\x8c\" is Google\'s Chinese name"},
{"\xe3\x83\xa1\xe3\x83\xbc\xe3\x83\xab\\\\are\\\\Japanese\\\\chars\\\\",
"\xe3\x83\xa1\xe3\x83\xbc\xe3\x83\xab\\are\\Japanese\\chars\\"},
{"\xed\x81\xac\xeb\xa1\xac\\010\\t\\n\\013\\014\\r",
"\xed\x81\xac\xeb\xa1\xac\010\011\012\013\014\015"}
};
epair utf8_hex_values[] = {
{"\x20\xe4\xbd\xa0\\t\xe5\xa5\xbd,\\r!\\n",
"\x20\xe4\xbd\xa0\t\xe5\xa5\xbd,\r!\n"},
{"\xe8\xa9\xa6\xe9\xa8\x93\\\' means \\\"test\\\"",
"\xe8\xa9\xa6\xe9\xa8\x93\' means \"test\""},
{"\\\\\xe6\x88\x91\\\\:\\\\\xe6\x9d\xa8\xe6\xac\xa2\\\\",
"\\\xe6\x88\x91\\:\\\xe6\x9d\xa8\xe6\xac\xa2\\"},
{"\xed\x81\xac\xeb\xa1\xac\\x08\\t\\n\\x0b\\x0c\\r",
"\xed\x81\xac\xeb\xa1\xac\010\011\012\013\014\015"}
};
for (const epair& val : oct_values) {
std::string escaped = absl::CEscape(val.unescaped);
EXPECT_EQ(escaped, val.escaped);
}
for (const epair& val : hex_values) {
std::string escaped = absl::CHexEscape(val.unescaped);
EXPECT_EQ(escaped, val.escaped);
}
for (const epair& val : utf8_oct_values) {
std::string escaped = absl::Utf8SafeCEscape(val.unescaped);
EXPECT_EQ(escaped, val.escaped);
}
for (const epair& val : utf8_hex_values) {
std::string escaped = absl::Utf8SafeCHexEscape(val.unescaped);
EXPECT_EQ(escaped, val.escaped);
}
}
TEST(Unescape, BasicFunction) {
epair tests[] =
{{"", ""},
{"\\u0030", "0"},
{"\\u00A3", "\xC2\xA3"},
{"\\u22FD", "\xE2\x8B\xBD"},
{"\\U00010000", "\xF0\x90\x80\x80"},
{"\\U0010FFFD", "\xF4\x8F\xBF\xBD"}};
for (const epair& val : tests) {
std::string out;
EXPECT_TRUE(absl::CUnescape(val.escaped, &out));
EXPECT_EQ(out, val.unescaped);
}
std::string bad[] = {"\\u1",
"\\U1",
"\\Uffffff",
"\\U00110000",
"\\uD835",
"\\U0000DD04",
"\\777",
"\\xABCD"};
for (const std::string& e : bad) {
std::string error;
std::string out;
EXPECT_FALSE(absl::CUnescape(e, &out, &error));
EXPECT_FALSE(error.empty());
out.erase();
EXPECT_FALSE(absl::CUnescape(e, &out));
}
}
class CUnescapeTest : public testing::Test {
protected:
static const char kStringWithMultipleOctalNulls[];
static const char kStringWithMultipleHexNulls[];
static const char kStringWithMultipleUnicodeNulls[];
std::string result_string_;
};
const char CUnescapeTest::kStringWithMultipleOctalNulls[] =
"\\0\\n"
"0\\n"
"\\00\\12"
"\\000";
const char CUnescapeTest::kStringWithMultipleHexNulls[] =
"\\x0\\n"
"0\\n"
"\\x00\\xa"
"\\x000";
const char CUnescapeTest::kStringWithMultipleUnicodeNulls[] =
"\\u0000\\n"
"0\\n"
"\\U00000000";
TEST_F(CUnescapeTest, Unescapes1CharOctalNull) {
std::string original_string = "\\0";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, Unescapes2CharOctalNull) {
std::string original_string = "\\00";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, Unescapes3CharOctalNull) {
std::string original_string = "\\000";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, Unescapes1CharHexNull) {
std::string original_string = "\\x0";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, Unescapes2CharHexNull) {
std::string original_string = "\\x00";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, Unescapes3CharHexNull) {
std::string original_string = "\\x000";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, Unescapes4CharUnicodeNull) {
std::string original_string = "\\u0000";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, Unescapes8CharUnicodeNull) {
std::string original_string = "\\U00000000";
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0", 1), result_string_);
}
TEST_F(CUnescapeTest, UnescapesMultipleOctalNulls) {
std::string original_string(kStringWithMultipleOctalNulls);
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0\n"
"0\n"
"\0\n"
"\0",
7),
result_string_);
}
TEST_F(CUnescapeTest, UnescapesMultipleHexNulls) {
std::string original_string(kStringWithMultipleHexNulls);
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0\n"
"0\n"
"\0\n"
"\0",
7),
result_string_);
}
TEST_F(CUnescapeTest, UnescapesMultipleUnicodeNulls) {
std::string original_string(kStringWithMultipleUnicodeNulls);
EXPECT_TRUE(absl::CUnescape(original_string, &result_string_));
EXPECT_EQ(std::string("\0\n"
"0\n"
"\0",
5),
result_string_);
}
static struct {
absl::string_view plaintext;
absl::string_view cyphertext;
} const base64_tests[] = {
{{"", 0}, {"", 0}},
{{nullptr, 0},
{"", 0}},
{{"\000", 1}, "AA=="},
{{"\001", 1}, "AQ=="},
{{"\002", 1}, "Ag=="},
{{"\004", 1}, "BA=="},
{{"\010", 1}, "CA=="},
{{"\020", 1}, "EA=="},
{{"\040", 1}, "IA=="},
{{"\100", 1}, "QA=="},
{{"\200", 1}, "gA=="},
{{"\377", 1}, "/w=="},
{{"\376", 1}, "/g=="},
{{"\375", 1}, "/Q=="},
{{"\373", 1}, "+w=="},
{{"\367", 1}, "9w=="},
{{"\357", 1}, "7w=="},
{{"\337", 1}, "3w=="},
{{"\277", 1}, "vw=="},
{{"\177", 1}, "fw=="},
{{"\000\000", 2}, "AAA="},
{{"\000\001", 2}, "AAE="},
{{"\000\002", 2}, "AAI="},
{{"\000\004", 2}, "AAQ="},
{{"\000\010", 2}, "AAg="},
{{"\000\020", 2}, "ABA="},
{{"\000\040", 2}, "ACA="},
{{"\000\100", 2}, "AEA="},
{{"\000\200", 2}, "AIA="},
{{"\001\000", 2}, "AQA="},
{{"\002\000", 2}, "AgA="},
{{"\004\000", 2}, "BAA="},
{{"\010\000", 2}, "CAA="},
{{"\020\000", 2}, "EAA="},
{{"\040\000", 2}, "IAA="},
{{"\100\000", 2}, "QAA="},
{{"\200\000", 2}, "gAA="},
{{"\377\377", 2}, "
{{"\377\376", 2}, "
{{"\377\375", 2}, "
{{"\377\373", 2}, "
{{"\377\367", 2}, "
{{"\377\357", 2}, "/+8="},
{{"\377\337", 2}, "/98="},
{{"\377\277", 2}, "/78="},
{{"\377\177", 2}, "/38="},
{{"\376\377", 2}, "/v8="},
{{"\375\377", 2}, "/f8="},
{{"\373\377", 2}, "+/8="},
{{"\367\377", 2}, "9/8="},
{{"\357\377", 2}, "7/8="},
{{"\337\377", 2}, "3/8="},
{{"\277\377", 2}, "v/8="},
{{"\177\377", 2}, "f/8="},
{{"\000\000\000", 3}, "AAAA"},
{{"\000\000\001", 3}, "AAAB"},
{{"\000\000\002", 3}, "AAAC"},
{{"\000\000\004", 3}, "AAAE"},
{{"\000\000\010", 3}, "AAAI"},
{{"\000\000\020", 3}, "AAAQ"},
{{"\000\000\040", 3}, "AAAg"},
{{"\000\000\100", 3}, "AABA"},
{{"\000\000\200", 3}, "AACA"},
{{"\000\001\000", 3}, "AAEA"},
{{"\000\002\000", 3}, "AAIA"},
{{"\000\004\000", 3}, "AAQA"},
{{"\000\010\000", 3}, "AAgA"},
{{"\000\020\000", 3}, "ABAA"},
{{"\000\040\000", 3}, "ACAA"},
{{"\000\100\000", 3}, "AEAA"},
{{"\000\200\000", 3}, "AIAA"},
{{"\001\000\000", 3}, "AQAA"},
{{"\002\000\000", 3}, "AgAA"},
{{"\004\000\000", 3}, "BAAA"},
{{"\010\000\000", 3}, "CAAA"},
{{"\020\000\000", 3}, "EAAA"},
{{"\040\000\000", 3}, "IAAA"},
{{"\100\000\000", 3}, "QAAA"},
{{"\200\000\000", 3}, "gAAA"},
{{"\377\377\377", 3}, "
{{"\377\377\376", 3}, "
{{"\377\377\375", 3}, "
{{"\377\377\373", 3}, "
{{"\377\377\367", 3}, "
{{"\377\377\357", 3}, "
{{"\377\377\337", 3}, "
{{"\377\377\277", 3}, "
{{"\377\377\177", 3}, "
{{"\377\376\377", 3}, "
{{"\377\375\377", 3}, "
{{"\377\373\377", 3}, "
{{"\377\367\377", 3}, "
{{"\377\357\377", 3}, "/+
{{"\377\337\377", 3}, "/9
{{"\377\277\377", 3}, "/7
{{"\377\177\377", 3}, "/3
{{"\376\377\377", 3}, "/v
{{"\375\377\377", 3}, "/f
{{"\373\377\377", 3}, "+
{{"\367\377\377", 3}, "9
{{"\357\377\377", 3}, "7
{{"\337\377\377", 3}, "3
{{"\277\377\377", 3}, "v
{{"\177\377\377", 3}, "f
{{"\243\361", 2}, "o/E="},
{{"\024\167", 2}, "FHc="},
{{"\313\252", 2}, "y6o="},
{{"\046\041", 2}, "JiE="},
{{"\145\236", 2}, "ZZ4="},
{{"\254\325", 2}, "rNU="},
{{"\061\330", 2}, "Mdg="},
{{"\245\032", 2}, "pRo="},
{{"\006\000", 2}, "BgA="},
{{"\375\131", 2}, "/Vk="},
{{"\303\210", 2}, "w4g="},
{{"\040\037", 2}, "IB8="},
{{"\261\372", 2}, "sfo="},
{{"\335\014", 2}, "3Qw="},
{{"\233\217", 2}, "m48="},
{{"\373\056", 2}, "+y4="},
{{"\247\232", 2}, "p5o="},
{{"\107\053", 2}, "Rys="},
{{"\204\077", 2}, "hD8="},
{{"\276\211", 2}, "vok="},
{{"\313\110", 2}, "y0g="},
{{"\363\376", 2}, "8/4="},
{{"\251\234", 2}, "qZw="},
{{"\103\262", 2}, "Q7I="},
{{"\142\312", 2}, "Yso="},
{{"\067\211", 2}, "N4k="},
{{"\220\001", 2}, "kAE="},
{{"\152\240", 2}, "aqA="},
{{"\367\061", 2}, "9zE="},
{{"\133\255", 2}, "W60="},
{{"\176\035", 2}, "fh0="},
{{"\032\231", 2}, "Gpk="},
{{"\013\007\144", 3}, "Cwdk"},
{{"\030\112\106", 3}, "GEpG"},
{{"\047\325\046", 3}, "J9Um"},
{{"\310\160\022", 3}, "yHAS"},
{{"\131\100\237", 3}, "WUCf"},
{{"\064\342\134", 3}, "NOJc"},
{{"\010\177\004", 3}, "CH8E"},
{{"\345\147\205", 3}, "5WeF"},
{{"\300\343\360", 3}, "wOPw"},
{{"\061\240\201", 3}, "MaCB"},
{{"\225\333\044", 3}, "ldsk"},
{{"\215\137\352", 3}, "jV/q"},
{{"\371\147\160", 3}, "+Wdw"},
{{"\030\320\051", 3}, "GNAp"},
{{"\044\174\241", 3}, "JHyh"},
{{"\260\127\037", 3}, "sFcf"},
{{"\111\045\033", 3}, "SSUb"},
{{"\202\114\107", 3}, "gkxH"},
{{"\057\371\042", 3}, "L/ki"},
{{"\223\247\244", 3}, "k6ek"},
{{"\047\216\144", 3}, "J45k"},
{{"\203\070\327", 3}, "gzjX"},
{{"\247\140\072", 3}, "p2A6"},
{{"\124\115\116", 3}, "VE1O"},
{{"\157\162\050", 3}, "b3Io"},
{{"\357\223\004", 3}, "75ME"},
{{"\052\117\156", 3}, "Kk9u"},
{{"\347\154\000", 3}, "52wA"},
{{"\303\012\142", 3}, "wwpi"},
{{"\060\035\362", 3}, "MB3y"},
{{"\130\226\361", 3}, "WJbx"},
{{"\173\013\071", 3}, "ews5"},
{{"\336\004\027", 3}, "3gQX"},
{{"\357\366\234", 3}, "7/ac"},
{{"\353\304\111", 3}, "68RJ"},
{{"\024\264\131", 3}, "FLRZ"},
{{"\075\114\251", 3}, "PUyp"},
{{"\315\031\225", 3}, "zRmV"},
{{"\154\201\276", 3}, "bIG+"},
{{"\200\066\072", 3}, "gDY6"},
{{"\142\350\267", 3}, "Yui3"},
{{"\033\000\166", 3}, "GwB2"},
{{"\210\055\077", 3}, "iC0/"},
{{"\341\037\124", 3}, "4R9U"},
{{"\161\103\152", 3}, "cUNq"},
{{"\270\142\131", 3}, "uGJZ"},
{{"\337\076\074", 3}, "3z48"},
{{"\375\106\362", 3}, "/Uby"},
{{"\227\301\127", 3}, "l8FX"},
{{"\340\002\234", 3}, "4AKc"},
{{"\121\064\033", 3}, "UTQb"},
{{"\157\134\143", 3}, "b1xj"},
{{"\247\055\327", 3}, "py3X"},
{{"\340\142\005", 3}, "4GIF"},
{{"\060\260\143", 3}, "MLBj"},
{{"\075\203\170", 3}, "PYN4"},
{{"\143\160\016", 3}, "Y3AO"},
{{"\313\013\063", 3}, "ywsz"},
{{"\174\236\135", 3}, "fJ5d"},
{{"\103\047\026", 3}, "QycW"},
{{"\365\005\343", 3}, "9QXj"},
{{"\271\160\223", 3}, "uXCT"},
{{"\362\255\172", 3}, "8q16"},
{{"\113\012\015", 3}, "SwoN"},
{{"", 0}, {"", 0}},
{"a", "YQ=="},
{"ab", "YWI="},
{"abc", "YWJj"},
{"abcd", "YWJjZA=="},
{"abcde", "YWJjZGU="},
{"abcdef", "YWJjZGVm"},
{"abcdefg", "YWJjZGVmZw=="},
{"abcdefgh", "YWJjZGVmZ2g="},
{"abcdefghi", "YWJjZGVmZ2hp"},
{"abcdefghij", "YWJjZGVmZ2hpag=="},
{"abcdefghijk", "YWJjZGVmZ2hpams="},
{"abcdefghijkl", "YWJjZGVmZ2hpamts"},
{"abcdefghijklm", "YWJjZGVmZ2hpamtsbQ=="},
{"abcdefghijklmn", "YWJjZGVmZ2hpamtsbW4="},
{"abcdefghijklmno", "YWJjZGVmZ2hpamtsbW5v"},
{"abcdefghijklmnop", "YWJjZGVmZ2hpamtsbW5vcA=="},
{"abcdefghijklmnopq", "YWJjZGVmZ2hpamtsbW5vcHE="},
{"abcdefghijklmnopqr", "YWJjZGVmZ2hpamtsbW5vcHFy"},
{"abcdefghijklmnopqrs", "YWJjZGVmZ2hpamtsbW5vcHFycw=="},
{"abcdefghijklmnopqrst", "YWJjZGVmZ2hpamtsbW5vcHFyc3Q="},
{"abcdefghijklmnopqrstu", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1"},
{"abcdefghijklmnopqrstuv", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dg=="},
{"abcdefghijklmnopqrstuvw", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnc="},
{"abcdefghijklmnopqrstuvwx", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4"},
{"abcdefghijklmnopqrstuvwxy", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eQ=="},
{"abcdefghijklmnopqrstuvwxyz", "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo="},
};
template <typename StringType>
void TestEscapeAndUnescape() {
for (const auto& tc : base64_tests) {
StringType encoded("this junk should be ignored");
absl::Base64Escape(tc.plaintext, &encoded);
EXPECT_EQ(encoded, tc.cyphertext);
EXPECT_EQ(absl::Base64Escape(tc.plaintext), tc.cyphertext);
StringType decoded("this junk should be ignored");
EXPECT_TRUE(absl::Base64Unescape(encoded, &decoded));
EXPECT_EQ(decoded, tc.plaintext);
StringType websafe_with_padding(tc.cyphertext);
for (unsigned int c = 0; c < websafe_with_padding.size(); ++c) {
if ('+' == websafe_with_padding[c]) websafe_with_padding[c] = '-';
if ('/' == websafe_with_padding[c]) websafe_with_padding[c] = '_';
}
StringType websafe(websafe_with_padding);
for (unsigned int c = 0; c < websafe.size(); ++c) {
if ('=' == websafe[c]) {
websafe.resize(c);
break;
}
}
encoded = "this junk should be ignored";
absl::WebSafeBase64Escape(tc.plaintext, &encoded);
EXPECT_EQ(encoded, websafe);
EXPECT_EQ(absl::WebSafeBase64Escape(tc.plaintext), websafe);
decoded = "this junk should be ignored";
EXPECT_TRUE(absl::WebSafeBase64Unescape(websafe, &decoded));
EXPECT_EQ(decoded, tc.plaintext);
}
for (const auto& tc : absl::strings_internal::base64_strings()) {
StringType buffer;
absl::WebSafeBase64Escape(tc.plaintext, &buffer);
EXPECT_EQ(tc.cyphertext, buffer);
EXPECT_EQ(absl::WebSafeBase64Escape(tc.plaintext), tc.cyphertext);
}
{
absl::string_view data_set[] = {"ab-/", absl::string_view("\0bcd", 4),
absl::string_view("abc.\0", 5)};
for (absl::string_view bad_data : data_set) {
StringType buf;
EXPECT_FALSE(absl::Base64Unescape(bad_data, &buf));
EXPECT_FALSE(absl::WebSafeBase64Unescape(bad_data, &buf));
EXPECT_TRUE(buf.empty());
}
}
}
TEST(Base64, EscapeAndUnescape) {
TestEscapeAndUnescape<std::string>();
}
TEST(Base64, Padding) {
std::initializer_list<absl::string_view> good_padding = {
"YQ",
"YQ==",
"YQ=.",
"YQ.=",
"YQ..",
};
for (absl::string_view b64 : good_padding) {
std::string decoded;
EXPECT_TRUE(absl::Base64Unescape(b64, &decoded));
EXPECT_EQ(decoded, "a");
std::string websafe_decoded;
EXPECT_TRUE(absl::WebSafeBase64Unescape(b64, &websafe_decoded));
EXPECT_EQ(websafe_decoded, "a");
}
std::initializer_list<absl::string_view> bad_padding = {
"YQ=",
"YQ.",
"YQ===",
"YQ==.",
"YQ=.=",
"YQ=..",
"YQ.==",
"YQ.=.",
"YQ..=",
"YQ...",
"YQ====",
"YQ....",
"YQ=====",
"YQ.....",
};
for (absl::string_view b64 : bad_padding) {
std::string decoded;
EXPECT_FALSE(absl::Base64Unescape(b64, &decoded));
std::string websafe_decoded;
EXPECT_FALSE(absl::WebSafeBase64Unescape(b64, &websafe_decoded));
}
}
TEST(Base64, DISABLED_HugeData) {
const size_t kSize = size_t(3) * 1000 * 1000 * 1000;
static_assert(kSize % 3 == 0, "kSize must be divisible by 3");
const std::string huge(kSize, 'x');
std::string escaped;
absl::Base64Escape(huge, &escaped);
std::string expected_encoding;
expected_encoding.reserve(kSize / 3 * 4);
for (size_t i = 0; i < kSize / 3; ++i) {
expected_encoding.append("eHh4");
}
EXPECT_EQ(expected_encoding, escaped);
std::string unescaped;
EXPECT_TRUE(absl::Base64Unescape(escaped, &unescaped));
EXPECT_EQ(huge, unescaped);
}
TEST(Escaping, HexStringToBytesBackToHex) {
std::string bytes, hex;
constexpr absl::string_view kTestHexLower = "1c2f0032f40123456789abcdef";
constexpr absl::string_view kTestHexUpper = "1C2F0032F40123456789ABCDEF";
constexpr absl::string_view kTestBytes = absl::string_view(
"\x1c\x2f\x00\x32\xf4\x01\x23\x45\x67\x89\xab\xcd\xef", 13);
EXPECT_TRUE(absl::HexStringToBytes(kTestHexLower, &bytes));
EXPECT_EQ(bytes, kTestBytes);
EXPECT_TRUE(absl::HexStringToBytes(kTestHexUpper, &bytes));
EXPECT_EQ(bytes, kTestBytes);
hex = absl::BytesToHexString(kTestBytes);
EXPECT_EQ(hex, kTestHexLower);
bytes = std::string(kTestHexUpper);
(void)absl::HexStringToBytes(bytes, &bytes);
EXPECT_FALSE(absl::HexStringToBytes("1c2f003", &bytes));
EXPECT_FALSE(absl::HexStringToBytes("1c2f00ft", &bytes));
bytes = "abc";
EXPECT_TRUE(absl::HexStringToBytes("", &bytes));
EXPECT_EQ("", bytes);
}
TEST(HexAndBack, HexStringToBytes_and_BytesToHexString) {
std::string hex_mixed = "0123456789abcdefABCDEF";
std::string bytes_expected = "\x01\x23\x45\x67\x89\xab\xcd\xef\xAB\xCD\xEF";
std::string hex_only_lower = "0123456789abcdefabcdef";
std::string bytes_result = absl::HexStringToBytes(hex_mixed);
EXPECT_EQ(bytes_expected, bytes_result);
std::string prefix_valid = hex_mixed + "?";
std::string prefix_valid_result = absl::HexStringToBytes(
absl::string_view(prefix_valid.data(), prefix_valid.size() - 1));
EXPECT_EQ(bytes_expected, prefix_valid_result);
std::string infix_valid = "?" + hex_mixed + "???";
std::string infix_valid_result = absl::HexStringToBytes(
absl::string_view(infix_valid.data() + 1, hex_mixed.size()));
EXPECT_EQ(bytes_expected, infix_valid_result);
std::string hex_result = absl::BytesToHexString(bytes_expected);
EXPECT_EQ(hex_only_lower, hex_result);
}
} |
2,547 | cpp | abseil/abseil-cpp | cord_buffer | absl/strings/cord_buffer.cc | absl/strings/cord_buffer_test.cc | #ifndef ABSL_STRINGS_CORD_BUFFER_H_
#define ABSL_STRINGS_CORD_BUFFER_H_
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/numeric/bits.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_flat.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Cord;
class CordBufferTestPeer;
class CordBuffer {
public:
static constexpr size_t kDefaultLimit = cord_internal::kMaxFlatLength;
static constexpr size_t kCustomLimit = 64U << 10;
CordBuffer() = default;
~CordBuffer();
CordBuffer(CordBuffer&& rhs) noexcept;
CordBuffer& operator=(CordBuffer&&) noexcept;
CordBuffer(const CordBuffer&) = delete;
CordBuffer& operator=(const CordBuffer&) = delete;
static constexpr size_t MaximumPayload();
static constexpr size_t MaximumPayload(size_t block_size);
static CordBuffer CreateWithDefaultLimit(size_t capacity);
static CordBuffer CreateWithCustomLimit(size_t block_size, size_t capacity);
absl::Span<char> available();
absl::Span<char> available_up_to(size_t size);
char* data();
const char* data() const;
size_t length() const;
size_t capacity() const;
void IncreaseLengthBy(size_t n);
void SetLength(size_t length);
private:
static_assert(kCustomLimit <= cord_internal::kMaxLargeFlatSize, "");
static constexpr size_t kMaxPageSlop = 128;
static constexpr size_t kOverhead = cord_internal::kFlatOverhead;
using CordRepFlat = cord_internal::CordRepFlat;
struct Rep {
static constexpr size_t kInlineCapacity = sizeof(intptr_t) * 2 - 1;
Rep() : short_rep{} {}
explicit Rep(cord_internal::CordRepFlat* rep) : long_rep{rep} {
assert(rep != nullptr);
}
bool is_short() const {
constexpr size_t offset = offsetof(Short, raw_size);
return (reinterpret_cast<const char*>(this)[offset] & 1) != 0;
}
absl::Span<char> short_available() {
const size_t length = short_length();
return absl::Span<char>(short_rep.data + length,
kInlineCapacity - length);
}
absl::Span<char> long_available() const {
assert(!is_short());
const size_t length = long_rep.rep->length;
return absl::Span<char>(long_rep.rep->Data() + length,
long_rep.rep->Capacity() - length);
}
size_t short_length() const {
assert(is_short());
return static_cast<size_t>(short_rep.raw_size >> 1);
}
void set_short_length(size_t length) {
short_rep.raw_size = static_cast<char>((length << 1) + 1);
}
void add_short_length(size_t n) {
assert(is_short());
short_rep.raw_size += static_cast<char>(n << 1);
}
char* data() {
assert(is_short());
return short_rep.data;
}
const char* data() const {
assert(is_short());
return short_rep.data;
}
cord_internal::CordRepFlat* rep() const {
assert(!is_short());
return long_rep.rep;
}
#if defined(ABSL_IS_BIG_ENDIAN)
struct Long {
explicit Long(cord_internal::CordRepFlat* rep_arg) : rep(rep_arg) {}
void* padding;
cord_internal::CordRepFlat* rep;
};
struct Short {
char data[sizeof(Long) - 1];
char raw_size = 1;
};
#else
struct Long {
explicit Long(cord_internal::CordRepFlat* rep_arg) : rep(rep_arg) {}
cord_internal::CordRepFlat* rep;
void* padding;
};
struct Short {
char raw_size = 1;
char data[sizeof(Long) - 1];
};
#endif
union {
Long long_rep;
Short short_rep;
};
};
static bool IsPow2(size_t size) { return absl::has_single_bit(size); }
static size_t Log2Floor(size_t size) {
return static_cast<size_t>(absl::bit_width(size) - 1);
}
static size_t Log2Ceil(size_t size) {
return static_cast<size_t>(absl::bit_width(size - 1));
}
template <typename... AllocationHints>
static CordBuffer CreateWithCustomLimitImpl(size_t block_size,
size_t capacity,
AllocationHints... hints);
cord_internal::CordRep* ConsumeValue(absl::string_view& short_value) {
cord_internal::CordRep* rep = nullptr;
if (rep_.is_short()) {
short_value = absl::string_view(rep_.data(), rep_.short_length());
} else {
rep = rep_.rep();
}
rep_.set_short_length(0);
return rep;
}
explicit CordBuffer(cord_internal::CordRepFlat* rep) : rep_(rep) {
assert(rep != nullptr);
}
Rep rep_;
friend class Cord;
friend class CordBufferTestPeer;
};
inline constexpr size_t CordBuffer::MaximumPayload() {
return cord_internal::kMaxFlatLength;
}
inline constexpr size_t CordBuffer::MaximumPayload(size_t block_size) {
return (std::min)(kCustomLimit, block_size) - cord_internal::kFlatOverhead;
}
inline CordBuffer CordBuffer::CreateWithDefaultLimit(size_t capacity) {
if (capacity > Rep::kInlineCapacity) {
auto* rep = cord_internal::CordRepFlat::New(capacity);
rep->length = 0;
return CordBuffer(rep);
}
return CordBuffer();
}
template <typename... AllocationHints>
inline CordBuffer CordBuffer::CreateWithCustomLimitImpl(
size_t block_size, size_t capacity, AllocationHints... hints) {
assert(IsPow2(block_size));
capacity = (std::min)(capacity, kCustomLimit);
block_size = (std::min)(block_size, kCustomLimit);
if (capacity + kOverhead >= block_size) {
capacity = block_size;
} else if (capacity <= kDefaultLimit) {
capacity = capacity + kOverhead;
} else if (!IsPow2(capacity)) {
const size_t rounded_up = size_t{1} << Log2Ceil(capacity);
const size_t slop = rounded_up - capacity;
if (slop >= kOverhead && slop <= kMaxPageSlop + kOverhead) {
capacity = rounded_up;
} else {
const size_t rounded_down = size_t{1} << Log2Floor(capacity);
capacity = rounded_down;
}
}
const size_t length = capacity - kOverhead;
auto* rep = CordRepFlat::New(CordRepFlat::Large(), length, hints...);
rep->length = 0;
return CordBuffer(rep);
}
inline CordBuffer CordBuffer::CreateWithCustomLimit(size_t block_size,
size_t capacity) {
return CreateWithCustomLimitImpl(block_size, capacity);
}
inline CordBuffer::~CordBuffer() {
if (!rep_.is_short()) {
cord_internal::CordRepFlat::Delete(rep_.rep());
}
}
inline CordBuffer::CordBuffer(CordBuffer&& rhs) noexcept : rep_(rhs.rep_) {
rhs.rep_.set_short_length(0);
}
inline CordBuffer& CordBuffer::operator=(CordBuffer&& rhs) noexcept {
if (!rep_.is_short()) cord_internal::CordRepFlat::Delete(rep_.rep());
rep_ = rhs.rep_;
rhs.rep_.set_short_length(0);
return *this;
}
inline absl::Span<char> CordBuffer::available() {
return rep_.is_short() ? rep_.short_available() : rep_.long_available();
}
inline absl::Span<char> CordBuffer::available_up_to(size_t size) {
return available().subspan(0, size);
}
inline char* CordBuffer::data() {
return rep_.is_short() ? rep_.data() : rep_.rep()->Data();
}
inline const char* CordBuffer::data() const {
return rep_.is_short() ? rep_.data() : rep_.rep()->Data();
}
inline size_t CordBuffer::capacity() const {
return rep_.is_short() ? Rep::kInlineCapacity : rep_.rep()->Capacity();
}
inline size_t CordBuffer::length() const {
return rep_.is_short() ? rep_.short_length() : rep_.rep()->length;
}
inline void CordBuffer::SetLength(size_t length) {
ABSL_HARDENING_ASSERT(length <= capacity());
if (rep_.is_short()) {
rep_.set_short_length(length);
} else {
rep_.rep()->length = length;
}
}
inline void CordBuffer::IncreaseLengthBy(size_t n) {
ABSL_HARDENING_ASSERT(n <= capacity() && length() + n <= capacity());
if (rep_.is_short()) {
rep_.add_short_length(n);
} else {
rep_.rep()->length += n;
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/cord_buffer.h"
#include <cstddef>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr size_t CordBuffer::kDefaultLimit;
constexpr size_t CordBuffer::kCustomLimit;
#endif
ABSL_NAMESPACE_END
} | #include "absl/strings/cord_buffer.h"
#include <algorithm>
#include <cstring>
#include <limits>
#include <string>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_flat.h"
#include "absl/strings/internal/cord_rep_test_util.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
using testing::Eq;
using testing::Ge;
using testing::Le;
using testing::Ne;
namespace absl {
ABSL_NAMESPACE_BEGIN
class CordBufferTestPeer {
public:
static cord_internal::CordRep* ConsumeValue(CordBuffer& buffer,
absl::string_view& short_value) {
return buffer.ConsumeValue(short_value);
}
};
namespace {
using ::absl::cordrep_testing::CordToString;
constexpr size_t kInlinedSize = sizeof(CordBuffer) - 1;
constexpr size_t kDefaultLimit = CordBuffer::kDefaultLimit;
constexpr size_t kCustomLimit = CordBuffer::kCustomLimit;
constexpr size_t kMaxFlatSize = cord_internal::kMaxFlatSize;
constexpr size_t kMaxFlatLength = cord_internal::kMaxFlatLength;
constexpr size_t kFlatOverhead = cord_internal::kFlatOverhead;
constexpr size_t k8KiB = 8 << 10;
constexpr size_t k16KiB = 16 << 10;
constexpr size_t k64KiB = 64 << 10;
constexpr size_t k1MB = 1 << 20;
class CordBufferTest : public testing::TestWithParam<size_t> {};
INSTANTIATE_TEST_SUITE_P(MediumSize, CordBufferTest,
testing::Values(1, kInlinedSize - 1, kInlinedSize,
kInlinedSize + 1, kDefaultLimit - 1,
kDefaultLimit));
TEST_P(CordBufferTest, MaximumPayload) {
EXPECT_THAT(CordBuffer::MaximumPayload(), Eq(kMaxFlatLength));
EXPECT_THAT(CordBuffer::MaximumPayload(512), Eq(512 - kFlatOverhead));
EXPECT_THAT(CordBuffer::MaximumPayload(k64KiB), Eq(k64KiB - kFlatOverhead));
EXPECT_THAT(CordBuffer::MaximumPayload(k1MB), Eq(k64KiB - kFlatOverhead));
}
TEST(CordBufferTest, ConstructDefault) {
CordBuffer buffer;
EXPECT_THAT(buffer.capacity(), Eq(sizeof(CordBuffer) - 1));
EXPECT_THAT(buffer.length(), Eq(0));
EXPECT_THAT(buffer.data(), Ne(nullptr));
EXPECT_THAT(buffer.available().data(), Eq(buffer.data()));
EXPECT_THAT(buffer.available().size(), Eq(buffer.capacity()));
memset(buffer.data(), 0xCD, buffer.capacity());
}
TEST(CordBufferTest, CreateSsoWithDefaultLimit) {
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(3);
EXPECT_THAT(buffer.capacity(), Ge(3));
EXPECT_THAT(buffer.capacity(), Le(sizeof(CordBuffer)));
EXPECT_THAT(buffer.length(), Eq(0));
memset(buffer.data(), 0xCD, buffer.capacity());
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
EXPECT_THAT(buffer.length(), Eq(3));
absl::string_view short_value;
EXPECT_THAT(CordBufferTestPeer::ConsumeValue(buffer, short_value),
Eq(nullptr));
EXPECT_THAT(absl::string_view(buffer.data(), 3), Eq("Abc"));
EXPECT_THAT(short_value, Eq("Abc"));
}
TEST_P(CordBufferTest, Available) {
const size_t requested = GetParam();
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested);
EXPECT_THAT(buffer.available().data(), Eq(buffer.data()));
EXPECT_THAT(buffer.available().size(), Eq(buffer.capacity()));
buffer.SetLength(2);
EXPECT_THAT(buffer.available().data(), Eq(buffer.data() + 2));
EXPECT_THAT(buffer.available().size(), Eq(buffer.capacity() - 2));
}
TEST_P(CordBufferTest, IncreaseLengthBy) {
const size_t requested = GetParam();
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested);
buffer.IncreaseLengthBy(2);
EXPECT_THAT(buffer.length(), Eq(2));
buffer.IncreaseLengthBy(5);
EXPECT_THAT(buffer.length(), Eq(7));
}
TEST_P(CordBufferTest, AvailableUpTo) {
const size_t requested = GetParam();
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested);
size_t expected_up_to = std::min<size_t>(3, buffer.capacity());
EXPECT_THAT(buffer.available_up_to(3).data(), Eq(buffer.data()));
EXPECT_THAT(buffer.available_up_to(3).size(), Eq(expected_up_to));
buffer.SetLength(2);
expected_up_to = std::min<size_t>(3, buffer.capacity() - 2);
EXPECT_THAT(buffer.available_up_to(3).data(), Eq(buffer.data() + 2));
EXPECT_THAT(buffer.available_up_to(3).size(), Eq(expected_up_to));
}
size_t MaxCapacityFor(size_t block_size, size_t requested) {
requested = (std::min)(requested, cord_internal::kMaxLargeFlatSize);
return block_size - kFlatOverhead;
}
TEST_P(CordBufferTest, CreateWithDefaultLimit) {
const size_t requested = GetParam();
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested);
EXPECT_THAT(buffer.capacity(), Ge(requested));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(kMaxFlatSize, requested)));
EXPECT_THAT(buffer.length(), Eq(0));
memset(buffer.data(), 0xCD, buffer.capacity());
std::string data(requested - 1, 'x');
memcpy(buffer.data(), data.c_str(), requested);
buffer.SetLength(requested);
EXPECT_THAT(buffer.length(), Eq(requested));
EXPECT_THAT(absl::string_view(buffer.data()), Eq(data));
}
TEST(CordBufferTest, CreateWithDefaultLimitAskingFor2GB) {
constexpr size_t k2GiB = 1U << 31;
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(k2GiB);
EXPECT_THAT(buffer.capacity(), Le(2 * CordBuffer::kDefaultLimit));
EXPECT_THAT(buffer.length(), Eq(0));
EXPECT_THAT(buffer.data(), Ne(nullptr));
memset(buffer.data(), 0xCD, buffer.capacity());
}
TEST_P(CordBufferTest, MoveConstruct) {
const size_t requested = GetParam();
CordBuffer from = CordBuffer::CreateWithDefaultLimit(requested);
const size_t capacity = from.capacity();
memcpy(from.data(), "Abc", 4);
from.SetLength(4);
CordBuffer to(std::move(from));
EXPECT_THAT(to.capacity(), Eq(capacity));
EXPECT_THAT(to.length(), Eq(4));
EXPECT_THAT(absl::string_view(to.data()), Eq("Abc"));
EXPECT_THAT(from.length(), Eq(0));
}
TEST_P(CordBufferTest, MoveAssign) {
const size_t requested = GetParam();
CordBuffer from = CordBuffer::CreateWithDefaultLimit(requested);
const size_t capacity = from.capacity();
memcpy(from.data(), "Abc", 4);
from.SetLength(4);
CordBuffer to;
to = std::move(from);
EXPECT_THAT(to.capacity(), Eq(capacity));
EXPECT_THAT(to.length(), Eq(4));
EXPECT_THAT(absl::string_view(to.data()), Eq("Abc"));
EXPECT_THAT(from.length(), Eq(0));
}
TEST_P(CordBufferTest, ConsumeValue) {
const size_t requested = GetParam();
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(requested);
memcpy(buffer.data(), "Abc", 4);
buffer.SetLength(3);
absl::string_view short_value;
if (cord_internal::CordRep* rep =
CordBufferTestPeer::ConsumeValue(buffer, short_value)) {
EXPECT_THAT(CordToString(rep), Eq("Abc"));
cord_internal::CordRep::Unref(rep);
} else {
EXPECT_THAT(short_value, Eq("Abc"));
}
EXPECT_THAT(buffer.length(), Eq(0));
}
TEST_P(CordBufferTest, CreateWithCustomLimitWithinDefaultLimit) {
const size_t requested = GetParam();
CordBuffer buffer =
CordBuffer::CreateWithCustomLimit(kMaxFlatSize, requested);
EXPECT_THAT(buffer.capacity(), Ge(requested));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(kMaxFlatSize, requested)));
EXPECT_THAT(buffer.length(), Eq(0));
memset(buffer.data(), 0xCD, buffer.capacity());
std::string data(requested - 1, 'x');
memcpy(buffer.data(), data.c_str(), requested);
buffer.SetLength(requested);
EXPECT_THAT(buffer.length(), Eq(requested));
EXPECT_THAT(absl::string_view(buffer.data()), Eq(data));
}
TEST(CordLargeBufferTest, CreateAtOrBelowDefaultLimit) {
CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k64KiB, kDefaultLimit);
EXPECT_THAT(buffer.capacity(), Ge(kDefaultLimit));
EXPECT_THAT(buffer.capacity(),
Le(MaxCapacityFor(kMaxFlatSize, kDefaultLimit)));
buffer = CordBuffer::CreateWithCustomLimit(k64KiB, 3178);
EXPECT_THAT(buffer.capacity(), Ge(3178));
}
TEST(CordLargeBufferTest, CreateWithCustomLimit) {
ASSERT_THAT((kMaxFlatSize & (kMaxFlatSize - 1)) == 0, "Must be power of 2");
for (size_t size = kMaxFlatSize; size <= kCustomLimit; size *= 2) {
CordBuffer buffer = CordBuffer::CreateWithCustomLimit(size, size);
size_t expected = size - kFlatOverhead;
ASSERT_THAT(buffer.capacity(), Ge(expected));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(size, expected)));
}
}
TEST(CordLargeBufferTest, CreateWithTooLargeLimit) {
CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k64KiB, k1MB);
ASSERT_THAT(buffer.capacity(), Ge(k64KiB - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(k64KiB, k1MB)));
}
TEST(CordLargeBufferTest, CreateWithHugeValueForOverFlowHardening) {
for (size_t dist_from_max = 0; dist_from_max <= 32; ++dist_from_max) {
size_t capacity = std::numeric_limits<size_t>::max() - dist_from_max;
CordBuffer buffer = CordBuffer::CreateWithDefaultLimit(capacity);
ASSERT_THAT(buffer.capacity(), Ge(kDefaultLimit));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(kMaxFlatSize, capacity)));
for (size_t limit = kMaxFlatSize; limit <= kCustomLimit; limit *= 2) {
CordBuffer buffer = CordBuffer::CreateWithCustomLimit(limit, capacity);
ASSERT_THAT(buffer.capacity(), Ge(limit - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(limit, capacity)));
}
}
}
TEST(CordLargeBufferTest, CreateWithSmallLimit) {
CordBuffer buffer = CordBuffer::CreateWithCustomLimit(512, 1024);
ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 1024)));
buffer = CordBuffer::CreateWithCustomLimit(512, 512);
ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 512)));
buffer = CordBuffer::CreateWithCustomLimit(512, 511);
ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 511)));
buffer = CordBuffer::CreateWithCustomLimit(512, 498);
ASSERT_THAT(buffer.capacity(), Ge(512 - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(512, 498)));
}
TEST(CordLargeBufferTest, CreateWasteFull) {
const size_t requested = (15 << 10);
CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k16KiB, requested);
ASSERT_THAT(buffer.capacity(), Ge(k8KiB - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(k8KiB, requested)));
}
TEST(CordLargeBufferTest, CreateSmallSlop) {
const size_t requested = k16KiB - 2 * kFlatOverhead;
CordBuffer buffer = CordBuffer::CreateWithCustomLimit(k16KiB, requested);
ASSERT_THAT(buffer.capacity(), Ge(k16KiB - kFlatOverhead));
EXPECT_THAT(buffer.capacity(), Le(MaxCapacityFor(k16KiB, requested)));
}
}
ABSL_NAMESPACE_END
} |
2,548 | cpp | abseil/abseil-cpp | str_cat | absl/strings/str_cat.cc | absl/strings/str_cat_test.cc | #ifndef ABSL_STRINGS_STR_CAT_H_
#define ABSL_STRINGS_STR_CAT_H_
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <limits>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/base/port.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/internal/resize_uninitialized.h"
#include "absl/strings/internal/stringify_sink.h"
#include "absl/strings/numbers.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
template <size_t max_size>
struct AlphaNumBuffer {
std::array<char, max_size> data;
size_t size;
};
}
enum PadSpec : uint8_t {
kNoPad = 1,
kZeroPad2,
kZeroPad3,
kZeroPad4,
kZeroPad5,
kZeroPad6,
kZeroPad7,
kZeroPad8,
kZeroPad9,
kZeroPad10,
kZeroPad11,
kZeroPad12,
kZeroPad13,
kZeroPad14,
kZeroPad15,
kZeroPad16,
kZeroPad17,
kZeroPad18,
kZeroPad19,
kZeroPad20,
kSpacePad2 = kZeroPad2 + 64,
kSpacePad3,
kSpacePad4,
kSpacePad5,
kSpacePad6,
kSpacePad7,
kSpacePad8,
kSpacePad9,
kSpacePad10,
kSpacePad11,
kSpacePad12,
kSpacePad13,
kSpacePad14,
kSpacePad15,
kSpacePad16,
kSpacePad17,
kSpacePad18,
kSpacePad19,
kSpacePad20,
};
struct Hex {
uint64_t value;
uint8_t width;
char fill;
template <typename Int>
explicit Hex(
Int v, PadSpec spec = absl::kNoPad,
typename std::enable_if<sizeof(Int) == 1 &&
!std::is_pointer<Int>::value>::type* = nullptr)
: Hex(spec, static_cast<uint8_t>(v)) {}
template <typename Int>
explicit Hex(
Int v, PadSpec spec = absl::kNoPad,
typename std::enable_if<sizeof(Int) == 2 &&
!std::is_pointer<Int>::value>::type* = nullptr)
: Hex(spec, static_cast<uint16_t>(v)) {}
template <typename Int>
explicit Hex(
Int v, PadSpec spec = absl::kNoPad,
typename std::enable_if<sizeof(Int) == 4 &&
!std::is_pointer<Int>::value>::type* = nullptr)
: Hex(spec, static_cast<uint32_t>(v)) {}
template <typename Int>
explicit Hex(
Int v, PadSpec spec = absl::kNoPad,
typename std::enable_if<sizeof(Int) == 8 &&
!std::is_pointer<Int>::value>::type* = nullptr)
: Hex(spec, static_cast<uint64_t>(v)) {}
template <typename Pointee>
explicit Hex(absl::Nullable<Pointee*> v, PadSpec spec = absl::kNoPad)
: Hex(spec, reinterpret_cast<uintptr_t>(v)) {}
template <typename S>
friend void AbslStringify(S& sink, Hex hex) {
static_assert(
numbers_internal::kFastToBufferSize >= 32,
"This function only works when output buffer >= 32 bytes long");
char buffer[numbers_internal::kFastToBufferSize];
char* const end = &buffer[numbers_internal::kFastToBufferSize];
auto real_width =
absl::numbers_internal::FastHexToBufferZeroPad16(hex.value, end - 16);
if (real_width >= hex.width) {
sink.Append(absl::string_view(end - real_width, real_width));
} else {
std::memset(end - 32, hex.fill, 16);
std::memset(end - real_width - 16, hex.fill, 16);
sink.Append(absl::string_view(end - hex.width, hex.width));
}
}
private:
Hex(PadSpec spec, uint64_t v)
: value(v),
width(spec == absl::kNoPad
? 1
: spec >= absl::kSpacePad2 ? spec - absl::kSpacePad2 + 2
: spec - absl::kZeroPad2 + 2),
fill(spec >= absl::kSpacePad2 ? ' ' : '0') {}
};
struct Dec {
uint64_t value;
uint8_t width;
char fill;
bool neg;
template <typename Int>
explicit Dec(Int v, PadSpec spec = absl::kNoPad,
typename std::enable_if<(sizeof(Int) <= 8)>::type* = nullptr)
: value(v >= 0 ? static_cast<uint64_t>(v)
: uint64_t{0} - static_cast<uint64_t>(v)),
width(spec == absl::kNoPad ? 1
: spec >= absl::kSpacePad2 ? spec - absl::kSpacePad2 + 2
: spec - absl::kZeroPad2 + 2),
fill(spec >= absl::kSpacePad2 ? ' ' : '0'),
neg(v < 0) {}
template <typename S>
friend void AbslStringify(S& sink, Dec dec) {
assert(dec.width <= numbers_internal::kFastToBufferSize);
char buffer[numbers_internal::kFastToBufferSize];
char* const end = &buffer[numbers_internal::kFastToBufferSize];
char* const minfill = end - dec.width;
char* writer = end;
uint64_t val = dec.value;
while (val > 9) {
*--writer = '0' + (val % 10);
val /= 10;
}
*--writer = '0' + static_cast<char>(val);
if (dec.neg) *--writer = '-';
ptrdiff_t fillers = writer - minfill;
if (fillers > 0) {
bool add_sign_again = false;
if (dec.neg && dec.fill == '0') {
++writer;
add_sign_again = true;
}
writer -= fillers;
std::fill_n(writer, fillers, dec.fill);
if (add_sign_again) *--writer = '-';
}
sink.Append(absl::string_view(writer, static_cast<size_t>(end - writer)));
}
};
class AlphaNum {
public:
template <typename T>
AlphaNum(std::initializer_list<T>) = delete;
AlphaNum(int x)
: piece_(digits_, static_cast<size_t>(
numbers_internal::FastIntToBuffer(x, digits_) -
&digits_[0])) {}
AlphaNum(unsigned int x)
: piece_(digits_, static_cast<size_t>(
numbers_internal::FastIntToBuffer(x, digits_) -
&digits_[0])) {}
AlphaNum(long x)
: piece_(digits_, static_cast<size_t>(
numbers_internal::FastIntToBuffer(x, digits_) -
&digits_[0])) {}
AlphaNum(unsigned long x)
: piece_(digits_, static_cast<size_t>(
numbers_internal::FastIntToBuffer(x, digits_) -
&digits_[0])) {}
AlphaNum(long long x)
: piece_(digits_, static_cast<size_t>(
numbers_internal::FastIntToBuffer(x, digits_) -
&digits_[0])) {}
AlphaNum(unsigned long long x)
: piece_(digits_, static_cast<size_t>(
numbers_internal::FastIntToBuffer(x, digits_) -
&digits_[0])) {}
AlphaNum(float f)
: piece_(digits_, numbers_internal::SixDigitsToBuffer(f, digits_)) {}
AlphaNum(double f)
: piece_(digits_, numbers_internal::SixDigitsToBuffer(f, digits_)) {}
template <size_t size>
AlphaNum(
const strings_internal::AlphaNumBuffer<size>& buf
ABSL_ATTRIBUTE_LIFETIME_BOUND)
: piece_(&buf.data[0], buf.size) {}
AlphaNum(absl::Nullable<const char*> c_str
ABSL_ATTRIBUTE_LIFETIME_BOUND)
: piece_(NullSafeStringView(c_str)) {}
AlphaNum(absl::string_view pc
ABSL_ATTRIBUTE_LIFETIME_BOUND)
: piece_(pc) {}
template <typename T, typename = typename std::enable_if<
HasAbslStringify<T>::value>::type>
AlphaNum(
const T& v ABSL_ATTRIBUTE_LIFETIME_BOUND,
strings_internal::StringifySink&& sink ABSL_ATTRIBUTE_LIFETIME_BOUND = {})
: piece_(strings_internal::ExtractStringification(sink, v)) {}
template <typename Allocator>
AlphaNum(
const std::basic_string<char, std::char_traits<char>, Allocator>& str
ABSL_ATTRIBUTE_LIFETIME_BOUND)
: piece_(str) {}
AlphaNum(char c) = delete;
AlphaNum(const AlphaNum&) = delete;
AlphaNum& operator=(const AlphaNum&) = delete;
absl::string_view::size_type size() const { return piece_.size(); }
absl::Nullable<const char*> data() const { return piece_.data(); }
absl::string_view Piece() const { return piece_; }
template <typename T,
typename = typename std::enable_if<
std::is_enum<T>{} && std::is_convertible<T, int>{} &&
!HasAbslStringify<T>::value>::type>
AlphaNum(T e)
: AlphaNum(+e) {}
template <typename T,
typename std::enable_if<std::is_enum<T>{} &&
!std::is_convertible<T, int>{} &&
!HasAbslStringify<T>::value,
char*>::type = nullptr>
AlphaNum(T e)
: AlphaNum(+static_cast<typename std::underlying_type<T>::type>(e)) {}
template <
typename T,
typename std::enable_if<
std::is_class<T>::value &&
(std::is_same<T, std::vector<bool>::reference>::value ||
std::is_same<T, std::vector<bool>::const_reference>::value)>::type* =
nullptr>
AlphaNum(T e) : AlphaNum(static_cast<bool>(e)) {}
private:
absl::string_view piece_;
char digits_[numbers_internal::kFastToBufferSize];
};
namespace strings_internal {
std::string CatPieces(std::initializer_list<absl::string_view> pieces);
void AppendPieces(absl::Nonnull<std::string*> dest,
std::initializer_list<absl::string_view> pieces);
template <typename Integer>
std::string IntegerToString(Integer i) {
constexpr size_t kMaxDigits10 = 22;
std::string result;
strings_internal::STLStringResizeUninitialized(&result, kMaxDigits10);
char* start = &result[0];
char* end = numbers_internal::FastIntToBuffer(i, start);
auto size = static_cast<size_t>(end - start);
assert((size < result.size()) &&
"StrCat(Integer) does not fit into kMaxDigits10");
result.erase(size);
return result;
}
template <typename Float>
std::string FloatToString(Float f) {
std::string result;
strings_internal::STLStringResizeUninitialized(
&result, numbers_internal::kSixDigitsToBufferSize);
char* start = &result[0];
result.erase(numbers_internal::SixDigitsToBuffer(f, start));
return result;
}
inline std::string SingleArgStrCat(int x) { return IntegerToString(x); }
inline std::string SingleArgStrCat(unsigned int x) {
return IntegerToString(x);
}
inline std::string SingleArgStrCat(long x) { return IntegerToString(x); }
inline std::string SingleArgStrCat(unsigned long x) {
return IntegerToString(x);
}
inline std::string SingleArgStrCat(long long x) { return IntegerToString(x); }
inline std::string SingleArgStrCat(unsigned long long x) {
return IntegerToString(x);
}
inline std::string SingleArgStrCat(float x) { return FloatToString(x); }
inline std::string SingleArgStrCat(double x) { return FloatToString(x); }
#ifdef _LIBCPP_VERSION
#define ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE true
#else
#define ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE false
#endif
template <typename T, typename = std::enable_if_t<
ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE &&
std::is_arithmetic<T>{} && !std::is_same<T, char>{}>>
using EnableIfFastCase = T;
#undef ABSL_INTERNAL_STRCAT_ENABLE_FAST_CASE
}
ABSL_MUST_USE_RESULT inline std::string StrCat() { return std::string(); }
template <typename T>
ABSL_MUST_USE_RESULT inline std::string StrCat(
strings_internal::EnableIfFastCase<T> a) {
return strings_internal::SingleArgStrCat(a);
}
ABSL_MUST_USE_RESULT inline std::string StrCat(const AlphaNum& a) {
return std::string(a.data(), a.size());
}
ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b);
ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b,
const AlphaNum& c);
ABSL_MUST_USE_RESULT std::string StrCat(const AlphaNum& a, const AlphaNum& b,
const AlphaNum& c, const AlphaNum& d);
template <typename... AV>
ABSL_MUST_USE_RESULT inline std::string StrCat(
const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d,
const AlphaNum& e, const AV&... args) {
return strings_internal::CatPieces(
{a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(),
static_cast<const AlphaNum&>(args).Piece()...});
}
inline void StrAppend(absl::Nonnull<std::string*>) {}
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a);
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a,
const AlphaNum& b);
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a,
const AlphaNum& b, const AlphaNum& c);
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a,
const AlphaNum& b, const AlphaNum& c, const AlphaNum& d);
template <typename... AV>
inline void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a,
const AlphaNum& b, const AlphaNum& c, const AlphaNum& d,
const AlphaNum& e, const AV&... args) {
strings_internal::AppendPieces(
dest, {a.Piece(), b.Piece(), c.Piece(), d.Piece(), e.Piece(),
static_cast<const AlphaNum&>(args).Piece()...});
}
inline strings_internal::AlphaNumBuffer<
numbers_internal::kSixDigitsToBufferSize>
SixDigits(double d) {
strings_internal::AlphaNumBuffer<numbers_internal::kSixDigitsToBufferSize>
result;
result.size = numbers_internal::SixDigitsToBuffer(d, &result.data[0]);
return result;
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/str_cat.h"
#include <assert.h>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <limits>
#include <string>
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/nullability.h"
#include "absl/strings/internal/resize_uninitialized.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
inline absl::Nonnull<char*> Append(absl::Nonnull<char*> out,
const AlphaNum& x) {
char* after = out + x.size();
if (x.size() != 0) {
memcpy(out, x.data(), x.size());
}
return after;
}
inline void STLStringAppendUninitializedAmortized(std::string* dest,
size_t to_append) {
strings_internal::AppendUninitializedTraits<std::string>::Append(dest,
to_append);
}
}
std::string StrCat(const AlphaNum& a, const AlphaNum& b) {
std::string result;
constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()};
const uint64_t result_size =
static_cast<uint64_t>(a.size()) + static_cast<uint64_t>(b.size());
ABSL_INTERNAL_CHECK(result_size <= kMaxSize, "size_t overflow");
absl::strings_internal::STLStringResizeUninitialized(
&result, static_cast<size_t>(result_size));
char* const begin = &result[0];
char* out = begin;
out = Append(out, a);
out = Append(out, b);
assert(out == begin + result.size());
return result;
}
std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c) {
std::string result;
constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()};
const uint64_t result_size = static_cast<uint64_t>(a.size()) +
static_cast<uint64_t>(b.size()) +
static_cast<uint64_t>(c.size());
ABSL_INTERNAL_CHECK(result_size <= kMaxSize, "size_t overflow");
strings_internal::STLStringResizeUninitialized(
&result, static_cast<size_t>(result_size));
char* const begin = &result[0];
char* out = begin;
out = Append(out, a);
out = Append(out, b);
out = Append(out, c);
assert(out == begin + result.size());
return result;
}
std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c,
const AlphaNum& d) {
std::string result;
constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()};
const uint64_t result_size = static_cast<uint64_t>(a.size()) +
static_cast<uint64_t>(b.size()) +
static_cast<uint64_t>(c.size()) +
static_cast<uint64_t>(d.size());
ABSL_INTERNAL_CHECK(result_size <= kMaxSize, "size_t overflow");
strings_internal::STLStringResizeUninitialized(
&result, static_cast<size_t>(result_size));
char* const begin = &result[0];
char* out = begin;
out = Append(out, a);
out = Append(out, b);
out = Append(out, c);
out = Append(out, d);
assert(out == begin + result.size());
return result;
}
namespace strings_internal {
std::string CatPieces(std::initializer_list<absl::string_view> pieces) {
std::string result;
constexpr uint64_t kMaxSize = uint64_t{std::numeric_limits<size_t>::max()};
uint64_t total_size = 0;
for (absl::string_view piece : pieces) {
total_size += piece.size();
}
ABSL_INTERNAL_CHECK(total_size <= kMaxSize, "size_t overflow");
strings_internal::STLStringResizeUninitialized(
&result, static_cast<size_t>(total_size));
char* const begin = &result[0];
char* out = begin;
for (absl::string_view piece : pieces) {
const size_t this_size = piece.size();
if (this_size != 0) {
memcpy(out, piece.data(), this_size);
out += this_size;
}
}
assert(out == begin + result.size());
return result;
}
#define ASSERT_NO_OVERLAP(dest, src) \
assert(((src).size() == 0) || \
(uintptr_t((src).data() - (dest).data()) > uintptr_t((dest).size())))
void AppendPieces(absl::Nonnull<std::string*> dest,
std::initializer_list<absl::string_view> pieces) {
size_t old_size = dest->size();
size_t to_append = 0;
for (absl::string_view piece : pieces) {
ASSERT_NO_OVERLAP(*dest, piece);
to_append += piece.size();
}
STLStringAppendUninitializedAmortized(dest, to_append);
char* const begin = &(*dest)[0];
char* out = begin + old_size;
for (absl::string_view piece : pieces) {
const size_t this_size = piece.size();
if (this_size != 0) {
memcpy(out, piece.data(), this_size);
out += this_size;
}
}
assert(out == begin + dest->size());
}
}
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a) {
ASSERT_NO_OVERLAP(*dest, a);
std::string::size_type old_size = dest->size();
STLStringAppendUninitializedAmortized(dest, a.size());
char* const begin = &(*dest)[0];
char* out = begin + old_size;
out = Append(out, a);
assert(out == begin + dest->size());
}
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a,
const AlphaNum& b) {
ASSERT_NO_OVERLAP(*dest, a);
ASSERT_NO_OVERLAP(*dest, b);
std::string::size_type old_size = dest->size();
STLStringAppendUninitializedAmortized(dest, a.size() + b.size());
char* const begin = &(*dest)[0];
char* out = begin + old_size;
out = Append(out, a);
out = Append(out, b);
assert(out == begin + dest->size());
}
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a,
const AlphaNum& b, const AlphaNum& c) {
ASSERT_NO_OVERLAP(*dest, a);
ASSERT_NO_OVERLAP(*dest, b);
ASSERT_NO_OVERLAP(*dest, c);
std::string::size_type old_size = dest->size();
STLStringAppendUninitializedAmortized(dest, a.size() + b.size() + c.size());
char* const begin = &(*dest)[0];
char* out = begin + old_size;
out = Append(out, a);
out = Append(out, b);
out = Append(out, c);
assert(out == begin + dest->size());
}
void StrAppend(absl::Nonnull<std::string*> dest, const AlphaNum& a,
const AlphaNum& b, const AlphaNum& c, const AlphaNum& d) {
ASSERT_NO_OVERLAP(*dest, a);
ASSERT_NO_OVERLAP(*dest, b);
ASSERT_NO_OVERLAP(*dest, c);
ASSERT_NO_OVERLAP(*dest, d);
std::string::size_type old_size = dest->size();
STLStringAppendUninitializedAmortized(
dest, a.size() + b.size() + c.size() + d.size());
char* const begin = &(*dest)[0];
char* out = begin + old_size;
out = Append(out, a);
out = Append(out, b);
out = Append(out, c);
out = Append(out, d);
assert(out == begin + dest->size());
}
ABSL_NAMESPACE_END
} | #include "absl/strings/str_cat.h"
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#ifdef __ANDROID__
#define ABSL_EXPECT_DEBUG_DEATH(statement, regex) \
EXPECT_DEBUG_DEATH(statement, ".*")
#else
#define ABSL_EXPECT_DEBUG_DEATH(statement, regex) \
EXPECT_DEBUG_DEATH(statement, regex)
#endif
namespace {
TEST(StrCat, Ints) {
const short s = -1;
const uint16_t us = 2;
const int i = -3;
const unsigned int ui = 4;
const long l = -5;
const unsigned long ul = 6;
const long long ll = -7;
const unsigned long long ull = 8;
const ptrdiff_t ptrdiff = -9;
const size_t size = 10;
const intptr_t intptr = -12;
const uintptr_t uintptr = 13;
std::string answer;
answer = absl::StrCat(s, us);
EXPECT_EQ(answer, "-12");
answer = absl::StrCat(i, ui);
EXPECT_EQ(answer, "-34");
answer = absl::StrCat(l, ul);
EXPECT_EQ(answer, "-56");
answer = absl::StrCat(ll, ull);
EXPECT_EQ(answer, "-78");
answer = absl::StrCat(ptrdiff, size);
EXPECT_EQ(answer, "-910");
answer = absl::StrCat(ptrdiff, intptr);
EXPECT_EQ(answer, "-9-12");
answer = absl::StrCat(uintptr, 0);
EXPECT_EQ(answer, "130");
}
TEST(StrCat, Enums) {
enum SmallNumbers { One = 1, Ten = 10 } e = Ten;
EXPECT_EQ("10", absl::StrCat(e));
EXPECT_EQ("-5", absl::StrCat(SmallNumbers(-5)));
enum class Option { Boxers = 1, Briefs = -1 };
EXPECT_EQ("-1", absl::StrCat(Option::Briefs));
enum class Airplane : uint64_t {
Airbus = 1,
Boeing = 1000,
Canary = 10000000000
};
EXPECT_EQ("10000000000", absl::StrCat(Airplane::Canary));
enum class TwoGig : int32_t {
TwoToTheZero = 1,
TwoToTheSixteenth = 1 << 16,
TwoToTheThirtyFirst = INT32_MIN
};
EXPECT_EQ("65536", absl::StrCat(TwoGig::TwoToTheSixteenth));
EXPECT_EQ("-2147483648", absl::StrCat(TwoGig::TwoToTheThirtyFirst));
EXPECT_EQ("-1", absl::StrCat(static_cast<TwoGig>(-1)));
enum class FourGig : uint32_t {
TwoToTheZero = 1,
TwoToTheSixteenth = 1 << 16,
TwoToTheThirtyFirst = 1U << 31
};
EXPECT_EQ("65536", absl::StrCat(FourGig::TwoToTheSixteenth));
EXPECT_EQ("2147483648", absl::StrCat(FourGig::TwoToTheThirtyFirst));
EXPECT_EQ("4294967295", absl::StrCat(static_cast<FourGig>(-1)));
EXPECT_EQ("10000000000", absl::StrCat(Airplane::Canary));
}
TEST(StrCat, Basics) {
std::string result;
std::string strs[] = {"Hello", "Cruel", "World"};
std::string stdstrs[] = {
"std::Hello",
"std::Cruel",
"std::World"
};
absl::string_view pieces[] = {"Hello", "Cruel", "World"};
const char* c_strs[] = {
"Hello",
"Cruel",
"World"
};
int32_t i32s[] = {'H', 'C', 'W'};
uint64_t ui64s[] = {12345678910LL, 10987654321LL};
EXPECT_EQ(absl::StrCat(), "");
result = absl::StrCat(false, true, 2, 3);
EXPECT_EQ(result, "0123");
result = absl::StrCat(-1);
EXPECT_EQ(result, "-1");
result = absl::StrCat(absl::SixDigits(0.5));
EXPECT_EQ(result, "0.5");
result = absl::StrCat(strs[1], pieces[2]);
EXPECT_EQ(result, "CruelWorld");
result = absl::StrCat(stdstrs[1], " ", stdstrs[2]);
EXPECT_EQ(result, "std::Cruel std::World");
result = absl::StrCat(strs[0], ", ", pieces[2]);
EXPECT_EQ(result, "Hello, World");
result = absl::StrCat(strs[0], ", ", strs[1], " ", strs[2], "!");
EXPECT_EQ(result, "Hello, Cruel World!");
result = absl::StrCat(pieces[0], ", ", pieces[1], " ", pieces[2]);
EXPECT_EQ(result, "Hello, Cruel World");
result = absl::StrCat(c_strs[0], ", ", c_strs[1], " ", c_strs[2]);
EXPECT_EQ(result, "Hello, Cruel World");
result = absl::StrCat("ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!");
EXPECT_EQ(result, "ASCII 72, 67 87!");
result = absl::StrCat(ui64s[0], ", ", ui64s[1], "!");
EXPECT_EQ(result, "12345678910, 10987654321!");
std::string one =
"1";
result = absl::StrCat("And a ", one.size(), " and a ",
&result[2] - &result[0], " and a ", one, " 2 3 4", "!");
EXPECT_EQ(result, "And a 1 and a 2 and a 1 2 3 4!");
result =
absl::StrCat("To output a char by ASCII/numeric value, use +: ", '!' + 0);
EXPECT_EQ(result, "To output a char by ASCII/numeric value, use +: 33");
float f = 100000.5;
result = absl::StrCat("A hundred K and a half is ", absl::SixDigits(f));
EXPECT_EQ(result, "A hundred K and a half is 100000");
f = 100001.5;
result =
absl::StrCat("A hundred K and one and a half is ", absl::SixDigits(f));
EXPECT_EQ(result, "A hundred K and one and a half is 100002");
double d = 100000.5;
d *= d;
result =
absl::StrCat("A hundred K and a half squared is ", absl::SixDigits(d));
EXPECT_EQ(result, "A hundred K and a half squared is 1.00001e+10");
result = absl::StrCat(1, 2, 333, 4444, 55555, 666666, 7777777, 88888888,
999999999);
EXPECT_EQ(result, "12333444455555666666777777788888888999999999");
}
TEST(StrCat, CornerCases) {
std::string result;
result = absl::StrCat("");
EXPECT_EQ(result, "");
result = absl::StrCat("", "");
EXPECT_EQ(result, "");
result = absl::StrCat("", "", "");
EXPECT_EQ(result, "");
result = absl::StrCat("", "", "", "");
EXPECT_EQ(result, "");
result = absl::StrCat("", "", "", "", "");
EXPECT_EQ(result, "");
}
TEST(StrCat, NullConstCharPtr) {
const char* null = nullptr;
EXPECT_EQ(absl::StrCat("mon", null, "key"), "monkey");
}
template <typename T>
struct Mallocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
size_type max_size() const {
return size_t(std::numeric_limits<size_type>::max()) / sizeof(value_type);
}
template <typename U>
struct rebind {
typedef Mallocator<U> other;
};
Mallocator() = default;
template <class U>
Mallocator(const Mallocator<U>&) {}
T* allocate(size_t n) { return static_cast<T*>(std::malloc(n * sizeof(T))); }
void deallocate(T* p, size_t) { std::free(p); }
};
template <typename T, typename U>
bool operator==(const Mallocator<T>&, const Mallocator<U>&) {
return true;
}
template <typename T, typename U>
bool operator!=(const Mallocator<T>&, const Mallocator<U>&) {
return false;
}
TEST(StrCat, CustomAllocator) {
using mstring =
std::basic_string<char, std::char_traits<char>, Mallocator<char>>;
const mstring str1("PARACHUTE OFF A BLIMP INTO MOSCONE!!");
const mstring str2("Read this book about coffee tables");
std::string result = absl::StrCat(str1, str2);
EXPECT_EQ(result,
"PARACHUTE OFF A BLIMP INTO MOSCONE!!"
"Read this book about coffee tables");
}
TEST(StrCat, MaxArgs) {
std::string result;
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a");
EXPECT_EQ(result, "123456789a");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b");
EXPECT_EQ(result, "123456789ab");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c");
EXPECT_EQ(result, "123456789abc");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d");
EXPECT_EQ(result, "123456789abcd");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e");
EXPECT_EQ(result, "123456789abcde");
result =
absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f");
EXPECT_EQ(result, "123456789abcdef");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g");
EXPECT_EQ(result, "123456789abcdefg");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h");
EXPECT_EQ(result, "123456789abcdefgh");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i");
EXPECT_EQ(result, "123456789abcdefghi");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j");
EXPECT_EQ(result, "123456789abcdefghij");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k");
EXPECT_EQ(result, "123456789abcdefghijk");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l");
EXPECT_EQ(result, "123456789abcdefghijkl");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m");
EXPECT_EQ(result, "123456789abcdefghijklm");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n");
EXPECT_EQ(result, "123456789abcdefghijklmn");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o");
EXPECT_EQ(result, "123456789abcdefghijklmno");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p");
EXPECT_EQ(result, "123456789abcdefghijklmnop");
result = absl::StrCat(1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q");
EXPECT_EQ(result, "123456789abcdefghijklmnopq");
result = absl::StrCat(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
EXPECT_EQ(result,
"12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
TEST(StrAppend, Basics) {
std::string result = "existing text";
std::string strs[] = {"Hello", "Cruel", "World"};
std::string stdstrs[] = {
"std::Hello",
"std::Cruel",
"std::World"
};
absl::string_view pieces[] = {"Hello", "Cruel", "World"};
const char* c_strs[] = {
"Hello",
"Cruel",
"World"
};
int32_t i32s[] = {'H', 'C', 'W'};
uint64_t ui64s[] = {12345678910LL, 10987654321LL};
std::string::size_type old_size = result.size();
absl::StrAppend(&result);
EXPECT_EQ(result.size(), old_size);
old_size = result.size();
absl::StrAppend(&result, strs[0]);
EXPECT_EQ(result.substr(old_size), "Hello");
old_size = result.size();
absl::StrAppend(&result, strs[1], pieces[2]);
EXPECT_EQ(result.substr(old_size), "CruelWorld");
old_size = result.size();
absl::StrAppend(&result, stdstrs[0], ", ", pieces[2]);
EXPECT_EQ(result.substr(old_size), "std::Hello, World");
old_size = result.size();
absl::StrAppend(&result, strs[0], ", ", stdstrs[1], " ", strs[2], "!");
EXPECT_EQ(result.substr(old_size), "Hello, std::Cruel World!");
old_size = result.size();
absl::StrAppend(&result, pieces[0], ", ", pieces[1], " ", pieces[2]);
EXPECT_EQ(result.substr(old_size), "Hello, Cruel World");
old_size = result.size();
absl::StrAppend(&result, c_strs[0], ", ", c_strs[1], " ", c_strs[2]);
EXPECT_EQ(result.substr(old_size), "Hello, Cruel World");
old_size = result.size();
absl::StrAppend(&result, "ASCII ", i32s[0], ", ", i32s[1], " ", i32s[2], "!");
EXPECT_EQ(result.substr(old_size), "ASCII 72, 67 87!");
old_size = result.size();
absl::StrAppend(&result, ui64s[0], ", ", ui64s[1], "!");
EXPECT_EQ(result.substr(old_size), "12345678910, 10987654321!");
std::string one =
"1";
old_size = result.size();
absl::StrAppend(&result, "And a ", one.size(), " and a ",
&result[2] - &result[0], " and a ", one, " 2 3 4", "!");
EXPECT_EQ(result.substr(old_size), "And a 1 and a 2 and a 1 2 3 4!");
old_size = result.size();
absl::StrAppend(&result,
"To output a char by ASCII/numeric value, use +: ", '!' + 0);
EXPECT_EQ(result.substr(old_size),
"To output a char by ASCII/numeric value, use +: 33");
old_size = result.size();
absl::StrAppend(&result, 1, 22, 333, 4444, 55555, 666666, 7777777, 88888888,
9);
EXPECT_EQ(result.substr(old_size), "1223334444555556666667777777888888889");
old_size = result.size();
absl::StrAppend(
&result, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"No limit thanks to C++11's variadic templates");
EXPECT_EQ(result.substr(old_size),
"12345678910abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"No limit thanks to C++11's variadic templates");
}
TEST(StrCat, VectorBoolReferenceTypes) {
std::vector<bool> v;
v.push_back(true);
v.push_back(false);
std::vector<bool> const& cv = v;
std::string result = absl::StrCat(v[0], v[1], cv[0], cv[1]);
EXPECT_EQ(result, "1010");
}
TEST(StrCat, AvoidsMemcpyWithNullptr) {
EXPECT_EQ(absl::StrCat(42, absl::string_view{}), "42");
EXPECT_EQ(absl::StrCat(1, 2, 3, 4, 5, absl::string_view{}), "12345");
std::string result;
absl::StrAppend(&result, 1, 2, 3, 4, 5, absl::string_view{});
EXPECT_EQ(result, "12345");
}
#if GTEST_HAS_DEATH_TEST
TEST(StrAppend, Death) {
std::string s = "self";
ABSL_EXPECT_DEBUG_DEATH(absl::StrAppend(&s, s.c_str() + 1),
"ssertion.*failed");
ABSL_EXPECT_DEBUG_DEATH(absl::StrAppend(&s, s), "ssertion.*failed");
}
#endif
TEST(StrAppend, CornerCases) {
std::string result;
absl::StrAppend(&result, "");
EXPECT_EQ(result, "");
absl::StrAppend(&result, "", "");
EXPECT_EQ(result, "");
absl::StrAppend(&result, "", "", "");
EXPECT_EQ(result, "");
absl::StrAppend(&result, "", "", "", "");
EXPECT_EQ(result, "");
absl::StrAppend(&result, "", "", "", "", "");
EXPECT_EQ(result, "");
}
TEST(StrAppend, CornerCasesNonEmptyAppend) {
for (std::string result : {"hello", "a string too long to fit in the SSO"}) {
const std::string expected = result;
absl::StrAppend(&result, "");
EXPECT_EQ(result, expected);
absl::StrAppend(&result, "", "");
EXPECT_EQ(result, expected);
absl::StrAppend(&result, "", "", "");
EXPECT_EQ(result, expected);
absl::StrAppend(&result, "", "", "", "");
EXPECT_EQ(result, expected);
absl::StrAppend(&result, "", "", "", "", "");
EXPECT_EQ(result, expected);
}
}
template <typename IntType>
void CheckHex(IntType v, const char* nopad_format, const char* zeropad_format,
const char* spacepad_format) {
char expected[256];
std::string actual = absl::StrCat(absl::Hex(v, absl::kNoPad));
snprintf(expected, sizeof(expected), nopad_format, v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
for (int spec = absl::kZeroPad2; spec <= absl::kZeroPad20; ++spec) {
std::string actual =
absl::StrCat(absl::Hex(v, static_cast<absl::PadSpec>(spec)));
snprintf(expected, sizeof(expected), zeropad_format,
spec - absl::kZeroPad2 + 2, v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
}
for (int spec = absl::kSpacePad2; spec <= absl::kSpacePad20; ++spec) {
std::string actual =
absl::StrCat(absl::Hex(v, static_cast<absl::PadSpec>(spec)));
snprintf(expected, sizeof(expected), spacepad_format,
spec - absl::kSpacePad2 + 2, v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
}
}
template <typename IntType>
void CheckDec(IntType v, const char* nopad_format, const char* zeropad_format,
const char* spacepad_format) {
char expected[256];
std::string actual = absl::StrCat(absl::Dec(v, absl::kNoPad));
snprintf(expected, sizeof(expected), nopad_format, v);
EXPECT_EQ(expected, actual) << " decimal value " << v;
for (int spec = absl::kZeroPad2; spec <= absl::kZeroPad20; ++spec) {
std::string actual =
absl::StrCat(absl::Dec(v, static_cast<absl::PadSpec>(spec)));
snprintf(expected, sizeof(expected), zeropad_format,
spec - absl::kZeroPad2 + 2, v);
EXPECT_EQ(expected, actual)
<< " decimal value " << v << " format '" << zeropad_format
<< "' digits " << (spec - absl::kZeroPad2 + 2);
}
for (int spec = absl::kSpacePad2; spec <= absl::kSpacePad20; ++spec) {
std::string actual =
absl::StrCat(absl::Dec(v, static_cast<absl::PadSpec>(spec)));
snprintf(expected, sizeof(expected), spacepad_format,
spec - absl::kSpacePad2 + 2, v);
EXPECT_EQ(expected, actual)
<< " decimal value " << v << " format '" << spacepad_format
<< "' digits " << (spec - absl::kSpacePad2 + 2);
}
}
void CheckHexDec64(uint64_t v) {
unsigned long long ullv = v;
CheckHex(ullv, "%llx", "%0*llx", "%*llx");
CheckDec(ullv, "%llu", "%0*llu", "%*llu");
long long llv = static_cast<long long>(ullv);
CheckDec(llv, "%lld", "%0*lld", "%*lld");
if (sizeof(v) == sizeof(&v)) {
auto uintptr = static_cast<uintptr_t>(v);
void* ptr = reinterpret_cast<void*>(uintptr);
CheckHex(ptr, "%llx", "%0*llx", "%*llx");
}
}
void CheckHexDec32(uint32_t uv) {
CheckHex(uv, "%x", "%0*x", "%*x");
CheckDec(uv, "%u", "%0*u", "%*u");
int32_t v = static_cast<int32_t>(uv);
CheckDec(v, "%d", "%0*d", "%*d");
if (sizeof(v) == sizeof(&v)) {
auto uintptr = static_cast<uintptr_t>(v);
void* ptr = reinterpret_cast<void*>(uintptr);
CheckHex(ptr, "%x", "%0*x", "%*x");
}
}
void CheckAll(uint64_t v) {
CheckHexDec64(v);
CheckHexDec32(static_cast<uint32_t>(v));
}
void TestFastPrints() {
for (int i = 0; i < 10000; i++) {
CheckAll(i);
}
CheckAll(std::numeric_limits<uint64_t>::max());
CheckAll(std::numeric_limits<uint64_t>::max() - 1);
CheckAll(std::numeric_limits<int64_t>::min());
CheckAll(std::numeric_limits<int64_t>::min() + 1);
CheckAll(std::numeric_limits<uint32_t>::max());
CheckAll(std::numeric_limits<uint32_t>::max() - 1);
CheckAll(std::numeric_limits<int32_t>::min());
CheckAll(std::numeric_limits<int32_t>::min() + 1);
CheckAll(999999999);
CheckAll(1000000000);
CheckAll(9999999999);
CheckAll(10000000000);
CheckAll(999999999999999999);
CheckAll(9999999999999999999u);
CheckAll(1000000000000000000);
CheckAll(10000000000000000000u);
CheckAll(999999999876543210);
CheckAll(9999999999876543210u);
CheckAll(0x123456789abcdef0);
CheckAll(0x12345678);
int8_t minus_one_8bit = -1;
EXPECT_EQ("ff", absl::StrCat(absl::Hex(minus_one_8bit)));
int16_t minus_one_16bit = -1;
EXPECT_EQ("ffff", absl::StrCat(absl::Hex(minus_one_16bit)));
}
TEST(Numbers, TestFunctionsMovedOverFromNumbersMain) {
TestFastPrints();
}
struct PointStringify {
template <typename FormatSink>
friend void AbslStringify(FormatSink& sink, const PointStringify& p) {
sink.Append("(");
sink.Append(absl::StrCat(p.x));
sink.Append(", ");
sink.Append(absl::StrCat(p.y));
sink.Append(")");
}
double x = 10.0;
double y = 20.0;
};
TEST(StrCat, AbslStringifyExample) {
PointStringify p;
EXPECT_EQ(absl::StrCat(p), "(10, 20)");
EXPECT_EQ(absl::StrCat("a ", p, " z"), "a (10, 20) z");
}
struct PointStringifyUsingFormat {
template <typename FormatSink>
friend void AbslStringify(FormatSink& sink,
const PointStringifyUsingFormat& p) {
absl::Format(&sink, "(%g, %g)", p.x, p.y);
}
double x = 10.0;
double y = 20.0;
};
TEST(StrCat, AbslStringifyExampleUsingFormat) {
PointStringifyUsingFormat p;
EXPECT_EQ(absl::StrCat(p), "(10, 20)");
EXPECT_EQ(absl::StrCat("a ", p, " z"), "a (10, 20) z");
}
enum class EnumWithStringify { Many = 0, Choices = 1 };
template <typename Sink>
void AbslStringify(Sink& sink, EnumWithStringify e) {
absl::Format(&sink, "%s", e == EnumWithStringify::Many ? "Many" : "Choices");
}
TEST(StrCat, AbslStringifyWithEnum) {
const auto e = EnumWithStringify::Choices;
EXPECT_EQ(absl::StrCat(e), "Choices");
}
template <typename Integer>
void CheckSingleArgumentIntegerLimits() {
Integer max = std::numeric_limits<Integer>::max();
Integer min = std::numeric_limits<Integer>::min();
EXPECT_EQ(absl::StrCat(max), std::to_string(max));
EXPECT_EQ(absl::StrCat(min), std::to_string(min));
}
TEST(StrCat, SingleArgumentLimits) {
CheckSingleArgumentIntegerLimits<int32_t>();
CheckSingleArgumentIntegerLimits<uint32_t>();
CheckSingleArgumentIntegerLimits<int64_t>();
CheckSingleArgumentIntegerLimits<uint64_t>();
}
} |
2,549 | cpp | abseil/abseil-cpp | str_split | absl/strings/str_split.cc | absl/strings/str_split_test.cc | #ifndef ABSL_STRINGS_STR_SPLIT_H_
#define ABSL_STRINGS_STR_SPLIT_H_
#include <algorithm>
#include <cstddef>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/internal/raw_logging.h"
#include "absl/base/macros.h"
#include "absl/strings/internal/str_split_internal.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class ByString {
public:
explicit ByString(absl::string_view sp);
absl::string_view Find(absl::string_view text, size_t pos) const;
private:
const std::string delimiter_;
};
class ByAsciiWhitespace {
public:
absl::string_view Find(absl::string_view text, size_t pos) const;
};
class ByChar {
public:
explicit ByChar(char c) : c_(c) {}
absl::string_view Find(absl::string_view text, size_t pos) const;
private:
char c_;
};
class ByAnyChar {
public:
explicit ByAnyChar(absl::string_view sp);
absl::string_view Find(absl::string_view text, size_t pos) const;
private:
const std::string delimiters_;
};
class ByLength {
public:
explicit ByLength(ptrdiff_t length);
absl::string_view Find(absl::string_view text, size_t pos) const;
private:
const ptrdiff_t length_;
};
namespace strings_internal {
template <typename Delimiter>
struct SelectDelimiter {
using type = Delimiter;
};
template <>
struct SelectDelimiter<char> {
using type = ByChar;
};
template <>
struct SelectDelimiter<char*> {
using type = ByString;
};
template <>
struct SelectDelimiter<const char*> {
using type = ByString;
};
template <>
struct SelectDelimiter<absl::string_view> {
using type = ByString;
};
template <>
struct SelectDelimiter<std::string> {
using type = ByString;
};
template <typename Delimiter>
class MaxSplitsImpl {
public:
MaxSplitsImpl(Delimiter delimiter, int limit)
: delimiter_(delimiter), limit_(limit), count_(0) {}
absl::string_view Find(absl::string_view text, size_t pos) {
if (count_++ == limit_) {
return absl::string_view(text.data() + text.size(),
0);
}
return delimiter_.Find(text, pos);
}
private:
Delimiter delimiter_;
const int limit_;
int count_;
};
}
template <typename Delimiter>
inline strings_internal::MaxSplitsImpl<
typename strings_internal::SelectDelimiter<Delimiter>::type>
MaxSplits(Delimiter delimiter, int limit) {
typedef
typename strings_internal::SelectDelimiter<Delimiter>::type DelimiterType;
return strings_internal::MaxSplitsImpl<DelimiterType>(
DelimiterType(delimiter), limit);
}
struct AllowEmpty {
bool operator()(absl::string_view) const { return true; }
};
struct SkipEmpty {
bool operator()(absl::string_view sp) const { return !sp.empty(); }
};
struct SkipWhitespace {
bool operator()(absl::string_view sp) const {
sp = absl::StripAsciiWhitespace(sp);
return !sp.empty();
}
};
template <typename T>
using EnableSplitIfString =
typename std::enable_if<std::is_same<T, std::string>::value ||
std::is_same<T, const std::string>::value,
int>::type;
template <typename Delimiter>
strings_internal::Splitter<
typename strings_internal::SelectDelimiter<Delimiter>::type, AllowEmpty,
absl::string_view>
StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d) {
using DelimiterType =
typename strings_internal::SelectDelimiter<Delimiter>::type;
return strings_internal::Splitter<DelimiterType, AllowEmpty,
absl::string_view>(
text.value(), DelimiterType(d), AllowEmpty());
}
template <typename Delimiter, typename StringType,
EnableSplitIfString<StringType> = 0>
strings_internal::Splitter<
typename strings_internal::SelectDelimiter<Delimiter>::type, AllowEmpty,
std::string>
StrSplit(StringType&& text, Delimiter d) {
using DelimiterType =
typename strings_internal::SelectDelimiter<Delimiter>::type;
return strings_internal::Splitter<DelimiterType, AllowEmpty, std::string>(
std::move(text), DelimiterType(d), AllowEmpty());
}
template <typename Delimiter, typename Predicate>
strings_internal::Splitter<
typename strings_internal::SelectDelimiter<Delimiter>::type, Predicate,
absl::string_view>
StrSplit(strings_internal::ConvertibleToStringView text, Delimiter d,
Predicate p) {
using DelimiterType =
typename strings_internal::SelectDelimiter<Delimiter>::type;
return strings_internal::Splitter<DelimiterType, Predicate,
absl::string_view>(
text.value(), DelimiterType(std::move(d)), std::move(p));
}
template <typename Delimiter, typename Predicate, typename StringType,
EnableSplitIfString<StringType> = 0>
strings_internal::Splitter<
typename strings_internal::SelectDelimiter<Delimiter>::type, Predicate,
std::string>
StrSplit(StringType&& text, Delimiter d, Predicate p) {
using DelimiterType =
typename strings_internal::SelectDelimiter<Delimiter>::type;
return strings_internal::Splitter<DelimiterType, Predicate, std::string>(
std::move(text), DelimiterType(d), std::move(p));
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/str_split.h"
#include <algorithm>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
template <typename FindPolicy>
absl::string_view GenericFind(absl::string_view text,
absl::string_view delimiter, size_t pos,
FindPolicy find_policy) {
if (delimiter.empty() && text.length() > 0) {
return absl::string_view(text.data() + pos + 1, 0);
}
size_t found_pos = absl::string_view::npos;
absl::string_view found(text.data() + text.size(),
0);
found_pos = find_policy.Find(text, delimiter, pos);
if (found_pos != absl::string_view::npos) {
found = absl::string_view(text.data() + found_pos,
find_policy.Length(delimiter));
}
return found;
}
struct LiteralPolicy {
static size_t Find(absl::string_view text, absl::string_view delimiter,
size_t pos) {
return text.find(delimiter, pos);
}
static size_t Length(absl::string_view delimiter) {
return delimiter.length();
}
};
struct AnyOfPolicy {
static size_t Find(absl::string_view text, absl::string_view delimiter,
size_t pos) {
return text.find_first_of(delimiter, pos);
}
static size_t Length(absl::string_view ) { return 1; }
};
}
ByString::ByString(absl::string_view sp) : delimiter_(sp) {}
absl::string_view ByString::Find(absl::string_view text, size_t pos) const {
if (delimiter_.length() == 1) {
size_t found_pos = text.find(delimiter_[0], pos);
if (found_pos == absl::string_view::npos)
return absl::string_view(text.data() + text.size(), 0);
return text.substr(found_pos, 1);
}
return GenericFind(text, delimiter_, pos, LiteralPolicy());
}
absl::string_view ByAsciiWhitespace::Find(absl::string_view text,
size_t pos) const {
return GenericFind(text, " \t\v\f\r\n", pos, AnyOfPolicy());
}
absl::string_view ByChar::Find(absl::string_view text, size_t pos) const {
size_t found_pos = text.find(c_, pos);
if (found_pos == absl::string_view::npos)
return absl::string_view(text.data() + text.size(), 0);
return text.substr(found_pos, 1);
}
ByAnyChar::ByAnyChar(absl::string_view sp) : delimiters_(sp) {}
absl::string_view ByAnyChar::Find(absl::string_view text, size_t pos) const {
return GenericFind(text, delimiters_, pos, AnyOfPolicy());
}
ByLength::ByLength(ptrdiff_t length) : length_(length) {
ABSL_RAW_CHECK(length > 0, "");
}
absl::string_view ByLength::Find(absl::string_view text, size_t pos) const {
pos = std::min(pos, text.size());
absl::string_view substr = text.substr(pos);
if (substr.length() <= static_cast<size_t>(length_))
return absl::string_view(text.data() + text.size(), 0);
return absl::string_view(substr.data() + length_, 0);
}
ABSL_NAMESPACE_END
} | #include "absl/strings/str_split.h"
#include <cstddef>
#include <cstdint>
#include <deque>
#include <initializer_list>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/macros.h"
#include "absl/container/btree_map.h"
#include "absl/container/btree_set.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/node_hash_map.h"
#include "absl/strings/string_view.h"
namespace {
using ::testing::ElementsAre;
using ::testing::IsEmpty;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
TEST(Split, TraitsTest) {
static_assert(!absl::strings_internal::SplitterIsConvertibleTo<int>::value,
"");
static_assert(
!absl::strings_internal::SplitterIsConvertibleTo<std::string>::value, "");
static_assert(absl::strings_internal::SplitterIsConvertibleTo<
std::vector<std::string>>::value,
"");
static_assert(
!absl::strings_internal::SplitterIsConvertibleTo<std::vector<int>>::value,
"");
static_assert(absl::strings_internal::SplitterIsConvertibleTo<
std::vector<absl::string_view>>::value,
"");
static_assert(absl::strings_internal::SplitterIsConvertibleTo<
std::map<std::string, std::string>>::value,
"");
static_assert(absl::strings_internal::SplitterIsConvertibleTo<
std::map<absl::string_view, absl::string_view>>::value,
"");
static_assert(!absl::strings_internal::SplitterIsConvertibleTo<
std::map<int, std::string>>::value,
"");
static_assert(!absl::strings_internal::SplitterIsConvertibleTo<
std::map<std::string, int>>::value,
"");
}
TEST(Split, APIExamples) {
{
std::vector<std::string> v = absl::StrSplit("a,b,c", ",");
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
using absl::ByString;
v = absl::StrSplit("a,b,c", ByString(","));
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
EXPECT_THAT(absl::StrSplit("a,b,c", ByString(",")),
ElementsAre("a", "b", "c"));
}
{
std::vector<std::string> v = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
using absl::ByChar;
v = absl::StrSplit("a,b,c", ByChar(','));
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
const std::vector<std::string> v = absl::StrSplit("a=>b=>c", "=>");
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
std::vector<absl::string_view> v = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
std::vector<std::string> v = absl::StrSplit(",a,b,c,", ',');
EXPECT_THAT(v, ElementsAre("", "a", "b", "c", ""));
}
{
std::vector<std::string> v = absl::StrSplit("abc", ',');
EXPECT_THAT(v, ElementsAre("abc"));
}
{
std::vector<std::string> v = absl::StrSplit("abc", "");
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
std::string embedded_nulls("a\0b\0c", 5);
std::string null_delim("\0", 1);
std::vector<std::string> v = absl::StrSplit(embedded_nulls, null_delim);
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
std::pair<std::string, std::string> p = absl::StrSplit("a,b,c", ',');
EXPECT_EQ("a", p.first);
EXPECT_EQ("b", p.second);
}
{
std::set<std::string> v = absl::StrSplit("a,b,c,a,b,c,a,b,c", ',');
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
char a[] = ",";
char* d = a + 0;
std::vector<std::string> v = absl::StrSplit("a,b,c", d);
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
using absl::ByAnyChar;
std::vector<std::string> v = absl::StrSplit("a,b;c", ByAnyChar(",;"));
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
using absl::SkipWhitespace;
std::vector<std::string> v =
absl::StrSplit(" a , ,,b,", ',', SkipWhitespace());
EXPECT_THAT(v, ElementsAre(" a ", "b"));
}
{
using absl::ByLength;
std::vector<std::string> v = absl::StrSplit("abcdefg", ByLength(3));
EXPECT_THAT(v, ElementsAre("abc", "def", "g"));
}
{
std::vector<std::string> v1 = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(v1, ElementsAre("a", "b", "c"));
std::vector<std::string> v2(absl::StrSplit("a,b,c", ','));
EXPECT_THAT(v2, ElementsAre("a", "b", "c"));
auto v3 = std::vector<std::string>(absl::StrSplit("a,b,c", ','));
EXPECT_THAT(v3, ElementsAre("a", "b", "c"));
v3 = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(v3, ElementsAre("a", "b", "c"));
}
{
std::map<std::string, std::string> m = absl::StrSplit("a,1,b,2,a,3", ',');
EXPECT_EQ(2, m.size());
EXPECT_EQ("3", m["a"]);
EXPECT_EQ("2", m["b"]);
}
{
std::multimap<std::string, std::string> m =
absl::StrSplit("a,1,b,2,a,3", ',');
EXPECT_EQ(3, m.size());
auto it = m.find("a");
EXPECT_EQ("1", it->second);
++it;
EXPECT_EQ("3", it->second);
it = m.find("b");
EXPECT_EQ("2", it->second);
}
{
std::string s = "x,x,x,x,x,x,x";
for (absl::string_view sp : absl::StrSplit(s, ',')) {
EXPECT_EQ("x", sp);
}
}
{
using absl::SkipWhitespace;
std::string s = " ,x,,x,,x,x,x,,";
for (absl::string_view sp : absl::StrSplit(s, ',', SkipWhitespace())) {
EXPECT_EQ("x", sp);
}
}
{
std::map<std::string, std::string> m;
for (absl::string_view sp : absl::StrSplit("a=b=c,d=e,f=,g", ',')) {
m.insert(absl::StrSplit(sp, absl::MaxSplits('=', 1)));
}
EXPECT_EQ("b=c", m.find("a")->second);
EXPECT_EQ("e", m.find("d")->second);
EXPECT_EQ("", m.find("f")->second);
EXPECT_EQ("", m.find("g")->second);
}
}
TEST(SplitIterator, Basics) {
auto splitter = absl::StrSplit("a,b", ',');
auto it = splitter.begin();
auto end = splitter.end();
EXPECT_NE(it, end);
EXPECT_EQ("a", *it);
++it;
EXPECT_NE(it, end);
EXPECT_EQ("b",
std::string(it->data(), it->size()));
it++;
EXPECT_EQ(it, end);
}
class Skip {
public:
explicit Skip(const std::string& s) : s_(s) {}
bool operator()(absl::string_view sp) { return sp != s_; }
private:
std::string s_;
};
TEST(SplitIterator, Predicate) {
auto splitter = absl::StrSplit("a,b,c", ',', Skip("b"));
auto it = splitter.begin();
auto end = splitter.end();
EXPECT_NE(it, end);
EXPECT_EQ("a", *it);
++it;
EXPECT_NE(it, end);
EXPECT_EQ("c",
std::string(it->data(), it->size()));
it++;
EXPECT_EQ(it, end);
}
TEST(SplitIterator, EdgeCases) {
struct {
std::string in;
std::vector<std::string> expect;
} specs[] = {
{"", {""}},
{"foo", {"foo"}},
{",", {"", ""}},
{",foo", {"", "foo"}},
{"foo,", {"foo", ""}},
{",foo,", {"", "foo", ""}},
{"foo,bar", {"foo", "bar"}},
};
for (const auto& spec : specs) {
SCOPED_TRACE(spec.in);
auto splitter = absl::StrSplit(spec.in, ',');
auto it = splitter.begin();
auto end = splitter.end();
for (const auto& expected : spec.expect) {
EXPECT_NE(it, end);
EXPECT_EQ(expected, *it++);
}
EXPECT_EQ(it, end);
}
}
TEST(Splitter, Const) {
const auto splitter = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(splitter, ElementsAre("a", "b", "c"));
}
TEST(Split, EmptyAndNull) {
EXPECT_THAT(absl::StrSplit(absl::string_view(""), '-'), ElementsAre(""));
EXPECT_THAT(absl::StrSplit(absl::string_view(), '-'), ElementsAre());
}
TEST(SplitIterator, EqualityAsEndCondition) {
auto splitter = absl::StrSplit("a,b,c", ',');
auto it = splitter.begin();
auto it2 = it;
++it2;
++it2;
EXPECT_EQ("c", *it2);
std::vector<absl::string_view> v;
for (; it != it2; ++it) {
v.push_back(*it);
}
EXPECT_THAT(v, ElementsAre("a", "b"));
}
TEST(Splitter, RangeIterators) {
auto splitter = absl::StrSplit("a,b,c", ',');
std::vector<absl::string_view> output;
for (absl::string_view p : splitter) {
output.push_back(p);
}
EXPECT_THAT(output, ElementsAre("a", "b", "c"));
}
template <typename ContainerType, typename Splitter>
void TestConversionOperator(const Splitter& splitter) {
ContainerType output = splitter;
EXPECT_THAT(output, UnorderedElementsAre("a", "b", "c", "d"));
}
template <typename MapType, typename Splitter>
void TestMapConversionOperator(const Splitter& splitter) {
MapType m = splitter;
EXPECT_THAT(m, UnorderedElementsAre(Pair("a", "b"), Pair("c", "d")));
}
template <typename FirstType, typename SecondType, typename Splitter>
void TestPairConversionOperator(const Splitter& splitter) {
std::pair<FirstType, SecondType> p = splitter;
EXPECT_EQ(p, (std::pair<FirstType, SecondType>("a", "b")));
}
TEST(Splitter, ConversionOperator) {
auto splitter = absl::StrSplit("a,b,c,d", ',');
TestConversionOperator<std::vector<absl::string_view>>(splitter);
TestConversionOperator<std::vector<std::string>>(splitter);
TestConversionOperator<std::list<absl::string_view>>(splitter);
TestConversionOperator<std::list<std::string>>(splitter);
TestConversionOperator<std::deque<absl::string_view>>(splitter);
TestConversionOperator<std::deque<std::string>>(splitter);
TestConversionOperator<std::set<absl::string_view>>(splitter);
TestConversionOperator<std::set<std::string>>(splitter);
TestConversionOperator<std::multiset<absl::string_view>>(splitter);
TestConversionOperator<std::multiset<std::string>>(splitter);
TestConversionOperator<absl::btree_set<absl::string_view>>(splitter);
TestConversionOperator<absl::btree_set<std::string>>(splitter);
TestConversionOperator<absl::btree_multiset<absl::string_view>>(splitter);
TestConversionOperator<absl::btree_multiset<std::string>>(splitter);
TestConversionOperator<std::unordered_set<std::string>>(splitter);
TestMapConversionOperator<std::map<absl::string_view, absl::string_view>>(
splitter);
TestMapConversionOperator<std::map<absl::string_view, std::string>>(splitter);
TestMapConversionOperator<std::map<std::string, absl::string_view>>(splitter);
TestMapConversionOperator<std::map<std::string, std::string>>(splitter);
TestMapConversionOperator<
std::multimap<absl::string_view, absl::string_view>>(splitter);
TestMapConversionOperator<std::multimap<absl::string_view, std::string>>(
splitter);
TestMapConversionOperator<std::multimap<std::string, absl::string_view>>(
splitter);
TestMapConversionOperator<std::multimap<std::string, std::string>>(splitter);
TestMapConversionOperator<
absl::btree_map<absl::string_view, absl::string_view>>(splitter);
TestMapConversionOperator<absl::btree_map<absl::string_view, std::string>>(
splitter);
TestMapConversionOperator<absl::btree_map<std::string, absl::string_view>>(
splitter);
TestMapConversionOperator<absl::btree_map<std::string, std::string>>(
splitter);
TestMapConversionOperator<
absl::btree_multimap<absl::string_view, absl::string_view>>(splitter);
TestMapConversionOperator<
absl::btree_multimap<absl::string_view, std::string>>(splitter);
TestMapConversionOperator<
absl::btree_multimap<std::string, absl::string_view>>(splitter);
TestMapConversionOperator<absl::btree_multimap<std::string, std::string>>(
splitter);
TestMapConversionOperator<std::unordered_map<std::string, std::string>>(
splitter);
TestMapConversionOperator<
absl::node_hash_map<absl::string_view, absl::string_view>>(splitter);
TestMapConversionOperator<
absl::node_hash_map<absl::string_view, std::string>>(splitter);
TestMapConversionOperator<
absl::node_hash_map<std::string, absl::string_view>>(splitter);
TestMapConversionOperator<
absl::flat_hash_map<absl::string_view, absl::string_view>>(splitter);
TestMapConversionOperator<
absl::flat_hash_map<absl::string_view, std::string>>(splitter);
TestMapConversionOperator<
absl::flat_hash_map<std::string, absl::string_view>>(splitter);
TestPairConversionOperator<absl::string_view, absl::string_view>(splitter);
TestPairConversionOperator<absl::string_view, std::string>(splitter);
TestPairConversionOperator<std::string, absl::string_view>(splitter);
TestPairConversionOperator<std::string, std::string>(splitter);
}
TEST(Splitter, ToPair) {
{
std::pair<std::string, std::string> p = absl::StrSplit("", ',');
EXPECT_EQ("", p.first);
EXPECT_EQ("", p.second);
}
{
std::pair<std::string, std::string> p = absl::StrSplit("a", ',');
EXPECT_EQ("a", p.first);
EXPECT_EQ("", p.second);
}
{
std::pair<std::string, std::string> p = absl::StrSplit(",b", ',');
EXPECT_EQ("", p.first);
EXPECT_EQ("b", p.second);
}
{
std::pair<std::string, std::string> p = absl::StrSplit("a,b", ',');
EXPECT_EQ("a", p.first);
EXPECT_EQ("b", p.second);
}
{
std::pair<std::string, std::string> p = absl::StrSplit("a,b,c", ',');
EXPECT_EQ("a", p.first);
EXPECT_EQ("b", p.second);
}
}
TEST(Splitter, Predicates) {
static const char kTestChars[] = ",a, ,b,";
using absl::AllowEmpty;
using absl::SkipEmpty;
using absl::SkipWhitespace;
{
auto splitter = absl::StrSplit(kTestChars, ',');
std::vector<std::string> v = splitter;
EXPECT_THAT(v, ElementsAre("", "a", " ", "b", ""));
}
{
auto splitter = absl::StrSplit(kTestChars, ',', AllowEmpty());
std::vector<std::string> v_allowempty = splitter;
EXPECT_THAT(v_allowempty, ElementsAre("", "a", " ", "b", ""));
auto splitter_nopredicate = absl::StrSplit(kTestChars, ',');
std::vector<std::string> v_nopredicate = splitter_nopredicate;
EXPECT_EQ(v_allowempty, v_nopredicate);
}
{
auto splitter = absl::StrSplit(kTestChars, ',', SkipEmpty());
std::vector<std::string> v = splitter;
EXPECT_THAT(v, ElementsAre("a", " ", "b"));
}
{
auto splitter = absl::StrSplit(kTestChars, ',', SkipWhitespace());
std::vector<std::string> v = splitter;
EXPECT_THAT(v, ElementsAre("a", "b"));
}
}
TEST(Split, Basics) {
{
absl::StrSplit("a,b,c", ',');
}
{
std::vector<absl::string_view> v = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
std::vector<std::string> v = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
}
{
std::vector<std::string> v;
v = absl::StrSplit("a,b,c", ',');
EXPECT_THAT(v, ElementsAre("a", "b", "c"));
std::map<std::string, std::string> m;
m = absl::StrSplit("a,b,c", ',');
EXPECT_EQ(2, m.size());
std::unordered_map<std::string, std::string> hm;
hm = absl::StrSplit("a,b,c", ',');
EXPECT_EQ(2, hm.size());
}
}
absl::string_view ReturnStringView() { return "Hello World"; }
const char* ReturnConstCharP() { return "Hello World"; }
char* ReturnCharP() { return const_cast<char*>("Hello World"); }
TEST(Split, AcceptsCertainTemporaries) {
std::vector<std::string> v;
v = absl::StrSplit(ReturnStringView(), ' ');
EXPECT_THAT(v, ElementsAre("Hello", "World"));
v = absl::StrSplit(ReturnConstCharP(), ' ');
EXPECT_THAT(v, ElementsAre("Hello", "World"));
v = absl::StrSplit(ReturnCharP(), ' ');
EXPECT_THAT(v, ElementsAre("Hello", "World"));
}
TEST(Split, Temporary) {
const char input[] = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u";
EXPECT_LT(sizeof(std::string), ABSL_ARRAYSIZE(input))
<< "Input should be larger than fits on the stack.";
auto splitter = absl::StrSplit(std::string(input), ',');
std::string expected = "a";
for (absl::string_view letter : splitter) {
EXPECT_EQ(expected, letter);
++expected[0];
}
EXPECT_EQ("v", expected);
auto std_splitter = absl::StrSplit(std::string(input), ',');
expected = "a";
for (absl::string_view letter : std_splitter) {
EXPECT_EQ(expected, letter);
++expected[0];
}
EXPECT_EQ("v", expected);
}
template <typename T>
static std::unique_ptr<T> CopyToHeap(const T& value) {
return std::unique_ptr<T>(new T(value));
}
TEST(Split, LvalueCaptureIsCopyable) {
std::string input = "a,b";
auto heap_splitter = CopyToHeap(absl::StrSplit(input, ','));
auto stack_splitter = *heap_splitter;
heap_splitter.reset();
std::vector<std::string> result = stack_splitter;
EXPECT_THAT(result, testing::ElementsAre("a", "b"));
}
TEST(Split, TemporaryCaptureIsCopyable) {
auto heap_splitter = CopyToHeap(absl::StrSplit(std::string("a,b"), ','));
auto stack_splitter = *heap_splitter;
heap_splitter.reset();
std::vector<std::string> result = stack_splitter;
EXPECT_THAT(result, testing::ElementsAre("a", "b"));
}
TEST(Split, SplitterIsCopyableAndMoveable) {
auto a = absl::StrSplit("foo", '-');
auto b = a;
auto c = std::move(a);
b = c;
c = std::move(b);
EXPECT_THAT(c, ElementsAre("foo"));
}
TEST(Split, StringDelimiter) {
{
std::vector<absl::string_view> v = absl::StrSplit("a,b", ',');
EXPECT_THAT(v, ElementsAre("a", "b"));
}
{
std::vector<absl::string_view> v = absl::StrSplit("a,b", std::string(","));
EXPECT_THAT(v, ElementsAre("a", "b"));
}
{
std::vector<absl::string_view> v =
absl::StrSplit("a,b", absl::string_view(","));
EXPECT_THAT(v, ElementsAre("a", "b"));
}
}
#if !defined(__cpp_char8_t)
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++2a-compat"
#endif
TEST(Split, UTF8) {
std::string utf8_string = u8"\u03BA\u1F79\u03C3\u03BC\u03B5";
{
std::string to_split = "a," + utf8_string;
std::vector<absl::string_view> v = absl::StrSplit(to_split, ',');
EXPECT_THAT(v, ElementsAre("a", utf8_string));
}
{
std::string to_split = "a," + utf8_string + ",b";
std::string unicode_delimiter = "," + utf8_string + ",";
std::vector<absl::string_view> v =
absl::StrSplit(to_split, unicode_delimiter);
EXPECT_THAT(v, ElementsAre("a", "b"));
}
{
std::vector<absl::string_view> v =
absl::StrSplit(u8"Foo h\u00E4llo th\u4E1Ere", absl::ByAnyChar(" \t"));
EXPECT_THAT(v, ElementsAre("Foo", u8"h\u00E4llo", u8"th\u4E1Ere"));
}
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif
TEST(Split, EmptyStringDelimiter) {
{
std::vector<std::string> v = absl::StrSplit("", "");
EXPECT_THAT(v, ElementsAre(""));
}
{
std::vector<std::string> v = absl::StrSplit("a", "");
EXPECT_THAT(v, ElementsAre("a"));
}
{
std::vector<std::string> v = absl::StrSplit("ab", "");
EXPECT_THAT(v, ElementsAre("a", "b"));
}
{
std::vector<std::string> v = absl::StrSplit("a b", "");
EXPECT_THAT(v, ElementsAre("a", " ", "b"));
}
}
TEST(Split, SubstrDelimiter) {
std::vector<absl::string_view> results;
absl::string_view delim("
results = absl::StrSplit("", delim);
EXPECT_THAT(results, ElementsAre(""));
results = absl::StrSplit("
EXPECT_THAT(results, ElementsAre("", ""));
results = absl::StrSplit("ab", delim);
EXPECT_THAT(results, ElementsAre("ab"));
results = absl::StrSplit("ab
EXPECT_THAT(results, ElementsAre("ab", ""));
results = absl::StrSplit("ab/", delim);
EXPECT_THAT(results, ElementsAre("ab/"));
results = absl::StrSplit("a/b", delim);
EXPECT_THAT(results, ElementsAre("a/b"));
results = absl::StrSplit("a
EXPECT_THAT(results, ElementsAre("a", "b"));
results = absl::StrSplit("a
EXPECT_THAT(results, ElementsAre("a", "/b"));
results = absl::StrSplit("a
EXPECT_THAT(results, ElementsAre("a", "", "b"));
}
TEST(Split, EmptyResults) {
std::vector<absl::string_view> results;
results = absl::StrSplit("", '#');
EXPECT_THAT(results, ElementsAre(""));
results = absl::StrSplit("#", '#');
EXPECT_THAT(results, ElementsAre("", ""));
results = absl::StrSplit("#cd", '#');
EXPECT_THAT(results, ElementsAre("", "cd"));
results = absl::StrSplit("ab#cd#", '#');
EXPECT_THAT(results, ElementsAre("ab", "cd", ""));
results = absl::StrSplit("ab##cd", '#');
EXPECT_THAT(results, ElementsAre("ab", "", "cd"));
results = absl::StrSplit("ab##", '#');
EXPECT_THAT(results, ElementsAre("ab", "", ""));
results = absl::StrSplit("ab#ab#", '#');
EXPECT_THAT(results, ElementsAre("ab", "ab", ""));
results = absl::StrSplit("aaaa", 'a');
EXPECT_THAT(results, ElementsAre("", "", "", "", ""));
results = absl::StrSplit("", '#', absl::SkipEmpty());
EXPECT_THAT(results, ElementsAre());
}
template <typename Delimiter>
static bool IsFoundAtStartingPos(absl::string_view text, Delimiter d,
size_t starting_pos, int expected_pos) {
absl::string_view found = d.Find(text, starting_pos);
return found.data() != text.data() + text.size() &&
expected_pos == found.data() - text.data();
}
template <typename Delimiter>
static bool IsFoundAt(absl::string_view text, Delimiter d, int expected_pos) {
const std::string leading_text = ",x,y,z,";
return IsFoundAtStartingPos(text, d, 0, expected_pos) &&
IsFoundAtStartingPos(leading_text + std::string(text), d,
leading_text.length(),
expected_pos + leading_text.length());
}
template <typename Delimiter>
void TestComma(Delimiter d) {
EXPECT_TRUE(IsFoundAt(",", d, 0));
EXPECT_TRUE(IsFoundAt("a,", d, 1));
EXPECT_TRUE(IsFoundAt(",b", d, 0));
EXPECT_TRUE(IsFoundAt("a,b", d, 1));
EXPECT_TRUE(IsFoundAt("a,b,", d, 1));
EXPECT_TRUE(IsFoundAt("a,b,c", d, 1));
EXPECT_FALSE(IsFoundAt("", d, -1));
EXPECT_FALSE(IsFoundAt(" ", d, -1));
EXPECT_FALSE(IsFoundAt("a", d, -1));
EXPECT_FALSE(IsFoundAt("a b c", d, -1));
EXPECT_FALSE(IsFoundAt("a;b;c", d, -1));
EXPECT_FALSE(IsFoundAt(";", d, -1));
}
TEST(Delimiter, ByString) {
using absl::ByString;
TestComma(ByString(","));
ByString comma_string(",");
TestComma(comma_string);
absl::string_view abc("abc");
EXPECT_EQ(0, abc.find(""));
ByString empty("");
EXPECT_FALSE(IsFoundAt("", empty, 0));
EXPECT_FALSE(IsFoundAt("a", empty, 0));
EXPECT_TRUE(IsFoundAt("ab", empty, 1));
EXPECT_TRUE(IsFoundAt("abc", empty, 1));
}
TEST(Split, ByChar) {
using absl::ByChar;
TestComma(ByChar(','));
ByChar comma_char(',');
TestComma(comma_char);
}
TEST(Delimiter, ByAnyChar) {
using absl::ByAnyChar;
ByAnyChar one_delim(",");
EXPECT_TRUE(IsFoundAt(",", one_delim, 0));
EXPECT_TRUE(IsFoundAt("a,", one_delim, 1));
EXPECT_TRUE(IsFoundAt("a,b", one_delim, 1));
EXPECT_TRUE(IsFoundAt(",b", one_delim, 0));
EXPECT_FALSE(IsFoundAt("", one_delim, -1));
EXPECT_FALSE(IsFoundAt(" ", one_delim, -1));
EXPECT_FALSE(IsFoundAt("a", one_delim, -1));
EXPECT_FALSE(IsFoundAt("a;b;c", one_delim, -1));
EXPECT_FALSE(IsFoundAt(";", one_delim, -1));
ByAnyChar two_delims(",;");
EXPECT_TRUE(IsFoundAt(",", two_delims, 0));
EXPECT_TRUE(IsFoundAt(";", two_delims, 0));
EXPECT_TRUE(IsFoundAt(",;", two_delims, 0));
EXPECT_TRUE(IsFoundAt(";,", two_delims, 0));
EXPECT_TRUE(IsFoundAt(",;b", two_delims, 0));
EXPECT_TRUE(IsFoundAt(";,b", two_delims, 0));
EXPECT_TRUE(IsFoundAt("a;,", two_delims, 1));
EXPECT_TRUE(IsFoundAt("a,;", two_delims, 1));
EXPECT_TRUE(IsFoundAt("a;,b", two_delims, 1));
EXPECT_TRUE(IsFoundAt("a,;b", two_delims, 1));
EXPECT_FALSE(IsFoundAt("", two_delims, -1));
EXPECT_FALSE(IsFoundAt(" ", two_delims, -1));
EXPECT_FALSE(IsFoundAt("a", two_delims, -1));
EXPECT_FALSE(IsFoundAt("a=b=c", two_delims, -1));
EXPECT_FALSE(IsFoundAt("=", two_delims, -1));
ByAnyChar empty("");
EXPECT_FALSE(IsFoundAt("", empty, 0));
EXPECT_FALSE(IsFoundAt("a", empty, 0));
EXPECT_TRUE(IsFoundAt("ab", empty, 1));
EXPECT_TRUE(IsFoundAt("abc", empty, 1));
}
TEST(Split, ByAsciiWhitespace) {
using absl::ByAsciiWhitespace;
using absl::SkipEmpty;
std::vector<absl::string_view> results;
results = absl::StrSplit("aaaa\n", ByAsciiWhitespace());
EXPECT_THAT(results, ElementsAre("aaaa", ""));
results = absl::StrSplit("aaaa\n", ByAsciiWhitespace(), SkipEmpty());
EXPECT_THAT(results, ElementsAre("aaaa"));
results = absl::StrSplit(" ", ByAsciiWhitespace());
EXPECT_THAT(results, ElementsAre("", ""));
results = absl::StrSplit(" ", ByAsciiWhitespace(), SkipEmpty());
EXPECT_THAT(results, IsEmpty());
results = absl::StrSplit("a", ByAsciiWhitespace());
EXPECT_THAT(results, ElementsAre("a"));
results = absl::StrSplit("", ByAsciiWhitespace());
EXPECT_THAT(results, ElementsAre(""));
results = absl::StrSplit("", ByAsciiWhitespace(), SkipEmpty());
EXPECT_THAT(results, IsEmpty());
results = absl::StrSplit("a b\tc\n d\n", ByAsciiWhitespace());
EXPECT_THAT(results, ElementsAre("a", "b", "c", "", "", "d", ""));
results = absl::StrSplit("a b\tc\n d \n", ByAsciiWhitespace(), SkipEmpty());
EXPECT_THAT(results, ElementsAre("a", "b", "c", "d"));
results = absl::StrSplit("a\t\n\v\f\r b", ByAsciiWhitespace(), SkipEmpty());
EXPECT_THAT(results, ElementsAre("a", "b"));
}
TEST(Delimiter, ByLength) {
using absl::ByLength;
ByLength four_char_delim(4);
EXPECT_TRUE(IsFoundAt("abcde", four_char_delim, 4));
EXPECT_TRUE(IsFoundAt("abcdefghijklmnopqrstuvwxyz", four_char_delim, 4));
EXPECT_TRUE(IsFoundAt("a b,c\nd", four_char_delim, 4));
EXPECT_FALSE(IsFoundAt("", four_char_delim, 0));
EXPECT_FALSE(IsFoundAt("a", four_char_delim, 0));
EXPECT_FALSE(IsFoundAt("ab", four_char_delim, 0));
EXPECT_FALSE(IsFoundAt("abc", four_char_delim, 0));
EXPECT_FALSE(IsFoundAt("abcd", four_char_delim, 0));
}
TEST(Split, WorksWithLargeStrings) {
#if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
defined(ABSL_HAVE_MEMORY_SANITIZE |
2,550 | cpp | abseil/abseil-cpp | numbers | absl/strings/numbers.cc | absl/strings/numbers_test.cc | #ifndef ABSL_STRINGS_NUMBERS_H_
#define ABSL_STRINGS_NUMBERS_H_
#ifdef __SSSE3__
#include <tmmintrin.h>
#endif
#ifdef _MSC_VER
#include <intrin.h>
#endif
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <limits>
#include <string>
#include <type_traits>
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/macros.h"
#include "absl/base/nullability.h"
#include "absl/base/port.h"
#include "absl/numeric/bits.h"
#include "absl/numeric/int128.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
template <typename int_type>
ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str,
absl::Nonnull<int_type*> out);
ABSL_MUST_USE_RESULT bool SimpleAtof(absl::string_view str,
absl::Nonnull<float*> out);
ABSL_MUST_USE_RESULT bool SimpleAtod(absl::string_view str,
absl::Nonnull<double*> out);
ABSL_MUST_USE_RESULT bool SimpleAtob(absl::string_view str,
absl::Nonnull<bool*> out);
template <typename int_type>
ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str,
absl::Nonnull<int_type*> out);
ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
absl::string_view str, absl::Nonnull<absl::int128*> out);
ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
absl::string_view str, absl::Nonnull<absl::uint128*> out);
ABSL_NAMESPACE_END
}
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace numbers_internal {
ABSL_DLL extern const char kHexChar[17];
ABSL_DLL extern const char
kHexTable[513];
void PutTwoDigits(uint32_t i, absl::Nonnull<char*> buf);
bool safe_strto32_base(absl::string_view text, absl::Nonnull<int32_t*> value,
int base);
bool safe_strto64_base(absl::string_view text, absl::Nonnull<int64_t*> value,
int base);
bool safe_strto128_base(absl::string_view text,
absl::Nonnull<absl::int128*> value, int base);
bool safe_strtou32_base(absl::string_view text, absl::Nonnull<uint32_t*> value,
int base);
bool safe_strtou64_base(absl::string_view text, absl::Nonnull<uint64_t*> value,
int base);
bool safe_strtou128_base(absl::string_view text,
absl::Nonnull<absl::uint128*> value, int base);
static const int kFastToBufferSize = 32;
static const int kSixDigitsToBufferSize = 16;
size_t SixDigitsToBuffer(double d, absl::Nonnull<char*> buffer);
absl::Nonnull<char*> FastIntToBuffer(int32_t i, absl::Nonnull<char*> buffer)
ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize);
absl::Nonnull<char*> FastIntToBuffer(uint32_t n, absl::Nonnull<char*> out_str)
ABSL_INTERNAL_NEED_MIN_SIZE(out_str, kFastToBufferSize);
absl::Nonnull<char*> FastIntToBuffer(int64_t i, absl::Nonnull<char*> buffer)
ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize);
absl::Nonnull<char*> FastIntToBuffer(uint64_t i, absl::Nonnull<char*> buffer)
ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize);
template <typename int_type>
absl::Nonnull<char*> FastIntToBuffer(int_type i, absl::Nonnull<char*> buffer)
ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize) {
static_assert(sizeof(i) <= 64 / 8,
"FastIntToBuffer works only with 64-bit-or-less integers.");
constexpr bool kIsSigned = static_cast<int_type>(1) - 2 < 0;
constexpr bool kUse64Bit = sizeof(i) > 32 / 8;
if (kIsSigned) {
if (kUse64Bit) {
return FastIntToBuffer(static_cast<int64_t>(i), buffer);
} else {
return FastIntToBuffer(static_cast<int32_t>(i), buffer);
}
} else {
if (kUse64Bit) {
return FastIntToBuffer(static_cast<uint64_t>(i), buffer);
} else {
return FastIntToBuffer(static_cast<uint32_t>(i), buffer);
}
}
}
template <typename int_type>
ABSL_MUST_USE_RESULT bool safe_strtoi_base(absl::string_view s,
absl::Nonnull<int_type*> out,
int base) {
static_assert(sizeof(*out) == 4 || sizeof(*out) == 8,
"SimpleAtoi works only with 32-bit or 64-bit integers.");
static_assert(!std::is_floating_point<int_type>::value,
"Use SimpleAtof or SimpleAtod instead.");
bool parsed;
constexpr bool kIsSigned = static_cast<int_type>(1) - 2 < 0;
constexpr bool kUse64Bit = sizeof(*out) == 64 / 8;
if (kIsSigned) {
if (kUse64Bit) {
int64_t val;
parsed = numbers_internal::safe_strto64_base(s, &val, base);
*out = static_cast<int_type>(val);
} else {
int32_t val;
parsed = numbers_internal::safe_strto32_base(s, &val, base);
*out = static_cast<int_type>(val);
}
} else {
if (kUse64Bit) {
uint64_t val;
parsed = numbers_internal::safe_strtou64_base(s, &val, base);
*out = static_cast<int_type>(val);
} else {
uint32_t val;
parsed = numbers_internal::safe_strtou32_base(s, &val, base);
*out = static_cast<int_type>(val);
}
}
return parsed;
}
inline size_t FastHexToBufferZeroPad16(uint64_t val, absl::Nonnull<char*> out) {
#ifdef ABSL_INTERNAL_HAVE_SSSE3
uint64_t be = absl::big_endian::FromHost64(val);
const auto kNibbleMask = _mm_set1_epi8(0xf);
const auto kHexDigits = _mm_setr_epi8('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
auto v = _mm_loadl_epi64(reinterpret_cast<__m128i*>(&be));
auto v4 = _mm_srli_epi64(v, 4);
auto il = _mm_unpacklo_epi8(v4, v);
auto m = _mm_and_si128(il, kNibbleMask);
auto hexchars = _mm_shuffle_epi8(kHexDigits, m);
_mm_storeu_si128(reinterpret_cast<__m128i*>(out), hexchars);
#else
for (int i = 0; i < 8; ++i) {
auto byte = (val >> (56 - 8 * i)) & 0xFF;
auto* hex = &absl::numbers_internal::kHexTable[byte * 2];
std::memcpy(out + 2 * i, hex, 2);
}
#endif
return 16 - static_cast<size_t>(countl_zero(val | 0x1) / 4);
}
}
template <typename int_type>
ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str,
absl::Nonnull<int_type*> out) {
return numbers_internal::safe_strtoi_base(str, out, 10);
}
ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str,
absl::Nonnull<absl::int128*> out) {
return numbers_internal::safe_strto128_base(str, out, 10);
}
ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str,
absl::Nonnull<absl::uint128*> out) {
return numbers_internal::safe_strtou128_base(str, out, 10);
}
template <typename int_type>
ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str,
absl::Nonnull<int_type*> out) {
return numbers_internal::safe_strtoi_base(str, out, 16);
}
ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
absl::string_view str, absl::Nonnull<absl::int128*> out) {
return numbers_internal::safe_strto128_base(str, out, 16);
}
ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
absl::string_view str, absl::Nonnull<absl::uint128*> out) {
return numbers_internal::safe_strtou128_base(str, out, 16);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/numbers.h"
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <limits>
#include <system_error>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
#include "absl/numeric/bits.h"
#include "absl/numeric/int128.h"
#include "absl/strings/ascii.h"
#include "absl/strings/charconv.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
bool SimpleAtof(absl::string_view str, absl::Nonnull<float*> out) {
*out = 0.0;
str = StripAsciiWhitespace(str);
if (!str.empty() && str[0] == '+') {
str.remove_prefix(1);
if (!str.empty() && str[0] == '-') {
return false;
}
}
auto result = absl::from_chars(str.data(), str.data() + str.size(), *out);
if (result.ec == std::errc::invalid_argument) {
return false;
}
if (result.ptr != str.data() + str.size()) {
return false;
}
if (result.ec == std::errc::result_out_of_range) {
if (*out > 1.0) {
*out = std::numeric_limits<float>::infinity();
} else if (*out < -1.0) {
*out = -std::numeric_limits<float>::infinity();
}
}
return true;
}
bool SimpleAtod(absl::string_view str, absl::Nonnull<double*> out) {
*out = 0.0;
str = StripAsciiWhitespace(str);
if (!str.empty() && str[0] == '+') {
str.remove_prefix(1);
if (!str.empty() && str[0] == '-') {
return false;
}
}
auto result = absl::from_chars(str.data(), str.data() + str.size(), *out);
if (result.ec == std::errc::invalid_argument) {
return false;
}
if (result.ptr != str.data() + str.size()) {
return false;
}
if (result.ec == std::errc::result_out_of_range) {
if (*out > 1.0) {
*out = std::numeric_limits<double>::infinity();
} else if (*out < -1.0) {
*out = -std::numeric_limits<double>::infinity();
}
}
return true;
}
bool SimpleAtob(absl::string_view str, absl::Nonnull<bool*> out) {
ABSL_RAW_CHECK(out != nullptr, "Output pointer must not be nullptr.");
if (EqualsIgnoreCase(str, "true") || EqualsIgnoreCase(str, "t") ||
EqualsIgnoreCase(str, "yes") || EqualsIgnoreCase(str, "y") ||
EqualsIgnoreCase(str, "1")) {
*out = true;
return true;
}
if (EqualsIgnoreCase(str, "false") || EqualsIgnoreCase(str, "f") ||
EqualsIgnoreCase(str, "no") || EqualsIgnoreCase(str, "n") ||
EqualsIgnoreCase(str, "0")) {
*out = false;
return true;
}
return false;
}
namespace {
constexpr uint32_t kTwoZeroBytes = 0x0101 * '0';
constexpr uint64_t kFourZeroBytes = 0x01010101 * '0';
constexpr uint64_t kEightZeroBytes = 0x0101010101010101ull * '0';
constexpr uint64_t kDivisionBy10Mul = 103u;
constexpr uint64_t kDivisionBy10Div = 1 << 10;
constexpr uint64_t kDivisionBy100Mul = 10486u;
constexpr uint64_t kDivisionBy100Div = 1 << 20;
inline char* EncodeHundred(uint32_t n, absl::Nonnull<char*> out_str) {
int num_digits = static_cast<int>(n - 10) >> 8;
uint32_t div10 = (n * kDivisionBy10Mul) / kDivisionBy10Div;
uint32_t mod10 = n - 10u * div10;
uint32_t base = kTwoZeroBytes + div10 + (mod10 << 8);
base >>= num_digits & 8;
little_endian::Store16(out_str, static_cast<uint16_t>(base));
return out_str + 2 + num_digits;
}
inline char* EncodeTenThousand(uint32_t n, absl::Nonnull<char*> out_str) {
uint32_t div100 = (n * kDivisionBy100Mul) / kDivisionBy100Div;
uint32_t mod100 = n - 100ull * div100;
uint32_t hundreds = (mod100 << 16) + div100;
uint32_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div;
tens &= (0xFull << 16) | 0xFull;
tens += (hundreds - 10ull * tens) << 8;
ABSL_ASSUME(tens != 0);
uint32_t zeroes = static_cast<uint32_t>(absl::countr_zero(tens)) & (0 - 8u);
tens += kFourZeroBytes;
tens >>= zeroes;
little_endian::Store32(out_str, tens);
return out_str + sizeof(tens) - zeroes / 8;
}
inline uint64_t PrepareEightDigits(uint32_t i) {
ABSL_ASSUME(i < 10000'0000);
uint32_t hi = i / 10000;
uint32_t lo = i % 10000;
uint64_t merged = hi | (uint64_t{lo} << 32);
uint64_t div100 = ((merged * kDivisionBy100Mul) / kDivisionBy100Div) &
((0x7Full << 32) | 0x7Full);
uint64_t mod100 = merged - 100ull * div100;
uint64_t hundreds = (mod100 << 16) + div100;
uint64_t tens = (hundreds * kDivisionBy10Mul) / kDivisionBy10Div;
tens &= (0xFull << 48) | (0xFull << 32) | (0xFull << 16) | 0xFull;
tens += (hundreds - 10ull * tens) << 8;
return tens;
}
inline ABSL_ATTRIBUTE_ALWAYS_INLINE absl::Nonnull<char*> EncodeFullU32(
uint32_t n, absl::Nonnull<char*> out_str) {
if (n < 10) {
*out_str = static_cast<char>('0' + n);
return out_str + 1;
}
if (n < 100'000'000) {
uint64_t bottom = PrepareEightDigits(n);
ABSL_ASSUME(bottom != 0);
uint32_t zeroes =
static_cast<uint32_t>(absl::countr_zero(bottom)) & (0 - 8u);
little_endian::Store64(out_str, (bottom + kEightZeroBytes) >> zeroes);
return out_str + sizeof(bottom) - zeroes / 8;
}
uint32_t div08 = n / 100'000'000;
uint32_t mod08 = n % 100'000'000;
uint64_t bottom = PrepareEightDigits(mod08) + kEightZeroBytes;
out_str = EncodeHundred(div08, out_str);
little_endian::Store64(out_str, bottom);
return out_str + sizeof(bottom);
}
inline ABSL_ATTRIBUTE_ALWAYS_INLINE char* EncodeFullU64(uint64_t i,
char* buffer) {
if (i <= std::numeric_limits<uint32_t>::max()) {
return EncodeFullU32(static_cast<uint32_t>(i), buffer);
}
uint32_t mod08;
if (i < 1'0000'0000'0000'0000ull) {
uint32_t div08 = static_cast<uint32_t>(i / 100'000'000ull);
mod08 = static_cast<uint32_t>(i % 100'000'000ull);
buffer = EncodeFullU32(div08, buffer);
} else {
uint64_t div08 = i / 100'000'000ull;
mod08 = static_cast<uint32_t>(i % 100'000'000ull);
uint32_t div016 = static_cast<uint32_t>(div08 / 100'000'000ull);
uint32_t div08mod08 = static_cast<uint32_t>(div08 % 100'000'000ull);
uint64_t mid_result = PrepareEightDigits(div08mod08) + kEightZeroBytes;
buffer = EncodeTenThousand(div016, buffer);
little_endian::Store64(buffer, mid_result);
buffer += sizeof(mid_result);
}
uint64_t mod_result = PrepareEightDigits(mod08) + kEightZeroBytes;
little_endian::Store64(buffer, mod_result);
return buffer + sizeof(mod_result);
}
}
void numbers_internal::PutTwoDigits(uint32_t i, absl::Nonnull<char*> buf) {
assert(i < 100);
uint32_t base = kTwoZeroBytes;
uint32_t div10 = (i * kDivisionBy10Mul) / kDivisionBy10Div;
uint32_t mod10 = i - 10u * div10;
base += div10 + (mod10 << 8);
little_endian::Store16(buf, static_cast<uint16_t>(base));
}
absl::Nonnull<char*> numbers_internal::FastIntToBuffer(
uint32_t n, absl::Nonnull<char*> out_str) {
out_str = EncodeFullU32(n, out_str);
*out_str = '\0';
return out_str;
}
absl::Nonnull<char*> numbers_internal::FastIntToBuffer(
int32_t i, absl::Nonnull<char*> buffer) {
uint32_t u = static_cast<uint32_t>(i);
if (i < 0) {
*buffer++ = '-';
u = 0 - u;
}
buffer = EncodeFullU32(u, buffer);
*buffer = '\0';
return buffer;
}
absl::Nonnull<char*> numbers_internal::FastIntToBuffer(
uint64_t i, absl::Nonnull<char*> buffer) {
buffer = EncodeFullU64(i, buffer);
*buffer = '\0';
return buffer;
}
absl::Nonnull<char*> numbers_internal::FastIntToBuffer(
int64_t i, absl::Nonnull<char*> buffer) {
uint64_t u = static_cast<uint64_t>(i);
if (i < 0) {
*buffer++ = '-';
u = 0 - u;
}
buffer = EncodeFullU64(u, buffer);
*buffer = '\0';
return buffer;
}
static std::pair<uint64_t, uint64_t> Mul32(std::pair<uint64_t, uint64_t> num,
uint32_t mul) {
uint64_t bits0_31 = num.second & 0xFFFFFFFF;
uint64_t bits32_63 = num.second >> 32;
uint64_t bits64_95 = num.first & 0xFFFFFFFF;
uint64_t bits96_127 = num.first >> 32;
bits0_31 *= mul;
bits32_63 *= mul;
bits64_95 *= mul;
bits96_127 *= mul;
uint64_t bits0_63 = bits0_31 + (bits32_63 << 32);
uint64_t bits64_127 = bits64_95 + (bits96_127 << 32) + (bits32_63 >> 32) +
(bits0_63 < bits0_31);
uint64_t bits128_up = (bits96_127 >> 32) + (bits64_127 < bits64_95);
if (bits128_up == 0) return {bits64_127, bits0_63};
auto shift = static_cast<unsigned>(bit_width(bits128_up));
uint64_t lo = (bits0_63 >> shift) + (bits64_127 << (64 - shift));
uint64_t hi = (bits64_127 >> shift) + (bits128_up << (64 - shift));
return {hi, lo};
}
static std::pair<uint64_t, uint64_t> PowFive(uint64_t num, int expfive) {
std::pair<uint64_t, uint64_t> result = {num, 0};
while (expfive >= 13) {
result = Mul32(result, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5);
expfive -= 13;
}
constexpr uint32_t powers_of_five[13] = {
1,
5,
5 * 5,
5 * 5 * 5,
5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5};
result = Mul32(result, powers_of_five[expfive & 15]);
int shift = countl_zero(result.first);
if (shift != 0) {
result.first = (result.first << shift) + (result.second >> (64 - shift));
result.second = (result.second << shift);
}
return result;
}
struct ExpDigits {
int32_t exponent;
char digits[6];
};
static ExpDigits SplitToSix(const double value) {
ExpDigits exp_dig;
int exp = 5;
double d = value;
if (d >= 999999.5) {
if (d >= 1e+261) exp += 256, d *= 1e-256;
if (d >= 1e+133) exp += 128, d *= 1e-128;
if (d >= 1e+69) exp += 64, d *= 1e-64;
if (d >= 1e+37) exp += 32, d *= 1e-32;
if (d >= 1e+21) exp += 16, d *= 1e-16;
if (d >= 1e+13) exp += 8, d *= 1e-8;
if (d >= 1e+9) exp += 4, d *= 1e-4;
if (d >= 1e+7) exp += 2, d *= 1e-2;
if (d >= 1e+6) exp += 1, d *= 1e-1;
} else {
if (d < 1e-250) exp -= 256, d *= 1e256;
if (d < 1e-122) exp -= 128, d *= 1e128;
if (d < 1e-58) exp -= 64, d *= 1e64;
if (d < 1e-26) exp -= 32, d *= 1e32;
if (d < 1e-10) exp -= 16, d *= 1e16;
if (d < 1e-2) exp -= 8, d *= 1e8;
if (d < 1e+2) exp -= 4, d *= 1e4;
if (d < 1e+4) exp -= 2, d *= 1e2;
if (d < 1e+5) exp -= 1, d *= 1e1;
}
uint64_t d64k = d * 65536;
uint32_t dddddd;
if ((d64k % 65536) == 32767 || (d64k % 65536) == 32768) {
dddddd = static_cast<uint32_t>(d64k / 65536);
int exp2;
double m = std::frexp(value, &exp2);
uint64_t mantissa = m * (32768.0 * 65536.0 * 65536.0 * 65536.0); | #include "absl/strings/numbers.h"
#include <sys/types.h>
#include <cfenv>
#include <cfloat>
#include <cinttypes>
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ios>
#include <limits>
#include <numeric>
#include <random>
#include <set>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/log/log.h"
#include "absl/numeric/int128.h"
#include "absl/random/distributions.h"
#include "absl/random/random.h"
#include "absl/strings/internal/numbers_test_common.h"
#include "absl/strings/internal/ostringstream.h"
#include "absl/strings/internal/pow10_helper.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace {
using absl::SimpleAtoi;
using absl::SimpleHexAtoi;
using absl::numbers_internal::kSixDigitsToBufferSize;
using absl::numbers_internal::safe_strto32_base;
using absl::numbers_internal::safe_strto64_base;
using absl::numbers_internal::safe_strtou32_base;
using absl::numbers_internal::safe_strtou64_base;
using absl::numbers_internal::SixDigitsToBuffer;
using absl::strings_internal::Itoa;
using absl::strings_internal::strtouint32_test_cases;
using absl::strings_internal::strtouint64_test_cases;
using testing::Eq;
using testing::MatchesRegex;
using testing::Pointee;
const int kFloatNumCases = 5000000;
std::string PerfectDtoa(double d) {
if (d == 0) return "0";
if (d < 0) return "-" + PerfectDtoa(-d);
int64_t mantissa, exp = 0;
while (d >= 1ULL << 63) ++exp, d *= 0.5;
while ((mantissa = d) != d) --exp, d *= 2.0;
constexpr int maxlen = 1100;
char buf[maxlen + 5];
for (int64_t num = mantissa, pos = maxlen; --pos >= 0;) {
buf[pos] = '0' + (num % 10);
num /= 10;
}
char* begin = &buf[0];
char* end = buf + maxlen;
for (int i = 0; i != exp; i += (exp > 0) ? 1 : -1) {
int carry = 0;
for (char* p = end; --p != begin;) {
int dig = *p - '0';
dig = dig * (exp > 0 ? 2 : 5) + carry;
carry = dig / 10;
dig %= 10;
*p = '0' + dig;
}
}
if (exp < 0) {
memmove(end + 1 + exp, end + exp, 1 - exp);
end[exp] = '.';
++end;
}
while (*begin == '0' && begin[1] != '.') ++begin;
return {begin, end};
}
TEST(ToString, PerfectDtoa) {
EXPECT_THAT(PerfectDtoa(1), Eq("1"));
EXPECT_THAT(PerfectDtoa(0.1),
Eq("0.1000000000000000055511151231257827021181583404541015625"));
EXPECT_THAT(PerfectDtoa(1e24), Eq("999999999999999983222784"));
EXPECT_THAT(PerfectDtoa(5e-324), MatchesRegex("0.0000.*625"));
for (int i = 0; i < 100; ++i) {
for (double multiplier :
{1e-300, 1e-200, 1e-100, 0.1, 1.0, 10.0, 1e100, 1e300}) {
double d = multiplier * i;
std::string s = PerfectDtoa(d);
EXPECT_DOUBLE_EQ(d, strtod(s.c_str(), nullptr));
}
}
}
template <typename integer>
struct MyInteger {
integer i;
explicit constexpr MyInteger(integer i) : i(i) {}
constexpr operator integer() const { return i; }
constexpr MyInteger operator+(MyInteger other) const { return i + other.i; }
constexpr MyInteger operator-(MyInteger other) const { return i - other.i; }
constexpr MyInteger operator*(MyInteger other) const { return i * other.i; }
constexpr MyInteger operator/(MyInteger other) const { return i / other.i; }
constexpr bool operator<(MyInteger other) const { return i < other.i; }
constexpr bool operator<=(MyInteger other) const { return i <= other.i; }
constexpr bool operator==(MyInteger other) const { return i == other.i; }
constexpr bool operator>=(MyInteger other) const { return i >= other.i; }
constexpr bool operator>(MyInteger other) const { return i > other.i; }
constexpr bool operator!=(MyInteger other) const { return i != other.i; }
integer as_integer() const { return i; }
};
typedef MyInteger<int64_t> MyInt64;
typedef MyInteger<uint64_t> MyUInt64;
void CheckInt32(int32_t x) {
char buffer[absl::numbers_internal::kFastToBufferSize];
char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
std::string expected = std::to_string(x);
EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x;
char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x;
}
void CheckInt64(int64_t x) {
char buffer[absl::numbers_internal::kFastToBufferSize + 3];
buffer[0] = '*';
buffer[23] = '*';
buffer[24] = '*';
char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
std::string expected = std::to_string(x);
EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x;
EXPECT_EQ(buffer[0], '*');
EXPECT_EQ(buffer[23], '*');
EXPECT_EQ(buffer[24], '*');
char* my_actual =
absl::numbers_internal::FastIntToBuffer(MyInt64(x), &buffer[1]);
EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x;
}
void CheckUInt32(uint32_t x) {
char buffer[absl::numbers_internal::kFastToBufferSize];
char* actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
std::string expected = std::to_string(x);
EXPECT_EQ(expected, std::string(buffer, actual)) << " Input " << x;
char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, buffer);
EXPECT_EQ(expected, std::string(buffer, generic_actual)) << " Input " << x;
}
void CheckUInt64(uint64_t x) {
char buffer[absl::numbers_internal::kFastToBufferSize + 1];
char* actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
std::string expected = std::to_string(x);
EXPECT_EQ(expected, std::string(&buffer[1], actual)) << " Input " << x;
char* generic_actual = absl::numbers_internal::FastIntToBuffer(x, &buffer[1]);
EXPECT_EQ(expected, std::string(&buffer[1], generic_actual))
<< " Input " << x;
char* my_actual =
absl::numbers_internal::FastIntToBuffer(MyUInt64(x), &buffer[1]);
EXPECT_EQ(expected, std::string(&buffer[1], my_actual)) << " Input " << x;
}
void CheckHex64(uint64_t v) {
char expected[16 + 1];
std::string actual = absl::StrCat(absl::Hex(v, absl::kZeroPad16));
snprintf(expected, sizeof(expected), "%016" PRIx64, static_cast<uint64_t>(v));
EXPECT_EQ(expected, actual) << " Input " << v;
actual = absl::StrCat(absl::Hex(v, absl::kSpacePad16));
snprintf(expected, sizeof(expected), "%16" PRIx64, static_cast<uint64_t>(v));
EXPECT_EQ(expected, actual) << " Input " << v;
}
TEST(Numbers, TestFastPrints) {
for (int i = -100; i <= 100; i++) {
CheckInt32(i);
CheckInt64(i);
}
for (int i = 0; i <= 100; i++) {
CheckUInt32(i);
CheckUInt64(i);
}
CheckInt32(INT_MIN);
CheckInt32(INT_MAX);
CheckInt64(LONG_MIN);
CheckInt64(uint64_t{1000000000});
CheckInt64(uint64_t{9999999999});
CheckInt64(uint64_t{100000000000000});
CheckInt64(uint64_t{999999999999999});
CheckInt64(uint64_t{1000000000000000000});
CheckInt64(uint64_t{1199999999999999999});
CheckInt64(int64_t{-700000000000000000});
CheckInt64(LONG_MAX);
CheckUInt32(std::numeric_limits<uint32_t>::max());
CheckUInt64(uint64_t{1000000000});
CheckUInt64(uint64_t{9999999999});
CheckUInt64(uint64_t{100000000000000});
CheckUInt64(uint64_t{999999999999999});
CheckUInt64(uint64_t{1000000000000000000});
CheckUInt64(uint64_t{1199999999999999999});
CheckUInt64(std::numeric_limits<uint64_t>::max());
for (int i = 0; i < 10000; i++) {
CheckHex64(i);
}
CheckHex64(uint64_t{0x123456789abcdef0});
}
template <typename int_type, typename in_val_type>
void VerifySimpleAtoiGood(in_val_type in_value, int_type exp_value) {
std::string s;
absl::strings_internal::OStringStream(&s) << in_value;
int_type x = static_cast<int_type>(~exp_value);
EXPECT_TRUE(SimpleAtoi(s, &x))
<< "in_value=" << in_value << " s=" << s << " x=" << x;
EXPECT_EQ(exp_value, x);
x = static_cast<int_type>(~exp_value);
EXPECT_TRUE(SimpleAtoi(s.c_str(), &x));
EXPECT_EQ(exp_value, x);
}
template <typename int_type, typename in_val_type>
void VerifySimpleAtoiBad(in_val_type in_value) {
std::string s;
absl::strings_internal::OStringStream(&s) << in_value;
int_type x;
EXPECT_FALSE(SimpleAtoi(s, &x));
EXPECT_FALSE(SimpleAtoi(s.c_str(), &x));
}
TEST(NumbersTest, Atoi) {
VerifySimpleAtoiGood<int32_t>(0, 0);
VerifySimpleAtoiGood<int32_t>(42, 42);
VerifySimpleAtoiGood<int32_t>(-42, -42);
VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::min());
VerifySimpleAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleAtoiGood<uint32_t>(0, 0);
VerifySimpleAtoiGood<uint32_t>(42, 42);
VerifySimpleAtoiBad<uint32_t>(-42);
VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min());
VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min());
VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max());
VerifySimpleAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max());
VerifySimpleAtoiGood<int64_t>(0, 0);
VerifySimpleAtoiGood<int64_t>(42, 42);
VerifySimpleAtoiGood<int64_t>(-42, -42);
VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::min());
VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::min());
VerifySimpleAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
VerifySimpleAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max());
VerifySimpleAtoiGood<uint64_t>(0, 0);
VerifySimpleAtoiGood<uint64_t>(42, 42);
VerifySimpleAtoiBad<uint64_t>(-42);
VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min());
VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min());
VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
VerifySimpleAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max());
VerifySimpleAtoiGood<absl::uint128>(0, 0);
VerifySimpleAtoiGood<absl::uint128>(42, 42);
VerifySimpleAtoiBad<absl::uint128>(-42);
VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min());
VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min());
VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
VerifySimpleAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max());
VerifySimpleAtoiGood<absl::uint128>(
std::numeric_limits<absl::uint128>::max(),
std::numeric_limits<absl::uint128>::max());
VerifySimpleAtoiGood<absl::int128>(0, 0);
VerifySimpleAtoiGood<absl::int128>(42, 42);
VerifySimpleAtoiGood<absl::int128>(-42, -42);
VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::min());
VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::min());
VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
VerifySimpleAtoiGood<absl::int128>(std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max());
VerifySimpleAtoiGood<absl::int128>(
std::numeric_limits<absl::int128>::min(),
std::numeric_limits<absl::int128>::min());
VerifySimpleAtoiGood<absl::int128>(
std::numeric_limits<absl::int128>::max(),
std::numeric_limits<absl::int128>::max());
VerifySimpleAtoiBad<absl::int128>(std::numeric_limits<absl::uint128>::max());
VerifySimpleAtoiGood<int>(-42, -42);
VerifySimpleAtoiGood<int32_t>(-42, -42);
VerifySimpleAtoiGood<uint32_t>(42, 42);
VerifySimpleAtoiGood<unsigned int>(42, 42);
VerifySimpleAtoiGood<int64_t>(-42, -42);
VerifySimpleAtoiGood<long>(-42, -42);
VerifySimpleAtoiGood<uint64_t>(42, 42);
VerifySimpleAtoiGood<size_t>(42, 42);
VerifySimpleAtoiGood<std::string::size_type>(42, 42);
}
TEST(NumbersTest, Atod) {
#if !defined(DBL_TRUE_MIN)
static constexpr double DBL_TRUE_MIN =
4.940656458412465441765687928682213723650598026143247644255856825e-324;
#endif
#if !defined(FLT_TRUE_MIN)
static constexpr float FLT_TRUE_MIN =
1.401298464324817070923729583289916131280261941876515771757068284e-45f;
#endif
double d;
float f;
EXPECT_TRUE(absl::SimpleAtod("NaN", &d));
EXPECT_TRUE(std::isnan(d));
EXPECT_TRUE(absl::SimpleAtod("nAN", &d));
EXPECT_TRUE(std::isnan(d));
EXPECT_TRUE(absl::SimpleAtod("-nan", &d));
EXPECT_TRUE(std::isnan(d));
EXPECT_TRUE(absl::SimpleAtod("inf", &d));
EXPECT_TRUE(std::isinf(d) && (d > 0));
EXPECT_TRUE(absl::SimpleAtod("+Infinity", &d));
EXPECT_TRUE(std::isinf(d) && (d > 0));
EXPECT_TRUE(absl::SimpleAtod("-INF", &d));
EXPECT_TRUE(std::isinf(d) && (d < 0));
EXPECT_TRUE(absl::SimpleAtod("1.7976931348623157e+308", &d));
EXPECT_EQ(d, 1.7976931348623157e+308);
EXPECT_TRUE(absl::SimpleAtod("5e308", &d));
EXPECT_TRUE(std::isinf(d) && (d > 0));
EXPECT_TRUE(absl::SimpleAtof("3.4028234663852886e+38", &f));
EXPECT_EQ(f, 3.4028234663852886e+38f);
EXPECT_TRUE(absl::SimpleAtof("7e38", &f));
EXPECT_TRUE(std::isinf(f) && (f > 0));
EXPECT_TRUE(absl::SimpleAtod("1e308", &d));
EXPECT_EQ(d, 1e308);
EXPECT_FALSE(std::isinf(d));
EXPECT_TRUE(absl::SimpleAtod("1e309", &d));
EXPECT_TRUE(std::isinf(d));
EXPECT_TRUE(absl::SimpleAtof("1e38", &f));
EXPECT_EQ(f, 1e38f);
EXPECT_FALSE(std::isinf(f));
EXPECT_TRUE(absl::SimpleAtof("1e39", &f));
EXPECT_TRUE(std::isinf(f));
EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e307", &d));
EXPECT_EQ(d, 9.999999999999999999e307);
EXPECT_FALSE(std::isinf(d));
EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e308", &d));
EXPECT_TRUE(std::isinf(d));
EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e37", &f));
EXPECT_EQ(f, 9.999999999999999999e37f);
EXPECT_FALSE(std::isinf(f));
EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e38", &f));
EXPECT_TRUE(std::isinf(f));
EXPECT_TRUE(absl::SimpleAtod("2.2250738585072014e-308", &d));
EXPECT_EQ(d, 2.2250738585072014e-308);
EXPECT_TRUE(absl::SimpleAtod("4.9406564584124654e-324", &d));
EXPECT_EQ(d, 4.9406564584124654e-324);
EXPECT_TRUE(absl::SimpleAtod("4.9406564584124654e-325", &d));
EXPECT_EQ(d, 0);
EXPECT_TRUE(absl::SimpleAtof("1.1754943508222875e-38", &f));
EXPECT_EQ(f, 1.1754943508222875e-38f);
EXPECT_TRUE(absl::SimpleAtof("1.4012984643248171e-45", &f));
EXPECT_EQ(f, 1.4012984643248171e-45f);
EXPECT_TRUE(absl::SimpleAtof("1.4012984643248171e-46", &f));
EXPECT_EQ(f, 0);
EXPECT_TRUE(absl::SimpleAtod("1e-307", &d));
EXPECT_EQ(d, 1e-307);
EXPECT_GE(d, DBL_MIN);
EXPECT_LT(d, DBL_MIN * 10);
EXPECT_TRUE(absl::SimpleAtod("1e-323", &d));
EXPECT_EQ(d, 1e-323);
EXPECT_GE(d, DBL_TRUE_MIN);
EXPECT_LT(d, DBL_TRUE_MIN * 10);
EXPECT_TRUE(absl::SimpleAtod("1e-324", &d));
EXPECT_EQ(d, 0);
EXPECT_TRUE(absl::SimpleAtof("1e-37", &f));
EXPECT_EQ(f, 1e-37f);
EXPECT_GE(f, FLT_MIN);
EXPECT_LT(f, FLT_MIN * 10);
EXPECT_TRUE(absl::SimpleAtof("1e-45", &f));
EXPECT_EQ(f, 1e-45f);
EXPECT_GE(f, FLT_TRUE_MIN);
EXPECT_LT(f, FLT_TRUE_MIN * 10);
EXPECT_TRUE(absl::SimpleAtof("1e-46", &f));
EXPECT_EQ(f, 0);
EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-308", &d));
EXPECT_EQ(d, 9.999999999999999999e-308);
EXPECT_GE(d, DBL_MIN);
EXPECT_LT(d, DBL_MIN * 10);
EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-324", &d));
EXPECT_EQ(d, 9.999999999999999999e-324);
EXPECT_GE(d, DBL_TRUE_MIN);
EXPECT_LT(d, DBL_TRUE_MIN * 10);
EXPECT_TRUE(absl::SimpleAtod("9.999999999999999999e-325", &d));
EXPECT_EQ(d, 0);
EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-38", &f));
EXPECT_EQ(f, 9.999999999999999999e-38f);
EXPECT_GE(f, FLT_MIN);
EXPECT_LT(f, FLT_MIN * 10);
EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-46", &f));
EXPECT_EQ(f, 9.999999999999999999e-46f);
EXPECT_GE(f, FLT_TRUE_MIN);
EXPECT_LT(f, FLT_TRUE_MIN * 10);
EXPECT_TRUE(absl::SimpleAtof("9.999999999999999999e-47", &f));
EXPECT_EQ(f, 0);
EXPECT_TRUE(absl::SimpleAtod(" \t\r\n 2.718", &d));
EXPECT_EQ(d, 2.718);
EXPECT_TRUE(absl::SimpleAtod(" 3.141 ", &d));
EXPECT_EQ(d, 3.141);
EXPECT_FALSE(absl::SimpleAtod("n 0", &d));
EXPECT_FALSE(absl::SimpleAtod("0n ", &d));
EXPECT_TRUE(absl::SimpleAtod("000123", &d));
EXPECT_EQ(d, 123);
EXPECT_TRUE(absl::SimpleAtod("000.456", &d));
EXPECT_EQ(d, 0.456);
EXPECT_TRUE(absl::SimpleAtod(".5", &d));
EXPECT_EQ(d, 0.5);
EXPECT_TRUE(absl::SimpleAtod("-.707", &d));
EXPECT_EQ(d, -0.707);
EXPECT_TRUE(absl::SimpleAtod("+6.0221408e+23", &d));
EXPECT_EQ(d, 6.0221408e+23);
EXPECT_FALSE(absl::SimpleAtod("123_456", &d));
EXPECT_TRUE(absl::SimpleAtod("8.9", &d));
EXPECT_FALSE(absl::SimpleAtod("8,9", &d));
EXPECT_TRUE(absl::SimpleAtod("4503599627370497.5", &d));
EXPECT_EQ(d, 4503599627370497.5);
EXPECT_TRUE(absl::SimpleAtod("1e+23", &d));
EXPECT_EQ(d, 1e+23);
EXPECT_TRUE(absl::SimpleAtod("9223372036854775807", &d));
EXPECT_EQ(d, 9223372036854775807);
EXPECT_TRUE(absl::SimpleAtof("0.0625", &f));
EXPECT_EQ(f, 0.0625f);
EXPECT_TRUE(absl::SimpleAtof("20040229.0", &f));
EXPECT_EQ(f, 20040229.0f);
EXPECT_TRUE(absl::SimpleAtof("2147483647.0", &f));
EXPECT_EQ(f, 2147483647.0f);
EXPECT_TRUE(absl::SimpleAtod("122.416294033786585", &d));
EXPECT_EQ(d, 122.416294033786585);
EXPECT_TRUE(absl::SimpleAtof("122.416294033786585", &f));
EXPECT_EQ(f, 122.416294033786585f);
}
TEST(NumbersTest, Prefixes) {
double d;
EXPECT_FALSE(absl::SimpleAtod("++1", &d));
EXPECT_FALSE(absl::SimpleAtod("+-1", &d));
EXPECT_FALSE(absl::SimpleAtod("-+1", &d));
EXPECT_FALSE(absl::SimpleAtod("--1", &d));
EXPECT_TRUE(absl::SimpleAtod("-1", &d));
EXPECT_EQ(d, -1.);
EXPECT_TRUE(absl::SimpleAtod("+1", &d));
EXPECT_EQ(d, +1.);
float f;
EXPECT_FALSE(absl::SimpleAtof("++1", &f));
EXPECT_FALSE(absl::SimpleAtof("+-1", &f));
EXPECT_FALSE(absl::SimpleAtof("-+1", &f));
EXPECT_FALSE(absl::SimpleAtof("--1", &f));
EXPECT_TRUE(absl::SimpleAtof("-1", &f));
EXPECT_EQ(f, -1.f);
EXPECT_TRUE(absl::SimpleAtof("+1", &f));
EXPECT_EQ(f, +1.f);
}
TEST(NumbersTest, Atoenum) {
enum E01 {
E01_zero = 0,
E01_one = 1,
};
VerifySimpleAtoiGood<E01>(E01_zero, E01_zero);
VerifySimpleAtoiGood<E01>(E01_one, E01_one);
enum E_101 {
E_101_minusone = -1,
E_101_zero = 0,
E_101_one = 1,
};
VerifySimpleAtoiGood<E_101>(E_101_minusone, E_101_minusone);
VerifySimpleAtoiGood<E_101>(E_101_zero, E_101_zero);
VerifySimpleAtoiGood<E_101>(E_101_one, E_101_one);
enum E_bigint {
E_bigint_zero = 0,
E_bigint_one = 1,
E_bigint_max31 = static_cast<int32_t>(0x7FFFFFFF),
};
VerifySimpleAtoiGood<E_bigint>(E_bigint_zero, E_bigint_zero);
VerifySimpleAtoiGood<E_bigint>(E_bigint_one, E_bigint_one);
VerifySimpleAtoiGood<E_bigint>(E_bigint_max31, E_bigint_max31);
enum E_fullint {
E_fullint_zero = 0,
E_fullint_one = 1,
E_fullint_max31 = static_cast<int32_t>(0x7FFFFFFF),
E_fullint_min32 = INT32_MIN,
};
VerifySimpleAtoiGood<E_fullint>(E_fullint_zero, E_fullint_zero);
VerifySimpleAtoiGood<E_fullint>(E_fullint_one, E_fullint_one);
VerifySimpleAtoiGood<E_fullint>(E_fullint_max31, E_fullint_max31);
VerifySimpleAtoiGood<E_fullint>(E_fullint_min32, E_fullint_min32);
enum E_biguint {
E_biguint_zero = 0,
E_biguint_one = 1,
E_biguint_max31 = static_cast<uint32_t>(0x7FFFFFFF),
E_biguint_max32 = static_cast<uint32_t>(0xFFFFFFFF),
};
VerifySimpleAtoiGood<E_biguint>(E_biguint_zero, E_biguint_zero);
VerifySimpleAtoiGood<E_biguint>(E_biguint_one, E_biguint_one);
VerifySimpleAtoiGood<E_biguint>(E_biguint_max31, E_biguint_max31);
VerifySimpleAtoiGood<E_biguint>(E_biguint_max32, E_biguint_max32);
}
template <typename int_type, typename in_val_type>
void VerifySimpleHexAtoiGood(in_val_type in_value, int_type exp_value) {
std::string s;
absl::strings_internal::OStringStream strm(&s);
if (in_value >= 0) {
strm << std::hex << in_value;
} else {
strm << "-" << std::hex << -absl::uint128(in_value);
}
int_type x = static_cast<int_type>(~exp_value);
EXPECT_TRUE(SimpleHexAtoi(s, &x))
<< "in_value=" << std::hex << in_value << " s=" << s << " x=" << x;
EXPECT_EQ(exp_value, x);
x = static_cast<int_type>(~exp_value);
EXPECT_TRUE(SimpleHexAtoi(
s.c_str(), &x));
EXPECT_EQ(exp_value, x);
}
template <typename int_type, typename in_val_type>
void VerifySimpleHexAtoiBad(in_val_type in_value) {
std::string s;
absl::strings_internal::OStringStream strm(&s);
if (in_value >= 0) {
strm << std::hex << in_value;
} else {
strm << "-" << std::hex << -absl::uint128(in_value);
}
int_type x;
EXPECT_FALSE(SimpleHexAtoi(s, &x));
EXPECT_FALSE(SimpleHexAtoi(
s.c_str(), &x));
}
TEST(NumbersTest, HexAtoi) {
VerifySimpleHexAtoiGood<int32_t>(0, 0);
VerifySimpleHexAtoiGood<int32_t>(0x42, 0x42);
VerifySimpleHexAtoiGood<int32_t>(-0x42, -0x42);
VerifySimpleHexAtoiGood<int32_t>(std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::min());
VerifySimpleHexAtoiGood<int32_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleHexAtoiGood<uint32_t>(0, 0);
VerifySimpleHexAtoiGood<uint32_t>(0x42, 0x42);
VerifySimpleHexAtoiBad<uint32_t>(-0x42);
VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int32_t>::min());
VerifySimpleHexAtoiGood<uint32_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleHexAtoiGood<uint32_t>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int64_t>::min());
VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<int64_t>::max());
VerifySimpleHexAtoiBad<uint32_t>(std::numeric_limits<uint64_t>::max());
VerifySimpleHexAtoiGood<int64_t>(0, 0);
VerifySimpleHexAtoiGood<int64_t>(0x42, 0x42);
VerifySimpleHexAtoiGood<int64_t>(-0x42, -0x42);
VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::min());
VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::min());
VerifySimpleHexAtoiGood<int64_t>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
VerifySimpleHexAtoiBad<int64_t>(std::numeric_limits<uint64_t>::max());
VerifySimpleHexAtoiGood<uint64_t>(0, 0);
VerifySimpleHexAtoiGood<uint64_t>(0x42, 0x42);
VerifySimpleHexAtoiBad<uint64_t>(-0x42);
VerifySimpleHexAtoiBad<uint64_t>(std::numeric_limits<int32_t>::min());
VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleHexAtoiBad<uint64_t>(std::numeric_limits<int64_t>::min());
VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
VerifySimpleHexAtoiGood<uint64_t>(std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max());
VerifySimpleHexAtoiGood<absl::uint128>(0, 0);
VerifySimpleHexAtoiGood<absl::uint128>(0x42, 0x42);
VerifySimpleHexAtoiBad<absl::uint128>(-0x42);
VerifySimpleHexAtoiBad<absl::uint128>(std::numeric_limits<int32_t>::min());
VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<int32_t>::max(),
std::numeric_limits<int32_t>::max());
VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<uint32_t>::max(),
std::numeric_limits<uint32_t>::max());
VerifySimpleHexAtoiBad<absl::uint128>(std::numeric_limits<int64_t>::min());
VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<int64_t>::max());
VerifySimpleHexAtoiGood<absl::uint128>(std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max());
VerifySimpleHexAtoiGood<absl::uint128>(
std::numeric_limits<absl::uint128>::max(),
std::numeric_limits<absl::uint128>::max());
VerifySimpleHexAtoiGood<int>(-0x42, -0x42);
VerifySimpleHexAtoiGood<int32_t>(-0x42, -0x42);
VerifySimpleHexAtoiGood<uint32_t>(0x42, 0x42);
VerifySimpleHexAtoiGood<unsigned int>(0x42, 0x42);
VerifySimpleHexAtoiGood<int64_t>(-0x42, -0x42);
VerifySimpleHexAtoiGood<long>(-0x42, -0x42);
VerifySimpleHexAtoiGood<uint64_t>(0x42, 0x42);
VerifySimpleHexAtoiGood<size_t>(0x42, 0x42);
VerifySimpleHexAtoiGood<std::string::size_type>(0x42, 0x42);
int32_t value;
EXPECT_TRUE(safe_strto32_base("0x34234324", &value, 16));
EXPECT_EQ(0x34234324, value);
EXPECT_TRUE(safe_strto32_base("0X34234324", &value, 16));
EXPECT_EQ(0x34234324, value);
EXPECT_TRUE(safe_strto32_base(" \t\n 34234324", &value, 16));
EXPECT_EQ(0x34234324, value);
EXPECT_TRUE(safe_str |
2,551 | cpp | abseil/abseil-cpp | string_view | absl/strings/string_view.cc | absl/strings/string_view_test.cc | #ifndef ABSL_STRINGS_STRING_VIEW_H_
#define ABSL_STRINGS_STRING_VIEW_H_
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <iosfwd>
#include <iterator>
#include <limits>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/base/config.h"
#include "absl/base/internal/throw_delegate.h"
#include "absl/base/macros.h"
#include "absl/base/optimization.h"
#include "absl/base/port.h"
#ifdef ABSL_USES_STD_STRING_VIEW
#include <string_view>
namespace absl {
ABSL_NAMESPACE_BEGIN
using string_view = std::string_view;
ABSL_NAMESPACE_END
}
#else
#if ABSL_HAVE_BUILTIN(__builtin_memcmp) || \
(defined(__GNUC__) && !defined(__clang__)) || \
(defined(_MSC_VER) && _MSC_VER >= 1928)
#define ABSL_INTERNAL_STRING_VIEW_MEMCMP __builtin_memcmp
#else
#define ABSL_INTERNAL_STRING_VIEW_MEMCMP memcmp
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
class ABSL_INTERNAL_ATTRIBUTE_VIEW string_view {
public:
using traits_type = std::char_traits<char>;
using value_type = char;
using pointer = absl::Nullable<char*>;
using const_pointer = absl::Nullable<const char*>;
using reference = char&;
using const_reference = const char&;
using const_iterator = absl::Nullable<const char*>;
using iterator = const_iterator;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using reverse_iterator = const_reverse_iterator;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using absl_internal_is_view = std::true_type;
static constexpr size_type npos = static_cast<size_type>(-1);
constexpr string_view() noexcept : ptr_(nullptr), length_(0) {}
template <typename Allocator>
string_view(
const std::basic_string<char, std::char_traits<char>, Allocator>& str
ABSL_ATTRIBUTE_LIFETIME_BOUND) noexcept
: string_view(str.data(), str.size(), SkipCheckLengthTag{}) {}
constexpr string_view(
absl::Nonnull<const char*> str)
: ptr_(str), length_(str ? StrlenInternal(str) : 0) {}
constexpr string_view(absl::Nullable<const char*> data, size_type len)
: ptr_(data), length_(CheckLengthInternal(len)) {}
constexpr const_iterator begin() const noexcept { return ptr_; }
constexpr const_iterator end() const noexcept { return ptr_ + length_; }
constexpr const_iterator cbegin() const noexcept { return begin(); }
constexpr const_iterator cend() const noexcept { return end(); }
const_reverse_iterator rbegin() const noexcept {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const noexcept {
return const_reverse_iterator(begin());
}
const_reverse_iterator crbegin() const noexcept { return rbegin(); }
const_reverse_iterator crend() const noexcept { return rend(); }
constexpr size_type size() const noexcept { return length_; }
constexpr size_type length() const noexcept { return size(); }
constexpr size_type max_size() const noexcept { return kMaxSize; }
constexpr bool empty() const noexcept { return length_ == 0; }
constexpr const_reference operator[](size_type i) const {
return ABSL_HARDENING_ASSERT(i < size()), ptr_[i];
}
constexpr const_reference at(size_type i) const {
return ABSL_PREDICT_TRUE(i < size())
? ptr_[i]
: ((void)base_internal::ThrowStdOutOfRange(
"absl::string_view::at"),
ptr_[i]);
}
constexpr const_reference front() const {
return ABSL_HARDENING_ASSERT(!empty()), ptr_[0];
}
constexpr const_reference back() const {
return ABSL_HARDENING_ASSERT(!empty()), ptr_[size() - 1];
}
constexpr const_pointer data() const noexcept { return ptr_; }
constexpr void remove_prefix(size_type n) {
ABSL_HARDENING_ASSERT(n <= length_);
ptr_ += n;
length_ -= n;
}
constexpr void remove_suffix(size_type n) {
ABSL_HARDENING_ASSERT(n <= length_);
length_ -= n;
}
constexpr void swap(string_view& s) noexcept {
auto t = *this;
*this = s;
s = t;
}
template <typename A>
explicit operator std::basic_string<char, traits_type, A>() const {
if (!data()) return {};
return std::basic_string<char, traits_type, A>(data(), size());
}
size_type copy(char* buf, size_type n, size_type pos = 0) const {
if (ABSL_PREDICT_FALSE(pos > length_)) {
base_internal::ThrowStdOutOfRange("absl::string_view::copy");
}
size_type rlen = (std::min)(length_ - pos, n);
if (rlen > 0) {
const char* start = ptr_ + pos;
traits_type::copy(buf, start, rlen);
}
return rlen;
}
constexpr string_view substr(size_type pos = 0, size_type n = npos) const {
return ABSL_PREDICT_FALSE(pos > length_)
? (base_internal::ThrowStdOutOfRange(
"absl::string_view::substr"),
string_view())
: string_view(ptr_ + pos, Min(n, length_ - pos));
}
constexpr int compare(string_view x) const noexcept {
return CompareImpl(length_, x.length_,
Min(length_, x.length_) == 0
? 0
: ABSL_INTERNAL_STRING_VIEW_MEMCMP(
ptr_, x.ptr_, Min(length_, x.length_)));
}
constexpr int compare(size_type pos1, size_type count1, string_view v) const {
return substr(pos1, count1).compare(v);
}
constexpr int compare(size_type pos1, size_type count1, string_view v,
size_type pos2, size_type count2) const {
return substr(pos1, count1).compare(v.substr(pos2, count2));
}
constexpr int compare(absl::Nonnull<const char*> s) const {
return compare(string_view(s));
}
constexpr int compare(size_type pos1, size_type count1,
absl::Nonnull<const char*> s) const {
return substr(pos1, count1).compare(string_view(s));
}
constexpr int compare(size_type pos1, size_type count1,
absl::Nonnull<const char*> s, size_type count2) const {
return substr(pos1, count1).compare(string_view(s, count2));
}
size_type find(string_view s, size_type pos = 0) const noexcept;
size_type find(char c, size_type pos = 0) const noexcept;
size_type find(absl::Nonnull<const char*> s, size_type pos,
size_type count) const {
return find(string_view(s, count), pos);
}
size_type find(absl::Nonnull<const char *> s, size_type pos = 0) const {
return find(string_view(s), pos);
}
size_type rfind(string_view s, size_type pos = npos) const noexcept;
size_type rfind(char c, size_type pos = npos) const noexcept;
size_type rfind(absl::Nonnull<const char*> s, size_type pos,
size_type count) const {
return rfind(string_view(s, count), pos);
}
size_type rfind(absl::Nonnull<const char*> s, size_type pos = npos) const {
return rfind(string_view(s), pos);
}
size_type find_first_of(string_view s, size_type pos = 0) const noexcept;
size_type find_first_of(char c, size_type pos = 0) const noexcept {
return find(c, pos);
}
size_type find_first_of(absl::Nonnull<const char*> s, size_type pos,
size_type count) const {
return find_first_of(string_view(s, count), pos);
}
size_type find_first_of(absl::Nonnull<const char*> s,
size_type pos = 0) const {
return find_first_of(string_view(s), pos);
}
size_type find_last_of(string_view s, size_type pos = npos) const noexcept;
size_type find_last_of(char c, size_type pos = npos) const noexcept {
return rfind(c, pos);
}
size_type find_last_of(absl::Nonnull<const char*> s, size_type pos,
size_type count) const {
return find_last_of(string_view(s, count), pos);
}
size_type find_last_of(absl::Nonnull<const char*> s,
size_type pos = npos) const {
return find_last_of(string_view(s), pos);
}
size_type find_first_not_of(string_view s, size_type pos = 0) const noexcept;
size_type find_first_not_of(char c, size_type pos = 0) const noexcept;
size_type find_first_not_of(absl::Nonnull<const char*> s, size_type pos,
size_type count) const {
return find_first_not_of(string_view(s, count), pos);
}
size_type find_first_not_of(absl::Nonnull<const char*> s,
size_type pos = 0) const {
return find_first_not_of(string_view(s), pos);
}
size_type find_last_not_of(string_view s,
size_type pos = npos) const noexcept;
size_type find_last_not_of(char c, size_type pos = npos) const noexcept;
size_type find_last_not_of(absl::Nonnull<const char*> s, size_type pos,
size_type count) const {
return find_last_not_of(string_view(s, count), pos);
}
size_type find_last_not_of(absl::Nonnull<const char*> s,
size_type pos = npos) const {
return find_last_not_of(string_view(s), pos);
}
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
constexpr bool starts_with(string_view s) const noexcept {
return s.empty() ||
(size() >= s.size() &&
ABSL_INTERNAL_STRING_VIEW_MEMCMP(data(), s.data(), s.size()) == 0);
}
constexpr bool starts_with(char c) const noexcept {
return !empty() && front() == c;
}
constexpr bool starts_with(const char* s) const {
return starts_with(string_view(s));
}
constexpr bool ends_with(string_view s) const noexcept {
return s.empty() || (size() >= s.size() && ABSL_INTERNAL_STRING_VIEW_MEMCMP(
data() + (size() - s.size()),
s.data(), s.size()) == 0);
}
constexpr bool ends_with(char c) const noexcept {
return !empty() && back() == c;
}
constexpr bool ends_with(const char* s) const {
return ends_with(string_view(s));
}
#endif
private:
struct SkipCheckLengthTag {};
string_view(absl::Nullable<const char*> data, size_type len,
SkipCheckLengthTag) noexcept
: ptr_(data), length_(len) {}
static constexpr size_type kMaxSize =
(std::numeric_limits<difference_type>::max)();
static constexpr size_type CheckLengthInternal(size_type len) {
return ABSL_HARDENING_ASSERT(len <= kMaxSize), len;
}
static constexpr size_type StrlenInternal(absl::Nonnull<const char*> str) {
#if defined(_MSC_VER) && !defined(__clang__)
const char* begin = str;
while (*str != '\0') ++str;
return str - begin;
#elif ABSL_HAVE_BUILTIN(__builtin_strlen) || \
(defined(__GNUC__) && !defined(__clang__))
return __builtin_strlen(str);
#else
return str ? strlen(str) : 0;
#endif
}
static constexpr size_t Min(size_type length_a, size_type length_b) {
return length_a < length_b ? length_a : length_b;
}
static constexpr int CompareImpl(size_type length_a, size_type length_b,
int compare_result) {
return compare_result == 0 ? static_cast<int>(length_a > length_b) -
static_cast<int>(length_a < length_b)
: (compare_result < 0 ? -1 : 1);
}
absl::Nullable<const char*> ptr_;
size_type length_;
};
constexpr bool operator==(string_view x, string_view y) noexcept {
return x.size() == y.size() &&
(x.empty() ||
ABSL_INTERNAL_STRING_VIEW_MEMCMP(x.data(), y.data(), x.size()) == 0);
}
constexpr bool operator!=(string_view x, string_view y) noexcept {
return !(x == y);
}
constexpr bool operator<(string_view x, string_view y) noexcept {
return x.compare(y) < 0;
}
constexpr bool operator>(string_view x, string_view y) noexcept {
return y < x;
}
constexpr bool operator<=(string_view x, string_view y) noexcept {
return !(y < x);
}
constexpr bool operator>=(string_view x, string_view y) noexcept {
return !(x < y);
}
std::ostream& operator<<(std::ostream& o, string_view piece);
ABSL_NAMESPACE_END
}
#undef ABSL_INTERNAL_STRING_VIEW_MEMCMP
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
inline string_view ClippedSubstr(string_view s, size_t pos,
size_t n = string_view::npos) {
pos = (std::min)(pos, static_cast<size_t>(s.size()));
return s.substr(pos, n);
}
constexpr string_view NullSafeStringView(absl::Nullable<const char*> p) {
return p ? string_view(p) : string_view();
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/string_view.h"
#ifndef ABSL_USES_STD_STRING_VIEW
#include <algorithm>
#include <climits>
#include <cstring>
#include <ostream>
#include "absl/base/nullability.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
absl::Nullable<const char*> memmatch(absl::Nullable<const char*> phaystack,
size_t haylen,
absl::Nullable<const char*> pneedle,
size_t neelen) {
if (0 == neelen) {
return phaystack;
}
if (haylen < neelen) return nullptr;
const char* match;
const char* hayend = phaystack + haylen - neelen + 1;
while (
(match = static_cast<const char*>(memchr(
phaystack, pneedle[0], static_cast<size_t>(hayend - phaystack))))) {
if (memcmp(match, pneedle, neelen) == 0)
return match;
else
phaystack = match + 1;
}
return nullptr;
}
void WritePadding(std::ostream& o, size_t pad) {
char fill_buf[32];
memset(fill_buf, o.fill(), sizeof(fill_buf));
while (pad) {
size_t n = std::min(pad, sizeof(fill_buf));
o.write(fill_buf, static_cast<std::streamsize>(n));
pad -= n;
}
}
class LookupTable {
public:
explicit LookupTable(string_view wanted) {
for (char c : wanted) {
table_[Index(c)] = true;
}
}
bool operator[](char c) const { return table_[Index(c)]; }
private:
static unsigned char Index(char c) { return static_cast<unsigned char>(c); }
bool table_[UCHAR_MAX + 1] = {};
};
}
std::ostream& operator<<(std::ostream& o, string_view piece) {
std::ostream::sentry sentry(o);
if (sentry) {
size_t lpad = 0;
size_t rpad = 0;
if (static_cast<size_t>(o.width()) > piece.size()) {
size_t pad = static_cast<size_t>(o.width()) - piece.size();
if ((o.flags() & o.adjustfield) == o.left) {
rpad = pad;
} else {
lpad = pad;
}
}
if (lpad) WritePadding(o, lpad);
o.write(piece.data(), static_cast<std::streamsize>(piece.size()));
if (rpa | #include "absl/strings/string_view.h"
#include <stdlib.h>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <ios>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/meta/type_traits.h"
#if defined(ABSL_HAVE_STD_STRING_VIEW) || defined(__ANDROID__)
#define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH_IF_SUPPORTED(statement, ".*")
#else
#define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
EXPECT_DEATH_IF_SUPPORTED(statement, regex)
#endif
namespace {
static_assert(!absl::type_traits_internal::IsOwner<absl::string_view>::value &&
absl::type_traits_internal::IsView<absl::string_view>::value,
"string_view is a view, not an owner");
static_assert(absl::type_traits_internal::IsLifetimeBoundAssignment<
absl::string_view, std::string>::value,
"lifetimebound assignment not detected");
template <typename T>
struct Mallocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
size_type max_size() const {
return size_t(std::numeric_limits<size_type>::max()) / sizeof(value_type);
}
template <typename U>
struct rebind {
typedef Mallocator<U> other;
};
Mallocator() = default;
template <class U>
Mallocator(const Mallocator<U>&) {}
T* allocate(size_t n) { return static_cast<T*>(std::malloc(n * sizeof(T))); }
void deallocate(T* p, size_t) { std::free(p); }
};
template <typename T, typename U>
bool operator==(const Mallocator<T>&, const Mallocator<U>&) {
return true;
}
template <typename T, typename U>
bool operator!=(const Mallocator<T>&, const Mallocator<U>&) {
return false;
}
TEST(StringViewTest, Ctor) {
{
absl::string_view s10;
EXPECT_TRUE(s10.data() == nullptr);
EXPECT_EQ(0u, s10.length());
}
{
const char* hello = "hello";
absl::string_view s20(hello);
EXPECT_TRUE(s20.data() == hello);
EXPECT_EQ(5u, s20.length());
absl::string_view s21(hello, 4);
EXPECT_TRUE(s21.data() == hello);
EXPECT_EQ(4u, s21.length());
absl::string_view s22(hello, 6);
EXPECT_TRUE(s22.data() == hello);
EXPECT_EQ(6u, s22.length());
}
{
std::string hola = "hola";
absl::string_view s30(hola);
EXPECT_TRUE(s30.data() == hola.data());
EXPECT_EQ(4u, s30.length());
hola.push_back('\0');
hola.append("h2");
hola.push_back('\0');
absl::string_view s31(hola);
EXPECT_TRUE(s31.data() == hola.data());
EXPECT_EQ(8u, s31.length());
}
{
using mstring =
std::basic_string<char, std::char_traits<char>, Mallocator<char>>;
mstring str1("BUNGIE-JUMPING!");
const mstring str2("SLEEPING!");
absl::string_view s1(str1);
s1.remove_prefix(strlen("BUNGIE-JUM"));
absl::string_view s2(str2);
s2.remove_prefix(strlen("SLEE"));
EXPECT_EQ(s1, s2);
EXPECT_EQ(s1, "PING!");
}
}
TEST(StringViewTest, Swap) {
absl::string_view a("a");
absl::string_view b("bbb");
EXPECT_TRUE(noexcept(a.swap(b)));
a.swap(b);
EXPECT_EQ(a, "bbb");
EXPECT_EQ(b, "a");
a.swap(b);
EXPECT_EQ(a, "a");
EXPECT_EQ(b, "bbb");
}
TEST(StringViewTest, STLComparator) {
std::string s1("foo");
std::string s2("bar");
std::string s3("baz");
absl::string_view p1(s1);
absl::string_view p2(s2);
absl::string_view p3(s3);
typedef std::map<absl::string_view, int> TestMap;
TestMap map;
map.insert(std::make_pair(p1, 0));
map.insert(std::make_pair(p2, 1));
map.insert(std::make_pair(p3, 2));
EXPECT_EQ(map.size(), 3u);
TestMap::const_iterator iter = map.begin();
EXPECT_EQ(iter->second, 1);
++iter;
EXPECT_EQ(iter->second, 2);
++iter;
EXPECT_EQ(iter->second, 0);
++iter;
EXPECT_TRUE(iter == map.end());
TestMap::iterator new_iter = map.find("zot");
EXPECT_TRUE(new_iter == map.end());
new_iter = map.find("bar");
EXPECT_TRUE(new_iter != map.end());
map.erase(new_iter);
EXPECT_EQ(map.size(), 2u);
iter = map.begin();
EXPECT_EQ(iter->second, 2);
++iter;
EXPECT_EQ(iter->second, 0);
++iter;
EXPECT_TRUE(iter == map.end());
}
#define COMPARE(result, op, x, y) \
EXPECT_EQ(result, absl::string_view((x)) op absl::string_view((y))); \
EXPECT_EQ(result, absl::string_view((x)).compare(absl::string_view((y))) op 0)
TEST(StringViewTest, ComparisonOperators) {
COMPARE(true, ==, "", "");
COMPARE(true, ==, "", absl::string_view());
COMPARE(true, ==, absl::string_view(), "");
COMPARE(true, ==, "a", "a");
COMPARE(true, ==, "aa", "aa");
COMPARE(false, ==, "a", "");
COMPARE(false, ==, "", "a");
COMPARE(false, ==, "a", "b");
COMPARE(false, ==, "a", "aa");
COMPARE(false, ==, "aa", "a");
COMPARE(false, !=, "", "");
COMPARE(false, !=, "a", "a");
COMPARE(false, !=, "aa", "aa");
COMPARE(true, !=, "a", "");
COMPARE(true, !=, "", "a");
COMPARE(true, !=, "a", "b");
COMPARE(true, !=, "a", "aa");
COMPARE(true, !=, "aa", "a");
COMPARE(true, <, "a", "b");
COMPARE(true, <, "a", "aa");
COMPARE(true, <, "aa", "b");
COMPARE(true, <, "aa", "bb");
COMPARE(false, <, "a", "a");
COMPARE(false, <, "b", "a");
COMPARE(false, <, "aa", "a");
COMPARE(false, <, "b", "aa");
COMPARE(false, <, "bb", "aa");
COMPARE(true, <=, "a", "a");
COMPARE(true, <=, "a", "b");
COMPARE(true, <=, "a", "aa");
COMPARE(true, <=, "aa", "b");
COMPARE(true, <=, "aa", "bb");
COMPARE(false, <=, "b", "a");
COMPARE(false, <=, "aa", "a");
COMPARE(false, <=, "b", "aa");
COMPARE(false, <=, "bb", "aa");
COMPARE(false, >=, "a", "b");
COMPARE(false, >=, "a", "aa");
COMPARE(false, >=, "aa", "b");
COMPARE(false, >=, "aa", "bb");
COMPARE(true, >=, "a", "a");
COMPARE(true, >=, "b", "a");
COMPARE(true, >=, "aa", "a");
COMPARE(true, >=, "b", "aa");
COMPARE(true, >=, "bb", "aa");
COMPARE(false, >, "a", "a");
COMPARE(false, >, "a", "b");
COMPARE(false, >, "a", "aa");
COMPARE(false, >, "aa", "b");
COMPARE(false, >, "aa", "bb");
COMPARE(true, >, "b", "a");
COMPARE(true, >, "aa", "a");
COMPARE(true, >, "b", "aa");
COMPARE(true, >, "bb", "aa");
}
TEST(StringViewTest, ComparisonOperatorsByCharacterPosition) {
std::string x;
for (size_t i = 0; i < 256; i++) {
x += 'a';
std::string y = x;
COMPARE(true, ==, x, y);
for (size_t j = 0; j < i; j++) {
std::string z = x;
z[j] = 'b';
COMPARE(false, ==, x, z);
COMPARE(true, <, x, z);
COMPARE(true, >, z, x);
if (j + 1 < i) {
z[j + 1] = 'A';
COMPARE(false, ==, x, z);
COMPARE(true, <, x, z);
COMPARE(true, >, z, x);
z[j + 1] = 'z';
COMPARE(false, ==, x, z);
COMPARE(true, <, x, z);
COMPARE(true, >, z, x);
}
}
}
}
#undef COMPARE
template <typename T>
struct is_type {
template <typename U>
static bool same(U) {
return false;
}
static bool same(T) { return true; }
};
TEST(StringViewTest, NposMatchesStdStringView) {
EXPECT_EQ(absl::string_view::npos, std::string::npos);
EXPECT_TRUE(is_type<size_t>::same(absl::string_view::npos));
EXPECT_FALSE(is_type<size_t>::same(""));
char test[absl::string_view::npos & 1] = {0};
EXPECT_EQ(0, test[0]);
}
TEST(StringViewTest, STL1) {
const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
const absl::string_view b("abc");
const absl::string_view c("xyz");
const absl::string_view d("foobar");
const absl::string_view e;
std::string temp("123");
temp += '\0';
temp += "456";
const absl::string_view f(temp);
EXPECT_EQ(a[6], 'g');
EXPECT_EQ(b[0], 'a');
EXPECT_EQ(c[2], 'z');
EXPECT_EQ(f[3], '\0');
EXPECT_EQ(f[5], '5');
EXPECT_EQ(*d.data(), 'f');
EXPECT_EQ(d.data()[5], 'r');
EXPECT_TRUE(e.data() == nullptr);
EXPECT_EQ(*a.begin(), 'a');
EXPECT_EQ(*(b.begin() + 2), 'c');
EXPECT_EQ(*(c.end() - 1), 'z');
EXPECT_EQ(*a.rbegin(), 'z');
EXPECT_EQ(*(b.rbegin() + 2), 'a');
EXPECT_EQ(*(c.rend() - 1), 'x');
EXPECT_TRUE(a.rbegin() + 26 == a.rend());
EXPECT_EQ(a.size(), 26u);
EXPECT_EQ(b.size(), 3u);
EXPECT_EQ(c.size(), 3u);
EXPECT_EQ(d.size(), 6u);
EXPECT_EQ(e.size(), 0u);
EXPECT_EQ(f.size(), 7u);
EXPECT_TRUE(!d.empty());
EXPECT_TRUE(d.begin() != d.end());
EXPECT_TRUE(d.begin() + 6 == d.end());
EXPECT_TRUE(e.empty());
EXPECT_TRUE(e.begin() == e.end());
char buf[4] = { '%', '%', '%', '%' };
EXPECT_EQ(a.copy(buf, 4), 4u);
EXPECT_EQ(buf[0], a[0]);
EXPECT_EQ(buf[1], a[1]);
EXPECT_EQ(buf[2], a[2]);
EXPECT_EQ(buf[3], a[3]);
EXPECT_EQ(a.copy(buf, 3, 7), 3u);
EXPECT_EQ(buf[0], a[7]);
EXPECT_EQ(buf[1], a[8]);
EXPECT_EQ(buf[2], a[9]);
EXPECT_EQ(buf[3], a[3]);
EXPECT_EQ(c.copy(buf, 99), 3u);
EXPECT_EQ(buf[0], c[0]);
EXPECT_EQ(buf[1], c[1]);
EXPECT_EQ(buf[2], c[2]);
EXPECT_EQ(buf[3], a[3]);
#ifdef ABSL_HAVE_EXCEPTIONS
EXPECT_THROW(a.copy(buf, 1, 27), std::out_of_range);
#else
ABSL_EXPECT_DEATH_IF_SUPPORTED(a.copy(buf, 1, 27), "absl::string_view::copy");
#endif
}
TEST(StringViewTest, STL2) {
const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
const absl::string_view b("abc");
const absl::string_view c("xyz");
absl::string_view d("foobar");
const absl::string_view e;
const absl::string_view f(
"123"
"\0"
"456",
7);
d = absl::string_view();
EXPECT_EQ(d.size(), 0u);
EXPECT_TRUE(d.empty());
EXPECT_TRUE(d.data() == nullptr);
EXPECT_TRUE(d.begin() == d.end());
EXPECT_EQ(a.find(b), 0u);
EXPECT_EQ(a.find(b, 1), absl::string_view::npos);
EXPECT_EQ(a.find(c), 23u);
EXPECT_EQ(a.find(c, 9), 23u);
EXPECT_EQ(a.find(c, absl::string_view::npos), absl::string_view::npos);
EXPECT_EQ(b.find(c), absl::string_view::npos);
EXPECT_EQ(b.find(c, absl::string_view::npos), absl::string_view::npos);
EXPECT_EQ(a.find(d), 0u);
EXPECT_EQ(a.find(e), 0u);
EXPECT_EQ(a.find(d, 12), 12u);
EXPECT_EQ(a.find(e, 17), 17u);
absl::string_view g("xx not found bb");
EXPECT_EQ(a.find(g), absl::string_view::npos);
EXPECT_EQ(d.find(b), absl::string_view::npos);
EXPECT_EQ(e.find(b), absl::string_view::npos);
EXPECT_EQ(d.find(b, 4), absl::string_view::npos);
EXPECT_EQ(e.find(b, 7), absl::string_view::npos);
size_t empty_search_pos = std::string().find(std::string());
EXPECT_EQ(d.find(d), empty_search_pos);
EXPECT_EQ(d.find(e), empty_search_pos);
EXPECT_EQ(e.find(d), empty_search_pos);
EXPECT_EQ(e.find(e), empty_search_pos);
EXPECT_EQ(d.find(d, 4), std::string().find(std::string(), 4));
EXPECT_EQ(d.find(e, 4), std::string().find(std::string(), 4));
EXPECT_EQ(e.find(d, 4), std::string().find(std::string(), 4));
EXPECT_EQ(e.find(e, 4), std::string().find(std::string(), 4));
EXPECT_EQ(a.find('a'), 0u);
EXPECT_EQ(a.find('c'), 2u);
EXPECT_EQ(a.find('z'), 25u);
EXPECT_EQ(a.find('$'), absl::string_view::npos);
EXPECT_EQ(a.find('\0'), absl::string_view::npos);
EXPECT_EQ(f.find('\0'), 3u);
EXPECT_EQ(f.find('3'), 2u);
EXPECT_EQ(f.find('5'), 5u);
EXPECT_EQ(g.find('o'), 4u);
EXPECT_EQ(g.find('o', 4), 4u);
EXPECT_EQ(g.find('o', 5), 8u);
EXPECT_EQ(a.find('b', 5), absl::string_view::npos);
EXPECT_EQ(d.find('\0'), absl::string_view::npos);
EXPECT_EQ(e.find('\0'), absl::string_view::npos);
EXPECT_EQ(d.find('\0', 4), absl::string_view::npos);
EXPECT_EQ(e.find('\0', 7), absl::string_view::npos);
EXPECT_EQ(d.find('x'), absl::string_view::npos);
EXPECT_EQ(e.find('x'), absl::string_view::npos);
EXPECT_EQ(d.find('x', 4), absl::string_view::npos);
EXPECT_EQ(e.find('x', 7), absl::string_view::npos);
EXPECT_EQ(a.find(b.data(), 1, 0), 1u);
EXPECT_EQ(a.find(c.data(), 9, 0), 9u);
EXPECT_EQ(a.find(c.data(), absl::string_view::npos, 0),
absl::string_view::npos);
EXPECT_EQ(b.find(c.data(), absl::string_view::npos, 0),
absl::string_view::npos);
EXPECT_EQ(d.find(b.data(), 4, 0), absl::string_view::npos);
EXPECT_EQ(e.find(b.data(), 7, 0), absl::string_view::npos);
EXPECT_EQ(a.find(b.data(), 1), absl::string_view::npos);
EXPECT_EQ(a.find(c.data(), 9), 23u);
EXPECT_EQ(a.find(c.data(), absl::string_view::npos), absl::string_view::npos);
EXPECT_EQ(b.find(c.data(), absl::string_view::npos), absl::string_view::npos);
EXPECT_EQ(d.find(b.data(), 4), absl::string_view::npos);
EXPECT_EQ(e.find(b.data(), 7), absl::string_view::npos);
EXPECT_EQ(a.rfind(b), 0u);
EXPECT_EQ(a.rfind(b, 1), 0u);
EXPECT_EQ(a.rfind(c), 23u);
EXPECT_EQ(a.rfind(c, 22), absl::string_view::npos);
EXPECT_EQ(a.rfind(c, 1), absl::string_view::npos);
EXPECT_EQ(a.rfind(c, 0), absl::string_view::npos);
EXPECT_EQ(b.rfind(c), absl::string_view::npos);
EXPECT_EQ(b.rfind(c, 0), absl::string_view::npos);
EXPECT_EQ(a.rfind(d), std::string(a).rfind(std::string()));
EXPECT_EQ(a.rfind(e), std::string(a).rfind(std::string()));
EXPECT_EQ(a.rfind(d, 12), 12u);
EXPECT_EQ(a.rfind(e, 17), 17u);
EXPECT_EQ(a.rfind(g), absl::string_view::npos);
EXPECT_EQ(d.rfind(b), absl::string_view::npos);
EXPECT_EQ(e.rfind(b), absl::string_view::npos);
EXPECT_EQ(d.rfind(b, 4), absl::string_view::npos);
EXPECT_EQ(e.rfind(b, 7), absl::string_view::npos);
EXPECT_EQ(d.rfind(d, 4), std::string().rfind(std::string()));
EXPECT_EQ(e.rfind(d, 7), std::string().rfind(std::string()));
EXPECT_EQ(d.rfind(e, 4), std::string().rfind(std::string()));
EXPECT_EQ(e.rfind(e, 7), std::string().rfind(std::string()));
EXPECT_EQ(d.rfind(d), std::string().rfind(std::string()));
EXPECT_EQ(e.rfind(d), std::string().rfind(std::string()));
EXPECT_EQ(d.rfind(e), std::string().rfind(std::string()));
EXPECT_EQ(e.rfind(e), std::string().rfind(std::string()));
EXPECT_EQ(g.rfind('o'), 8u);
EXPECT_EQ(g.rfind('q'), absl::string_view::npos);
EXPECT_EQ(g.rfind('o', 8), 8u);
EXPECT_EQ(g.rfind('o', 7), 4u);
EXPECT_EQ(g.rfind('o', 3), absl::string_view::npos);
EXPECT_EQ(f.rfind('\0'), 3u);
EXPECT_EQ(f.rfind('\0', 12), 3u);
EXPECT_EQ(f.rfind('3'), 2u);
EXPECT_EQ(f.rfind('5'), 5u);
EXPECT_EQ(d.rfind('o'), absl::string_view::npos);
EXPECT_EQ(e.rfind('o'), absl::string_view::npos);
EXPECT_EQ(d.rfind('o', 4), absl::string_view::npos);
EXPECT_EQ(e.rfind('o', 7), absl::string_view::npos);
EXPECT_EQ(a.rfind(b.data(), 1, 0), 1u);
EXPECT_EQ(a.rfind(c.data(), 22, 0), 22u);
EXPECT_EQ(a.rfind(c.data(), 1, 0), 1u);
EXPECT_EQ(a.rfind(c.data(), 0, 0), 0u);
EXPECT_EQ(b.rfind(c.data(), 0, 0), 0u);
EXPECT_EQ(d.rfind(b.data(), 4, 0), 0u);
EXPECT_EQ(e.rfind(b.data(), 7, 0), 0u);
}
TEST(StringViewTest, STL2FindFirst) {
const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
const absl::string_view b("abc");
const absl::string_view c("xyz");
absl::string_view d("foobar");
const absl::string_view e;
const absl::string_view f(
"123"
"\0"
"456",
7);
absl::string_view g("xx not found bb");
d = absl::string_view();
EXPECT_EQ(a.find_first_of(b), 0u);
EXPECT_EQ(a.find_first_of(b, 0), 0u);
EXPECT_EQ(a.find_first_of(b, 1), 1u);
EXPECT_EQ(a.find_first_of(b, 2), 2u);
EXPECT_EQ(a.find_first_of(b, 3), absl::string_view::npos);
EXPECT_EQ(a.find_first_of(c), 23u);
EXPECT_EQ(a.find_first_of(c, 23), 23u);
EXPECT_EQ(a.find_first_of(c, 24), 24u);
EXPECT_EQ(a.find_first_of(c, 25), 25u);
EXPECT_EQ(a.find_first_of(c, 26), absl::string_view::npos);
EXPECT_EQ(g.find_first_of(b), 13u);
EXPECT_EQ(g.find_first_of(c), 0u);
EXPECT_EQ(a.find_first_of(f), absl::string_view::npos);
EXPECT_EQ(f.find_first_of(a), absl::string_view::npos);
EXPECT_EQ(a.find_first_of(d), absl::string_view::npos);
EXPECT_EQ(a.find_first_of(e), absl::string_view::npos);
EXPECT_EQ(d.find_first_of(b), absl::string_view::npos);
EXPECT_EQ(e.find_first_of(b), absl::string_view::npos);
EXPECT_EQ(d.find_first_of(d), absl::string_view::npos);
EXPECT_EQ(e.find_first_of(d), absl::string_view::npos);
EXPECT_EQ(d.find_first_of(e), absl::string_view::npos);
EXPECT_EQ(e.find_first_of(e), absl::string_view::npos);
EXPECT_EQ(a.find_first_not_of(b), 3u);
EXPECT_EQ(a.find_first_not_of(c), 0u);
EXPECT_EQ(b.find_first_not_of(a), absl::string_view::npos);
EXPECT_EQ(c.find_first_not_of(a), absl::string_view::npos);
EXPECT_EQ(f.find_first_not_of(a), 0u);
EXPECT_EQ(a.find_first_not_of(f), 0u);
EXPECT_EQ(a.find_first_not_of(d), 0u);
EXPECT_EQ(a.find_first_not_of(e), 0u);
EXPECT_EQ(a.find_first_not_of(d), 0u);
EXPECT_EQ(a.find_first_not_of(e), 0u);
EXPECT_EQ(a.find_first_not_of(d, 1), 1u);
EXPECT_EQ(a.find_first_not_of(e, 1), 1u);
EXPECT_EQ(a.find_first_not_of(d, a.size() - 1), a.size() - 1);
EXPECT_EQ(a.find_first_not_of(e, a.size() - 1), a.size() - 1);
EXPECT_EQ(a.find_first_not_of(d, a.size()), absl::string_view::npos);
EXPECT_EQ(a.find_first_not_of(e, a.size()), absl::string_view::npos);
EXPECT_EQ(a.find_first_not_of(d, absl::string_view::npos),
absl::string_view::npos);
EXPECT_EQ(a.find_first_not_of(e, absl::string_view::npos),
absl::string_view::npos);
EXPECT_EQ(d.find_first_not_of(a), absl::string_view::npos);
EXPECT_EQ(e.find_first_not_of(a), absl::string_view::npos);
EXPECT_EQ(d.find_first_not_of(d), absl::string_view::npos);
EXPECT_EQ(e.find_first_not_of(d), absl::string_view::npos);
EXPECT_EQ(d.find_first_not_of(e), absl::string_view::npos);
EXPECT_EQ(e.find_first_not_of(e), absl::string_view::npos);
absl::string_view h("====");
EXPECT_EQ(h.find_first_not_of('='), absl::string_view::npos);
EXPECT_EQ(h.find_first_not_of('=', 3), absl::string_view::npos);
EXPECT_EQ(h.find_first_not_of('\0'), 0u);
EXPECT_EQ(g.find_first_not_of('x'), 2u);
EXPECT_EQ(f.find_first_not_of('\0'), 0u);
EXPECT_EQ(f.find_first_not_of('\0', 3), 4u);
EXPECT_EQ(f.find_first_not_of('\0', 2), 2u);
EXPECT_EQ(d.find_first_not_of('x'), absl::string_view::npos);
EXPECT_EQ(e.find_first_not_of('x'), absl::string_view::npos);
EXPECT_EQ(d.find_first_not_of('\0'), absl::string_view::npos);
EXPECT_EQ(e.find_first_not_of('\0'), absl::string_view::npos);
}
TEST(StringViewTest, STL2FindLast) {
const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
const absl::string_view b("abc");
const absl::string_view c("xyz");
absl::string_view d("foobar");
const absl::string_view e;
const absl::string_view f(
"123"
"\0"
"456",
7);
absl::string_view g("xx not found bb");
absl::string_view h("====");
absl::string_view i("56");
d = absl::string_view();
EXPECT_EQ(h.find_last_of(a), absl::string_view::npos);
EXPECT_EQ(g.find_last_of(a), g.size() - 1);
EXPECT_EQ(a.find_last_of(b), 2u);
EXPECT_EQ(a.find_last_of(c), a.size() - 1);
EXPECT_EQ(f.find_last_of(i), 6u);
EXPECT_EQ(a.find_last_of('a'), 0u);
EXPECT_EQ(a.find_last_of('b'), 1u);
EXPECT_EQ(a.find_last_of('z'), 25u);
EXPECT_EQ(a.find_last_of('a', 5), 0u);
EXPECT_EQ(a.find_last_of('b', 5), 1u);
EXPECT_EQ(a.find_last_of('b', 0), absl::string_view::npos);
EXPECT_EQ(a.find_last_of('z', 25), 25u);
EXPECT_EQ(a.find_last_of('z', 24), absl::string_view::npos);
EXPECT_EQ(f.find_last_of(i, 5), 5u);
EXPECT_EQ(f.find_last_of(i, 6), 6u);
EXPECT_EQ(f.find_last_of(a, 4), absl::string_view::npos);
EXPECT_EQ(f.find_last_of(d), absl::string_view::npos);
EXPECT_EQ(f.find_last_of(e), absl::string_view::npos);
EXPECT_EQ(f.find_last_of(d, 4), absl::string_view::npos);
EXPECT_EQ(f.find_last_of(e, 4), absl::string_view::npos);
EXPECT_EQ(d.find_last_of(d), absl::string_view::npos);
EXPECT_EQ(d.find_last_of(e), absl::string_view::npos);
EXPECT_EQ(e.find_last_of(d), absl::string_view::npos);
EXPECT_EQ(e.find_last_of(e), absl::string_view::npos);
EXPECT_EQ(d.find_last_of(f), absl::string_view::npos);
EXPECT_EQ(e.find_last_of(f), absl::string_view::npos);
EXPECT_EQ(d.find_last_of(d, 4), absl::string_view::npos);
EXPECT_EQ(d.find_last_of(e, 4), absl::string_view::npos);
EXPECT_EQ(e.find_last_of(d, 4), absl::string_view::npos);
EXPECT_EQ(e.find_last_of(e, 4), absl::string_view::npos);
EXPECT_EQ(d.find_last_of(f, 4), absl::string_view::npos);
EXPECT_EQ(e.find_last_of(f, 4), absl::string_view::npos);
EXPECT_EQ(a.find_last_not_of(b), a.size() - 1);
EXPECT_EQ(a.find_last_not_of(c), 22u);
EXPECT_EQ(b.find_last_not_of(a), absl::string_view::npos);
EXPECT_EQ(b.find_last_not_of(b), absl::string_view::npos);
EXPECT_EQ(f.find_last_not_of(i), 4u);
EXPECT_EQ(a.find_last_not_of(c, 24), 22u);
EXPECT_EQ(a.find_last_not_of(b, 3), 3u);
EXPECT_EQ(a.find_last_not_of(b, 2), absl::string_view::npos);
EXPECT_EQ(f.find_last_not_of(d), f.size() - 1);
EXPECT_EQ(f.find_last_not_of(e), f.size() - 1);
EXPECT_EQ(f.find_last_not_of(d, 4), 4u);
EXPECT_EQ(f.find_last_not_of(e, 4), 4u);
EXPECT_EQ(d.find_last_not_of(d), absl::string_view::npos);
EXPECT_EQ(d.find_last_not_of(e), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of(d), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of(e), absl::string_view::npos);
EXPECT_EQ(d.find_last_not_of(f), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of(f), absl::string_view::npos);
EXPECT_EQ(d.find_last_not_of(d, 4), absl::string_view::npos);
EXPECT_EQ(d.find_last_not_of(e, 4), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of(d, 4), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of(e, 4), absl::string_view::npos);
EXPECT_EQ(d.find_last_not_of(f, 4), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of(f, 4), absl::string_view::npos);
EXPECT_EQ(h.find_last_not_of('x'), h.size() - 1);
EXPECT_EQ(h.find_last_not_of('='), absl::string_view::npos);
EXPECT_EQ(b.find_last_not_of('c'), 1u);
EXPECT_EQ(h.find_last_not_of('x', 2), 2u);
EXPECT_EQ(h.find_last_not_of('=', 2), absl::string_view::npos);
EXPECT_EQ(b.find_last_not_of('b', 1), 0u);
EXPECT_EQ(d.find_last_not_of('x'), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of('x'), absl::string_view::npos);
EXPECT_EQ(d.find_last_not_of('\0'), absl::string_view::npos);
EXPECT_EQ(e.find_last_not_of('\0'), absl::string_view::npos);
}
TEST(StringViewTest, STL2Substr) {
const absl::string_view a("abcdefghijklmnopqrstuvwxyz");
const absl::string_view b("abc");
const absl::string_view c("xyz");
absl::string_view d("foobar");
const absl::string_view e;
d = absl::string_view();
EXPECT_EQ(a.substr(0, 3), b);
EXPECT_EQ(a.substr(23), c);
EXPECT_EQ(a.substr(23, 3), c);
EXPECT_EQ(a.substr(23, 99), c);
EXPECT_EQ(a.substr(0), a);
EXPECT_EQ(a.substr(), a);
EXPECT_EQ(a.substr(3, 2), "de");
EXPECT_EQ(d.substr(0, 99), e);
EXPECT_EQ(a.substr(0, absl::string_view::npos), a);
EXPECT_EQ(a.substr(23, absl::string_view::npos), c);
#ifdef ABSL_HAVE_EXCEPTIONS
EXPECT_THROW((void)a.substr(99, 2), std::out_of_range);
#else
ABSL_EXPECT_DEATH_IF_SUPPORTED((void)a.substr(99, 2),
"absl::string_view::substr");
#endif
}
TEST(StringViewTest, TruncSubstr) {
const absl::string_view hi("hi");
EXPECT_EQ("", absl::ClippedSubstr(hi, 0, 0));
EXPECT_EQ("h", absl::ClippedSubstr(hi, 0, 1));
EXPECT_EQ("hi", absl::ClippedSubstr(hi, 0));
EXPECT_EQ("i", absl::ClippedSubstr(hi, 1));
EXPECT_EQ("", absl::ClippedSubstr(hi, 2));
EXPECT_EQ("", absl::ClippedSubstr(hi, 3));
EXPECT_EQ("", absl::ClippedSubstr(hi, 3, 2));
}
TEST(StringViewTest, UTF8) {
std::string utf8 = "\u00E1";
std::string utf8_twice = utf8 + " " + utf8;
size_t utf8_len = strlen(utf8.data());
EXPECT_EQ(utf8_len, absl::string_view(utf8_twice).find_first_of(" "));
EXPECT_EQ(utf8_len, absl::string_view(utf8_twice).find_first_of(" \t"));
}
TEST(StringViewTest, FindConformance) {
struct {
std::string haystack;
std::string needle;
} specs[] = {
{"", ""},
{"", "a"},
{"a", ""},
{"a", "a"},
{"a", "b"},
{"aa", ""},
{"aa", "a"},
{"aa", "b"},
{"ab", "a"},
{"ab", "b"},
{"abcd", ""},
{"abcd", "a"},
{"abcd", "d"},
{"abcd", "ab"},
{"abcd", "bc"},
{"abcd", "cd"},
{"abcd", "abcd"},
};
for (const auto& s : specs) {
SCOPED_TRACE(s.haystack);
SCOPED_TRACE(s.needle);
std::string st = s.haystack;
absl::string_view sp = s.haystack;
for (size_t i = 0; i <= sp.size(); ++i) {
size_t pos = (i == sp.size()) ? absl::string_view::npos : i;
SCOPED_TRACE(pos);
EXPECT_EQ(sp.find(s.needle, pos),
st.find(s.needle, pos));
EXPECT_EQ(sp.rfind(s.needle, pos),
st.rfind(s.needle, pos));
EXPECT_EQ(sp.find_first_of(s.needle, pos),
st.find_first_of(s.needle, pos));
EXPECT_EQ(sp.find_first_not_of(s.needle, pos),
st.find_first_not_of(s.needle, pos));
EXPECT_EQ(sp.find_last_of(s.needle, pos),
st.find_last_of(s.needle, pos));
EXPECT_EQ(sp.find_last_not_of(s.needle, pos),
st.find_last_not_of(s.needle, pos));
}
}
}
TEST(StringViewTest, Remove) {
absl::string_view a("foobar");
std::string s1("123");
s1 += '\0';
s1 += "456";
absl::string_view e;
std::string s2;
absl::string_view c(a);
c.remove_prefix(3);
EXPECT_EQ(c, "bar");
c = a;
c.remove_prefix(0);
EXPECT_EQ(c, a);
c.remove_prefix(c.size());
EXPECT_EQ(c, e);
c = a;
c.remove_suffix(3);
EXPECT_EQ(c, "foo");
c = a;
c.remove_suffix(0);
EXPECT_EQ(c, a);
c.remove_suffix(c.size());
EXPECT_EQ(c, e);
}
TEST(StringViewTest, Set) {
absl::string_view a("foobar");
absl::string_view empty;
absl::string_view b;
b = absl::string_view("foobar", 6);
EXPECT_EQ(b, a);
b = absl::string_view("foobar", 0);
EXPECT_EQ(b, empty);
b = absl::string_view("foobar", 7);
EXPECT_NE(b, a);
b = absl::string_view("foobar");
EXPECT_EQ(b, a);
}
TEST(StringViewTest, FrontBack) {
static const char arr[] = "abcd";
const absl::string_view csp(arr, 4);
EXPECT_EQ(&arr[0], &csp.front());
EXPECT_EQ(&arr[3], &csp.back());
}
TEST(StringViewTest, FrontBackSingleChar) {
static const char c = 'a';
const absl::string_view csp(&c, 1);
EXPECT_EQ(&c, &csp.front());
EXPECT_EQ(&c, &csp.back());
}
TEST(StringViewTest, FrontBackEmpty) {
#ifndef ABSL_USES_STD_STRING_VIEW
#if !defined(NDEBUG) || ABSL_OPTION_HARDENED
absl::string_view sv;
ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.front(), "");
ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.back(), "");
#endif
#endif
}
#if !defined(ABSL_USES_STD_STRING_VIEW) || \
(!(defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE >= 9) && \
!defined(_LIBCPP_VERSION) && !defined(_MSC_VER))
#define ABSL_HAVE_STRING_VIEW_FROM_NULLPTR 1
#endif
TEST(StringViewTest, NULLInput) {
absl::string_view s;
EXPECT_EQ(s.data(), nullptr);
EXPECT_EQ(s.size(), 0u);
#ifdef ABSL_HAVE_STRING_VIEW_FROM_NULLPTR
s = absl::string_view(nullptr);
EXPECT_EQ(s.data(), nullptr);
EXPECT_EQ(s.size(), 0u);
EXPECT_EQ("", std::string(s));
#endif
}
TEST(StringViewTest, Comparisons2) {
absl::string_view abc("abcdefghijklmnopqrstuvwxyz");
EXPECT_EQ(abc, absl::string_view("abcdefghijklmnopqrstuvwxyz"));
EXPECT_EQ(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxyz")), 0);
EXPECT_LT(abc, absl::string_view("abcdefghijklmnopqrstuvwxzz"));
EXPECT_LT(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxzz")), 0);
EXPECT_GT(abc, absl::string_view("abcdefghijklmnopqrstuvwxyy"));
EXPECT_GT(abc.compare(absl::string_view("abcdefghijklmnopqrstuvwxyy")), 0);
absl::string_view digits("0123456789");
auto npos = absl::string_view::npos;
EXPECT_EQ(digits.compare(3, npos, absl::string_view("3456789")), 0);
EXPECT_EQ(digits.compare(3, 4, absl::string_view("3456")), 0);
EXPECT_EQ(digits.compare(10, 0, absl::string_view()), 0);
EXPECT_EQ(digits.compare(3, 4, absl::string_view("0123456789"), 3, 4),
0);
EXPECT_LT(digits.compare(3, 4, absl::string_view("0123456789"), 3, 5),
0);
EXPECT_LT(digits.compare(0, npos, absl::string_view("0123456789"), 3, 5),
0);
EXPECT_EQ(digits.compare(3, 4, "3456"), 0);
EXPECT_EQ(digits.compare(3, npos, "3456789"), 0);
EXPECT_EQ(digits.compare(10, 0, ""), 0);
EXPECT_EQ(digits.compare(3, 4, "0123456789", 3, 4), 0);
EXPECT_LT(digits.compare(3, 4, "0123456789", 3, 5), 0);
EXPECT_LT(digits.compare(0, npos, "0123456789", 3, 5), 0);
}
TEST(StringViewTest, At) {
absl::string_view abc = "abc";
EXPECT_EQ(abc.at(0), 'a');
EXPECT_EQ(abc.at(1), 'b');
EXPECT_EQ(abc.at(2), 'c');
#ifdef ABSL_HAVE_EXCEPTIONS
EXPECT_THROW((void)abc.at(3), std::out_of_range);
#else
ABSL_EXPECT_DEATH_IF_SUPPORTED((void)abc.at(3), "absl::string_view::at");
#endif
}
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
TEST(St |
2,552 | cpp | abseil/abseil-cpp | str_replace | absl/strings/str_replace.cc | absl/strings/str_replace_test.cc | #ifndef ABSL_STRINGS_STR_REPLACE_H_
#define ABSL_STRINGS_STR_REPLACE_H_
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
ABSL_MUST_USE_RESULT std::string StrReplaceAll(
absl::string_view s,
std::initializer_list<std::pair<absl::string_view, absl::string_view>>
replacements);
template <typename StrToStrMapping>
std::string StrReplaceAll(absl::string_view s,
const StrToStrMapping& replacements);
int StrReplaceAll(
std::initializer_list<std::pair<absl::string_view, absl::string_view>>
replacements,
absl::Nonnull<std::string*> target);
template <typename StrToStrMapping>
int StrReplaceAll(const StrToStrMapping& replacements,
absl::Nonnull<std::string*> target);
namespace strings_internal {
struct ViableSubstitution {
absl::string_view old;
absl::string_view replacement;
size_t offset;
ViableSubstitution(absl::string_view old_str,
absl::string_view replacement_str, size_t offset_val)
: old(old_str), replacement(replacement_str), offset(offset_val) {}
bool OccursBefore(const ViableSubstitution& y) const {
if (offset != y.offset) return offset < y.offset;
return old.size() > y.old.size();
}
};
template <typename StrToStrMapping>
std::vector<ViableSubstitution> FindSubstitutions(
absl::string_view s, const StrToStrMapping& replacements) {
std::vector<ViableSubstitution> subs;
subs.reserve(replacements.size());
for (const auto& rep : replacements) {
using std::get;
absl::string_view old(get<0>(rep));
size_t pos = s.find(old);
if (pos == s.npos) continue;
if (old.empty()) continue;
subs.emplace_back(old, get<1>(rep), pos);
size_t index = subs.size();
while (--index && subs[index - 1].OccursBefore(subs[index])) {
std::swap(subs[index], subs[index - 1]);
}
}
return subs;
}
int ApplySubstitutions(absl::string_view s,
absl::Nonnull<std::vector<ViableSubstitution>*> subs_ptr,
absl::Nonnull<std::string*> result_ptr);
}
template <typename StrToStrMapping>
std::string StrReplaceAll(absl::string_view s,
const StrToStrMapping& replacements) {
auto subs = strings_internal::FindSubstitutions(s, replacements);
std::string result;
result.reserve(s.size());
strings_internal::ApplySubstitutions(s, &subs, &result);
return result;
}
template <typename StrToStrMapping>
int StrReplaceAll(const StrToStrMapping& replacements,
absl::Nonnull<std::string*> target) {
auto subs = strings_internal::FindSubstitutions(*target, replacements);
if (subs.empty()) return 0;
std::string result;
result.reserve(target->size());
int substitutions =
strings_internal::ApplySubstitutions(*target, &subs, &result);
target->swap(result);
return substitutions;
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/str_replace.h"
#include <cstddef>
#include <initializer_list>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/config.h"
#include "absl/base/nullability.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
using FixedMapping =
std::initializer_list<std::pair<absl::string_view, absl::string_view>>;
int ApplySubstitutions(
absl::string_view s,
absl::Nonnull<std::vector<strings_internal::ViableSubstitution>*> subs_ptr,
absl::Nonnull<std::string*> result_ptr) {
auto& subs = *subs_ptr;
int substitutions = 0;
size_t pos = 0;
while (!subs.empty()) {
auto& sub = subs.back();
if (sub.offset >= pos) {
if (pos <= s.size()) {
StrAppend(result_ptr, s.substr(pos, sub.offset - pos), sub.replacement);
}
pos = sub.offset + sub.old.size();
substitutions += 1;
}
sub.offset = s.find(sub.old, pos);
if (sub.offset == s.npos) {
subs.pop_back();
} else {
size_t index = subs.size();
while (--index && subs[index - 1].OccursBefore(subs[index])) {
std::swap(subs[index], subs[index - 1]);
}
}
}
result_ptr->append(s.data() + pos, s.size() - pos);
return substitutions;
}
}
std::string StrReplaceAll(absl::string_view s,
strings_internal::FixedMapping replacements) {
return StrReplaceAll<strings_internal::FixedMapping>(s, replacements);
}
int StrReplaceAll(strings_internal::FixedMapping replacements,
absl::Nonnull<std::string*> target) {
return StrReplaceAll<strings_internal::FixedMapping>(replacements, target);
}
ABSL_NAMESPACE_END
} | #include "absl/strings/str_replace.h"
#include <list>
#include <map>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
TEST(StrReplaceAll, OneReplacement) {
std::string s;
s = absl::StrReplaceAll(s, {{"", ""}});
EXPECT_EQ(s, "");
s = absl::StrReplaceAll(s, {{"x", ""}});
EXPECT_EQ(s, "");
s = absl::StrReplaceAll(s, {{"", "y"}});
EXPECT_EQ(s, "");
s = absl::StrReplaceAll(s, {{"x", "y"}});
EXPECT_EQ(s, "");
s = absl::StrReplaceAll("abc", {{"", ""}});
EXPECT_EQ(s, "abc");
s = absl::StrReplaceAll("abc", {{"", "y"}});
EXPECT_EQ(s, "abc");
s = absl::StrReplaceAll("abc", {{"x", ""}});
EXPECT_EQ(s, "abc");
s = absl::StrReplaceAll("abc", {{"xyz", "123"}});
EXPECT_EQ(s, "abc");
s = absl::StrReplaceAll("abc", {{"abc", "xyz"}});
EXPECT_EQ(s, "xyz");
s = absl::StrReplaceAll("abc", {{"a", "x"}});
EXPECT_EQ(s, "xbc");
s = absl::StrReplaceAll("abc", {{"b", "x"}});
EXPECT_EQ(s, "axc");
s = absl::StrReplaceAll("abc", {{"c", "x"}});
EXPECT_EQ(s, "abx");
s = absl::StrReplaceAll("ababa", {{"a", "xxx"}});
EXPECT_EQ(s, "xxxbxxxbxxx");
s = absl::StrReplaceAll("ababa", {{"b", "xxx"}});
EXPECT_EQ(s, "axxxaxxxa");
s = absl::StrReplaceAll("aaabaaabaaa", {{"aaa", "x"}});
EXPECT_EQ(s, "xbxbx");
s = absl::StrReplaceAll("abbbabbba", {{"bbb", "x"}});
EXPECT_EQ(s, "axaxa");
s = absl::StrReplaceAll("aaa", {{"aa", "x"}});
EXPECT_EQ(s, "xa");
s = absl::StrReplaceAll("aaa", {{"aa", "a"}});
EXPECT_EQ(s, "aa");
}
TEST(StrReplaceAll, ManyReplacements) {
std::string s;
s = absl::StrReplaceAll("", {{"", ""}, {"x", ""}, {"", "y"}, {"x", "y"}});
EXPECT_EQ(s, "");
s = absl::StrReplaceAll("abc", {{"", ""}, {"", "y"}, {"x", ""}});
EXPECT_EQ(s, "abc");
s = absl::StrReplaceAll("abc", {{"a", "x"}, {"b", "y"}, {"c", "z"}});
EXPECT_EQ(s, "xyz");
s = absl::StrReplaceAll("zxy", {{"z", "x"}, {"x", "y"}, {"y", "z"}});
EXPECT_EQ(s, "xyz");
s = absl::StrReplaceAll("abc", {{"a", "x"}, {"ab", "xy"}, {"abc", "xyz"}});
EXPECT_EQ(s, "xyz");
s = absl::StrReplaceAll(
"Abc!", {{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc", "yz"}, {"c", "z"}});
EXPECT_EQ(s, "Ayz!");
s = absl::StrReplaceAll(
"Abc!",
{{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc!", "yz?"}, {"c!", "z;"}});
EXPECT_EQ(s, "Ayz?");
s = absl::StrReplaceAll("ababa", {{"a", "xxx"}, {"b", "XXXX"}});
EXPECT_EQ(s, "xxxXXXXxxxXXXXxxx");
s = absl::StrReplaceAll("aaa", {{"aa", "x"}, {"a", "X"}});
EXPECT_EQ(s, "xX");
s = absl::StrReplaceAll("aaa", {{"a", "X"}, {"aa", "x"}});
EXPECT_EQ(s, "xX");
s = absl::StrReplaceAll("the quick brown fox jumped over the lazy dogs",
{
{"brown", "box"},
{"dogs", "jugs"},
{"fox", "with"},
{"jumped", "five"},
{"over", "dozen"},
{"quick", "my"},
{"the", "pack"},
{"the lazy", "liquor"},
});
EXPECT_EQ(s, "pack my box with five dozen liquor jugs");
}
TEST(StrReplaceAll, ManyReplacementsInMap) {
std::map<const char *, const char *> replacements;
replacements["$who"] = "Bob";
replacements["$count"] = "5";
replacements["#Noun"] = "Apples";
std::string s = absl::StrReplaceAll("$who bought $count #Noun. Thanks $who!",
replacements);
EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
}
TEST(StrReplaceAll, ReplacementsInPlace) {
std::string s = std::string("$who bought $count #Noun. Thanks $who!");
int count;
count = absl::StrReplaceAll({{"$count", absl::StrCat(5)},
{"$who", "Bob"},
{"#Noun", "Apples"}}, &s);
EXPECT_EQ(count, 4);
EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
}
TEST(StrReplaceAll, ReplacementsInPlaceInMap) {
std::string s = std::string("$who bought $count #Noun. Thanks $who!");
std::map<absl::string_view, absl::string_view> replacements;
replacements["$who"] = "Bob";
replacements["$count"] = "5";
replacements["#Noun"] = "Apples";
int count;
count = absl::StrReplaceAll(replacements, &s);
EXPECT_EQ(count, 4);
EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
}
struct Cont {
Cont() = default;
explicit Cont(absl::string_view src) : data(src) {}
absl::string_view data;
};
template <int index>
absl::string_view get(const Cont& c) {
auto splitter = absl::StrSplit(c.data, ':');
auto it = splitter.begin();
for (int i = 0; i < index; ++i) ++it;
return *it;
}
TEST(StrReplaceAll, VariableNumber) {
std::string s;
{
std::vector<std::pair<std::string, std::string>> replacements;
s = "abc";
EXPECT_EQ(0, absl::StrReplaceAll(replacements, &s));
EXPECT_EQ("abc", s);
s = "abc";
replacements.push_back({"a", "A"});
EXPECT_EQ(1, absl::StrReplaceAll(replacements, &s));
EXPECT_EQ("Abc", s);
s = "abc";
replacements.push_back({"b", "B"});
EXPECT_EQ(2, absl::StrReplaceAll(replacements, &s));
EXPECT_EQ("ABc", s);
s = "abc";
replacements.push_back({"d", "D"});
EXPECT_EQ(2, absl::StrReplaceAll(replacements, &s));
EXPECT_EQ("ABc", s);
EXPECT_EQ("ABcABc", absl::StrReplaceAll("abcabc", replacements));
}
{
std::map<const char*, const char*> replacements;
replacements["aa"] = "x";
replacements["a"] = "X";
s = "aaa";
EXPECT_EQ(2, absl::StrReplaceAll(replacements, &s));
EXPECT_EQ("xX", s);
EXPECT_EQ("xxX", absl::StrReplaceAll("aaaaa", replacements));
}
{
std::list<std::pair<absl::string_view, absl::string_view>> replacements = {
{"a", "x"}, {"b", "y"}, {"c", "z"}};
std::string s = absl::StrReplaceAll("abc", replacements);
EXPECT_EQ(s, "xyz");
}
{
using X = std::tuple<absl::string_view, std::string, int>;
std::vector<X> replacements(3);
replacements[0] = X{"a", "x", 1};
replacements[1] = X{"b", "y", 0};
replacements[2] = X{"c", "z", -1};
std::string s = absl::StrReplaceAll("abc", replacements);
EXPECT_EQ(s, "xyz");
}
{
std::vector<Cont> replacements(3);
replacements[0] = Cont{"a:x"};
replacements[1] = Cont{"b:y"};
replacements[2] = Cont{"c:z"};
std::string s = absl::StrReplaceAll("abc", replacements);
EXPECT_EQ(s, "xyz");
}
}
TEST(StrReplaceAll, Inplace) {
std::string s;
int reps;
s = "";
reps = absl::StrReplaceAll({{"", ""}, {"x", ""}, {"", "y"}, {"x", "y"}}, &s);
EXPECT_EQ(reps, 0);
EXPECT_EQ(s, "");
s = "abc";
reps = absl::StrReplaceAll({{"", ""}, {"", "y"}, {"x", ""}}, &s);
EXPECT_EQ(reps, 0);
EXPECT_EQ(s, "abc");
s = "abc";
reps = absl::StrReplaceAll({{"a", "x"}, {"b", "y"}, {"c", "z"}}, &s);
EXPECT_EQ(reps, 3);
EXPECT_EQ(s, "xyz");
s = "zxy";
reps = absl::StrReplaceAll({{"z", "x"}, {"x", "y"}, {"y", "z"}}, &s);
EXPECT_EQ(reps, 3);
EXPECT_EQ(s, "xyz");
s = "abc";
reps = absl::StrReplaceAll({{"a", "x"}, {"ab", "xy"}, {"abc", "xyz"}}, &s);
EXPECT_EQ(reps, 1);
EXPECT_EQ(s, "xyz");
s = "Abc!";
reps = absl::StrReplaceAll(
{{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc", "yz"}, {"c", "z"}}, &s);
EXPECT_EQ(reps, 1);
EXPECT_EQ(s, "Ayz!");
s = "Abc!";
reps = absl::StrReplaceAll(
{{"a", "x"}, {"ab", "xy"}, {"b", "y"}, {"bc!", "yz?"}, {"c!", "z;"}}, &s);
EXPECT_EQ(reps, 1);
EXPECT_EQ(s, "Ayz?");
s = "ababa";
reps = absl::StrReplaceAll({{"a", "xxx"}, {"b", "XXXX"}}, &s);
EXPECT_EQ(reps, 5);
EXPECT_EQ(s, "xxxXXXXxxxXXXXxxx");
s = "aaa";
reps = absl::StrReplaceAll({{"aa", "x"}, {"a", "X"}}, &s);
EXPECT_EQ(reps, 2);
EXPECT_EQ(s, "xX");
s = "aaa";
reps = absl::StrReplaceAll({{"a", "X"}, {"aa", "x"}}, &s);
EXPECT_EQ(reps, 2);
EXPECT_EQ(s, "xX");
s = "the quick brown fox jumped over the lazy dogs";
reps = absl::StrReplaceAll(
{
{"brown", "box"},
{"dogs", "jugs"},
{"fox", "with"},
{"jumped", "five"},
{"over", "dozen"},
{"quick", "my"},
{"the", "pack"},
{"the lazy", "liquor"},
},
&s);
EXPECT_EQ(reps, 8);
EXPECT_EQ(s, "pack my box with five dozen liquor jugs");
} |
2,553 | cpp | abseil/abseil-cpp | charconv_bigint | absl/strings/internal/charconv_bigint.cc | absl/strings/internal/charconv_bigint_test.cc | #ifndef ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_
#define ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include "absl/base/config.h"
#include "absl/strings/ascii.h"
#include "absl/strings/internal/charconv_parse.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
constexpr int kMaxSmallPowerOfFive = 13;
constexpr int kMaxSmallPowerOfTen = 9;
ABSL_DLL extern const uint32_t
kFiveToNth[kMaxSmallPowerOfFive + 1];
ABSL_DLL extern const uint32_t kTenToNth[kMaxSmallPowerOfTen + 1];
template <int max_words>
class BigUnsigned {
public:
static_assert(max_words == 4 || max_words == 84,
"unsupported max_words value");
BigUnsigned() : size_(0), words_{} {}
explicit constexpr BigUnsigned(uint64_t v)
: size_((v >> 32) ? 2 : v ? 1 : 0),
words_{static_cast<uint32_t>(v & 0xffffffffu),
static_cast<uint32_t>(v >> 32)} {}
explicit BigUnsigned(absl::string_view sv) : size_(0), words_{} {
if (std::find_if_not(sv.begin(), sv.end(), ascii_isdigit) != sv.end() ||
sv.empty()) {
return;
}
int exponent_adjust =
ReadDigits(sv.data(), sv.data() + sv.size(), Digits10() + 1);
if (exponent_adjust > 0) {
MultiplyByTenToTheNth(exponent_adjust);
}
}
int ReadFloatMantissa(const ParsedFloat& fp, int significant_digits);
static constexpr int Digits10() {
return static_cast<uint64_t>(max_words) * 9975007 / 1035508;
}
void ShiftLeft(int count) {
if (count > 0) {
const int word_shift = count / 32;
if (word_shift >= max_words) {
SetToZero();
return;
}
size_ = (std::min)(size_ + word_shift, max_words);
count %= 32;
if (count == 0) {
#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(14, 0)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
#endif
std::copy_backward(words_, words_ + size_ - word_shift, words_ + size_);
#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(14, 0)
#pragma GCC diagnostic pop
#endif
} else {
for (int i = (std::min)(size_, max_words - 1); i > word_shift; --i) {
words_[i] = (words_[i - word_shift] << count) |
(words_[i - word_shift - 1] >> (32 - count));
}
words_[word_shift] = words_[0] << count;
if (size_ < max_words && words_[size_]) {
++size_;
}
}
std::fill_n(words_, word_shift, 0u);
}
}
void MultiplyBy(uint32_t v) {
if (size_ == 0 || v == 1) {
return;
}
if (v == 0) {
SetToZero();
return;
}
const uint64_t factor = v;
uint64_t window = 0;
for (int i = 0; i < size_; ++i) {
window += factor * words_[i];
words_[i] = window & 0xffffffff;
window >>= 32;
}
if (window && size_ < max_words) {
words_[size_] = window & 0xffffffff;
++size_;
}
}
void MultiplyBy(uint64_t v) {
uint32_t words[2];
words[0] = static_cast<uint32_t>(v);
words[1] = static_cast<uint32_t>(v >> 32);
if (words[1] == 0) {
MultiplyBy(words[0]);
} else {
MultiplyBy(2, words);
}
}
void MultiplyByFiveToTheNth(int n) {
while (n >= kMaxSmallPowerOfFive) {
MultiplyBy(kFiveToNth[kMaxSmallPowerOfFive]);
n -= kMaxSmallPowerOfFive;
}
if (n > 0) {
MultiplyBy(kFiveToNth[n]);
}
}
void MultiplyByTenToTheNth(int n) {
if (n > kMaxSmallPowerOfTen) {
MultiplyByFiveToTheNth(n);
ShiftLeft(n);
} else if (n > 0) {
MultiplyBy(kTenToNth[n]);
}
}
static BigUnsigned FiveToTheNth(int n);
template <int M>
void MultiplyBy(const BigUnsigned<M>& other) {
MultiplyBy(other.size(), other.words());
}
void SetToZero() {
std::fill_n(words_, size_, 0u);
size_ = 0;
}
uint32_t GetWord(int index) const {
if (index < 0 || index >= size_) {
return 0;
}
return words_[index];
}
std::string ToString() const;
int size() const { return size_; }
const uint32_t* words() const { return words_; }
private:
int ReadDigits(const char* begin, const char* end, int significant_digits);
void MultiplyStep(int original_size, const uint32_t* other_words,
int other_size, int step);
void MultiplyBy(int other_size, const uint32_t* other_words) {
const int original_size = size_;
const int first_step =
(std::min)(original_size + other_size - 2, max_words - 1);
for (int step = first_step; step >= 0; --step) {
MultiplyStep(original_size, other_words, other_size, step);
}
}
void AddWithCarry(int index, uint32_t value) {
if (value) {
while (index < max_words && value > 0) {
words_[index] += value;
if (value > words_[index]) {
value = 1;
++index;
} else {
value = 0;
}
}
size_ = (std::min)(max_words, (std::max)(index + 1, size_));
}
}
void AddWithCarry(int index, uint64_t value) {
if (value && index < max_words) {
uint32_t high = value >> 32;
uint32_t low = value & 0xffffffff;
words_[index] += low;
if (words_[index] < low) {
++high;
if (high == 0) {
AddWithCarry(index + 2, static_cast<uint32_t>(1));
return;
}
}
if (high > 0) {
AddWithCarry(index + 1, high);
} else {
size_ = (std::min)(max_words, (std::max)(index + 1, size_));
}
}
}
template <uint32_t divisor>
uint32_t DivMod() {
uint64_t accumulator = 0;
for (int i = size_ - 1; i >= 0; --i) {
accumulator <<= 32;
accumulator += words_[i];
words_[i] = static_cast<uint32_t>(accumulator / divisor);
accumulator = accumulator % divisor;
}
while (size_ > 0 && words_[size_ - 1] == 0) {
--size_;
}
return static_cast<uint32_t>(accumulator);
}
int size_;
uint32_t words_[max_words];
};
template <int N, int M>
int Compare(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
int limit = (std::max)(lhs.size(), rhs.size());
for (int i = limit - 1; i >= 0; --i) {
const uint32_t lhs_word = lhs.GetWord(i);
const uint32_t rhs_word = rhs.GetWord(i);
if (lhs_word < rhs_word) {
return -1;
} else if (lhs_word > rhs_word) {
return 1;
}
}
return 0;
}
template <int N, int M>
bool operator==(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
int limit = (std::max)(lhs.size(), rhs.size());
for (int i = 0; i < limit; ++i) {
if (lhs.GetWord(i) != rhs.GetWord(i)) {
return false;
}
}
return true;
}
template <int N, int M>
bool operator!=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
return !(lhs == rhs);
}
template <int N, int M>
bool operator<(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
return Compare(lhs, rhs) == -1;
}
template <int N, int M>
bool operator>(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
return rhs < lhs;
}
template <int N, int M>
bool operator<=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
return !(rhs < lhs);
}
template <int N, int M>
bool operator>=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
return !(lhs < rhs);
}
template <int N>
std::ostream& operator<<(std::ostream& os, const BigUnsigned<N>& num) {
return os << num.ToString();
}
extern template class BigUnsigned<4>;
extern template class BigUnsigned<84>;
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/charconv_bigint.h"
#include <algorithm>
#include <cassert>
#include <string>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
namespace {
constexpr int kLargePowerOfFiveStep = 27;
constexpr int kLargestPowerOfFiveIndex = 20;
const uint32_t kLargePowersOfFive[] = {
0xfa10079dU, 0x6765c793U,
0x97d9f649U, 0x6664242dU, 0x29939b14U, 0x29c30f10U,
0xc4f809c5U, 0x7bf3f22aU, 0x67bdae34U, 0xad340517U, 0x369d1b5fU, 0x10de1593U,
0x92b260d1U, 0x9efff7c7U, 0x81de0ec6U, 0xaeba5d56U, 0x410664a4U, 0x4f40737aU,
0x20d3846fU, 0x06d00f73U,
0xff1b172dU, 0x13a1d71cU, 0xefa07617U, 0x7f682d3dU, 0xff8c90c0U, 0x3f0131e7U,
0x3fdcb9feU, 0x917b0177U, 0x16c407a7U, 0x02c06b9dU,
0x960f7199U, 0x056667ecU, 0xe07aefd8U, 0x80f2b9ccU, 0x8273f5e3U, 0xeb9a214aU,
0x40b38005U, 0x0e477ad4U, 0x277d08e6U, 0xfa28b11eU, 0xd3f7d784U, 0x011c835bU,
0xf723d9d5U, 0x3282d3f3U, 0xe00857d1U, 0x69659d25U, 0x2cf117cfU, 0x24da6d07U,
0x954d1417U, 0x3e5d8cedU, 0x7a8bb766U, 0xfd785ae6U, 0x645436d2U, 0x40c78b34U,
0x94151217U, 0x0072e9f7U,
0x2b416aa1U, 0x7893c5a7U, 0xe37dc6d4U, 0x2bad2beaU, 0xf0fc846cU, 0x7575ae4bU,
0x62587b14U, 0x83b67a34U, 0x02110cdbU, 0xf7992f55U, 0x00deb022U, 0xa4a23becU,
0x8af5c5cdU, 0xb85b654fU, 0x818df38bU, 0x002e69d2U,
0x3518cbbdU, 0x20b0c15fU, 0x38756c2fU, 0xfb5dc3ddU, 0x22ad2d94U, 0xbf35a952U,
0xa699192aU, 0x9a613326U, 0xad2a9cedU, 0xd7f48968U, 0xe87dfb54U, 0xc8f05db6U,
0x5ef67531U, 0x31c1ab49U, 0xe202ac9fU, 0x9b2957b5U, 0xa143f6d3U, 0x0012bf07U,
0x8b971de9U, 0x21aba2e1U, 0x63944362U, 0x57172336U, 0xd9544225U, 0xfb534166U,
0x08c563eeU, 0x14640ee2U, 0x24e40d31U, 0x02b06537U, 0x03887f14U, 0x0285e533U,
0xb744ef26U, 0x8be3a6c4U, 0x266979b4U, 0x6761ece2U, 0xd9cb39e4U, 0xe67de319U,
0x0d39e796U, 0x00079250U,
0x260eb6e5U, 0xf414a796U, 0xee1a7491U, 0xdb9368ebU, 0xf50c105bU, 0x59157750U,
0x9ed2fb5cU, 0xf6e56d8bU, 0xeaee8d23U, 0x0f319f75U, 0x2aa134d6U, 0xac2908e9U,
0xd4413298U, 0x02f02a55U, 0x989d5a7aU, 0x70dde184U, 0xba8040a7U, 0x03200981U,
0xbe03b11cU, 0x3c1c2a18U, 0xd60427a1U, 0x00030ee0U,
0xce566d71U, 0xf1c4aa25U, 0x4e93ca53U, 0xa72283d0U, 0x551a73eaU, 0x3d0538e2U,
0x8da4303fU, 0x6a58de60U, 0x0e660221U, 0x49cf61a6U, 0x8d058fc1U, 0xb9d1a14cU,
0x4bab157dU, 0xc85c6932U, 0x518c8b9eU, 0x9b92b8d0U, 0x0d8a0e21U, 0xbd855df9U,
0xb3ea59a1U, 0x8da29289U, 0x4584d506U, 0x3752d80fU, 0xb72569c6U, 0x00013c33U,
0x190f354dU, 0x83695cfeU, 0xe5a4d0c7U, 0xb60fb7e8U, 0xee5bbcc4U, 0xb922054cU,
0xbb4f0d85U, 0x48394028U, 0x1d8957dbU, 0x0d7edb14U, 0x4ecc7587U, 0x505e9e02U,
0x4c87f36bU, 0x99e66bd6U, 0x44b9ed35U, 0x753037d4U, 0xe5fe5f27U, 0x2742c203U,
0x13b2ed2bU, 0xdc525d2cU, 0xe6fde59aU, 0x77ffb18fU, 0x13c5752cU, 0x08a84bccU,
0x859a4940U, 0x00007fb6U,
0x4f98cb39U, 0xa60edbbcU, 0x83b5872eU, 0xa501acffU, 0x9cc76f78U, 0xbadd4c73U,
0x43e989faU, 0xca7acf80U, 0x2e0c824fU, 0xb19f4ffcU, 0x092fd81cU, 0xe4eb645bU,
0xa1ff84c2U, 0x8a5a83baU, 0xa8a1fae9U, 0x1db43609U, 0xb0fed50bU, 0x0dd7d2bdU,
0x7d7accd8U, 0x91fa640fU, 0x37dcc6c5U, 0x1c417fd5U, 0xe4d462adU, 0xe8a43399U,
0x131bf9a5U, 0x8df54d29U, 0x36547dc1U, 0x00003395U,
0x5bd330f5U, 0x77d21967U, 0x1ac481b7U, 0x6be2f7ceU, 0x7f4792a9U, 0xe84c2c52U,
0x84592228U, 0x9dcaf829U, 0xdab44ce1U, 0x3d0c311bU, 0x532e297dU, 0x4704e8b4U,
0x9cdc32beU, 0x41e64d9dU, 0x7717bea1U, 0xa824c00dU, 0x08f50b27U, 0x0f198d77U,
0x49bbfdf0U, 0x025c6c69U, 0xd4e55cd3U, 0xf083602bU, 0xb9f0fecdU, 0xc0864aeaU,
0x9cb98681U, 0xaaf620e9U, 0xacb6df30U, 0x4faafe66U, 0x8af13c3bU, 0x000014d5U,
0x682bb941U, 0x89a9f297U, 0xcba75d7bU, 0x404217b1U, 0xb4e519e9U, 0xa1bc162bU,
0xf7f5910aU, 0x98715af5U, 0x2ff53e57U, 0xe3ef118cU, 0x490c4543U, 0xbc9b1734U,
0x2affbe4dU, 0x4cedcb4cU, 0xfb14e99eU, 0x35e34212U, 0xece39c24U, 0x07673ab3U,
0xe73115ddU, 0xd15d38e7U, 0x093eed3bU, 0xf8e7eac5U, 0x78a8cc80U, 0x25227aacU,
0x3f590551U, 0x413da1cbU, 0xdf643a55U, 0xab65ad44U, 0xd70b23d7U, 0xc672cd76U,
0x3364ea62U, 0x0000086aU,
0x22f163ddU, 0x23cf07acU, 0xbe2af6c2U, 0xf412f6f6U, 0xc3ff541eU, 0x6eeaf7deU,
0xa47047e0U, 0x408cda92U, 0x0f0eeb08U, 0x56deba9dU, 0xcfc6b090U, 0x8bbbdf04U,
0x3933cdb3U, 0x9e7bb67dU, 0x9f297035U, 0x38946244U, 0xee1d37bbU, 0xde898174U,
0x63f3559dU, 0x705b72fbU, 0x138d27d9U, 0xf8603a78U, 0x735eec44U, 0xe30987d5U,
0xc6d38070U, 0x9cfe548eU, 0x9ff01422U, 0x7c564aa8U, 0x91cc60baU, 0xcbc3565dU,
0x7550a50bU, 0x6909aeadU, 0x13234c45U, 0x00000366U,
0x17954989U, 0x3a7d7709U, 0x98042de5U, 0xa9011443U, 0x45e723c2U, 0x269ffd6fU,
0x58852a46U, 0xaaa1042aU, 0x2eee8153U, 0xb2b6c39eU, 0xaf845b65U, 0xf6c365d7U,
0xe4cffb2bU, 0xc840e90cU, 0xabea8abbU, 0x5c58f8d2U, 0x5c19fa3aU, 0x4670910aU,
0x4449f21cU, 0xefa645b3U, 0xcc427decU, 0x083c3d73U, 0x467cb413U, 0x6fe10ae4U,
0x3caffc72U, 0x9f8da55eU, 0x5e5c8ea7U, 0x490594bbU, 0xf0871b0bU, 0xdd89816cU,
0x8e931df8U, 0xe85ce1c9U, 0xcca090a5U, 0x575fa16bU, 0x6b9f106cU, 0x0000015fU,
0xee20d805U, 0x57bc3c07U, 0xcdea624eU, 0xd3f0f52dU, 0x9924b4f4U, 0xcf968640U,
0x61d41962U, 0xe87fb464U, 0xeaaf51c7U, 0x564c8b60U, 0xccda4028U, 0x529428bbU,
0x313a1fa8U, 0x96bd0f94U, 0x7a82ebaaU, 0xad99e7e9U, 0xf2668cd4U, 0xbe33a45eU,
0xfd0db669U, 0x87ee369fU, 0xd3ec20edU, 0x9c4d7db7U, 0xdedcf0d8U, 0x7cd2ca64U,
0xe25a6577U, 0x61003fd4U, 0xe56f54ccU, 0x10b7c748U, 0x40526e5eU, 0x7300ae87U,
0x5c439261U, 0x2c0ff469U, 0xbf723f12U, 0xb2379b61U, 0xbf59b4f5U, 0xc91b1c3fU,
0xf0046d27U, 0x0000008dU,
0x525c9e11U, 0xf4e0eb41U, 0xebb2895dU, 0x5da512f9U, 0x7d9b29d4U, 0x452f4edcU,
0x0b90bc37U, 0x341777cbU, 0x63d269afU, 0x1da77929U, 0x0a5c1826U, 0x77991898U,
0x5aeddf86U, 0xf853a877U, 0x538c31ccU, 0xe84896daU, 0xb7a0010bU, 0x17ef4de5U,
0xa52a2adeU, 0x029fd81cU, 0x987ce701U, 0x27fefd77U, 0xdb46c66fU, 0x5d301900U,
0x496998c0U, 0xbb6598b9U, 0x5eebb607U, 0xe547354aU, 0xdf4a2f7eU, 0xf06c4955U,
0x96242ffaU, 0x1775fb27U, 0xbecc58ceU, 0xebf2a53bU, 0x3eaad82aU, 0xf41137baU,
0x573e6fbaU, 0xfb4866b8U, 0x54002148U, 0x00000039U,
};
const uint32_t* LargePowerOfFiveData(int i) {
return kLargePowersOfFive + i * (i - 1);
}
int LargePowerOfFiveSize(int i) { return 2 * i; }
}
ABSL_DLL const uint32_t kFiveToNth[14] = {
1, 5, 25, 125, 625, 3125, 15625,
78125, 390625, 1953125, 9765625, 48828125, 244140625, 1220703125,
};
ABSL_DLL const uint32_t kTenToNth[10] = {
1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
};
template <int max_words>
int BigUnsigned<max_words>::ReadFloatMantissa(const ParsedFloat& fp,
int significant_digits) {
SetToZero();
assert(fp.type == FloatType::kNumber);
if (fp.subrange_begin == nullptr) {
words_[0] = fp.mantissa & 0xffffffffu;
words_[1] = fp.mantissa >> 32;
if (words_[1]) {
size_ = 2;
} else if (words_[0]) {
size_ = 1;
}
return fp.exponent;
}
int exponent_adjust =
ReadDigits(fp.subrange_begin, fp.subrange_end, significant_digits);
return fp.literal_exponent + exponent_adjust;
}
template <int max_words>
int BigUnsigned<max_words>::ReadDigits(const char* begin, const char* end,
int significant_digits) {
assert(significant_digits <= Digits10() + 1);
SetToZero();
bool after_decimal_point = false;
while (begin < end && *begin == '0') {
++begin;
}
int dropped_digits = 0;
while (begin < end && *std::prev(end) == '0') {
--end;
++dropped_digits;
}
if (begin < end && *std::prev(end) == '.') {
dropped_digits = 0;
--end;
while (begin < end && *std::prev(end) == '0') {
--end;
++dropped_digits;
}
} else if (dropped_digits) {
const char* dp = std::find(begin, end, '.');
if (dp != end) {
dropped_digits = 0;
}
}
int exponent_adjust = dropped_digits;
uint32_t queued = 0;
int digits_queued = 0;
for (; begin != end && significant_digits > 0; ++begin) {
if (*begin == '.') {
after_decimal_point = true;
continue;
}
if (after_decimal_point) {
--exponent_adjust;
}
char digit = (*begin - '0');
--significant_digits;
if (significant_digits == 0 && std::next(begin) != end &&
(digit == 0 || digit == 5)) {
++digit;
}
queued = 10 * queued + static_cast<uint32_t>(digit);
++digits_queued;
if (digits_queued == kMaxSmallPowerOfTen) {
MultiplyBy(kTenToNth[kMaxSmallPowerOfTen]);
AddWithCarry(0, queued);
queued = digits_queued = 0;
}
}
if (digits_queued) {
MultiplyBy(kTenToNth[digits_queued]);
AddWithCarry(0, queued);
}
if (begin < end && !after_decimal_point) {
const char* decimal_point = std::find(begin, end, '.');
exponent_adjust += (decimal_point - begin);
}
return exponent_adjust;
}
template <int max_words>
BigUnsigned<max_words> BigUnsigned<max_words>::FiveToTheNth(
int n) {
BigUnsigned answer(1u);
bool first_pass = true;
while (n >= kLargePowerOfFiveStep) {
int big_power =
std::min(n / kLargePowerOfFiveStep, kLargestPowerOfFiveIndex);
if (first_pass) {
std::copy_n(LargePowerOfFiveData(big_power),
LargePowerOfFiveSize(big_power), answer.words_);
answer.size_ = LargePowerOfFiveSize(big_power);
first_pass = false;
} else {
answer.MultiplyBy(LargePowerOfFiveSize(big_power),
LargePowerOfFiveData(big_power));
}
n -= kLargePowerOfFiveStep * big_power;
}
answer.MultiplyByFiveToTheNth(n);
return answer;
}
template <int max_words>
void BigUnsigned<max_words>::MultiplyStep(int original_size,
const uint32_t* other_words,
int other_size, int step) {
int this_i = std::min(original_size - 1, step);
int other_i = step - this_i;
uint64_t this_word = 0;
uint64_t carry = 0;
for (; this_i >= 0 && other_i < other_size; --this_i, ++other_i) {
uint64_t product = words_[this_i];
product *= other_words[other_i];
this_word += product;
carry += (this_word >> 32);
this_word &= 0xffffffff;
}
AddWithCarry(step + 1, carry);
words_[step] = this_word & 0xffffffff;
if (this_word > 0 && size_ <= step) {
size_ = step + 1;
}
}
template <int max_words>
std::string BigUnsigned<max_words>::ToString() const {
BigUnsigned<max_words> copy = *this;
std::string result;
while (copy.size() > 0) {
uint32_t next_digit = copy.DivMod<10>();
result.push_back('0' + static_cast<char>(next_digit));
}
if (result.empty()) {
result.push_back('0');
}
std::reverse(result.begin(), result.end());
return result;
}
template class BigUnsigned<4>;
template class BigUnsigned<84>;
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/charconv_bigint.h"
#include <string>
#include "gtest/gtest.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
TEST(BigUnsigned, ShiftLeft) {
{
BigUnsigned<4> num(3u);
num.ShiftLeft(100);
EXPECT_EQ(num, BigUnsigned<4>("3802951800684688204490109616128"));
}
{
BigUnsigned<4> a(15u);
BigUnsigned<4> b(7u);
BigUnsigned<4> c(3u);
a.ShiftLeft(125);
b.ShiftLeft(125);
c.ShiftLeft(125);
EXPECT_EQ(a, b);
EXPECT_NE(a, c);
}
{
BigUnsigned<84> a(15u);
BigUnsigned<84> b(7u);
BigUnsigned<84> c(3u);
a.ShiftLeft(84 * 32 - 3);
b.ShiftLeft(84 * 32 - 3);
c.ShiftLeft(84 * 32 - 3);
EXPECT_EQ(a, b);
EXPECT_NE(a, c);
}
{
const std::string seed = "1234567890123456789012345678901234567890";
BigUnsigned<84> a(seed);
for (int i = 1; i <= 84 * 32; ++i) {
a.ShiftLeft(1);
BigUnsigned<84> b(seed);
b.ShiftLeft(i);
EXPECT_EQ(a, b);
}
EXPECT_EQ(a, BigUnsigned<84>(0u));
}
{
const BigUnsigned<84> all_bits_one(
"1474444211396924248063325089479706787923460402125687709454567433186613"
"6228083464060749874845919674257665016359189106695900028098437021384227"
"3285029708032466536084583113729486015826557532750465299832071590813090"
"2011853039837649252477307070509704043541368002938784757296893793903797"
"8180292336310543540677175225040919704702800559606097685920595947397024"
"8303316808753252115729411497720357971050627997031988036134171378490368"
"6008000778741115399296162550786288457245180872759047016734959330367829"
"5235612397427686310674725251378116268607113017720538636924549612987647"
"5767411074510311386444547332882472126067840027882117834454260409440463"
"9345147252664893456053258463203120637089916304618696601333953616715125"
"2115882482473279040772264257431663818610405673876655957323083702713344"
"4201105427930770976052393421467136557055");
const BigUnsigned<84> zero(0u);
const BigUnsigned<84> one(1u);
for (int i = 1; i < 84*32; ++i) {
BigUnsigned<84> big_shifted = all_bits_one;
big_shifted.ShiftLeft(i);
EXPECT_GT(all_bits_one, big_shifted);
BigUnsigned<84> small_shifted = one;
small_shifted.ShiftLeft(i);
EXPECT_LT(one, small_shifted);
}
for (int no_op_shift : {0, -1, -84 * 32, std::numeric_limits<int>::min()}) {
BigUnsigned<84> big_shifted = all_bits_one;
big_shifted.ShiftLeft(no_op_shift);
EXPECT_EQ(all_bits_one, big_shifted);
BigUnsigned<84> small_shifted = one;
big_shifted.ShiftLeft(no_op_shift);
EXPECT_EQ(one, small_shifted);
}
for (int out_of_bounds_shift :
{84 * 32, 84 * 32 + 1, std::numeric_limits<int>::max()}) {
BigUnsigned<84> big_shifted = all_bits_one;
big_shifted.ShiftLeft(out_of_bounds_shift);
EXPECT_EQ(zero, big_shifted);
BigUnsigned<84> small_shifted = one;
small_shifted.ShiftLeft(out_of_bounds_shift);
EXPECT_EQ(zero, small_shifted);
}
}
}
TEST(BigUnsigned, MultiplyByUint32) {
const BigUnsigned<84> factorial_100(
"933262154439441526816992388562667004907159682643816214685929638952175999"
"932299156089414639761565182862536979208272237582511852109168640000000000"
"00000000000000");
BigUnsigned<84> a(1u);
for (uint32_t i = 1; i <= 100; ++i) {
a.MultiplyBy(i);
}
EXPECT_EQ(a, BigUnsigned<84>(factorial_100));
}
TEST(BigUnsigned, MultiplyByBigUnsigned) {
{
const BigUnsigned<84> factorial_200(
"7886578673647905035523632139321850622951359776871732632947425332443594"
"4996340334292030428401198462390417721213891963883025764279024263710506"
"1926624952829931113462857270763317237396988943922445621451664240254033"
"2918641312274282948532775242424075739032403212574055795686602260319041"
"7032406235170085879617892222278962370389737472000000000000000000000000"
"0000000000000000000000000");
BigUnsigned<84> evens(1u);
BigUnsigned<84> odds(1u);
for (uint32_t i = 1; i < 200; i += 2) {
odds.MultiplyBy(i);
evens.MultiplyBy(i + 1);
}
evens.MultiplyBy(odds);
EXPECT_EQ(evens, factorial_200);
}
{
for (int a = 0 ; a < 700; a += 25) {
SCOPED_TRACE(a);
BigUnsigned<84> a_value("3" + std::string(a, '0'));
for (int b = 0; b < (700 - a); b += 25) {
SCOPED_TRACE(b);
BigUnsigned<84> b_value("2" + std::string(b, '0'));
BigUnsigned<84> expected_product("6" + std::string(a + b, '0'));
b_value.MultiplyBy(a_value);
EXPECT_EQ(b_value, expected_product);
}
}
}
}
TEST(BigUnsigned, MultiplyByOverflow) {
{
BigUnsigned<4> all_bits_on("340282366920938463463374607431768211455");
all_bits_on.MultiplyBy(all_bits_on);
EXPECT_EQ(all_bits_on, BigUnsigned<4>(1u));
}
{
BigUnsigned<4> value_1("12345678901234567890123456789012345678");
BigUnsigned<4> value_2("12345678901234567890123456789012345678");
BigUnsigned<4> two_to_fiftieth(1u);
two_to_fiftieth.ShiftLeft(50);
value_1.ShiftLeft(50);
value_2.MultiplyBy(two_to_fiftieth);
EXPECT_EQ(value_1, value_2);
}
}
TEST(BigUnsigned, FiveToTheNth) {
{
for (int i = 0; i < 1160; ++i) {
SCOPED_TRACE(i);
BigUnsigned<84> value_1(123u);
BigUnsigned<84> value_2(123u);
value_1.MultiplyByFiveToTheNth(i);
for (int j = 0; j < i; j++) {
value_2.MultiplyBy(5u);
}
EXPECT_EQ(value_1, value_2);
}
}
{
for (int i = 0; i < 1160; ++i) {
SCOPED_TRACE(i);
BigUnsigned<84> value_1(1u);
value_1.MultiplyByFiveToTheNth(i);
BigUnsigned<84> value_2 = BigUnsigned<84>::FiveToTheNth(i);
EXPECT_EQ(value_1, value_2);
}
}
}
TEST(BigUnsigned, TenToTheNth) {
{
for (int i = 0; i < 800; ++i) {
SCOPED_TRACE(i);
BigUnsigned<84> value_1(123u);
BigUnsigned<84> value_2(123u);
value_1.MultiplyByTenToTheNth(i);
for (int j = 0; j < i; j++) {
value_2.MultiplyBy(10u);
}
EXPECT_EQ(value_1, value_2);
}
}
{
for (int i = 0; i < 200; ++i) {
SCOPED_TRACE(i);
BigUnsigned<84> value_1(135u);
value_1.MultiplyByTenToTheNth(i);
BigUnsigned<84> value_2("135" + std::string(i, '0'));
EXPECT_EQ(value_1, value_2);
}
}
}
}
ABSL_NAMESPACE_END
} |
2,554 | cpp | abseil/abseil-cpp | cordz_functions | absl/strings/internal/cordz_functions.cc | absl/strings/internal/cordz_functions_test.cc | #ifndef ABSL_STRINGS_INTERNAL_CORDZ_FUNCTIONS_H_
#define ABSL_STRINGS_INTERNAL_CORDZ_FUNCTIONS_H_
#include <stdint.h>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/optimization.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
int32_t get_cordz_mean_interval();
void set_cordz_mean_interval(int32_t mean_interval);
#if defined(ABSL_INTERNAL_CORDZ_ENABLED)
#error ABSL_INTERNAL_CORDZ_ENABLED cannot be set directly
#elif defined(__linux__) && defined(ABSL_HAVE_THREAD_LOCAL)
#define ABSL_INTERNAL_CORDZ_ENABLED 1
#endif
#ifdef ABSL_INTERNAL_CORDZ_ENABLED
struct SamplingState {
int64_t next_sample;
int64_t sample_stride;
};
ABSL_CONST_INIT extern thread_local SamplingState cordz_next_sample;
int64_t cordz_should_profile_slow(SamplingState& state);
inline int64_t cordz_should_profile() {
if (ABSL_PREDICT_TRUE(cordz_next_sample.next_sample > 1)) {
cordz_next_sample.next_sample--;
return 0;
}
return cordz_should_profile_slow(cordz_next_sample);
}
void cordz_set_next_sample_for_testing(int64_t next_sample);
#else
inline int64_t cordz_should_profile() { return 0; }
inline void cordz_set_next_sample_for_testing(int64_t) {}
#endif
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/cordz_functions.h"
#include <atomic>
#include <cmath>
#include <limits>
#include <random>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/profiling/internal/exponential_biased.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
std::atomic<int> g_cordz_mean_interval(50000);
}
#ifdef ABSL_INTERNAL_CORDZ_ENABLED
static constexpr int64_t kInitCordzNextSample = -1;
ABSL_CONST_INIT thread_local SamplingState cordz_next_sample = {
kInitCordzNextSample, 1};
constexpr int64_t kIntervalIfDisabled = 1 << 16;
ABSL_ATTRIBUTE_NOINLINE int64_t
cordz_should_profile_slow(SamplingState& state) {
thread_local absl::profiling_internal::ExponentialBiased
exponential_biased_generator;
int32_t mean_interval = get_cordz_mean_interval();
if (mean_interval <= 0) {
state = {kIntervalIfDisabled, kIntervalIfDisabled};
return 0;
}
if (mean_interval == 1) {
state = {1, 1};
return 1;
}
if (cordz_next_sample.next_sample <= 0) {
const bool initialized =
cordz_next_sample.next_sample != kInitCordzNextSample;
auto old_stride = state.sample_stride;
auto stride = exponential_biased_generator.GetStride(mean_interval);
state = {stride, stride};
bool should_sample = initialized || cordz_should_profile() > 0;
return should_sample ? old_stride : 0;
}
--state.next_sample;
return 0;
}
void cordz_set_next_sample_for_testing(int64_t next_sample) {
cordz_next_sample = {next_sample, next_sample};
}
#endif
int32_t get_cordz_mean_interval() {
return g_cordz_mean_interval.load(std::memory_order_acquire);
}
void set_cordz_mean_interval(int32_t mean_interval) {
g_cordz_mean_interval.store(mean_interval, std::memory_order_release);
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/cordz_functions.h"
#include <thread>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::Eq;
using ::testing::Ge;
using ::testing::Le;
TEST(CordzFunctionsTest, SampleRate) {
int32_t orig_sample_rate = get_cordz_mean_interval();
int32_t expected_sample_rate = 123;
set_cordz_mean_interval(expected_sample_rate);
EXPECT_THAT(get_cordz_mean_interval(), Eq(expected_sample_rate));
set_cordz_mean_interval(orig_sample_rate);
}
#ifdef ABSL_INTERNAL_CORDZ_ENABLED
TEST(CordzFunctionsTest, ShouldProfileDisable) {
int32_t orig_sample_rate = get_cordz_mean_interval();
set_cordz_mean_interval(0);
cordz_set_next_sample_for_testing(0);
EXPECT_EQ(cordz_should_profile(), 0);
EXPECT_THAT(cordz_next_sample.next_sample, Eq(1 << 16));
set_cordz_mean_interval(orig_sample_rate);
}
TEST(CordzFunctionsTest, ShouldProfileAlways) {
int32_t orig_sample_rate = get_cordz_mean_interval();
set_cordz_mean_interval(1);
cordz_set_next_sample_for_testing(1);
EXPECT_GT(cordz_should_profile(), 0);
EXPECT_THAT(cordz_next_sample.next_sample, Le(1));
set_cordz_mean_interval(orig_sample_rate);
}
TEST(CordzFunctionsTest, DoesNotAlwaysSampleFirstCord) {
set_cordz_mean_interval(10000);
int tries = 0;
bool sampled = false;
do {
++tries;
ASSERT_THAT(tries, Le(1000));
std::thread thread([&sampled] { sampled = cordz_should_profile() > 0; });
thread.join();
} while (sampled);
}
TEST(CordzFunctionsTest, ShouldProfileRate) {
static constexpr int kDesiredMeanInterval = 1000;
static constexpr int kSamples = 10000;
int32_t orig_sample_rate = get_cordz_mean_interval();
set_cordz_mean_interval(kDesiredMeanInterval);
int64_t sum_of_intervals = 0;
for (int i = 0; i < kSamples; i++) {
cordz_set_next_sample_for_testing(0);
cordz_should_profile();
sum_of_intervals += cordz_next_sample.next_sample;
}
EXPECT_THAT(sum_of_intervals, Ge(9396115));
EXPECT_THAT(sum_of_intervals, Le(10618100));
set_cordz_mean_interval(orig_sample_rate);
}
#else
TEST(CordzFunctionsTest, ShouldProfileDisabled) {
int32_t orig_sample_rate = get_cordz_mean_interval();
set_cordz_mean_interval(1);
cordz_set_next_sample_for_testing(0);
EXPECT_FALSE(cordz_should_profile());
set_cordz_mean_interval(orig_sample_rate);
}
#endif
}
}
ABSL_NAMESPACE_END
} |
2,555 | cpp | abseil/abseil-cpp | ostringstream | absl/strings/internal/ostringstream.cc | absl/strings/internal/ostringstream_test.cc | #ifndef ABSL_STRINGS_INTERNAL_OSTRINGSTREAM_H_
#define ABSL_STRINGS_INTERNAL_OSTRINGSTREAM_H_
#include <cassert>
#include <ios>
#include <ostream>
#include <streambuf>
#include <string>
#include <utility>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
class OStringStream final : public std::ostream {
public:
explicit OStringStream(std::string* str)
: std::ostream(&buf_), buf_(str) {}
OStringStream(OStringStream&& that)
: std::ostream(std::move(static_cast<std::ostream&>(that))),
buf_(that.buf_) {
rdbuf(&buf_);
}
OStringStream& operator=(OStringStream&& that) {
std::ostream::operator=(std::move(static_cast<std::ostream&>(that)));
buf_ = that.buf_;
rdbuf(&buf_);
return *this;
}
std::string* str() { return buf_.str(); }
const std::string* str() const { return buf_.str(); }
void str(std::string* str) { buf_.str(str); }
private:
class Streambuf final : public std::streambuf {
public:
explicit Streambuf(std::string* str) : str_(str) {}
Streambuf(const Streambuf&) = default;
Streambuf& operator=(const Streambuf&) = default;
std::string* str() { return str_; }
const std::string* str() const { return str_; }
void str(std::string* str) { str_ = str; }
protected:
int_type overflow(int c) override;
std::streamsize xsputn(const char* s, std::streamsize n) override;
private:
std::string* str_;
} buf_;
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/ostringstream.h"
#include <cassert>
#include <cstddef>
#include <ios>
#include <streambuf>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
OStringStream::Streambuf::int_type OStringStream::Streambuf::overflow(int c) {
assert(str_);
if (!std::streambuf::traits_type::eq_int_type(
c, std::streambuf::traits_type::eof()))
str_->push_back(static_cast<char>(c));
return 1;
}
std::streamsize OStringStream::Streambuf::xsputn(const char* s,
std::streamsize n) {
assert(str_);
str_->append(s, static_cast<size_t>(n));
return n;
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/ostringstream.h"
#include <ios>
#include <memory>
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include "gtest/gtest.h"
namespace {
TEST(OStringStream, IsOStream) {
static_assert(
std::is_base_of<std::ostream, absl::strings_internal::OStringStream>(),
"");
}
TEST(OStringStream, ConstructNullptr) {
absl::strings_internal::OStringStream strm(nullptr);
EXPECT_EQ(nullptr, strm.str());
}
TEST(OStringStream, ConstructStr) {
std::string s = "abc";
{
absl::strings_internal::OStringStream strm(&s);
EXPECT_EQ(&s, strm.str());
}
EXPECT_EQ("abc", s);
}
TEST(OStringStream, Destroy) {
std::unique_ptr<std::string> s(new std::string);
absl::strings_internal::OStringStream strm(s.get());
s.reset();
}
TEST(OStringStream, MoveConstruct) {
std::string s = "abc";
{
absl::strings_internal::OStringStream strm1(&s);
strm1 << std::hex << 16;
EXPECT_EQ(&s, strm1.str());
absl::strings_internal::OStringStream strm2(std::move(strm1));
strm2 << 16;
EXPECT_EQ(&s, strm2.str());
}
EXPECT_EQ("abc1010", s);
}
TEST(OStringStream, MoveAssign) {
std::string s = "abc";
{
absl::strings_internal::OStringStream strm1(&s);
strm1 << std::hex << 16;
EXPECT_EQ(&s, strm1.str());
absl::strings_internal::OStringStream strm2(nullptr);
strm2 = std::move(strm1);
strm2 << 16;
EXPECT_EQ(&s, strm2.str());
}
EXPECT_EQ("abc1010", s);
}
TEST(OStringStream, Str) {
std::string s1;
absl::strings_internal::OStringStream strm(&s1);
const absl::strings_internal::OStringStream& c_strm(strm);
static_assert(std::is_same<decltype(strm.str()), std::string*>(), "");
static_assert(std::is_same<decltype(c_strm.str()), const std::string*>(), "");
EXPECT_EQ(&s1, strm.str());
EXPECT_EQ(&s1, c_strm.str());
strm.str(&s1);
EXPECT_EQ(&s1, strm.str());
EXPECT_EQ(&s1, c_strm.str());
std::string s2;
strm.str(&s2);
EXPECT_EQ(&s2, strm.str());
EXPECT_EQ(&s2, c_strm.str());
strm.str(nullptr);
EXPECT_EQ(nullptr, strm.str());
EXPECT_EQ(nullptr, c_strm.str());
}
TEST(OStreamStream, WriteToLValue) {
std::string s = "abc";
{
absl::strings_internal::OStringStream strm(&s);
EXPECT_EQ("abc", s);
strm << "";
EXPECT_EQ("abc", s);
strm << 42;
EXPECT_EQ("abc42", s);
strm << 'x' << 'y';
EXPECT_EQ("abc42xy", s);
}
EXPECT_EQ("abc42xy", s);
}
TEST(OStreamStream, WriteToRValue) {
std::string s = "abc";
absl::strings_internal::OStringStream(&s) << "";
EXPECT_EQ("abc", s);
absl::strings_internal::OStringStream(&s) << 42;
EXPECT_EQ("abc42", s);
absl::strings_internal::OStringStream(&s) << 'x' << 'y';
EXPECT_EQ("abc42xy", s);
}
} |
2,556 | cpp | abseil/abseil-cpp | cordz_info | absl/strings/internal/cordz_info.cc | absl/strings/internal/cordz_info_test.cc | #ifndef ABSL_STRINGS_INTERNAL_CORDZ_INFO_H_
#define ABSL_STRINGS_INTERNAL_CORDZ_INFO_H_
#include <atomic>
#include <cstdint>
#include <functional>
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/internal/spinlock.h"
#include "absl/base/thread_annotations.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cordz_functions.h"
#include "absl/strings/internal/cordz_handle.h"
#include "absl/strings/internal/cordz_statistics.h"
#include "absl/strings/internal/cordz_update_tracker.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
class ABSL_LOCKABLE CordzInfo : public CordzHandle {
public:
using MethodIdentifier = CordzUpdateTracker::MethodIdentifier;
static void TrackCord(InlineData& cord, MethodIdentifier method,
int64_t sampling_stride);
static void TrackCord(InlineData& cord, const InlineData& src,
MethodIdentifier method);
static void MaybeTrackCord(InlineData& cord, MethodIdentifier method);
static void MaybeTrackCord(InlineData& cord, const InlineData& src,
MethodIdentifier method);
void Untrack();
static void MaybeUntrackCord(CordzInfo* info);
CordzInfo() = delete;
CordzInfo(const CordzInfo&) = delete;
CordzInfo& operator=(const CordzInfo&) = delete;
static CordzInfo* Head(const CordzSnapshot& snapshot)
ABSL_NO_THREAD_SAFETY_ANALYSIS;
CordzInfo* Next(const CordzSnapshot& snapshot) const
ABSL_NO_THREAD_SAFETY_ANALYSIS;
void Lock(MethodIdentifier method) ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex_);
void Unlock() ABSL_UNLOCK_FUNCTION(mutex_);
void AssertHeld() ABSL_ASSERT_EXCLUSIVE_LOCK(mutex_);
void SetCordRep(CordRep* rep);
CordRep* RefCordRep() const ABSL_LOCKS_EXCLUDED(mutex_);
CordRep* GetCordRepForTesting() const ABSL_NO_THREAD_SAFETY_ANALYSIS {
return rep_;
}
void SetCordRepForTesting(CordRep* rep) ABSL_NO_THREAD_SAFETY_ANALYSIS {
rep_ = rep;
}
absl::Span<void* const> GetStack() const;
absl::Span<void* const> GetParentStack() const;
CordzStatistics GetCordzStatistics() const;
int64_t sampling_stride() const { return sampling_stride_; }
private:
using SpinLock = absl::base_internal::SpinLock;
using SpinLockHolder = ::absl::base_internal::SpinLockHolder;
struct List {
constexpr explicit List(absl::ConstInitType)
: mutex(absl::kConstInit,
absl::base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL) {}
SpinLock mutex;
std::atomic<CordzInfo*> head ABSL_GUARDED_BY(mutex){nullptr};
};
static constexpr size_t kMaxStackDepth = 64;
explicit CordzInfo(CordRep* rep, const CordzInfo* src,
MethodIdentifier method, int64_t weight);
~CordzInfo() override;
void UnsafeSetCordRep(CordRep* rep) ABSL_NO_THREAD_SAFETY_ANALYSIS;
void Track();
static MethodIdentifier GetParentMethod(const CordzInfo* src);
static size_t FillParentStack(const CordzInfo* src, void** stack);
void ODRCheck() const {
#ifndef NDEBUG
ABSL_RAW_CHECK(list_ == &global_list_, "ODR violation in Cord");
#endif
}
static void MaybeTrackCordImpl(InlineData& cord, const InlineData& src,
MethodIdentifier method);
ABSL_CONST_INIT static List global_list_;
List* const list_ = &global_list_;
std::atomic<CordzInfo*> ci_prev_{nullptr};
std::atomic<CordzInfo*> ci_next_{nullptr};
mutable absl::Mutex mutex_;
CordRep* rep_ ABSL_GUARDED_BY(mutex_);
void* stack_[kMaxStackDepth];
void* parent_stack_[kMaxStackDepth];
const size_t stack_depth_;
const size_t parent_stack_depth_;
const MethodIdentifier method_;
const MethodIdentifier parent_method_;
CordzUpdateTracker update_tracker_;
const absl::Time create_time_;
const int64_t sampling_stride_;
};
inline ABSL_ATTRIBUTE_ALWAYS_INLINE void CordzInfo::MaybeTrackCord(
InlineData& cord, MethodIdentifier method) {
auto stride = cordz_should_profile();
if (ABSL_PREDICT_FALSE(stride > 0)) {
TrackCord(cord, method, stride);
}
}
inline ABSL_ATTRIBUTE_ALWAYS_INLINE void CordzInfo::MaybeTrackCord(
InlineData& cord, const InlineData& src, MethodIdentifier method) {
if (ABSL_PREDICT_FALSE(InlineData::is_either_profiled(cord, src))) {
MaybeTrackCordImpl(cord, src, method);
}
}
inline ABSL_ATTRIBUTE_ALWAYS_INLINE void CordzInfo::MaybeUntrackCord(
CordzInfo* info) {
if (ABSL_PREDICT_FALSE(info)) {
info->Untrack();
}
}
inline void CordzInfo::AssertHeld() ABSL_ASSERT_EXCLUSIVE_LOCK(mutex_) {
#ifndef NDEBUG
mutex_.AssertHeld();
#endif
}
inline void CordzInfo::SetCordRep(CordRep* rep) {
AssertHeld();
rep_ = rep;
}
inline void CordzInfo::UnsafeSetCordRep(CordRep* rep) { rep_ = rep; }
inline CordRep* CordzInfo::RefCordRep() const ABSL_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
return rep_ ? CordRep::Ref(rep_) : nullptr;
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/cordz_info.h"
#include <cstdint>
#include "absl/base/config.h"
#include "absl/base/internal/spinlock.h"
#include "absl/container/inlined_vector.h"
#include "absl/debugging/stacktrace.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_crc.h"
#include "absl/strings/internal/cordz_handle.h"
#include "absl/strings/internal/cordz_statistics.h"
#include "absl/strings/internal/cordz_update_tracker.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
constexpr size_t CordzInfo::kMaxStackDepth;
#endif
ABSL_CONST_INIT CordzInfo::List CordzInfo::global_list_{absl::kConstInit};
namespace {
class CordRepAnalyzer {
public:
explicit CordRepAnalyzer(CordzStatistics& statistics)
: statistics_(statistics) {}
void AnalyzeCordRep(const CordRep* rep) {
ABSL_ASSERT(rep != nullptr);
size_t refcount = rep->refcount.Get();
RepRef repref{rep, (refcount > 1) ? refcount - 1 : 1};
if (repref.tag() == CRC) {
statistics_.node_count++;
statistics_.node_counts.crc++;
memory_usage_.Add(sizeof(CordRepCrc), repref.refcount);
repref = repref.Child(repref.rep->crc()->child);
}
repref = CountLinearReps(repref, memory_usage_);
switch (repref.tag()) {
case CordRepKind::BTREE:
AnalyzeBtree(repref);
break;
default:
ABSL_ASSERT(repref.tag() == CordRepKind::UNUSED_0);
break;
}
statistics_.estimated_memory_usage += memory_usage_.total;
statistics_.estimated_fair_share_memory_usage +=
static_cast<size_t>(memory_usage_.fair_share);
}
private:
struct RepRef {
const CordRep* rep;
size_t refcount;
RepRef Child(const CordRep* child) const {
if (child == nullptr) return RepRef{nullptr, 0};
return RepRef{child, refcount * child->refcount.Get()};
}
constexpr CordRepKind tag() const {
ABSL_ASSERT(rep == nullptr || rep->tag != CordRepKind::UNUSED_0);
return rep ? static_cast<CordRepKind>(rep->tag) : CordRepKind::UNUSED_0;
}
};
struct MemoryUsage {
size_t total = 0;
double fair_share = 0.0;
void Add(size_t size, size_t refcount) {
total += size;
fair_share += static_cast<double>(size) / refcount;
}
};
void CountFlat(size_t size) {
statistics_.node_count++;
statistics_.node_counts.flat++;
if (size <= 64) {
statistics_.node_counts.flat_64++;
} else if (size <= 128) {
statistics_.node_counts.flat_128++;
} else if (size <= 256) {
statistics_.node_counts.flat_256++;
} else if (size <= 512) {
statistics_.node_counts.flat_512++;
} else if (size <= 1024) {
statistics_.node_counts.flat_1k++;
}
}
RepRef CountLinearReps(RepRef rep, MemoryUsage& memory_usage) {
while (rep.tag() == SUBSTRING) {
statistics_.node_count++;
statistics_.node_counts.substring++;
memory_usage.Add(sizeof(CordRepSubstring), rep.refcount);
rep = rep.Child(rep.rep->substring()->child);
}
if (rep.tag() >= FLAT) {
size_t size = rep.rep->flat()->AllocatedSize();
CountFlat(size);
memory_usage.Add(size, rep.refcount);
return RepRef{nullptr, 0};
}
if (rep.tag() == EXTERNAL) {
statistics_.node_count++;
statistics_.node_counts.external++;
size_t size = rep.rep->length + sizeof(CordRepExternalImpl<intptr_t>);
memory_usage.Add(size, rep.refcount);
return RepRef{nullptr, 0};
}
return rep;
}
void AnalyzeBtree(RepRef rep) {
statistics_.node_count++;
statistics_.node_counts.btree++;
memory_usage_.Add(sizeof(CordRepBtree), rep.refcount);
const CordRepBtree* tree = rep.rep->btree();
if (tree->height() > 0) {
for (CordRep* edge : tree->Edges()) {
AnalyzeBtree(rep.Child(edge));
}
} else {
for (CordRep* edge : tree->Edges()) {
CountLinearReps(rep.Child(edge), memory_usage_);
}
}
}
CordzStatistics& statistics_;
MemoryUsage memory_usage_;
};
}
CordzInfo* CordzInfo::Head(const CordzSnapshot& snapshot) {
ABSL_ASSERT(snapshot.is_snapshot());
CordzInfo* head = global_list_.head.load(std::memory_order_acquire);
ABSL_ASSERT(snapshot.DiagnosticsHandleIsSafeToInspect(head));
return head;
}
CordzInfo* CordzInfo::Next(const CordzSnapshot& snapshot) const {
ABSL_ASSERT(snapshot.is_snapshot());
CordzInfo* next = ci_next_.load(std::memory_order_acquire);
ABSL_ASSERT(snapshot.DiagnosticsHandleIsSafeToInspect(this));
ABSL_ASSERT(snapshot.DiagnosticsHandleIsSafeToInspect(next));
return next;
}
void CordzInfo::TrackCord(InlineData& cord, MethodIdentifier method,
int64_t sampling_stride) {
assert(cord.is_tree());
assert(!cord.is_profiled());
CordzInfo* cordz_info =
new CordzInfo(cord.as_tree(), nullptr, method, sampling_stride);
cord.set_cordz_info(cordz_info);
cordz_info->Track();
}
void CordzInfo::TrackCord(InlineData& cord, const InlineData& src,
MethodIdentifier method) {
assert(cord.is_tree());
assert(src.is_tree());
CordzInfo* cordz_info = cord.cordz_info();
if (cordz_info != nullptr) cordz_info->Untrack();
cordz_info = new CordzInfo(cord.as_tree(), src.cordz_info(), method,
src.cordz_info()->sampling_stride());
cord.set_cordz_info(cordz_info);
cordz_info->Track();
}
void CordzInfo::MaybeTrackCordImpl(InlineData& cord, const InlineData& src,
MethodIdentifier method) {
if (src.is_profiled()) {
TrackCord(cord, src, method);
} else if (cord.is_profiled()) {
cord.cordz_info()->Untrack();
cord.clear_cordz_info();
}
}
CordzInfo::MethodIdentifier CordzInfo::GetParentMethod(const CordzInfo* src) {
if (src == nullptr) return MethodIdentifier::kUnknown;
return src->parent_method_ != MethodIdentifier::kUnknown ? src->parent_method_
: src->method_;
}
size_t CordzInfo::FillParentStack(const CordzInfo* src, void** stack) {
assert(stack);
if (src == nullptr) return 0;
if (src->parent_stack_depth_) {
memcpy(stack, src->parent_stack_, src->parent_stack_depth_ * sizeof(void*));
return src->parent_stack_depth_;
}
memcpy(stack, src->stack_, src->stack_depth_ * sizeof(void*));
return src->stack_depth_;
}
CordzInfo::CordzInfo(CordRep* rep, const CordzInfo* src,
MethodIdentifier method, int64_t sampling_stride)
: rep_(rep),
stack_depth_(
static_cast<size_t>(absl::GetStackTrace(stack_,
kMaxStackDepth,
1))),
parent_stack_depth_(FillParentStack(src, parent_stack_)),
method_(method),
parent_method_(GetParentMethod(src)),
create_time_(absl::Now()),
sampling_stride_(sampling_stride) {
update_tracker_.LossyAdd(method);
if (src) {
update_tracker_.LossyAdd(src->update_tracker_);
}
}
CordzInfo::~CordzInfo() {
if (ABSL_PREDICT_FALSE(rep_)) {
CordRep::Unref(rep_);
}
}
void CordzInfo::Track() {
SpinLockHolder l(&list_->mutex);
CordzInfo* const head = list_->head.load(std::memory_order_acquire);
if (head != nullptr) {
head->ci_prev_.store(this, std::memory_order_release);
}
ci_next_.store(head, std::memory_order_release);
list_->head.store(this, std::memory_order_release);
}
void CordzInfo::Untrack() {
ODRCheck();
{
SpinLockHolder l(&list_->mutex);
CordzInfo* const head = list_->head.load(std::memory_order_acquire);
CordzInfo* const next = ci_next_.load(std::memory_order_acquire);
CordzInfo* const prev = ci_prev_.load(std::memory_order_acquire);
if (next) {
ABSL_ASSERT(next->ci_prev_.load(std::memory_order_acquire) == this);
next->ci_prev_.store(prev, std::memory_order_release);
}
if (prev) {
ABSL_ASSERT(head != this);
ABSL_ASSERT(prev->ci_next_.load(std::memory_order_acquire) == this);
prev->ci_next_.store(next, std::memory_order_release);
} else {
ABSL_ASSERT(head == this);
list_->head.store(next, std::memory_order_release);
}
}
if (SafeToDelete()) {
UnsafeSetCordRep(nullptr);
delete this;
return;
}
{
absl::MutexLock lock(&mutex_);
if (rep_) CordRep::Ref(rep_);
}
CordzHandle::Delete(this);
}
void CordzInfo::Lock(MethodIdentifier method)
ABSL_EXCLUSIVE_LOCK_FUNCTION(mutex_) {
mutex_.Lock();
update_tracker_.LossyAdd(method);
assert(rep_);
}
void CordzInfo::Unlock() ABSL_UNLOCK_FUNCTION(mutex_) {
bool tracked = rep_ != nullptr;
mutex_.Unlock();
if (!tracked) {
Untrack();
}
}
absl::Span<void* const> CordzInfo::GetStack() const {
return absl::MakeConstSpan(stack_, stack_depth_);
}
absl::Span<void* const> CordzInfo::GetParentStack() const {
return absl::MakeConstSpan(parent_stack_, parent_stack_depth_);
}
CordzStatistics CordzInfo::GetCordzStatistics() const {
CordzStatistics stats;
stats.method = method_;
stats.parent_method = parent_method_;
stats.update_tracker = update_tracker_;
if (CordRep* rep = RefCordRep()) {
stats.size = rep->length;
CordRepAnalyzer analyzer(stats);
analyzer.AnalyzeCordRep(rep);
CordRep::Unref(rep);
}
return stats;
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/cordz_info.h"
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/debugging/stacktrace.h"
#include "absl/debugging/symbolize.h"
#include "absl/strings/cordz_test_helpers.h"
#include "absl/strings/internal/cord_rep_flat.h"
#include "absl/strings/internal/cordz_handle.h"
#include "absl/strings/internal/cordz_statistics.h"
#include "absl/strings/internal/cordz_update_tracker.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Ne;
using ::testing::SizeIs;
auto constexpr kUnknownMethod = CordzUpdateTracker::kUnknown;
auto constexpr kTrackCordMethod = CordzUpdateTracker::kConstructorString;
auto constexpr kChildMethod = CordzUpdateTracker::kConstructorCord;
auto constexpr kUpdateMethod = CordzUpdateTracker::kAppendString;
std::vector<const CordzHandle*> DeleteQueue() {
return CordzHandle::DiagnosticsGetDeleteQueue();
}
std::string FormatStack(absl::Span<void* const> raw_stack) {
static constexpr size_t buf_size = 1 << 14;
std::unique_ptr<char[]> buf(new char[buf_size]);
std::string output;
for (void* stackp : raw_stack) {
if (absl::Symbolize(stackp, buf.get(), buf_size)) {
absl::StrAppend(&output, " ", buf.get(), "\n");
}
}
return output;
}
TEST(CordzInfoTest, TrackCord) {
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
ASSERT_THAT(info, Ne(nullptr));
EXPECT_FALSE(info->is_snapshot());
EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(info));
EXPECT_THAT(info->GetCordRepForTesting(), Eq(data.rep.rep));
info->Untrack();
}
TEST(CordzInfoTest, MaybeTrackChildCordWithoutSampling) {
CordzSamplingIntervalHelper sample_none(99999);
TestCordData parent, child;
CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod);
EXPECT_THAT(child.data.cordz_info(), Eq(nullptr));
}
TEST(CordzInfoTest, MaybeTrackChildCordWithSampling) {
CordzSamplingIntervalHelper sample_all(1);
TestCordData parent, child;
CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod);
EXPECT_THAT(child.data.cordz_info(), Eq(nullptr));
}
TEST(CordzInfoTest, MaybeTrackChildCordWithoutSamplingParentSampled) {
CordzSamplingIntervalHelper sample_none(99999);
TestCordData parent, child;
CordzInfo::TrackCord(parent.data, kTrackCordMethod, 1);
CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod);
CordzInfo* parent_info = parent.data.cordz_info();
CordzInfo* child_info = child.data.cordz_info();
ASSERT_THAT(child_info, Ne(nullptr));
EXPECT_THAT(child_info->GetCordRepForTesting(), Eq(child.rep.rep));
EXPECT_THAT(child_info->GetParentStack(), parent_info->GetStack());
parent_info->Untrack();
child_info->Untrack();
}
TEST(CordzInfoTest, MaybeTrackChildCordWithoutSamplingChildSampled) {
CordzSamplingIntervalHelper sample_none(99999);
TestCordData parent, child;
CordzInfo::TrackCord(child.data, kTrackCordMethod, 1);
CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod);
EXPECT_THAT(child.data.cordz_info(), Eq(nullptr));
}
TEST(CordzInfoTest, MaybeTrackChildCordWithSamplingChildSampled) {
CordzSamplingIntervalHelper sample_all(1);
TestCordData parent, child;
CordzInfo::TrackCord(child.data, kTrackCordMethod, 1);
CordzInfo::MaybeTrackCord(child.data, parent.data, kTrackCordMethod);
EXPECT_THAT(child.data.cordz_info(), Eq(nullptr));
}
TEST(CordzInfoTest, UntrackCord) {
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
info->Untrack();
EXPECT_THAT(DeleteQueue(), SizeIs(0u));
}
TEST(CordzInfoTest, UntrackCordWithSnapshot) {
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
CordzSnapshot snapshot;
info->Untrack();
EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(nullptr));
EXPECT_THAT(info->GetCordRepForTesting(), Eq(data.rep.rep));
EXPECT_THAT(DeleteQueue(), ElementsAre(info, &snapshot));
}
TEST(CordzInfoTest, SetCordRep) {
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
TestCordRep rep;
info->Lock(CordzUpdateTracker::kAppendCord);
info->SetCordRep(rep.rep);
info->Unlock();
EXPECT_THAT(info->GetCordRepForTesting(), Eq(rep.rep));
info->Untrack();
}
TEST(CordzInfoTest, SetCordRepNullUntracksCordOnUnlock) {
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
info->Lock(CordzUpdateTracker::kAppendString);
info->SetCordRep(nullptr);
EXPECT_THAT(info->GetCordRepForTesting(), Eq(nullptr));
EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(info));
info->Unlock();
EXPECT_THAT(CordzInfo::Head(CordzSnapshot()), Eq(nullptr));
}
TEST(CordzInfoTest, RefCordRep) {
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
size_t refcount = data.rep.rep->refcount.Get();
EXPECT_THAT(info->RefCordRep(), Eq(data.rep.rep));
EXPECT_THAT(data.rep.rep->refcount.Get(), Eq(refcount + 1));
CordRep::Unref(data.rep.rep);
info->Untrack();
}
#if GTEST_HAS_DEATH_TEST
TEST(CordzInfoTest, SetCordRepRequiresMutex) {
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
TestCordRep rep;
EXPECT_DEBUG_DEATH(info->SetCordRep(rep.rep), ".*");
info->Untrack();
}
#endif
TEST(CordzInfoTest, TrackUntrackHeadFirstV2) {
CordzSnapshot snapshot;
EXPECT_THAT(CordzInfo::Head(snapshot), Eq(nullptr));
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info1 = data.data.cordz_info();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info1));
EXPECT_THAT(info1->Next(snapshot), Eq(nullptr));
TestCordData data2;
CordzInfo::TrackCord(data2.data, kTrackCordMethod, 1);
CordzInfo* info2 = data2.data.cordz_info();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info2));
EXPECT_THAT(info2->Next(snapshot), Eq(info1));
EXPECT_THAT(info1->Next(snapshot), Eq(nullptr));
info2->Untrack();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info1));
EXPECT_THAT(info1->Next(snapshot), Eq(nullptr));
info1->Untrack();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(nullptr));
}
TEST(CordzInfoTest, TrackUntrackTailFirstV2) {
CordzSnapshot snapshot;
EXPECT_THAT(CordzInfo::Head(snapshot), Eq(nullptr));
TestCordData data;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info1 = data.data.cordz_info();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info1));
EXPECT_THAT(info1->Next(snapshot), Eq(nullptr));
TestCordData data2;
CordzInfo::TrackCord(data2.data, kTrackCordMethod, 1);
CordzInfo* info2 = data2.data.cordz_info();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info2));
EXPECT_THAT(info2->Next(snapshot), Eq(info1));
EXPECT_THAT(info1->Next(snapshot), Eq(nullptr));
info1->Untrack();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(info2));
EXPECT_THAT(info2->Next(snapshot), Eq(nullptr));
info2->Untrack();
ASSERT_THAT(CordzInfo::Head(snapshot), Eq(nullptr));
}
TEST(CordzInfoTest, StackV2) {
TestCordData data;
static constexpr int kMaxStackDepth = 50;
CordzInfo::TrackCord(data.data, kTrackCordMethod, 1);
CordzInfo* info = data.data.cordz_info();
std::vector<void*> local_stack;
local_stack.resize(kMaxStackDepth);
local_stack.resize(static_cast<size_t>(
absl::GetStackTrace(local_stack.data(), kMaxStackDepth,
1)));
std::string got_stack = FormatStack(info->GetStack());
std::string expected_stack = FormatStack(local_stack);
EXPECT_THAT(got_stack, HasSubstr(expected_stack));
info->Untrack();
}
CordzInfo* TrackChildCord(InlineData& data, const InlineData& parent) {
CordzInfo::TrackCord(data, parent, kChildMethod);
return data.cordz_info();
}
CordzInfo* TrackParentCord(InlineData& data) {
CordzInfo::TrackCord(data, kTrackCordMethod, 1);
return data.cordz_info();
}
TEST(CordzInfoTest, GetStatistics) {
TestCordData data;
CordzInfo* info = TrackParentCord(data.data);
CordzStatistics statistics = info->GetCordzStatistics();
EXPECT_THAT(statistics.size, Eq(data.rep.rep->length));
EXPECT_THAT(statistics.method, Eq(kTrackCordMethod));
EXPECT_THAT(statistics.parent_method, Eq(kUnknownMethod));
EXPECT_THAT(statistics.update_tracker.Value(kTrackCordMethod), Eq(1));
info->Untrack();
}
TEST(CordzInfoTest, LockCountsMethod) {
TestCordData data;
CordzInfo* info = TrackParentCord(data.data);
info->Lock(kUpdateMethod);
info->Unlock();
info->Lock(kUpdateMethod);
info->Unlock();
CordzStatistics statistics = info->GetCordzStatistics();
EXPECT_THAT(statistics.update_tracker.Value(kUpdateMethod), Eq(2));
info->Untrack();
}
TEST(CordzInfoTest, FromParent) {
TestCordData parent;
TestCordData child;
CordzInfo* info_parent = TrackParentCord(parent.data);
CordzInfo* info_child = TrackChildCord(child.data, parent.data);
std::string stack = FormatStack(info_parent->GetStack());
std::string parent_stack = FormatStack(info_child->GetParentStack());
EXPECT_THAT(stack, Eq(parent_stack));
CordzStatistics statistics = info_child->GetCordzStatistics();
EXPECT_THAT(statistics.size, Eq(child.rep.rep->length));
EXPECT_THAT(statistics.method, Eq(kChildMethod));
EXPECT_THAT(statistics.parent_method, Eq(kTrackCordMethod));
EXPECT_THAT(statistics.update_tracker.Value(kChildMethod), Eq(1));
info_parent->Untrack();
info_child->Untrack();
}
}
}
ABSL_NAMESPACE_END
} |
2,557 | cpp | abseil/abseil-cpp | charconv_parse | absl/strings/internal/charconv_parse.cc | absl/strings/internal/charconv_parse_test.cc | #ifndef ABSL_STRINGS_INTERNAL_CHARCONV_PARSE_H_
#define ABSL_STRINGS_INTERNAL_CHARCONV_PARSE_H_
#include <cstdint>
#include "absl/base/config.h"
#include "absl/strings/charconv.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
enum class FloatType { kNumber, kInfinity, kNan };
struct ParsedFloat {
uint64_t mantissa = 0;
int exponent = 0;
int literal_exponent = 0;
FloatType type = FloatType::kNumber;
const char* subrange_begin = nullptr;
const char* subrange_end = nullptr;
const char* end = nullptr;
};
template <int base>
ParsedFloat ParseFloat(const char* begin, const char* end,
absl::chars_format format_flags);
extern template ParsedFloat ParseFloat<10>(const char* begin, const char* end,
absl::chars_format format_flags);
extern template ParsedFloat ParseFloat<16>(const char* begin, const char* end,
absl::chars_format format_flags);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/charconv_parse.h"
#include "absl/strings/charconv.h"
#include <cassert>
#include <cstdint>
#include <limits>
#include "absl/strings/internal/memutil.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
constexpr int kDecimalMantissaDigitsMax = 19;
static_assert(std::numeric_limits<uint64_t>::digits10 ==
kDecimalMantissaDigitsMax,
"(a) above");
static_assert(std::numeric_limits<double>::is_iec559, "IEEE double assumed");
static_assert(std::numeric_limits<double>::radix == 2, "IEEE double fact");
static_assert(std::numeric_limits<double>::digits == 53, "IEEE double fact");
static_assert(1000000000000000000u > (uint64_t{1} << (53 + 3)), "(b) above");
constexpr int kHexadecimalMantissaDigitsMax = 15;
constexpr int kGuaranteedHexadecimalMantissaBitPrecision =
4 * kHexadecimalMantissaDigitsMax - 3;
static_assert(kGuaranteedHexadecimalMantissaBitPrecision >
std::numeric_limits<double>::digits + 2,
"kHexadecimalMantissaDigitsMax too small");
constexpr int kDecimalExponentDigitsMax = 9;
static_assert(std::numeric_limits<int>::digits10 >= kDecimalExponentDigitsMax,
"int type too small");
constexpr int kDecimalDigitLimit = 50000000;
constexpr int kHexadecimalDigitLimit = kDecimalDigitLimit / 4;
static_assert(999999999 + 2 * kDecimalDigitLimit <
std::numeric_limits<int>::max(),
"int type too small");
static_assert(999999999 + 2 * (4 * kHexadecimalDigitLimit) <
std::numeric_limits<int>::max(),
"int type too small");
bool AllowExponent(chars_format flags) {
bool fixed = (flags & chars_format::fixed) == chars_format::fixed;
bool scientific =
(flags & chars_format::scientific) == chars_format::scientific;
return scientific || !fixed;
}
bool RequireExponent(chars_format flags) {
bool fixed = (flags & chars_format::fixed) == chars_format::fixed;
bool scientific =
(flags & chars_format::scientific) == chars_format::scientific;
return scientific && !fixed;
}
const int8_t kAsciiToInt[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1};
template <int base>
bool IsDigit(char ch);
template <int base>
unsigned ToDigit(char ch);
template <int base>
bool IsExponentCharacter(char ch);
template <int base>
constexpr int MantissaDigitsMax();
template <int base>
constexpr int DigitLimit();
template <int base>
constexpr int DigitMagnitude();
template <>
bool IsDigit<10>(char ch) {
return ch >= '0' && ch <= '9';
}
template <>
bool IsDigit<16>(char ch) {
return kAsciiToInt[static_cast<unsigned char>(ch)] >= 0;
}
template <>
unsigned ToDigit<10>(char ch) {
return static_cast<unsigned>(ch - '0');
}
template <>
unsigned ToDigit<16>(char ch) {
return static_cast<unsigned>(kAsciiToInt[static_cast<unsigned char>(ch)]);
}
template <>
bool IsExponentCharacter<10>(char ch) {
return ch == 'e' || ch == 'E';
}
template <>
bool IsExponentCharacter<16>(char ch) {
return ch == 'p' || ch == 'P';
}
template <>
constexpr int MantissaDigitsMax<10>() {
return kDecimalMantissaDigitsMax;
}
template <>
constexpr int MantissaDigitsMax<16>() {
return kHexadecimalMantissaDigitsMax;
}
template <>
constexpr int DigitLimit<10>() {
return kDecimalDigitLimit;
}
template <>
constexpr int DigitLimit<16>() {
return kHexadecimalDigitLimit;
}
template <>
constexpr int DigitMagnitude<10>() {
return 1;
}
template <>
constexpr int DigitMagnitude<16>() {
return 4;
}
template <int base, typename T>
int ConsumeDigits(const char* begin, const char* end, int max_digits, T* out,
bool* dropped_nonzero_digit) {
if (base == 10) {
assert(max_digits <= std::numeric_limits<T>::digits10);
} else if (base == 16) {
assert(max_digits * 4 <= std::numeric_limits<T>::digits);
}
const char* const original_begin = begin;
while (!*out && end != begin && *begin == '0') ++begin;
T accumulator = *out;
const char* significant_digits_end =
(end - begin > max_digits) ? begin + max_digits : end;
while (begin < significant_digits_end && IsDigit<base>(*begin)) {
auto digit = static_cast<T>(ToDigit<base>(*begin));
assert(accumulator * base >= accumulator);
accumulator *= base;
assert(accumulator + digit >= accumulator);
accumulator += digit;
++begin;
}
bool dropped_nonzero = false;
while (begin < end && IsDigit<base>(*begin)) {
dropped_nonzero = dropped_nonzero || (*begin != '0');
++begin;
}
if (dropped_nonzero && dropped_nonzero_digit != nullptr) {
*dropped_nonzero_digit = true;
}
*out = accumulator;
return static_cast<int>(begin - original_begin);
}
bool IsNanChar(char v) {
return (v == '_') || (v >= '0' && v <= '9') || (v >= 'a' && v <= 'z') ||
(v >= 'A' && v <= 'Z');
}
bool ParseInfinityOrNan(const char* begin, const char* end,
strings_internal::ParsedFloat* out) {
if (end - begin < 3) {
return false;
}
switch (*begin) {
case 'i':
case 'I': {
if (strings_internal::memcasecmp(begin + 1, "nf", 2) != 0) {
return false;
}
out->type = strings_internal::FloatType::kInfinity;
if (end - begin >= 8 &&
strings_internal::memcasecmp(begin + 3, "inity", 5) == 0) {
out->end = begin + 8;
} else {
out->end = begin + 3;
}
return true;
}
case 'n':
case 'N': {
if (strings_internal::memcasecmp(begin + 1, "an", 2) != 0) {
return false;
}
out->type = strings_internal::FloatType::kNan;
out->end = begin + 3;
begin += 3;
if (begin < end && *begin == '(') {
const char* nan_begin = begin + 1;
while (nan_begin < end && IsNanChar(*nan_begin)) {
++nan_begin;
}
if (nan_begin < end && *nan_begin == ')') {
out->subrange_begin = begin + 1;
out->subrange_end = nan_begin;
out->end = nan_begin + 1;
}
}
return true;
}
default:
return false;
}
}
}
namespace strings_internal {
template <int base>
strings_internal::ParsedFloat ParseFloat(const char* begin, const char* end,
chars_format format_flags) {
strings_internal::ParsedFloat result;
if (begin == end) return result;
if (ParseInfinityOrNan(begin, end, &result)) {
return result;
}
const char* const mantissa_begin = begin;
while (begin < end && *begin == '0') {
++begin;
}
uint64_t mantissa = 0;
int exponent_adjustment = 0;
bool mantissa_is_inexact = false;
int pre_decimal_digits = ConsumeDigits<base>(
begin, end, MantissaDigitsMax<base>(), &mantissa, &mantissa_is_inexact);
begin += pre_decimal_digits;
int digits_left;
if (pre_decimal_digits >= DigitLimit<base>()) {
return result;
} else if (pre_decimal_digits > MantissaDigitsMax<base>()) {
exponent_adjustment =
static_cast<int>(pre_decimal_digits - MantissaDigitsMax<base>());
digits_left = 0;
} else {
digits_left =
static_cast<int>(MantissaDigitsMax<base>() - pre_decimal_digits);
}
if (begin < end && *begin == '.') {
++begin;
if (mantissa == 0) {
const char* begin_zeros = begin;
while (begin < end && *begin == '0') {
++begin;
}
int zeros_skipped = static_cast<int>(begin - begin_zeros);
if (zeros_skipped >= DigitLimit<base>()) {
return result;
}
exponent_adjustment -= static_cast<int>(zeros_skipped);
}
int post_decimal_digits = ConsumeDigits<base>(
begin, end, digits_left, &mantissa, &mantissa_is_inexact);
begin += post_decimal_digits;
if (post_decimal_digits >= DigitLimit<base>()) {
return result;
} else if (post_decimal_digits > digits_left) {
exponent_adjustment -= digits_left;
} else {
exponent_adjustment -= post_decimal_digits;
}
}
if (mantissa_begin == begin) {
return result;
}
if (begin - mantissa_begin == 1 && *mantissa_begin == '.') {
return result;
}
if (mantissa_is_inexact) {
if (base == 10) {
result.subrange_begin = mantissa_begin;
result.subrange_end = begin;
} else if (base == 16) {
mantissa |= 1;
}
}
result.mantissa = mantissa;
const char* const exponent_begin = begin;
result.literal_exponent = 0;
bool found_exponent = false;
if (AllowExponent(format_flags) && begin < end &&
IsExponentCharacter<base>(*begin)) {
bool negative_exponent = false;
++begin;
if (begin < end && *begin == '-') {
negative_exponent = true;
++begin;
} else if (begin < end && *begin == '+') {
++begin;
}
const char* const exponent_digits_begin = begin;
begin += ConsumeDigits<10>(begin, end, kDecimalExponentDigitsMax,
&result.literal_exponent, nullptr);
if (begin == exponent_digits_begin) {
found_exponent = false;
begin = exponent_begin;
} else {
found_exponent = true;
if (negative_exponent) {
result.literal_exponent = -result.literal_exponent;
}
}
}
if (!found_exponent && RequireExponent(format_flags)) {
return result;
}
result.type = strings_internal::FloatType::kNumber;
if (result.mantissa > 0) {
result.exponent = result.literal_exponent +
(DigitMagnitude<base>() * exponent_adjustment);
} else {
result.exponent = 0;
}
result.end = begin;
return result;
}
template ParsedFloat ParseFloat<10>(const char* begin, const char* end,
chars_format format_flags);
template ParsedFloat ParseFloat<16>(const char* begin, const char* end,
chars_format format_flags);
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/charconv_parse.h"
#include <string>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/log/check.h"
#include "absl/strings/str_cat.h"
using absl::chars_format;
using absl::strings_internal::FloatType;
using absl::strings_internal::ParsedFloat;
using absl::strings_internal::ParseFloat;
namespace {
template <int base>
void ExpectParsedFloat(std::string s, absl::chars_format format_flags,
FloatType expected_type, uint64_t expected_mantissa,
int expected_exponent,
int expected_literal_exponent = -999) {
SCOPED_TRACE(s);
int begin_subrange = -1;
int end_subrange = -1;
std::string::size_type open_bracket_pos = s.find('[');
if (open_bracket_pos != std::string::npos) {
begin_subrange = static_cast<int>(open_bracket_pos);
s.replace(open_bracket_pos, 1, "");
std::string::size_type close_bracket_pos = s.find(']');
CHECK_NE(close_bracket_pos, absl::string_view::npos)
<< "Test input contains [ without matching ]";
end_subrange = static_cast<int>(close_bracket_pos);
s.replace(close_bracket_pos, 1, "");
}
const std::string::size_type expected_characters_matched = s.find('$');
CHECK_NE(expected_characters_matched, std::string::npos)
<< "Input string must contain $";
s.replace(expected_characters_matched, 1, "");
ParsedFloat parsed =
ParseFloat<base>(s.data(), s.data() + s.size(), format_flags);
EXPECT_NE(parsed.end, nullptr);
if (parsed.end == nullptr) {
return;
}
EXPECT_EQ(parsed.type, expected_type);
if (begin_subrange == -1) {
EXPECT_EQ(parsed.subrange_begin, nullptr);
EXPECT_EQ(parsed.subrange_end, nullptr);
} else {
EXPECT_EQ(parsed.subrange_begin, s.data() + begin_subrange);
EXPECT_EQ(parsed.subrange_end, s.data() + end_subrange);
}
if (parsed.type == FloatType::kNumber) {
EXPECT_EQ(parsed.mantissa, expected_mantissa);
EXPECT_EQ(parsed.exponent, expected_exponent);
if (expected_literal_exponent != -999) {
EXPECT_EQ(parsed.literal_exponent, expected_literal_exponent);
}
}
auto characters_matched = static_cast<int>(parsed.end - s.data());
EXPECT_EQ(characters_matched, expected_characters_matched);
}
template <int base>
void ExpectNumber(std::string s, absl::chars_format format_flags,
uint64_t expected_mantissa, int expected_exponent,
int expected_literal_exponent = -999) {
ExpectParsedFloat<base>(std::move(s), format_flags, FloatType::kNumber,
expected_mantissa, expected_exponent,
expected_literal_exponent);
}
void ExpectSpecial(const std::string& s, absl::chars_format format_flags,
FloatType type) {
ExpectParsedFloat<10>(s, format_flags, type, 0, 0);
ExpectParsedFloat<16>(s, format_flags, type, 0, 0);
}
template <int base>
void ExpectFailedParse(absl::string_view s, absl::chars_format format_flags) {
ParsedFloat parsed =
ParseFloat<base>(s.data(), s.data() + s.size(), format_flags);
EXPECT_EQ(parsed.end, nullptr);
}
TEST(ParseFloat, SimpleValue) {
ExpectNumber<10>("1.23456789e5$", chars_format::general, 123456789, -3);
ExpectNumber<10>("1.23456789e+5$", chars_format::general, 123456789, -3);
ExpectNumber<10>("1.23456789E5$", chars_format::general, 123456789, -3);
ExpectNumber<10>("1.23456789e05$", chars_format::general, 123456789, -3);
ExpectNumber<10>("123.456789e3$", chars_format::general, 123456789, -3);
ExpectNumber<10>("0.000123456789e9$", chars_format::general, 123456789, -3);
ExpectNumber<10>("123456.789$", chars_format::general, 123456789, -3);
ExpectNumber<10>("123456789e-3$", chars_format::general, 123456789, -3);
ExpectNumber<16>("1.234abcdefp28$", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<16>("1.234abcdefp+28$", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<16>("1.234ABCDEFp28$", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<16>("1.234AbCdEfP0028$", chars_format::general, 0x1234abcdef,
-8);
ExpectNumber<16>("123.4abcdefp20$", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<16>("0.0001234abcdefp44$", chars_format::general, 0x1234abcdef,
-8);
ExpectNumber<16>("1234abcd.ef$", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<16>("1234abcdefp-8$", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<10>("0001.2345678900e005$", chars_format::general, 12345678900,
-5);
ExpectNumber<16>("0001.234abcdef000p28$", chars_format::general,
0x1234abcdef000, -20);
ExpectNumber<10>("1.23456789e5$ ", chars_format::general, 123456789, -3);
ExpectNumber<10>("1.23456789e5$e5e5", chars_format::general, 123456789, -3);
ExpectNumber<10>("1.23456789e5$.25", chars_format::general, 123456789, -3);
ExpectNumber<10>("1.23456789e5$-", chars_format::general, 123456789, -3);
ExpectNumber<10>("1.23456789e5$PUPPERS!!!", chars_format::general, 123456789,
-3);
ExpectNumber<10>("123456.789$efghij", chars_format::general, 123456789, -3);
ExpectNumber<10>("123456.789$e", chars_format::general, 123456789, -3);
ExpectNumber<10>("123456.789$p5", chars_format::general, 123456789, -3);
ExpectNumber<10>("123456.789$.10", chars_format::general, 123456789, -3);
ExpectNumber<16>("1.234abcdefp28$ ", chars_format::general, 0x1234abcdef,
-8);
ExpectNumber<16>("1.234abcdefp28$p28", chars_format::general, 0x1234abcdef,
-8);
ExpectNumber<16>("1.234abcdefp28$.125", chars_format::general, 0x1234abcdef,
-8);
ExpectNumber<16>("1.234abcdefp28$-", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<16>("1.234abcdefp28$KITTEHS!!!", chars_format::general,
0x1234abcdef, -8);
ExpectNumber<16>("1234abcd.ef$ghijk", chars_format::general, 0x1234abcdef,
-8);
ExpectNumber<16>("1234abcd.ef$p", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<16>("1234abcd.ef$.10", chars_format::general, 0x1234abcdef, -8);
ExpectNumber<10>("9999999999999999999$", chars_format::general,
9999999999999999999u, 0);
ExpectNumber<16>("fffffffffffffff$", chars_format::general,
0xfffffffffffffffu, 0);
ExpectNumber<10>("0$", chars_format::general, 0, 0);
ExpectNumber<16>("0$", chars_format::general, 0, 0);
ExpectNumber<10>("000000000000000000000000000000000000000$",
chars_format::general, 0, 0);
ExpectNumber<16>("000000000000000000000000000000000000000$",
chars_format::general, 0, 0);
ExpectNumber<10>("0000000000000000000000.000000000000000000$",
chars_format::general, 0, 0);
ExpectNumber<16>("0000000000000000000000.000000000000000000$",
chars_format::general, 0, 0);
ExpectNumber<10>("0.00000000000000000000000000000000e123456$",
chars_format::general, 0, 0);
ExpectNumber<16>("0.00000000000000000000000000000000p123456$",
chars_format::general, 0, 0);
}
TEST(ParseFloat, LargeDecimalMantissa) {
ExpectNumber<10>("100000000000000000000000000$", chars_format::general,
1000000000000000000,
8);
ExpectNumber<10>("123456789123456789100000000$", chars_format::general,
1234567891234567891,
8);
ExpectNumber<10>("[123456789123456789123456789]$", chars_format::general,
1234567891234567891,
8,
0);
ExpectNumber<10>("[123456789123456789100000009]$", chars_format::general,
1234567891234567891,
8,
0);
ExpectNumber<10>("[123456789123456789120000000]$", chars_format::general,
1234567891234567891,
8,
0);
ExpectNumber<10>("[00000000123456789123456789123456789]$",
chars_format::general, 1234567891234567891,
8,
0);
ExpectNumber<10>("00000000123456789123456789100000000$",
chars_format::general, 1234567891234567891,
8);
ExpectNumber<10>("1.234567891234567891e123$", chars_format::general,
1234567891234567891, 105);
ExpectNumber<10>("[1.23456789123456789123456789]e123$", chars_format::general,
1234567891234567891,
105,
123);
ExpectNumber<10>("[1999999999999999999999]$", chars_format::general,
1999999999999999999,
3,
0);
}
TEST(ParseFloat, LargeHexadecimalMantissa) {
ExpectNumber<16>("123456789abcdef123456789abcdef$", chars_format::general,
0x123456789abcdef, 60);
ExpectNumber<16>("000000123456789abcdef123456789abcdef$",
chars_format::general, 0x123456789abcdef, 60);
ExpectNumber<16>("1.23456789abcdefp100$", chars_format::general,
0x123456789abcdef, 44);
ExpectNumber<16>("1.23456789abcdef123456789abcdefp100$",
chars_format::general, 0x123456789abcdef, 44);
ExpectNumber<16>("123456789abcdee123456789abcdee$", chars_format::general,
0x123456789abcdef, 60);
ExpectNumber<16>("123456789abcdee000000000000001$", chars_format::general,
0x123456789abcdef, 60);
ExpectNumber<16>("123456789abcdee000000000000000$", chars_format::general,
0x123456789abcdee, 60);
}
TEST(ParseFloat, ScientificVsFixed) {
ExpectNumber<10>("1.23456789$e5", chars_format::fixed, 123456789, -8);
ExpectNumber<10>("123456.789$", chars_format::fixed, 123456789, -3);
ExpectNumber<16>("1.234abcdef$p28", chars_format::fixed, 0x1234abcdef, -36);
ExpectNumber<16>("1234abcd.ef$", chars_format::fixed, 0x1234abcdef, -8);
ExpectNumber<10>("1.23456789e5$", chars_format::scientific, 123456789, -3);
ExpectFailedParse<10>("-123456.789$", chars_format::scientific);
ExpectNumber<16>("1.234abcdefp28$", chars_format::scientific, 0x1234abcdef,
-8);
ExpectFailedParse<16>("1234abcd.ef$", chars_format::scientific);
}
TEST(ParseFloat, Infinity) {
ExpectFailedParse<10>("in", chars_format::general);
ExpectFailedParse<16>("in", chars_format::general);
ExpectFailedParse<10>("inx", chars_format::general);
ExpectFailedParse<16>("inx", chars_format::general);
ExpectSpecial("inf$", chars_format::general, FloatType::kInfinity);
ExpectSpecial("Inf$", chars_format::general, FloatType::kInfinity);
ExpectSpecial("INF$", chars_format::general, FloatType::kInfinity);
ExpectSpecial("inf$inite", chars_format::general, FloatType::kInfinity);
ExpectSpecial("iNfInItY$", chars_format::general, FloatType::kInfinity);
ExpectSpecial("infinity$!!!", chars_format::general, FloatType::kInfinity);
}
TEST(ParseFloat, NaN) {
ExpectFailedParse<10>("na", chars_format::general);
ExpectFailedParse<16>("na", chars_format::general);
ExpectFailedParse<10>("nah", chars_format::general);
ExpectFailedParse<16>("nah", chars_format::general);
ExpectSpecial("nan$", chars_format::general, FloatType::kNan);
ExpectSpecial("NaN$", chars_format::general, FloatType::kNan);
ExpectSpecial("nAn$", chars_format::general, FloatType::kNan);
ExpectSpecial("NAN$", chars_format::general, FloatType::kNan);
ExpectSpecial("NaN$aNaNaNaNaBatman!", chars_format::general, FloatType::kNan);
ExpectSpecial("nan([0xabcdef])$", chars_format::general, FloatType::kNan);
ExpectSpecial("nan([0xabcdef])$...", chars_format::general, FloatType::kNan);
ExpectSpecial("nan([0xabcdef])$)...", chars_format::general, FloatType::kNan);
ExpectSpecial("nan([])$", chars_format::general, FloatType::kNan);
ExpectSpecial("nan([aAzZ09_])$", chars_format::general, FloatType::kNan);
ExpectSpecial("nan$(bad-char)", chars_format::general, FloatType::kNan);
ExpectSpecial("nan$(0xabcdef", chars_format::general, FloatType::kNan);
}
} |
2,558 | cpp | abseil/abseil-cpp | cord_rep_btree | absl/strings/internal/cord_rep_btree.cc | absl/strings/internal/cord_rep_btree_test.cc | #ifndef ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_H_
#define ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_H_
#include <cassert>
#include <cstdint>
#include <iosfwd>
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/optimization.h"
#include "absl/strings/internal/cord_data_edge.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_flat.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
void SetCordBtreeExhaustiveValidation(bool do_exaustive_validation);
bool IsCordBtreeExhaustiveValidationEnabled();
class CordRepBtreeNavigator;
class CordRepBtree : public CordRep {
public:
enum class EdgeType { kFront, kBack };
static constexpr EdgeType kFront = EdgeType::kFront;
static constexpr EdgeType kBack = EdgeType::kBack;
static constexpr size_t kMaxCapacity = 6;
static constexpr size_t kMaxDepth = 12;
static constexpr int kMaxHeight = static_cast<int>(kMaxDepth - 1);
enum Action { kSelf, kCopied, kPopped };
struct OpResult {
CordRepBtree* tree;
Action action;
};
struct CopyResult {
CordRep* edge;
int height;
};
struct Position {
size_t index;
size_t n;
};
static CordRepBtree* Create(CordRep* rep);
static void Destroy(CordRepBtree* tree);
static void Delete(CordRepBtree* tree) { delete tree; }
using CordRep::Unref;
static void Unref(absl::Span<CordRep* const> edges);
static CordRepBtree* Append(CordRepBtree* tree, CordRep* rep);
static CordRepBtree* Prepend(CordRepBtree* tree, CordRep* rep);
static CordRepBtree* Append(CordRepBtree* tree, string_view data,
size_t extra = 0);
static CordRepBtree* Prepend(CordRepBtree* tree, string_view data,
size_t extra = 0);
CordRep* SubTree(size_t offset, size_t n);
static CordRep* RemoveSuffix(CordRepBtree* tree, size_t n);
char GetCharacter(size_t offset) const;
bool IsFlat(absl::string_view* fragment) const;
bool IsFlat(size_t offset, size_t n, absl::string_view* fragment) const;
Span<char> GetAppendBuffer(size_t size);
static ExtractResult ExtractAppendBuffer(CordRepBtree* tree,
size_t extra_capacity = 1);
int height() const { return static_cast<int>(storage[0]); }
size_t begin() const { return static_cast<size_t>(storage[1]); }
size_t back() const { return static_cast<size_t>(storage[2]) - 1; }
size_t end() const { return static_cast<size_t>(storage[2]); }
size_t index(EdgeType edge) const {
return edge == kFront ? begin() : back();
}
size_t size() const { return end() - begin(); }
size_t capacity() const { return kMaxCapacity; }
inline CordRep* Edge(size_t index) const;
inline CordRep* Edge(EdgeType edge_type) const;
inline absl::Span<CordRep* const> Edges() const;
inline absl::Span<CordRep* const> Edges(size_t begin, size_t end) const;
inline absl::string_view Data(size_t index) const;
static bool IsValid(const CordRepBtree* tree, bool shallow = false);
static CordRepBtree* AssertValid(CordRepBtree* tree, bool shallow = true);
static const CordRepBtree* AssertValid(const CordRepBtree* tree,
bool shallow = true);
static void Dump(const CordRep* rep, std::ostream& stream);
static void Dump(const CordRep* rep, absl::string_view label,
std::ostream& stream);
static void Dump(const CordRep* rep, absl::string_view label,
bool include_contents, std::ostream& stream);
template <EdgeType edge_type>
inline OpResult AddEdge(bool owned, CordRep* edge, size_t delta);
template <EdgeType edge_type>
OpResult SetEdge(bool owned, CordRep* edge, size_t delta);
static CordRepBtree* New(int height = 0);
static CordRepBtree* New(CordRep* rep);
static CordRepBtree* New(CordRepBtree* front, CordRepBtree* back);
static CordRepBtree* Rebuild(CordRepBtree* tree);
private:
CordRepBtree() = default;
~CordRepBtree() = default;
inline void InitInstance(int height, size_t begin = 0, size_t end = 0);
void set_begin(size_t begin) { storage[1] = static_cast<uint8_t>(begin); }
void set_end(size_t end) { storage[2] = static_cast<uint8_t>(end); }
size_t sub_fetch_begin(size_t n) {
storage[1] -= static_cast<uint8_t>(n);
return storage[1];
}
size_t fetch_add_end(size_t n) {
const uint8_t current = storage[2];
storage[2] = static_cast<uint8_t>(current + n);
return current;
}
Position IndexOf(size_t offset) const;
Position IndexBefore(size_t offset) const;
Position IndexOfLength(size_t n) const;
Position IndexBefore(Position front, size_t offset) const;
Position IndexBeyond(size_t offset) const;
template <EdgeType edge_type>
static CordRepBtree* NewLeaf(absl::string_view data, size_t extra);
CordRepBtree* CopyRaw(size_t new_length) const;
CordRepBtree* Copy() const;
CordRepBtree* CopyBeginTo(size_t end, size_t new_length) const;
static CordRepBtree* ConsumeBeginTo(CordRepBtree* tree, size_t end,
size_t new_length);
CordRepBtree* CopyToEndFrom(size_t begin, size_t new_length) const;
static CordRep* ExtractFront(CordRepBtree* tree);
static CordRepBtree* MergeTrees(CordRepBtree* left, CordRepBtree* right);
static CordRepBtree* CreateSlow(CordRep* rep);
static CordRepBtree* AppendSlow(CordRepBtree*, CordRep* rep);
static CordRepBtree* PrependSlow(CordRepBtree*, CordRep* rep);
static void Rebuild(CordRepBtree** stack, CordRepBtree* tree, bool consume);
inline void AlignBegin();
inline void AlignEnd();
template <EdgeType edge_type>
inline void Add(CordRep* rep);
template <EdgeType edge_type>
inline void Add(absl::Span<CordRep* const>);
template <EdgeType edge_type>
absl::string_view AddData(absl::string_view data, size_t extra);
template <EdgeType edge_type>
inline void SetEdge(CordRep* edge);
CopyResult CopyPrefix(size_t n, bool allow_folding = true);
CopyResult CopySuffix(size_t offset);
inline OpResult ToOpResult(bool owned);
template <EdgeType edge_type>
static CordRepBtree* AddCordRep(CordRepBtree* tree, CordRep* rep);
template <EdgeType edge_type>
static CordRepBtree* AddData(CordRepBtree* tree, absl::string_view data,
size_t extra = 0);
template <EdgeType edge_type>
static CordRepBtree* Merge(CordRepBtree* dst, CordRepBtree* src);
Span<char> GetAppendBufferSlow(size_t size);
CordRep* edges_[kMaxCapacity];
friend class CordRepBtreeTestPeer;
friend class CordRepBtreeNavigator;
};
inline CordRepBtree* CordRep::btree() {
assert(IsBtree());
return static_cast<CordRepBtree*>(this);
}
inline const CordRepBtree* CordRep::btree() const {
assert(IsBtree());
return static_cast<const CordRepBtree*>(this);
}
inline void CordRepBtree::InitInstance(int height, size_t begin, size_t end) {
tag = BTREE;
storage[0] = static_cast<uint8_t>(height);
storage[1] = static_cast<uint8_t>(begin);
storage[2] = static_cast<uint8_t>(end);
}
inline CordRep* CordRepBtree::Edge(size_t index) const {
assert(index >= begin());
assert(index < end());
return edges_[index];
}
inline CordRep* CordRepBtree::Edge(EdgeType edge_type) const {
return edges_[edge_type == kFront ? begin() : back()];
}
inline absl::Span<CordRep* const> CordRepBtree::Edges() const {
return {edges_ + begin(), size()};
}
inline absl::Span<CordRep* const> CordRepBtree::Edges(size_t begin,
size_t end) const {
assert(begin <= end);
assert(begin >= this->begin());
assert(end <= this->end());
return {edges_ + begin, static_cast<size_t>(end - begin)};
}
inline absl::string_view CordRepBtree::Data(size_t index) const {
assert(height() == 0);
return EdgeData(Edge(index));
}
inline CordRepBtree* CordRepBtree::New(int height) {
CordRepBtree* tree = new CordRepBtree;
tree->length = 0;
tree->InitInstance(height);
return tree;
}
inline CordRepBtree* CordRepBtree::New(CordRep* rep) {
CordRepBtree* tree = new CordRepBtree;
int height = rep->IsBtree() ? rep->btree()->height() + 1 : 0;
tree->length = rep->length;
tree->InitInstance(height, 0, 1);
tree->edges_[0] = rep;
return tree;
}
inline CordRepBtree* CordRepBtree::New(CordRepBtree* front,
CordRepBtree* back) {
assert(front->height() == back->height());
CordRepBtree* tree = new CordRepBtree;
tree->length = front->length + back->length;
tree->InitInstance(front->height() + 1, 0, 2);
tree->edges_[0] = front;
tree->edges_[1] = back;
return tree;
}
inline void CordRepBtree::Unref(absl::Span<CordRep* const> edges) {
for (CordRep* edge : edges) {
if (ABSL_PREDICT_FALSE(!edge->refcount.Decrement())) {
CordRep::Destroy(edge);
}
}
}
inline CordRepBtree* CordRepBtree::CopyRaw(size_t new_length) const {
CordRepBtree* tree = new CordRepBtree; | #include "absl/strings/internal/cord_rep_btree.h"
#include <cmath>
#include <deque>
#include <iostream>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/cleanup/cleanup.h"
#include "absl/strings/internal/cord_data_edge.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_test_util.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
class CordRepBtreeTestPeer {
public:
static void SetEdge(CordRepBtree* node, size_t idx, CordRep* edge) {
node->edges_[idx] = edge;
}
static void AddEdge(CordRepBtree* node, CordRep* edge) {
node->edges_[node->fetch_add_end(1)] = edge;
}
};
namespace {
using ::absl::cordrep_testing::AutoUnref;
using ::absl::cordrep_testing::CordCollectRepsIf;
using ::absl::cordrep_testing::CordToString;
using ::absl::cordrep_testing::CordVisitReps;
using ::absl::cordrep_testing::CreateFlatsFromString;
using ::absl::cordrep_testing::CreateRandomString;
using ::absl::cordrep_testing::MakeExternal;
using ::absl::cordrep_testing::MakeFlat;
using ::absl::cordrep_testing::MakeSubstring;
using ::testing::_;
using ::testing::AllOf;
using ::testing::AnyOf;
using ::testing::Conditional;
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Le;
using ::testing::Ne;
using ::testing::Not;
using ::testing::SizeIs;
using ::testing::TypedEq;
MATCHER_P(EqFlatHolding, data, "Equals flat holding data") {
if (arg->tag < FLAT) {
*result_listener << "Expected FLAT, got tag " << static_cast<int>(arg->tag);
return false;
}
std::string actual = CordToString(arg);
if (actual != data) {
*result_listener << "Expected flat holding \"" << data
<< "\", got flat holding \"" << actual << "\"";
return false;
}
return true;
}
MATCHER_P(IsNode, height, absl::StrCat("Is a valid node of height ", height)) {
if (arg == nullptr) {
*result_listener << "Expected NODE, got nullptr";
return false;
}
if (arg->tag != BTREE) {
*result_listener << "Expected NODE, got " << static_cast<int>(arg->tag);
return false;
}
if (!CordRepBtree::IsValid(arg->btree())) {
CordRepBtree::Dump(arg->btree(), "Expected valid NODE, got:", false,
*result_listener->stream());
return false;
}
if (arg->btree()->height() != height) {
*result_listener << "Expected NODE of height " << height << ", got "
<< arg->btree()->height();
return false;
}
return true;
}
MATCHER_P2(IsSubstring, start, length,
absl::StrCat("Is a substring(start = ", start, ", length = ", length,
")")) {
if (arg == nullptr) {
*result_listener << "Expected substring, got nullptr";
return false;
}
if (arg->tag != SUBSTRING) {
*result_listener << "Expected SUBSTRING, got "
<< static_cast<int>(arg->tag);
return false;
}
const CordRepSubstring* const substr = arg->substring();
if (substr->start != start || substr->length != length) {
*result_listener << "Expected substring(" << start << ", " << length
<< "), got substring(" << substr->start << ", "
<< substr->length << ")";
return false;
}
return true;
}
MATCHER_P2(EqExtractResult, tree, rep, "Equals ExtractResult") {
if (arg.tree != tree || arg.extracted != rep) {
*result_listener << "Expected {" << static_cast<const void*>(tree) << ", "
<< static_cast<const void*>(rep) << "}, got {" << arg.tree
<< ", " << arg.extracted << "}";
return false;
}
return true;
}
class DataConsumer {
public:
DataConsumer(absl::string_view data, bool forward)
: data_(data), forward_(forward) {}
absl::string_view Next(size_t n) {
assert(n <= data_.size() - consumed_);
consumed_ += n;
return data_.substr(forward_ ? consumed_ - n : data_.size() - consumed_, n);
}
absl::string_view Consumed() const {
return forward_ ? data_.substr(0, consumed_)
: data_.substr(data_.size() - consumed_);
}
private:
absl::string_view data_;
size_t consumed_ = 0;
bool forward_;
};
CordRepBtree* BtreeAdd(CordRepBtree* node, bool append,
absl::string_view data) {
return append ? CordRepBtree::Append(node, data)
: CordRepBtree::Prepend(node, data);
}
void GetLeafEdges(const CordRepBtree* tree, std::vector<CordRep*>& edges) {
if (tree->height() == 0) {
for (CordRep* edge : tree->Edges()) {
edges.push_back(edge);
}
} else {
for (CordRep* edge : tree->Edges()) {
GetLeafEdges(edge->btree(), edges);
}
}
}
std::vector<CordRep*> GetLeafEdges(const CordRepBtree* tree) {
std::vector<CordRep*> edges;
GetLeafEdges(tree, edges);
return edges;
}
CordRepFlat* MakeHexFlat(size_t i) {
return MakeFlat(absl::StrCat("0x", absl::Hex(i, absl::kZeroPad4)));
}
CordRepBtree* MakeLeaf(size_t size = CordRepBtree::kMaxCapacity) {
assert(size <= CordRepBtree::kMaxCapacity);
CordRepBtree* leaf = CordRepBtree::Create(MakeHexFlat(0));
for (size_t i = 1; i < size; ++i) {
leaf = CordRepBtree::Append(leaf, MakeHexFlat(i));
}
return leaf;
}
CordRepBtree* MakeTree(size_t size, bool append = true) {
CordRepBtree* tree = CordRepBtree::Create(MakeHexFlat(0));
for (size_t i = 1; i < size; ++i) {
tree = append ? CordRepBtree::Append(tree, MakeHexFlat(i))
: CordRepBtree::Prepend(tree, MakeHexFlat(i));
}
return tree;
}
CordRepBtree* CreateTree(absl::Span<CordRep* const> reps) {
auto it = reps.begin();
CordRepBtree* tree = CordRepBtree::Create(*it);
while (++it != reps.end()) tree = CordRepBtree::Append(tree, *it);
return tree;
}
CordRepBtree* CreateTree(absl::string_view data, size_t chunk_size) {
return CreateTree(CreateFlatsFromString(data, chunk_size));
}
CordRepBtree* CreateTreeReverse(absl::string_view data, size_t chunk_size) {
std::vector<CordRep*> flats = CreateFlatsFromString(data, chunk_size);
auto rit = flats.rbegin();
CordRepBtree* tree = CordRepBtree::Create(*rit);
while (++rit != flats.rend()) tree = CordRepBtree::Prepend(tree, *rit);
return tree;
}
class CordRepBtreeTest : public testing::TestWithParam<bool> {
public:
bool shared() const { return GetParam(); }
static std::string ToString(testing::TestParamInfo<bool> param) {
return param.param ? "Shared" : "Private";
}
};
INSTANTIATE_TEST_SUITE_P(WithParam, CordRepBtreeTest, testing::Bool(),
CordRepBtreeTest::ToString);
class CordRepBtreeHeightTest : public testing::TestWithParam<int> {
public:
int height() const { return GetParam(); }
static std::string ToString(testing::TestParamInfo<int> param) {
return absl::StrCat(param.param);
}
};
INSTANTIATE_TEST_SUITE_P(WithHeights, CordRepBtreeHeightTest,
testing::Range(0, CordRepBtree::kMaxHeight),
CordRepBtreeHeightTest::ToString);
using TwoBools = testing::tuple<bool, bool>;
class CordRepBtreeDualTest : public testing::TestWithParam<TwoBools> {
public:
bool first_shared() const { return std::get<0>(GetParam()); }
bool second_shared() const { return std::get<1>(GetParam()); }
static std::string ToString(testing::TestParamInfo<TwoBools> param) {
if (std::get<0>(param.param)) {
return std::get<1>(param.param) ? "BothShared" : "FirstShared";
}
return std::get<1>(param.param) ? "SecondShared" : "Private";
}
};
INSTANTIATE_TEST_SUITE_P(WithParam, CordRepBtreeDualTest,
testing::Combine(testing::Bool(), testing::Bool()),
CordRepBtreeDualTest::ToString);
TEST(CordRepBtreeTest, SizeIsMultipleOf64) {
if (sizeof(size_t) == 8 && sizeof(void*) == 8) {
EXPECT_THAT(sizeof(CordRepBtree) % 64, Eq(0u))
<< "Should be multiple of 64";
}
}
TEST(CordRepBtreeTest, NewDestroyEmptyTree) {
auto* tree = CordRepBtree::New();
EXPECT_THAT(tree->size(), Eq(0u));
EXPECT_THAT(tree->height(), Eq(0));
EXPECT_THAT(tree->Edges(), ElementsAre());
CordRepBtree::Destroy(tree);
}
TEST(CordRepBtreeTest, NewDestroyEmptyTreeAtHeight) {
auto* tree = CordRepBtree::New(3);
EXPECT_THAT(tree->size(), Eq(0u));
EXPECT_THAT(tree->height(), Eq(3));
EXPECT_THAT(tree->Edges(), ElementsAre());
CordRepBtree::Destroy(tree);
}
TEST(CordRepBtreeTest, Btree) {
CordRep* rep = CordRepBtree::New();
EXPECT_THAT(rep->btree(), Eq(rep));
EXPECT_THAT(static_cast<const CordRep*>(rep)->btree(), Eq(rep));
CordRep::Unref(rep);
#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
rep = MakeFlat("Hello world");
EXPECT_DEATH(rep->btree(), ".*");
EXPECT_DEATH(static_cast<const CordRep*>(rep)->btree(), ".*");
CordRep::Unref(rep);
#endif
}
TEST(CordRepBtreeTest, EdgeData) {
CordRepFlat* flat = MakeFlat("Hello world");
CordRepExternal* external = MakeExternal("Hello external");
CordRep* substr1 = MakeSubstring(1, 6, CordRep::Ref(flat));
CordRep* substr2 = MakeSubstring(1, 6, CordRep::Ref(external));
CordRep* bad_substr = MakeSubstring(1, 2, CordRep::Ref(substr1));
EXPECT_TRUE(IsDataEdge(flat));
EXPECT_THAT(EdgeData(flat).data(), TypedEq<const void*>(flat->Data()));
EXPECT_THAT(EdgeData(flat), Eq("Hello world"));
EXPECT_TRUE(IsDataEdge(external));
EXPECT_THAT(EdgeData(external).data(), TypedEq<const void*>(external->base));
EXPECT_THAT(EdgeData(external), Eq("Hello external"));
EXPECT_TRUE(IsDataEdge(substr1));
EXPECT_THAT(EdgeData(substr1).data(), TypedEq<const void*>(flat->Data() + 1));
EXPECT_THAT(EdgeData(substr1), Eq("ello w"));
EXPECT_TRUE(IsDataEdge(substr2));
EXPECT_THAT(EdgeData(substr2).data(),
TypedEq<const void*>(external->base + 1));
EXPECT_THAT(EdgeData(substr2), Eq("ello e"));
EXPECT_FALSE(IsDataEdge(bad_substr));
#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
EXPECT_DEATH(EdgeData(bad_substr), ".*");
#endif
CordRep::Unref(bad_substr);
CordRep::Unref(substr2);
CordRep::Unref(substr1);
CordRep::Unref(external);
CordRep::Unref(flat);
}
TEST(CordRepBtreeTest, CreateUnrefLeaf) {
auto* flat = MakeFlat("a");
auto* leaf = CordRepBtree::Create(flat);
EXPECT_THAT(leaf->size(), Eq(1u));
EXPECT_THAT(leaf->height(), Eq(0));
EXPECT_THAT(leaf->Edges(), ElementsAre(flat));
CordRepBtree::Unref(leaf);
}
TEST(CordRepBtreeTest, NewUnrefNode) {
auto* leaf = CordRepBtree::Create(MakeFlat("a"));
CordRepBtree* tree = CordRepBtree::New(leaf);
EXPECT_THAT(tree->size(), Eq(1u));
EXPECT_THAT(tree->height(), Eq(1));
EXPECT_THAT(tree->Edges(), ElementsAre(leaf));
CordRepBtree::Unref(tree);
}
TEST_P(CordRepBtreeTest, AppendToLeafToCapacity) {
AutoUnref refs;
std::vector<CordRep*> flats;
flats.push_back(MakeHexFlat(0));
auto* leaf = CordRepBtree::Create(flats.back());
for (size_t i = 1; i < CordRepBtree::kMaxCapacity; ++i) {
refs.RefIf(shared(), leaf);
flats.push_back(MakeHexFlat(i));
auto* result = CordRepBtree::Append(leaf, flats.back());
EXPECT_THAT(result->height(), Eq(0));
EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf)));
EXPECT_THAT(result->Edges(), ElementsAreArray(flats));
leaf = result;
}
CordRep::Unref(leaf);
}
TEST_P(CordRepBtreeTest, PrependToLeafToCapacity) {
AutoUnref refs;
std::deque<CordRep*> flats;
flats.push_front(MakeHexFlat(0));
auto* leaf = CordRepBtree::Create(flats.front());
for (size_t i = 1; i < CordRepBtree::kMaxCapacity; ++i) {
refs.RefIf(shared(), leaf);
flats.push_front(MakeHexFlat(i));
auto* result = CordRepBtree::Prepend(leaf, flats.front());
EXPECT_THAT(result->height(), Eq(0));
EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf)));
EXPECT_THAT(result->Edges(), ElementsAreArray(flats));
leaf = result;
}
CordRep::Unref(leaf);
}
TEST_P(CordRepBtreeTest, AppendPrependToLeafToCapacity) {
AutoUnref refs;
std::deque<CordRep*> flats;
flats.push_front(MakeHexFlat(0));
auto* leaf = CordRepBtree::Create(flats.front());
for (size_t i = 1; i < CordRepBtree::kMaxCapacity; ++i) {
refs.RefIf(shared(), leaf);
CordRepBtree* result;
if (i % 2 != 0) {
flats.push_front(MakeHexFlat(i));
result = CordRepBtree::Prepend(leaf, flats.front());
} else {
flats.push_back(MakeHexFlat(i));
result = CordRepBtree::Append(leaf, flats.back());
}
EXPECT_THAT(result->height(), Eq(0));
EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf)));
EXPECT_THAT(result->Edges(), ElementsAreArray(flats));
leaf = result;
}
CordRep::Unref(leaf);
}
TEST_P(CordRepBtreeTest, AppendToLeafBeyondCapacity) {
AutoUnref refs;
auto* leaf = MakeLeaf();
refs.RefIf(shared(), leaf);
CordRep* flat = MakeFlat("abc");
auto* result = CordRepBtree::Append(leaf, flat);
ASSERT_THAT(result, IsNode(1));
EXPECT_THAT(result, Ne(leaf));
absl::Span<CordRep* const> edges = result->Edges();
ASSERT_THAT(edges, ElementsAre(leaf, IsNode(0)));
EXPECT_THAT(edges[1]->btree()->Edges(), ElementsAre(flat));
CordRep::Unref(result);
}
TEST_P(CordRepBtreeTest, PrependToLeafBeyondCapacity) {
AutoUnref refs;
auto* leaf = MakeLeaf();
refs.RefIf(shared(), leaf);
CordRep* flat = MakeFlat("abc");
auto* result = CordRepBtree::Prepend(leaf, flat);
ASSERT_THAT(result, IsNode(1));
EXPECT_THAT(result, Ne(leaf));
absl::Span<CordRep* const> edges = result->Edges();
ASSERT_THAT(edges, ElementsAre(IsNode(0), leaf));
EXPECT_THAT(edges[0]->btree()->Edges(), ElementsAre(flat));
CordRep::Unref(result);
}
TEST_P(CordRepBtreeTest, AppendToTreeOneDeep) {
constexpr size_t max_cap = CordRepBtree::kMaxCapacity;
AutoUnref refs;
std::vector<CordRep*> flats;
flats.push_back(MakeHexFlat(0));
CordRepBtree* tree = CordRepBtree::Create(flats.back());
for (size_t i = 1; i <= max_cap; ++i) {
flats.push_back(MakeHexFlat(i));
tree = CordRepBtree::Append(tree, flats.back());
}
ASSERT_THAT(tree, IsNode(1));
for (size_t i = max_cap + 1; i < max_cap * max_cap; ++i) {
refs.RefIf(shared(), tree);
refs.RefIf(i % 4 == 0, tree->Edges().back());
flats.push_back(MakeHexFlat(i));
CordRepBtree* result = CordRepBtree::Append(tree, flats.back());
ASSERT_THAT(result, IsNode(1));
ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree)));
std::vector<CordRep*> edges = GetLeafEdges(result);
ASSERT_THAT(edges, ElementsAreArray(flats));
tree = result;
}
CordRep::Unref(tree);
}
TEST_P(CordRepBtreeTest, AppendToTreeTwoDeep) {
constexpr size_t max_cap = CordRepBtree::kMaxCapacity;
AutoUnref refs;
std::vector<CordRep*> flats;
flats.push_back(MakeHexFlat(0));
CordRepBtree* tree = CordRepBtree::Create(flats.back());
for (size_t i = 1; i <= max_cap * max_cap; ++i) {
flats.push_back(MakeHexFlat(i));
tree = CordRepBtree::Append(tree, flats.back());
}
ASSERT_THAT(tree, IsNode(2));
for (size_t i = max_cap * max_cap + 1; i < max_cap * max_cap * max_cap; ++i) {
refs.RefIf(shared(), tree);
refs.RefIf(i % 16 == 0, tree->Edges().back());
refs.RefIf(i % 4 == 0, tree->Edges().back()->btree()->Edges().back());
flats.push_back(MakeHexFlat(i));
CordRepBtree* result = CordRepBtree::Append(tree, flats.back());
ASSERT_THAT(result, IsNode(2));
ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree)));
std::vector<CordRep*> edges = GetLeafEdges(result);
ASSERT_THAT(edges, ElementsAreArray(flats));
tree = result;
}
CordRep::Unref(tree);
}
TEST_P(CordRepBtreeTest, PrependToTreeOneDeep) {
constexpr size_t max_cap = CordRepBtree::kMaxCapacity;
AutoUnref refs;
std::deque<CordRep*> flats;
flats.push_back(MakeHexFlat(0));
CordRepBtree* tree = CordRepBtree::Create(flats.back());
for (size_t i = 1; i <= max_cap; ++i) {
flats.push_front(MakeHexFlat(i));
tree = CordRepBtree::Prepend(tree, flats.front());
}
ASSERT_THAT(tree, IsNode(1));
for (size_t i = max_cap + 1; i < max_cap * max_cap; ++i) {
refs.RefIf(shared(), tree);
refs.RefIf(i % 4 == 0, tree->Edges().back());
flats.push_front(MakeHexFlat(i));
CordRepBtree* result = CordRepBtree::Prepend(tree, flats.front());
ASSERT_THAT(result, IsNode(1));
ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree)));
std::vector<CordRep*> edges = GetLeafEdges(result);
ASSERT_THAT(edges, ElementsAreArray(flats));
tree = result;
}
CordRep::Unref(tree);
}
TEST_P(CordRepBtreeTest, PrependToTreeTwoDeep) {
constexpr size_t max_cap = CordRepBtree::kMaxCapacity;
AutoUnref refs;
std::deque<CordRep*> flats;
flats.push_back(MakeHexFlat(0));
CordRepBtree* tree = CordRepBtree::Create(flats.back());
for (size_t i = 1; i <= max_cap * max_cap; ++i) {
flats.push_front(MakeHexFlat(i));
tree = CordRepBtree::Prepend(tree, flats.front());
}
ASSERT_THAT(tree, IsNode(2));
for (size_t i = max_cap * max_cap + 1; i < max_cap * max_cap * max_cap; ++i) {
refs.RefIf(shared(), tree);
refs.RefIf(i % 16 == 0, tree->Edges().back());
refs.RefIf(i % 4 == 0, tree->Edges().back()->btree()->Edges().back());
flats.push_front(MakeHexFlat(i));
CordRepBtree* result = CordRepBtree::Prepend(tree, flats.front());
ASSERT_THAT(result, IsNode(2));
ASSERT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree)));
std::vector<CordRep*> edges = GetLeafEdges(result);
ASSERT_THAT(edges, ElementsAreArray(flats));
tree = result;
}
CordRep::Unref(tree);
}
TEST_P(CordRepBtreeDualTest, MergeLeafsNotExceedingCapacity) {
for (bool use_append : {false, true}) {
SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend");
AutoUnref refs;
std::vector<CordRep*> flats;
CordRepBtree* left = MakeLeaf(3);
GetLeafEdges(left, flats);
refs.RefIf(first_shared(), left);
CordRepBtree* right = MakeLeaf(2);
GetLeafEdges(right, flats);
refs.RefIf(second_shared(), right);
CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right)
: CordRepBtree::Prepend(right, left);
EXPECT_THAT(tree, IsNode(0));
EXPECT_THAT(tree->Edges(), ElementsAreArray(flats));
CordRepBtree::Unref(tree);
}
}
TEST_P(CordRepBtreeDualTest, MergeLeafsExceedingCapacity) {
for (bool use_append : {false, true}) {
SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend");
AutoUnref refs;
CordRepBtree* left = MakeLeaf(CordRepBtree::kMaxCapacity - 2);
refs.RefIf(first_shared(), left);
CordRepBtree* right = MakeLeaf(CordRepBtree::kMaxCapacity - 1);
refs.RefIf(second_shared(), right);
CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right)
: CordRepBtree::Prepend(right, left);
EXPECT_THAT(tree, IsNode(1));
EXPECT_THAT(tree->Edges(), ElementsAre(left, right));
CordRepBtree::Unref(tree);
}
}
TEST_P(CordRepBtreeDualTest, MergeEqualHeightTrees) {
for (bool use_append : {false, true}) {
SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend");
AutoUnref refs;
std::vector<CordRep*> flats;
CordRepBtree* left = MakeTree(CordRepBtree::kMaxCapacity * 3);
GetLeafEdges(left, flats);
refs.RefIf(first_shared(), left);
CordRepBtree* right = MakeTree(CordRepBtree::kMaxCapacity * 2);
GetLeafEdges(right, flats);
refs.RefIf(second_shared(), right);
CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right)
: CordRepBtree::Prepend(right, left);
EXPECT_THAT(tree, IsNode(1));
EXPECT_THAT(tree->Edges(), SizeIs(5u));
EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats));
CordRepBtree::Unref(tree);
}
}
TEST_P(CordRepBtreeDualTest, MergeLeafWithTreeNotExceedingLeafCapacity) {
for (bool use_append : {false, true}) {
SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend");
AutoUnref refs;
std::vector<CordRep*> flats;
CordRepBtree* left = MakeTree(CordRepBtree::kMaxCapacity * 2 + 2);
GetLeafEdges(left, flats);
refs.RefIf(first_shared(), left);
CordRepBtree* right = MakeTree(3);
GetLeafEdges(right, flats);
refs.RefIf(second_shared(), right);
CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right)
: CordRepBtree::Prepend(right, left);
EXPECT_THAT(tree, IsNode(1));
EXPECT_THAT(tree->Edges(), SizeIs(3u));
EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats));
CordRepBtree::Unref(tree);
}
}
TEST_P(CordRepBtreeDualTest, MergeLeafWithTreeExceedingLeafCapacity) {
for (bool use_append : {false, true}) {
SCOPED_TRACE(use_append ? "Using Append" : "Using Prepend");
AutoUnref refs;
std::vector<CordRep*> flats;
CordRepBtree* left = MakeTree(CordRepBtree::kMaxCapacity * 3 - 2);
GetLeafEdges(left, flats);
refs.RefIf(first_shared(), left);
CordRepBtree* right = MakeTree(3);
GetLeafEdges(right, flats);
refs.RefIf(second_shared(), right);
CordRepBtree* tree = use_append ? CordRepBtree::Append(left, right)
: CordRepBtree::Prepend(right, left);
EXPECT_THAT(tree, IsNode(1));
EXPECT_THAT(tree->Edges(), SizeIs(4u));
EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats));
CordRepBtree::Unref(tree);
}
}
void RefEdgesAt(size_t depth, AutoUnref& refs, CordRepBtree* tree) {
absl::Span<CordRep* const> edges = tree->Edges();
if (depth == 0) {
refs.Ref(edges.front());
refs.Ref(edges.back());
} else {
assert(tree->height() > 0);
RefEdgesAt(depth - 1, refs, edges.front()->btree());
RefEdgesAt(depth - 1, refs, edges.back()->btree());
}
}
TEST(CordRepBtreeTest, MergeFuzzTest) {
constexpr size_t max_cap = CordRepBtree::kMaxCapacity;
std::minstd_rand rnd;
std::uniform_int_distribution<int> coin_flip(0, 1);
std::uniform_int_distribution<int> dice_throw(1, 6);
auto random_leaf_count = [&]() {
std::uniform_int_distribution<int> dist_height(0, 3);
std::uniform_int_distribution<int> dist_leaf(0, max_cap - 1);
const int height = dist_height(rnd);
return (height ? pow(max_cap, height) : 0) + dist_leaf(rnd);
};
for (int i = 0; i < 10000; ++i) {
AutoUnref refs;
std::vector<CordRep*> flats;
CordRepBtree* left = MakeTree(random_leaf_count(), coin_flip(rnd));
GetLeafEdges(left, flats);
if (dice_throw(rnd) == 1) {
std::uniform_int_distribution<size_t> dist(
0, static_cast<size_t>(left->height()));
RefEdgesAt(dist(rnd), refs, left);
}
CordRepBtree* right = MakeTree(random_leaf_count(), coin_flip(rnd));
GetLeafEdges(right, flats);
if (dice_throw(rnd) == 1) {
std::uniform_int_distribution<size_t> dist(
0, static_cast<size_t>(right->height()));
RefEdgesAt(dist(rnd), refs, right);
}
CordRepBtree* tree = CordRepBtree::Append(left, right);
EXPECT_THAT(GetLeafEdges(tree), ElementsAreArray(flats));
CordRepBtree::Unref(tree);
}
}
TEST_P(CordRepBtreeTest, RemoveSuffix) {
constexpr size_t max_cap = CordRepBtree::kMaxCapacity;
for (size_t cap : {max_cap - 1, max_cap * 2, max_cap * max_cap * 2}) {
const std::string data = CreateRandomString(cap * 512);
{
AutoUnref refs;
CordRepBtree* node = refs.RefIf(shared(), CreateTree(data, 512));
EXPECT_THAT(CordRepBtree::RemoveSuffix(node, data.length()), Eq(nullptr));
node = refs.RefIf(shared(), CreateTree(data, 512));
EXPECT_THAT(CordRepBtree::RemoveSuffix(node, 0), Eq(node));
CordRep::Unref(node);
}
for (size_t n = 1; n < data.length(); ++n) {
AutoUnref refs;
auto flats = CreateFlatsFromString(data, 512);
CordRepBtree* node = refs.RefIf(shared(), CreateTree(flats));
CordRep* rep = refs.Add(CordRepBtree::RemoveSuffix(node, n));
EXPECT_THAT(CordToString(rep), Eq(data.substr(0, data.length() - n)));
auto is_flat = [](CordRep* rep) { return rep->tag >= FLAT; };
std::vector<CordRep*> edges = CordCollectRepsIf(is_flat, rep);
ASSERT_THAT(edges.size(), Le(flats.size()));
CordRep* last_edge = edges.back();
edges.pop_back();
const size_t last_length = rep->length - edges.size() * 512;
size_t index = 0;
for (CordRep* edge : edges) {
ASSERT_THAT(edge, Eq(flats[index++]));
ASSERT_THAT(edge->length, Eq(512u));
}
if (last_length >= 500) {
EXPECT_THAT(last_edge, Eq(flats[index++]));
if (shared()) {
EXPECT_THAT(last_edge->length, Eq(512u));
} else {
EXPECT_TRUE(last_edge->refcount.IsOne());
EXPECT_THAT(last_edge->length, Eq(last_length));
}
}
}
}
}
TEST(CordRepBtreeTest, SubTree) {
constexpr size_t max_cap = CordRepBtree::kMaxCapacity;
const size_t n = max_cap * max_cap * 2;
const std::string data = CreateRandomString(n * 3);
std::vector<CordRep*> flats;
for (absl::string_view s = data; !s.empty(); s.remove_prefix(3)) {
flats.push_back(MakeFlat(s.substr(0, 3)));
}
CordRepBtree* node = CordRepBtree::Create(CordRep::Ref(flats[0]));
for (size_t i = 1; i < flats.size(); ++i) {
node = CordRepBtree::Append(node, CordRep::Ref(flats[i]));
}
for (size_t offset = 0; offset < data.length(); ++offset) {
for (size_t length = 1; length <= data.length() - offset; ++length) {
CordRep* rep = node->SubTree(offset, length);
EXPECT_THAT(CordToString(rep), Eq(data.substr(offset, length)));
CordRep::Unref(rep);
}
}
CordRepBtree::Unref(node);
for (CordRep* rep : flats) {
CordRep::Unref(rep);
}
}
TEST(CordRepBtreeTest, SubTreeOnExistingSubstring) {
AutoUnref refs;
std::string data = CreateRandomString(1000);
CordRepBtree* leaf = CordRepBtree::Create(MakeFlat("abc"));
CordRep* flat = MakeFlat(data);
leaf = CordRepBtree::Append(leaf, flat);
CordRep* result = leaf->SubTree(0, 3 + 990);
ASSERT_THAT(result->tag, Eq(BTREE));
CordRep::Unref(leaf);
leaf = result->btree();
ASSERT_THAT(leaf->Edges(), ElementsAre(_, IsSubstring(0u, 990u)));
EXPECT_THAT(leaf->Edges()[1]->substring()->child, Eq(flat));
result = leaf->SubTree(3 + 5, 970);
ASSERT_THAT(result, IsSubstring(5u, 970u));
EXPECT_THAT(result->substring()->child, Eq(flat));
CordRep::Unref(result);
CordRep::Unref(leaf);
}
TEST_P(CordRepBtreeTest, AddDataToLeaf) {
const size_t n = CordRepBtree::kMaxCapacity;
const std::string data = CreateRandomString(n * 3);
for (bool append : {true, false}) {
AutoUnref refs;
DataConsumer consumer(data, append);
SCOPED_TRACE(append ? "Append" : "Prepend");
CordRepBtree* leaf = CordRepBtree::Create(MakeFlat(consumer.Next(3)));
for (size_t i = 1; i < n; ++i) {
refs.RefIf(shared(), leaf);
CordRepBtree* result = BtreeAdd(leaf, append, consumer.Next(3));
EXPECT_THAT(result, Conditional(shared(), Ne(leaf), Eq(leaf)));
EXPECT_THAT(CordToString(result), Eq(consumer.Consumed()));
leaf = result;
}
CordRep::Unref(leaf);
}
}
TEST_P(CordRepBtreeTest, AppendDataToTree) {
AutoUnref refs;
size_t n = CordRepBtree::kMaxCapacity + CordRepBtree::kMaxCapacity / 2;
std::string data = CreateRandomString(n * 3);
CordRepBtree* tree = refs.RefIf(shared(), CreateTree(data, 3));
CordRepBtree* leaf0 = tree->Edges()[0]->btree();
CordRepBtree* leaf1 = tree->Edges()[1]->btree();
CordRepBtree* result = CordRepBtree::Append(tree, "123456789");
EXPECT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree)));
EXPECT_THAT(result->Edges(),
ElementsAre(leaf0, Conditional(shared(), Ne(leaf1), Eq(leaf1))));
EXPECT_THAT(CordToString(result), Eq(data + "123456789"));
CordRep::Unref(result);
}
TEST_P(CordRepBtreeTest, PrependDataToTree) {
AutoUnref refs;
size_t n = CordRepBtree::kMaxCapacity + CordRepBtree::kMaxCapacity / 2;
std::string data = CreateRandomString(n * 3);
CordRepBtree* tree = refs.RefIf(shared(), CreateTreeReverse(data, 3));
CordRepBtree* leaf0 = tree->Edges()[0]->btree();
CordRepBtree* leaf1 = tree->Edges()[1]->btree();
CordRepBtree* result = CordRepBtree::Prepend(tree, "123456789");
EXPECT_THAT(result, Conditional(shared(), Ne(tree), Eq(tree)));
EXPECT_THAT(result->Edges(), |
2,559 | cpp | abseil/abseil-cpp | damerau_levenshtein_distance | absl/strings/internal/damerau_levenshtein_distance.cc | absl/strings/internal/damerau_levenshtein_distance_test.cc | #ifndef ABSL_STRINGS_INTERNAL_DAMERAU_LEVENSHTEIN_DISTANCE_H_
#define ABSL_STRINGS_INTERNAL_DAMERAU_LEVENSHTEIN_DISTANCE_H_
#include <cstdint>
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
uint8_t CappedDamerauLevenshteinDistance(absl::string_view s1,
absl::string_view s2, uint8_t cutoff);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/damerau_levenshtein_distance.h"
#include <algorithm>
#include <array>
#include <numeric>
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
uint8_t CappedDamerauLevenshteinDistance(absl::string_view s1,
absl::string_view s2, uint8_t cutoff) {
const uint8_t MAX_SIZE = 100;
const uint8_t _cutoff = std::min(MAX_SIZE, cutoff);
const uint8_t cutoff_plus_1 = static_cast<uint8_t>(_cutoff + 1);
if (s1.size() > s2.size()) std::swap(s1, s2);
if (s1.size() + _cutoff < s2.size() || s2.size() > MAX_SIZE)
return cutoff_plus_1;
if (s1.empty())
return static_cast<uint8_t>(s2.size());
const uint8_t lower_diag =
_cutoff - static_cast<uint8_t>(s2.size() - s1.size());
const uint8_t upper_diag = _cutoff;
std::array<std::array<uint8_t, MAX_SIZE + 2>, MAX_SIZE + 2> d;
std::iota(d[0].begin(), d[0].begin() + upper_diag + 1, 0);
d[0][cutoff_plus_1] = cutoff_plus_1;
for (size_t i = 1; i <= s1.size(); ++i) {
size_t j_begin = 1;
if (i > lower_diag) {
j_begin = i - lower_diag;
d[i][j_begin - 1] = cutoff_plus_1;
} else {
d[i][0] = static_cast<uint8_t>(i);
}
size_t j_end = i + upper_diag;
if (j_end > s2.size()) {
j_end = s2.size();
} else {
d[i][j_end + 1] = cutoff_plus_1;
}
for (size_t j = j_begin; j <= j_end; ++j) {
const uint8_t deletion_distance = d[i - 1][j] + 1;
const uint8_t insertion_distance = d[i][j - 1] + 1;
const uint8_t mismatched_tail_cost = s1[i - 1] == s2[j - 1] ? 0 : 1;
const uint8_t mismatch_distance = d[i - 1][j - 1] + mismatched_tail_cost;
uint8_t transposition_distance = _cutoff + 1;
if (i > 1 && j > 1 && s1[i - 1] == s2[j - 2] && s1[i - 2] == s2[j - 1])
transposition_distance = d[i - 2][j - 2] + 1;
d[i][j] = std::min({cutoff_plus_1, deletion_distance, insertion_distance,
mismatch_distance, transposition_distance});
}
}
return d[s1.size()][s2.size()];
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/damerau_levenshtein_distance.h"
#include <cstdint>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace {
using absl::strings_internal::CappedDamerauLevenshteinDistance;
TEST(Distance, TestDistances) {
EXPECT_THAT(CappedDamerauLevenshteinDistance("ab", "ab", 6), uint8_t{0});
EXPECT_THAT(CappedDamerauLevenshteinDistance("a", "b", 6), uint8_t{1});
EXPECT_THAT(CappedDamerauLevenshteinDistance("ca", "abc", 6), uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "ad", 6), uint8_t{2});
EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "cadb", 6), uint8_t{4});
EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "bdac", 6), uint8_t{4});
EXPECT_THAT(CappedDamerauLevenshteinDistance("ab", "ab", 0), uint8_t{0});
EXPECT_THAT(CappedDamerauLevenshteinDistance("", "", 0), uint8_t{0});
EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", "abc", 6), uint8_t{0});
for (auto res :
{"", "ca", "efg", "ea", "ce", "ceb", "eca", "cae", "cea", "bea"}) {
EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", res, 6), uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance(res, "abc", 6), uint8_t{3});
}
for (auto res :
{"a", "b", "c", "ba", "cb", "bca", "cab", "cba", "ace",
"efc", "ebf", "aef", "ae", "be", "eb", "ec", "ecb", "bec",
"bce", "cbe", "ace", "eac", "aeb", "bae", "eab", "eba"}) {
EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", res, 6), uint8_t{2});
EXPECT_THAT(CappedDamerauLevenshteinDistance(res, "abc", 6), uint8_t{2});
}
for (auto res : {"ab", "ac", "bc", "acb", "bac", "ebc", "aec", "abe"}) {
EXPECT_THAT(CappedDamerauLevenshteinDistance("abc", res, 6), uint8_t{1});
EXPECT_THAT(CappedDamerauLevenshteinDistance(res, "abc", 6), uint8_t{1});
}
}
TEST(Distance, TestCutoff) {
EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "a", 3), uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "a", 2), uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance("abcd", "a", 1), uint8_t{2});
EXPECT_THAT(CappedDamerauLevenshteinDistance("abcdefg", "a", 2), uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance("a", "abcde", 2), uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(102, 'a'),
std::string(102, 'a'), 105),
uint8_t{101});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'),
std::string(100, 'a'), 100),
uint8_t{0});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'),
std::string(100, 'b'), 100),
uint8_t{100});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'),
std::string(99, 'a'), 2),
uint8_t{1});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'),
std::string(101, 'a'), 2),
uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(100, 'a'),
std::string(101, 'a'), 2),
uint8_t{3});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(UINT8_MAX + 1, 'a'),
std::string(UINT8_MAX + 1, 'b'),
UINT8_MAX),
uint8_t{101});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(UINT8_MAX - 1, 'a'),
std::string(UINT8_MAX - 1, 'b'),
UINT8_MAX),
uint8_t{101});
EXPECT_THAT(
CappedDamerauLevenshteinDistance(std::string(UINT8_MAX, 'a'),
std::string(UINT8_MAX, 'b'), UINT8_MAX),
uint8_t{101});
EXPECT_THAT(CappedDamerauLevenshteinDistance(std::string(UINT8_MAX - 1, 'a'),
std::string(UINT8_MAX - 1, 'a'),
UINT8_MAX),
uint8_t{101});
}
} |
2,560 | cpp | abseil/abseil-cpp | memutil | absl/strings/internal/memutil.cc | absl/strings/internal/memutil_test.cc | #ifndef ABSL_STRINGS_INTERNAL_MEMUTIL_H_
#define ABSL_STRINGS_INTERNAL_MEMUTIL_H_
#include <cstddef>
#include <cstring>
#include "absl/base/port.h"
#include "absl/strings/ascii.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
int memcasecmp(const char* s1, const char* s2, size_t len);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/memutil.h"
#include <cstdlib>
#include "absl/strings/ascii.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
int memcasecmp(const char* s1, const char* s2, size_t len) {
const unsigned char* us1 = reinterpret_cast<const unsigned char*>(s1);
const unsigned char* us2 = reinterpret_cast<const unsigned char*>(s2);
for (size_t i = 0; i < len; i++) {
unsigned char c1 = us1[i];
unsigned char c2 = us2[i];
if (c1 != c2) {
c1 = c1 >= 'A' && c1 <= 'Z' ? c1 - 'A' + 'a' : c1;
c2 = c2 >= 'A' && c2 <= 'Z' ? c2 - 'A' + 'a' : c2;
const int diff = int{c1} - int{c2};
if (diff != 0) return diff;
}
}
return 0;
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/memutil.h"
#include <cstdlib>
#include "gtest/gtest.h"
namespace {
TEST(MemUtil, memcasecmp) {
const char a[] = "hello there";
EXPECT_EQ(absl::strings_internal::memcasecmp(a, "heLLO there",
sizeof("hello there") - 1),
0);
EXPECT_EQ(absl::strings_internal::memcasecmp(a, "heLLO therf",
sizeof("hello there") - 1),
-1);
EXPECT_EQ(absl::strings_internal::memcasecmp(a, "heLLO therf",
sizeof("hello there") - 2),
0);
EXPECT_EQ(absl::strings_internal::memcasecmp(a, "whatever", 0), 0);
}
} |
2,561 | cpp | abseil/abseil-cpp | cordz_sample_token | absl/strings/internal/cordz_sample_token.cc | absl/strings/internal/cordz_sample_token_test.cc | #include "absl/base/config.h"
#include "absl/strings/internal/cordz_handle.h"
#include "absl/strings/internal/cordz_info.h"
#ifndef ABSL_STRINGS_INTERNAL_CORDZ_SAMPLE_TOKEN_H_
#define ABSL_STRINGS_INTERNAL_CORDZ_SAMPLE_TOKEN_H_
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
class CordzSampleToken : public CordzSnapshot {
public:
class Iterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = const CordzInfo&;
using difference_type = ptrdiff_t;
using pointer = const CordzInfo*;
using reference = value_type;
Iterator() = default;
Iterator& operator++();
Iterator operator++(int);
friend bool operator==(const Iterator& lhs, const Iterator& rhs);
friend bool operator!=(const Iterator& lhs, const Iterator& rhs);
reference operator*() const;
pointer operator->() const;
private:
friend class CordzSampleToken;
explicit Iterator(const CordzSampleToken* token);
const CordzSampleToken* token_ = nullptr;
pointer current_ = nullptr;
};
CordzSampleToken() = default;
CordzSampleToken(const CordzSampleToken&) = delete;
CordzSampleToken& operator=(const CordzSampleToken&) = delete;
Iterator begin() { return Iterator(this); }
Iterator end() { return Iterator(); }
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/cordz_sample_token.h"
#include "absl/base/config.h"
#include "absl/strings/internal/cordz_handle.h"
#include "absl/strings/internal/cordz_info.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
CordzSampleToken::Iterator& CordzSampleToken::Iterator::operator++() {
if (current_) {
current_ = current_->Next(*token_);
}
return *this;
}
CordzSampleToken::Iterator CordzSampleToken::Iterator::operator++(int) {
Iterator it(*this);
operator++();
return it;
}
bool operator==(const CordzSampleToken::Iterator& lhs,
const CordzSampleToken::Iterator& rhs) {
return lhs.current_ == rhs.current_ &&
(lhs.current_ == nullptr || lhs.token_ == rhs.token_);
}
bool operator!=(const CordzSampleToken::Iterator& lhs,
const CordzSampleToken::Iterator& rhs) {
return !(lhs == rhs);
}
CordzSampleToken::Iterator::reference CordzSampleToken::Iterator::operator*()
const {
return *current_;
}
CordzSampleToken::Iterator::pointer CordzSampleToken::Iterator::operator->()
const {
return current_;
}
CordzSampleToken::Iterator::Iterator(const CordzSampleToken* token)
: token_(token), current_(CordzInfo::Head(*token)) {}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/cordz_sample_token.h"
#include <memory>
#include <type_traits>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/random/random.h"
#include "absl/strings/cordz_test_helpers.h"
#include "absl/strings/internal/cord_rep_flat.h"
#include "absl/strings/internal/cordz_handle.h"
#include "absl/strings/internal/cordz_info.h"
#include "absl/synchronization/internal/thread_pool.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Ne;
auto constexpr kTrackCordMethod = CordzUpdateTracker::kConstructorString;
TEST(CordzSampleTokenTest, IteratorTraits) {
static_assert(std::is_copy_constructible<CordzSampleToken::Iterator>::value,
"");
static_assert(std::is_copy_assignable<CordzSampleToken::Iterator>::value, "");
static_assert(std::is_move_constructible<CordzSampleToken::Iterator>::value,
"");
static_assert(std::is_move_assignable<CordzSampleToken::Iterator>::value, "");
static_assert(
std::is_same<
std::iterator_traits<CordzSampleToken::Iterator>::iterator_category,
std::input_iterator_tag>::value,
"");
static_assert(
std::is_same<std::iterator_traits<CordzSampleToken::Iterator>::value_type,
const CordzInfo&>::value,
"");
static_assert(
std::is_same<
std::iterator_traits<CordzSampleToken::Iterator>::difference_type,
ptrdiff_t>::value,
"");
static_assert(
std::is_same<std::iterator_traits<CordzSampleToken::Iterator>::pointer,
const CordzInfo*>::value,
"");
static_assert(
std::is_same<std::iterator_traits<CordzSampleToken::Iterator>::reference,
const CordzInfo&>::value,
"");
}
TEST(CordzSampleTokenTest, IteratorEmpty) {
CordzSampleToken token;
EXPECT_THAT(token.begin(), Eq(token.end()));
}
TEST(CordzSampleTokenTest, Iterator) {
TestCordData cord1, cord2, cord3;
CordzInfo::TrackCord(cord1.data, kTrackCordMethod, 1);
CordzInfo* info1 = cord1.data.cordz_info();
CordzInfo::TrackCord(cord2.data, kTrackCordMethod, 1);
CordzInfo* info2 = cord2.data.cordz_info();
CordzInfo::TrackCord(cord3.data, kTrackCordMethod, 1);
CordzInfo* info3 = cord3.data.cordz_info();
CordzSampleToken token;
std::vector<const CordzInfo*> found;
for (const CordzInfo& cord_info : token) {
found.push_back(&cord_info);
}
EXPECT_THAT(found, ElementsAre(info3, info2, info1));
info1->Untrack();
info2->Untrack();
info3->Untrack();
}
TEST(CordzSampleTokenTest, IteratorEquality) {
TestCordData cord1;
TestCordData cord2;
TestCordData cord3;
CordzInfo::TrackCord(cord1.data, kTrackCordMethod, 1);
CordzInfo* info1 = cord1.data.cordz_info();
CordzSampleToken token1;
CordzSampleToken::Iterator lhs = token1.begin();
CordzInfo::TrackCord(cord2.data, kTrackCordMethod, 1);
CordzInfo* info2 = cord2.data.cordz_info();
CordzSampleToken token2;
CordzSampleToken::Iterator rhs = token2.begin();
CordzInfo::TrackCord(cord3.data, kTrackCordMethod, 1);
CordzInfo* info3 = cord3.data.cordz_info();
EXPECT_THAT(lhs, Ne(rhs));
rhs++;
EXPECT_THAT(lhs, Ne(rhs));
lhs++;
rhs++;
EXPECT_THAT(lhs, Eq(rhs));
info1->Untrack();
info2->Untrack();
info3->Untrack();
}
TEST(CordzSampleTokenTest, MultiThreaded) {
Notification stop;
static constexpr int kNumThreads = 4;
static constexpr int kNumCords = 3;
static constexpr int kNumTokens = 3;
absl::synchronization_internal::ThreadPool pool(kNumThreads);
for (int i = 0; i < kNumThreads; ++i) {
pool.Schedule([&stop]() {
absl::BitGen gen;
TestCordData cords[kNumCords];
std::unique_ptr<CordzSampleToken> tokens[kNumTokens];
while (!stop.HasBeenNotified()) {
int index = absl::Uniform(gen, 0, kNumCords);
if (absl::Bernoulli(gen, 0.5)) {
TestCordData& cord = cords[index];
if (cord.data.is_profiled()) {
cord.data.cordz_info()->Untrack();
cord.data.clear_cordz_info();
} else {
CordzInfo::TrackCord(cord.data, kTrackCordMethod, 1);
}
} else {
std::unique_ptr<CordzSampleToken>& token = tokens[index];
if (token) {
if (absl::Bernoulli(gen, 0.5)) {
for (const CordzInfo& info : *token) {
EXPECT_THAT(info.Next(*token), Ne(&info));
}
} else {
token = nullptr;
}
} else {
token = absl::make_unique<CordzSampleToken>();
}
}
}
for (TestCordData& cord : cords) {
CordzInfo::MaybeUntrackCord(cord.data.cordz_info());
}
});
}
absl::SleepFor(absl::Seconds(3));
stop.Notify();
}
}
}
ABSL_NAMESPACE_END
} |
2,562 | cpp | abseil/abseil-cpp | cordz_handle | absl/strings/internal/cordz_handle.cc | absl/strings/internal/cordz_handle_test.cc | #ifndef ABSL_STRINGS_INTERNAL_CORDZ_HANDLE_H_
#define ABSL_STRINGS_INTERNAL_CORDZ_HANDLE_H_
#include <atomic>
#include <vector>
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
class ABSL_DLL CordzHandle {
public:
CordzHandle() : CordzHandle(false) {}
bool is_snapshot() const { return is_snapshot_; }
bool SafeToDelete() const;
static void Delete(CordzHandle* handle);
static std::vector<const CordzHandle*> DiagnosticsGetDeleteQueue();
bool DiagnosticsHandleIsSafeToInspect(const CordzHandle* handle) const;
std::vector<const CordzHandle*> DiagnosticsGetSafeToInspectDeletedHandles();
protected:
explicit CordzHandle(bool is_snapshot);
virtual ~CordzHandle();
private:
const bool is_snapshot_;
CordzHandle* dq_prev_ = nullptr;
CordzHandle* dq_next_ = nullptr;
};
class CordzSnapshot : public CordzHandle {
public:
CordzSnapshot() : CordzHandle(true) {}
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/cordz_handle.h"
#include <atomic>
#include "absl/base/internal/raw_logging.h"
#include "absl/base/no_destructor.h"
#include "absl/synchronization/mutex.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
struct Queue {
Queue() = default;
absl::Mutex mutex;
std::atomic<CordzHandle*> dq_tail ABSL_GUARDED_BY(mutex){nullptr};
bool IsEmpty() const ABSL_NO_THREAD_SAFETY_ANALYSIS {
return dq_tail.load(std::memory_order_acquire) == nullptr;
}
};
static Queue& GlobalQueue() {
static absl::NoDestructor<Queue> global_queue;
return *global_queue;
}
}
CordzHandle::CordzHandle(bool is_snapshot) : is_snapshot_(is_snapshot) {
Queue& global_queue = GlobalQueue();
if (is_snapshot) {
MutexLock lock(&global_queue.mutex);
CordzHandle* dq_tail = global_queue.dq_tail.load(std::memory_order_acquire);
if (dq_tail != nullptr) {
dq_prev_ = dq_tail;
dq_tail->dq_next_ = this;
}
global_queue.dq_tail.store(this, std::memory_order_release);
}
}
CordzHandle::~CordzHandle() {
Queue& global_queue = GlobalQueue();
if (is_snapshot_) {
std::vector<CordzHandle*> to_delete;
{
MutexLock lock(&global_queue.mutex);
CordzHandle* next = dq_next_;
if (dq_prev_ == nullptr) {
while (next && !next->is_snapshot_) {
to_delete.push_back(next);
next = next->dq_next_;
}
} else {
dq_prev_->dq_next_ = next;
}
if (next) {
next->dq_prev_ = dq_prev_;
} else {
global_queue.dq_tail.store(dq_prev_, std::memory_order_release);
}
}
for (CordzHandle* handle : to_delete) {
delete handle;
}
}
}
bool CordzHandle::SafeToDelete() const {
return is_snapshot_ || GlobalQueue().IsEmpty();
}
void CordzHandle::Delete(CordzHandle* handle) {
assert(handle);
if (handle) {
Queue& queue = GlobalQueue();
if (!handle->SafeToDelete()) {
MutexLock lock(&queue.mutex);
CordzHandle* dq_tail = queue.dq_tail.load(std::memory_order_acquire);
if (dq_tail != nullptr) {
handle->dq_prev_ = dq_tail;
dq_tail->dq_next_ = handle;
queue.dq_tail.store(handle, std::memory_order_release);
return;
}
}
delete handle;
}
}
std::vector<const CordzHandle*> CordzHandle::DiagnosticsGetDeleteQueue() {
std::vector<const CordzHandle*> handles;
Queue& global_queue = GlobalQueue();
MutexLock lock(&global_queue.mutex);
CordzHandle* dq_tail = global_queue.dq_tail.load(std::memory_order_acquire);
for (const CordzHandle* p = dq_tail; p; p = p->dq_prev_) {
handles.push_back(p);
}
return handles;
}
bool CordzHandle::DiagnosticsHandleIsSafeToInspect(
const CordzHandle* handle) const {
if (!is_snapshot_) return false;
if (handle == nullptr) return true;
if (handle->is_snapshot_) return false;
bool snapshot_found = false;
Queue& global_queue = GlobalQueue();
MutexLock lock(&global_queue.mutex);
for (const CordzHandle* p = global_queue.dq_tail; p; p = p->dq_prev_) {
if (p == handle) return !snapshot_found;
if (p == this) snapshot_found = true;
}
ABSL_ASSERT(snapshot_found);
return true;
}
std::vector<const CordzHandle*>
CordzHandle::DiagnosticsGetSafeToInspectDeletedHandles() {
std::vector<const CordzHandle*> handles;
if (!is_snapshot()) {
return handles;
}
Queue& global_queue = GlobalQueue();
MutexLock lock(&global_queue.mutex);
for (const CordzHandle* p = dq_next_; p != nullptr; p = p->dq_next_) {
if (!p->is_snapshot()) {
handles.push_back(p);
}
}
return handles;
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/cordz_handle.h"
#include <random>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/synchronization/internal/thread_pool.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::ElementsAre;
using ::testing::Gt;
using ::testing::IsEmpty;
using ::testing::SizeIs;
std::vector<const CordzHandle*> DeleteQueue() {
return CordzHandle::DiagnosticsGetDeleteQueue();
}
struct CordzHandleDeleteTracker : public CordzHandle {
bool* deleted;
explicit CordzHandleDeleteTracker(bool* deleted) : deleted(deleted) {}
~CordzHandleDeleteTracker() override { *deleted = true; }
};
TEST(CordzHandleTest, DeleteQueueIsEmpty) {
EXPECT_THAT(DeleteQueue(), SizeIs(0));
}
TEST(CordzHandleTest, CordzHandleCreateDelete) {
bool deleted = false;
auto* handle = new CordzHandleDeleteTracker(&deleted);
EXPECT_FALSE(handle->is_snapshot());
EXPECT_TRUE(handle->SafeToDelete());
EXPECT_THAT(DeleteQueue(), SizeIs(0));
CordzHandle::Delete(handle);
EXPECT_THAT(DeleteQueue(), SizeIs(0));
EXPECT_TRUE(deleted);
}
TEST(CordzHandleTest, CordzSnapshotCreateDelete) {
auto* snapshot = new CordzSnapshot();
EXPECT_TRUE(snapshot->is_snapshot());
EXPECT_TRUE(snapshot->SafeToDelete());
EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot));
delete snapshot;
EXPECT_THAT(DeleteQueue(), SizeIs(0));
}
TEST(CordzHandleTest, CordzHandleCreateDeleteWithSnapshot) {
bool deleted = false;
auto* snapshot = new CordzSnapshot();
auto* handle = new CordzHandleDeleteTracker(&deleted);
EXPECT_FALSE(handle->SafeToDelete());
CordzHandle::Delete(handle);
EXPECT_THAT(DeleteQueue(), ElementsAre(handle, snapshot));
EXPECT_FALSE(deleted);
EXPECT_FALSE(handle->SafeToDelete());
delete snapshot;
EXPECT_THAT(DeleteQueue(), SizeIs(0));
EXPECT_TRUE(deleted);
}
TEST(CordzHandleTest, MultiSnapshot) {
bool deleted[3] = {false, false, false};
CordzSnapshot* snapshot[3];
CordzHandleDeleteTracker* handle[3];
for (int i = 0; i < 3; ++i) {
snapshot[i] = new CordzSnapshot();
handle[i] = new CordzHandleDeleteTracker(&deleted[i]);
CordzHandle::Delete(handle[i]);
}
EXPECT_THAT(DeleteQueue(), ElementsAre(handle[2], snapshot[2], handle[1],
snapshot[1], handle[0], snapshot[0]));
EXPECT_THAT(deleted, ElementsAre(false, false, false));
delete snapshot[1];
EXPECT_THAT(DeleteQueue(), ElementsAre(handle[2], snapshot[2], handle[1],
handle[0], snapshot[0]));
EXPECT_THAT(deleted, ElementsAre(false, false, false));
delete snapshot[0];
EXPECT_THAT(DeleteQueue(), ElementsAre(handle[2], snapshot[2]));
EXPECT_THAT(deleted, ElementsAre(true, true, false));
delete snapshot[2];
EXPECT_THAT(DeleteQueue(), SizeIs(0));
EXPECT_THAT(deleted, ElementsAre(true, true, deleted));
}
TEST(CordzHandleTest, DiagnosticsHandleIsSafeToInspect) {
CordzSnapshot snapshot1;
EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(nullptr));
auto* handle1 = new CordzHandle();
EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1));
CordzHandle::Delete(handle1);
EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1));
CordzSnapshot snapshot2;
auto* handle2 = new CordzHandle();
EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1));
EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle2));
EXPECT_FALSE(snapshot2.DiagnosticsHandleIsSafeToInspect(handle1));
EXPECT_TRUE(snapshot2.DiagnosticsHandleIsSafeToInspect(handle2));
CordzHandle::Delete(handle2);
EXPECT_TRUE(snapshot1.DiagnosticsHandleIsSafeToInspect(handle1));
}
TEST(CordzHandleTest, DiagnosticsGetSafeToInspectDeletedHandles) {
EXPECT_THAT(DeleteQueue(), IsEmpty());
auto* handle = new CordzHandle();
auto* snapshot1 = new CordzSnapshot();
EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot1));
EXPECT_TRUE(snapshot1->DiagnosticsHandleIsSafeToInspect(handle));
EXPECT_THAT(snapshot1->DiagnosticsGetSafeToInspectDeletedHandles(),
IsEmpty());
CordzHandle::Delete(handle);
auto* snapshot2 = new CordzSnapshot();
EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot2, handle, snapshot1));
EXPECT_TRUE(snapshot1->DiagnosticsHandleIsSafeToInspect(handle));
EXPECT_FALSE(snapshot2->DiagnosticsHandleIsSafeToInspect(handle));
EXPECT_THAT(snapshot1->DiagnosticsGetSafeToInspectDeletedHandles(),
ElementsAre(handle));
EXPECT_THAT(snapshot2->DiagnosticsGetSafeToInspectDeletedHandles(),
IsEmpty());
CordzHandle::Delete(snapshot1);
EXPECT_THAT(DeleteQueue(), ElementsAre(snapshot2));
CordzHandle::Delete(snapshot2);
EXPECT_THAT(DeleteQueue(), IsEmpty());
}
TEST(CordzHandleTest, MultiThreaded) {
Notification stop;
static constexpr int kNumThreads = 4;
static constexpr int kNumHandles = 10;
std::vector<std::atomic<CordzHandle*>> handles(kNumHandles);
std::atomic<bool> found_safe_to_inspect(false);
{
absl::synchronization_internal::ThreadPool pool(kNumThreads);
for (int i = 0; i < kNumThreads; ++i) {
pool.Schedule([&stop, &handles, &found_safe_to_inspect]() {
std::minstd_rand gen;
std::uniform_int_distribution<int> dist_type(0, 2);
std::uniform_int_distribution<int> dist_handle(0, kNumHandles - 1);
while (!stop.HasBeenNotified()) {
CordzHandle* handle;
switch (dist_type(gen)) {
case 0:
handle = new CordzHandle();
break;
case 1:
handle = new CordzSnapshot();
break;
default:
handle = nullptr;
break;
}
CordzHandle* old_handle = handles[dist_handle(gen)].exchange(handle);
if (old_handle != nullptr) {
std::vector<const CordzHandle*> safe_to_inspect =
old_handle->DiagnosticsGetSafeToInspectDeletedHandles();
for (const CordzHandle* handle : safe_to_inspect) {
ASSERT_FALSE(handle->is_snapshot());
}
if (!safe_to_inspect.empty()) {
found_safe_to_inspect.store(true);
}
CordzHandle::Delete(old_handle);
}
}
for (auto& h : handles) {
if (CordzHandle* handle = h.exchange(nullptr)) {
CordzHandle::Delete(handle);
}
}
});
}
absl::SleepFor(absl::Seconds(3));
stop.Notify();
}
EXPECT_TRUE(found_safe_to_inspect.load());
}
}
}
ABSL_NAMESPACE_END
} |
2,563 | cpp | abseil/abseil-cpp | pow10_helper | absl/strings/internal/pow10_helper.cc | absl/strings/internal/pow10_helper_test.cc | #ifndef ABSL_STRINGS_INTERNAL_POW10_HELPER_H_
#define ABSL_STRINGS_INTERNAL_POW10_HELPER_H_
#include <vector>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
double Pow10(int exp);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/pow10_helper.h"
#include <cmath>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
namespace {
constexpr double k1e23 = 9999999999999999e7;
constexpr double kPowersOfTen[] = {
0.0, 1e-323, 1e-322, 1e-321, 1e-320, 1e-319, 1e-318, 1e-317, 1e-316,
1e-315, 1e-314, 1e-313, 1e-312, 1e-311, 1e-310, 1e-309, 1e-308, 1e-307,
1e-306, 1e-305, 1e-304, 1e-303, 1e-302, 1e-301, 1e-300, 1e-299, 1e-298,
1e-297, 1e-296, 1e-295, 1e-294, 1e-293, 1e-292, 1e-291, 1e-290, 1e-289,
1e-288, 1e-287, 1e-286, 1e-285, 1e-284, 1e-283, 1e-282, 1e-281, 1e-280,
1e-279, 1e-278, 1e-277, 1e-276, 1e-275, 1e-274, 1e-273, 1e-272, 1e-271,
1e-270, 1e-269, 1e-268, 1e-267, 1e-266, 1e-265, 1e-264, 1e-263, 1e-262,
1e-261, 1e-260, 1e-259, 1e-258, 1e-257, 1e-256, 1e-255, 1e-254, 1e-253,
1e-252, 1e-251, 1e-250, 1e-249, 1e-248, 1e-247, 1e-246, 1e-245, 1e-244,
1e-243, 1e-242, 1e-241, 1e-240, 1e-239, 1e-238, 1e-237, 1e-236, 1e-235,
1e-234, 1e-233, 1e-232, 1e-231, 1e-230, 1e-229, 1e-228, 1e-227, 1e-226,
1e-225, 1e-224, 1e-223, 1e-222, 1e-221, 1e-220, 1e-219, 1e-218, 1e-217,
1e-216, 1e-215, 1e-214, 1e-213, 1e-212, 1e-211, 1e-210, 1e-209, 1e-208,
1e-207, 1e-206, 1e-205, 1e-204, 1e-203, 1e-202, 1e-201, 1e-200, 1e-199,
1e-198, 1e-197, 1e-196, 1e-195, 1e-194, 1e-193, 1e-192, 1e-191, 1e-190,
1e-189, 1e-188, 1e-187, 1e-186, 1e-185, 1e-184, 1e-183, 1e-182, 1e-181,
1e-180, 1e-179, 1e-178, 1e-177, 1e-176, 1e-175, 1e-174, 1e-173, 1e-172,
1e-171, 1e-170, 1e-169, 1e-168, 1e-167, 1e-166, 1e-165, 1e-164, 1e-163,
1e-162, 1e-161, 1e-160, 1e-159, 1e-158, 1e-157, 1e-156, 1e-155, 1e-154,
1e-153, 1e-152, 1e-151, 1e-150, 1e-149, 1e-148, 1e-147, 1e-146, 1e-145,
1e-144, 1e-143, 1e-142, 1e-141, 1e-140, 1e-139, 1e-138, 1e-137, 1e-136,
1e-135, 1e-134, 1e-133, 1e-132, 1e-131, 1e-130, 1e-129, 1e-128, 1e-127,
1e-126, 1e-125, 1e-124, 1e-123, 1e-122, 1e-121, 1e-120, 1e-119, 1e-118,
1e-117, 1e-116, 1e-115, 1e-114, 1e-113, 1e-112, 1e-111, 1e-110, 1e-109,
1e-108, 1e-107, 1e-106, 1e-105, 1e-104, 1e-103, 1e-102, 1e-101, 1e-100,
1e-99, 1e-98, 1e-97, 1e-96, 1e-95, 1e-94, 1e-93, 1e-92, 1e-91,
1e-90, 1e-89, 1e-88, 1e-87, 1e-86, 1e-85, 1e-84, 1e-83, 1e-82,
1e-81, 1e-80, 1e-79, 1e-78, 1e-77, 1e-76, 1e-75, 1e-74, 1e-73,
1e-72, 1e-71, 1e-70, 1e-69, 1e-68, 1e-67, 1e-66, 1e-65, 1e-64,
1e-63, 1e-62, 1e-61, 1e-60, 1e-59, 1e-58, 1e-57, 1e-56, 1e-55,
1e-54, 1e-53, 1e-52, 1e-51, 1e-50, 1e-49, 1e-48, 1e-47, 1e-46,
1e-45, 1e-44, 1e-43, 1e-42, 1e-41, 1e-40, 1e-39, 1e-38, 1e-37,
1e-36, 1e-35, 1e-34, 1e-33, 1e-32, 1e-31, 1e-30, 1e-29, 1e-28,
1e-27, 1e-26, 1e-25, 1e-24, 1e-23, 1e-22, 1e-21, 1e-20, 1e-19,
1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10,
1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1,
1e+0, 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8,
1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17,
1e+18, 1e+19, 1e+20, 1e+21, 1e+22, k1e23, 1e+24, 1e+25, 1e+26,
1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35,
1e+36, 1e+37, 1e+38, 1e+39, 1e+40, 1e+41, 1e+42, 1e+43, 1e+44,
1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53,
1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, 1e+61, 1e+62,
1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71,
1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80,
1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89,
1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98,
1e+99, 1e+100, 1e+101, 1e+102, 1e+103, 1e+104, 1e+105, 1e+106, 1e+107,
1e+108, 1e+109, 1e+110, 1e+111, 1e+112, 1e+113, 1e+114, 1e+115, 1e+116,
1e+117, 1e+118, 1e+119, 1e+120, 1e+121, 1e+122, 1e+123, 1e+124, 1e+125,
1e+126, 1e+127, 1e+128, 1e+129, 1e+130, 1e+131, 1e+132, 1e+133, 1e+134,
1e+135, 1e+136, 1e+137, 1e+138, 1e+139, 1e+140, 1e+141, 1e+142, 1e+143,
1e+144, 1e+145, 1e+146, 1e+147, 1e+148, 1e+149, 1e+150, 1e+151, 1e+152,
1e+153, 1e+154, 1e+155, 1e+156, 1e+157, 1e+158, 1e+159, 1e+160, 1e+161,
1e+162, 1e+163, 1e+164, 1e+165, 1e+166, 1e+167, 1e+168, 1e+169, 1e+170,
1e+171, 1e+172, 1e+173, 1e+174, 1e+175, 1e+176, 1e+177, 1e+178, 1e+179,
1e+180, 1e+181, 1e+182, 1e+183, 1e+184, 1e+185, 1e+186, 1e+187, 1e+188,
1e+189, 1e+190, 1e+191, 1e+192, 1e+193, 1e+194, 1e+195, 1e+196, 1e+197,
1e+198, 1e+199, 1e+200, 1e+201, 1e+202, 1e+203, 1e+204, 1e+205, 1e+206,
1e+207, 1e+208, 1e+209, 1e+210, 1e+211, 1e+212, 1e+213, 1e+214, 1e+215,
1e+216, 1e+217, 1e+218, 1e+219, 1e+220, 1e+221, 1e+222, 1e+223, 1e+224,
1e+225, 1e+226, 1e+227, 1e+228, 1e+229, 1e+230, 1e+231, 1e+232, 1e+233,
1e+234, 1e+235, 1e+236, 1e+237, 1e+238, 1e+239, 1e+240, 1e+241, 1e+242,
1e+243, 1e+244, 1e+245, 1e+246, 1e+247, 1e+248, 1e+249, 1e+250, 1e+251,
1e+252, 1e+253, 1e+254, 1e+255, 1e+256, 1e+257, 1e+258, 1e+259, 1e+260,
1e+261, 1e+262, 1e+263, 1e+264, 1e+265, 1e+266, 1e+267, 1e+268, 1e+269,
1e+270, 1e+271, 1e+272, 1e+273, 1e+274, 1e+275, 1e+276, 1e+277, 1e+278,
1e+279, 1e+280, 1e+281, 1e+282, 1e+283, 1e+284, 1e+285, 1e+286, 1e+287,
1e+288, 1e+289, 1e+290, 1e+291, 1e+292, 1e+293, 1e+294, 1e+295, 1e+296,
1e+297, 1e+298, 1e+299, 1e+300, 1e+301, 1e+302, 1e+303, 1e+304, 1e+305,
1e+306, 1e+307, 1e+308,
};
}
double Pow10(int exp) {
if (exp < -324) {
return 0.0;
} else if (exp > 308) {
return INFINITY;
} else {
return kPowersOfTen[exp + 324];
}
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/pow10_helper.h"
#include <cmath>
#include "gtest/gtest.h"
#include "absl/strings/str_format.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
namespace {
struct TestCase {
int power;
uint64_t significand;
int radix;
};
TEST(Pow10HelperTest, Works) {
constexpr TestCase kTestCases[] = {
{-323, 0x2, -1074},
{-322, 0x14, -1074},
{-321, 0xca, -1074},
{-320, 0x7e8, -1074},
{-319, 0x4f10, -1074},
{-318, 0x316a2, -1074},
{-317, 0x1ee257, -1074},
{-316, 0x134d761, -1074},
{-315, 0xc1069cd, -1074},
{-314, 0x78a42205, -1074},
{-313, 0x4b6695433, -1074},
{-312, 0x2f201d49fb, -1074},
{-311, 0x1d74124e3d1, -1074},
{-310, 0x12688b70e62b, -1074},
{-309, 0xb8157268fdaf, -1074},
{-308, 0x730d67819e8d2, -1074},
{-307, 0x11fa182c40c60d, -1072},
{-290, 0x18f2b061aea072, -1016},
{-276, 0x11BA03F5B21000, -969},
{-259, 0x1899C2F6732210, -913},
{-252, 0x1D53844EE47DD1, -890},
{-227, 0x1E5297287C2F45, -807},
{-198, 0x1322E220A5B17E, -710},
{-195, 0x12B010D3E1CF56, -700},
{-192, 0x123FF06EEA847A, -690},
{-163, 0x1708D0F84D3DE7, -594},
{-145, 0x13FAAC3E3FA1F3, -534},
{-111, 0x133D4032C2C7F5, -421},
{-106, 0x1D5B561574765B, -405},
{-104, 0x16EF5B40C2FC77, -398},
{-88, 0x197683DF2F268D, -345},
{-86, 0x13E497065CD61F, -338},
{-76, 0x17288E1271F513, -305},
{-63, 0x1A53FC9631D10D, -262},
{-30, 0x14484BFEEBC2A0, -152},
{-21, 0x12E3B40A0E9B4F, -122},
{-5, 0x14F8B588E368F1, -69},
{23, 0x152D02C7E14AF6, 24},
{29, 0x1431E0FAE6D721, 44},
{34, 0x1ED09BEAD87C03, 60},
{70, 0x172EBAD6DDC73D, 180},
{105, 0x1BE7ABD3781ECA, 296},
{126, 0x17A2ECC414A03F, 366},
{130, 0x1CDA62055B2D9E, 379},
{165, 0x115D847AD00087, 496},
{172, 0x14B378469B6732, 519},
{187, 0x1262DFEEBBB0F9, 569},
{210, 0x18557F31326BBB, 645},
{212, 0x1302CB5E6F642A, 652},
{215, 0x1290BA9A38C7D1, 662},
{236, 0x1F736F9B3494E9, 731},
{244, 0x176EC98994F489, 758},
{250, 0x1658E3AB795204, 778},
{252, 0x117571DDF6C814, 785},
{254, 0x1B4781EAD1989E, 791},
{260, 0x1A03FDE214CAF1, 811},
{284, 0x1585041B2C477F, 891},
{304, 0x1D2A1BE4048F90, 957},
{-324, 0x0, 0},
{-325, 0x0, 0},
{-326, 0x0, 0},
{309, 1, 2000},
{310, 1, 2000},
{311, 1, 2000},
};
for (const TestCase& test_case : kTestCases) {
EXPECT_EQ(Pow10(test_case.power),
std::ldexp(test_case.significand, test_case.radix))
<< absl::StrFormat("Failure for Pow10(%d): %a vs %a", test_case.power,
Pow10(test_case.power),
std::ldexp(test_case.significand, test_case.radix));
}
}
}
}
ABSL_NAMESPACE_END
} |
2,564 | 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 | #ifndef ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_READER_H_
#define ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_READER_H_
#include <cassert>
#include "absl/base/config.h"
#include "absl/strings/internal/cord_data_edge.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_btree_navigator.h"
#include "absl/strings/internal/cord_rep_flat.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
class CordRepBtreeReader {
public:
using ReadResult = CordRepBtreeNavigator::ReadResult;
using Position = CordRepBtreeNavigator::Position;
explicit operator bool() const { return navigator_.btree() != nullptr; }
CordRepBtree* btree() const { return navigator_.btree(); }
CordRep* node() const { return navigator_.Current(); }
size_t length() const;
size_t remaining() const { return remaining_; }
void Reset() { navigator_.Reset(); }
absl::string_view Init(CordRepBtree* tree);
absl::string_view Next();
absl::string_view Skip(size_t skip);
absl::string_view Read(size_t n, size_t chunk_size, CordRep*& tree);
absl::string_view Seek(size_t offset);
private:
size_t remaining_ = 0;
CordRepBtreeNavigator navigator_;
};
inline size_t CordRepBtreeReader::length() const {
assert(btree() != nullptr);
return btree()->length;
}
inline absl::string_view CordRepBtreeReader::Init(CordRepBtree* tree) {
assert(tree != nullptr);
const CordRep* edge = navigator_.InitFirst(tree);
remaining_ = tree->length - edge->length;
return EdgeData(edge);
}
inline absl::string_view CordRepBtreeReader::Next() {
if (remaining_ == 0) return {};
const CordRep* edge = navigator_.Next();
assert(edge != nullptr);
remaining_ -= edge->length;
return EdgeData(edge);
}
inline absl::string_view CordRepBtreeReader::Skip(size_t skip) {
const size_t edge_length = navigator_.Current()->length;
CordRepBtreeNavigator::Position pos = navigator_.Skip(skip + edge_length);
if (ABSL_PREDICT_FALSE(pos.edge == nullptr)) {
remaining_ = 0;
return {};
}
remaining_ -= skip - pos.offset + pos.edge->length;
return EdgeData(pos.edge).substr(pos.offset);
}
inline absl::string_view CordRepBtreeReader::Seek(size_t offset) {
const CordRepBtreeNavigator::Position pos = navigator_.Seek(offset);
if (ABSL_PREDICT_FALSE(pos.edge == nullptr)) {
remaining_ = 0;
return {};
}
absl::string_view chunk = EdgeData(pos.edge).substr(pos.offset);
remaining_ = length() - offset - chunk.length();
return chunk;
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/cord_rep_btree_reader.h"
#include <cassert>
#include "absl/base/config.h"
#include "absl/strings/internal/cord_data_edge.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_btree_navigator.h"
#include "absl/strings/internal/cord_rep_flat.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
absl::string_view CordRepBtreeReader::Read(size_t n, size_t chunk_size,
CordRep*& tree) {
assert(chunk_size <= navigator_.Current()->length);
CordRep* edge = chunk_size ? navigator_.Current() : navigator_.Next();
const size_t offset = chunk_size ? edge->length - chunk_size : 0;
ReadResult result = navigator_.Read(offset, n);
tree = result.tree;
if (n < chunk_size) return EdgeData(edge).substr(result.n);
const size_t consumed_by_read = n - chunk_size - result.n;
if (consumed_by_read >= remaining_) {
remaining_ = 0;
return {};
}
edge = navigator_.Current();
remaining_ -= consumed_by_read + edge->length;
return EdgeData(edge).substr(result.n);
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/cord_rep_btree_reader.h"
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/strings/cord.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_test_util.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Ne;
using ::testing::Not;
using ::absl::cordrep_testing::CordRepBtreeFromFlats;
using ::absl::cordrep_testing::MakeFlat;
using ::absl::cordrep_testing::CordToString;
using ::absl::cordrep_testing::CreateFlatsFromString;
using ::absl::cordrep_testing::CreateRandomString;
using ReadResult = CordRepBtreeReader::ReadResult;
TEST(CordRepBtreeReaderTest, Next) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
size_t counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (size_t count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
CordRepBtreeReader reader;
size_t remaining = data.length();
absl::string_view chunk = reader.Init(node);
EXPECT_THAT(chunk, Eq(data.substr(0, chunk.length())));
remaining -= chunk.length();
EXPECT_THAT(reader.remaining(), Eq(remaining));
while (remaining > 0) {
const size_t offset = data.length() - remaining;
chunk = reader.Next();
EXPECT_THAT(chunk, Eq(data.substr(offset, chunk.length())));
remaining -= chunk.length();
EXPECT_THAT(reader.remaining(), Eq(remaining));
}
EXPECT_THAT(reader.remaining(), Eq(0u));
EXPECT_THAT(reader.Next(), testing::IsEmpty());
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, Skip) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
size_t counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (size_t count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t skip1 = 0; skip1 < data.length() - kChars; ++skip1) {
for (size_t skip2 = 0; skip2 < data.length() - kChars; ++skip2) {
CordRepBtreeReader reader;
size_t remaining = data.length();
absl::string_view chunk = reader.Init(node);
remaining -= chunk.length();
chunk = reader.Skip(skip1);
size_t offset = data.length() - remaining;
ASSERT_THAT(chunk, Eq(data.substr(offset + skip1, chunk.length())));
remaining -= chunk.length() + skip1;
ASSERT_THAT(reader.remaining(), Eq(remaining));
if (remaining == 0) continue;
size_t skip = std::min(remaining - 1, skip2);
chunk = reader.Skip(skip);
offset = data.length() - remaining;
ASSERT_THAT(chunk, Eq(data.substr(offset + skip, chunk.length())));
}
}
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, SkipBeyondLength) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
tree = CordRepBtree::Append(tree, MakeFlat("def"));
CordRepBtreeReader reader;
reader.Init(tree);
EXPECT_THAT(reader.Skip(100), IsEmpty());
EXPECT_THAT(reader.remaining(), Eq(0u));
CordRep::Unref(tree);
}
TEST(CordRepBtreeReaderTest, Seek) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
size_t counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (size_t count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t seek = 0; seek < data.length() - 1; ++seek) {
CordRepBtreeReader reader;
reader.Init(node);
absl::string_view chunk = reader.Seek(seek);
ASSERT_THAT(chunk, Not(IsEmpty()));
ASSERT_THAT(chunk, Eq(data.substr(seek, chunk.length())));
ASSERT_THAT(reader.remaining(),
Eq(data.length() - seek - chunk.length()));
}
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, SeekBeyondLength) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
tree = CordRepBtree::Append(tree, MakeFlat("def"));
CordRepBtreeReader reader;
reader.Init(tree);
EXPECT_THAT(reader.Seek(6), IsEmpty());
EXPECT_THAT(reader.remaining(), Eq(0u));
EXPECT_THAT(reader.Seek(100), IsEmpty());
EXPECT_THAT(reader.remaining(), Eq(0u));
CordRep::Unref(tree);
}
TEST(CordRepBtreeReaderTest, Read) {
std::string data = "abcdefghijklmno";
std::vector<CordRep*> flats = CreateFlatsFromString(data, 5);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
CordRep* tree;
CordRepBtreeReader reader;
absl::string_view chunk;
chunk = reader.Init(node);
chunk = reader.Read(0, chunk.length(), tree);
EXPECT_THAT(tree, Eq(nullptr));
EXPECT_THAT(chunk, Eq("abcde"));
EXPECT_THAT(reader.remaining(), Eq(10u));
EXPECT_THAT(reader.Next(), Eq("fghij"));
chunk = reader.Init(node);
chunk = reader.Read(15, chunk.length(), tree);
EXPECT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("abcdefghijklmno"));
EXPECT_THAT(chunk, Eq(""));
EXPECT_THAT(reader.remaining(), Eq(0u));
CordRep::Unref(tree);
chunk = reader.Init(node);
chunk = reader.Read(3, chunk.length(), tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("abc"));
EXPECT_THAT(chunk, Eq("de"));
EXPECT_THAT(reader.remaining(), Eq(10u));
EXPECT_THAT(reader.Next(), Eq("fghij"));
CordRep::Unref(tree);
chunk = reader.Init(node);
chunk = reader.Read(2, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cd"));
EXPECT_THAT(chunk, Eq("e"));
EXPECT_THAT(reader.remaining(), Eq(10u));
EXPECT_THAT(reader.Next(), Eq("fghij"));
CordRep::Unref(tree);
chunk = reader.Init(node);
chunk = reader.Read(3, 0, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("fgh"));
EXPECT_THAT(chunk, Eq("ij"));
EXPECT_THAT(reader.remaining(), Eq(5u));
EXPECT_THAT(reader.Next(), Eq("klmno"));
CordRep::Unref(tree);
chunk = reader.Init(node);
chunk = reader.Read(12, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cdefghijklmn"));
EXPECT_THAT(chunk, Eq("o"));
EXPECT_THAT(reader.remaining(), Eq(0u));
CordRep::Unref(tree);
chunk = reader.Init(node);
chunk = reader.Read(10 - 2, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cdefghij"));
EXPECT_THAT(chunk, Eq("klmno"));
EXPECT_THAT(reader.remaining(), Eq(0u));
CordRep::Unref(tree);
CordRep::Unref(node);
}
TEST(CordRepBtreeReaderTest, ReadExhaustive) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
size_t counts[] = {1, 2, cap, cap * cap + 1, cap * cap * cap * 2 + 17};
for (size_t count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t read_size : {kChars - 1, kChars, kChars + 7, cap * cap}) {
CordRepBtreeReader reader;
absl::string_view chunk = reader.Init(node);
size_t consumed = 0;
size_t remaining = data.length();
while (remaining > 0) {
CordRep* tree;
size_t n = (std::min)(remaining, read_size);
chunk = reader.Read(n, chunk.length(), tree);
EXPECT_THAT(tree, Ne(nullptr));
if (tree) {
EXPECT_THAT(CordToString(tree), Eq(data.substr(consumed, n)));
CordRep::Unref(tree);
}
consumed += n;
remaining -= n;
EXPECT_THAT(reader.remaining(), Eq(remaining - chunk.length()));
if (remaining > 0) {
ASSERT_FALSE(chunk.empty());
ASSERT_THAT(chunk, Eq(data.substr(consumed, chunk.length())));
} else {
ASSERT_TRUE(chunk.empty()) << chunk;
}
}
}
CordRep::Unref(node);
}
}
}
}
ABSL_NAMESPACE_END
} |
2,565 | cpp | abseil/abseil-cpp | utf8 | absl/strings/internal/utf8.cc | absl/strings/internal/utf8_test.cc | #ifndef ABSL_STRINGS_INTERNAL_UTF8_H_
#define ABSL_STRINGS_INTERNAL_UTF8_H_
#include <cstddef>
#include <cstdint>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
enum { kMaxEncodedUTF8Size = 4 };
size_t EncodeUTF8Char(char *buffer, char32_t utf8_char);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/utf8.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace strings_internal {
size_t EncodeUTF8Char(char *buffer, char32_t utf8_char) {
if (utf8_char <= 0x7F) {
*buffer = static_cast<char>(utf8_char);
return 1;
} else if (utf8_char <= 0x7FF) {
buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F));
utf8_char >>= 6;
buffer[0] = static_cast<char>(0xC0 | utf8_char);
return 2;
} else if (utf8_char <= 0xFFFF) {
buffer[2] = static_cast<char>(0x80 | (utf8_char & 0x3F));
utf8_char >>= 6;
buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F));
utf8_char >>= 6;
buffer[0] = static_cast<char>(0xE0 | utf8_char);
return 3;
} else {
buffer[3] = static_cast<char>(0x80 | (utf8_char & 0x3F));
utf8_char >>= 6;
buffer[2] = static_cast<char>(0x80 | (utf8_char & 0x3F));
utf8_char >>= 6;
buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F));
utf8_char >>= 6;
buffer[0] = static_cast<char>(0xF0 | utf8_char);
return 4;
}
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/utf8.h"
#include <cstdint>
#include <utility>
#include "gtest/gtest.h"
#include "absl/base/port.h"
namespace {
#if !defined(__cpp_char8_t)
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++2a-compat"
#endif
TEST(EncodeUTF8Char, BasicFunction) {
std::pair<char32_t, std::string> tests[] = {{0x0030, u8"\u0030"},
{0x00A3, u8"\u00A3"},
{0x00010000, u8"\U00010000"},
{0x0000FFFF, u8"\U0000FFFF"},
{0x0010FFFD, u8"\U0010FFFD"}};
for (auto &test : tests) {
char buf0[7] = {'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'};
char buf1[7] = {'\xFF', '\xFF', '\xFF', '\xFF', '\xFF', '\xFF', '\xFF'};
char *buf0_written =
&buf0[absl::strings_internal::EncodeUTF8Char(buf0, test.first)];
char *buf1_written =
&buf1[absl::strings_internal::EncodeUTF8Char(buf1, test.first)];
int apparent_length = 7;
while (buf0[apparent_length - 1] == '\x00' &&
buf1[apparent_length - 1] == '\xFF') {
if (--apparent_length == 0) break;
}
EXPECT_EQ(apparent_length, buf0_written - buf0);
EXPECT_EQ(apparent_length, buf1_written - buf1);
EXPECT_EQ(apparent_length, test.second.length());
EXPECT_EQ(std::string(buf0, apparent_length), test.second);
EXPECT_EQ(std::string(buf1, apparent_length), test.second);
}
char buf[32] = "Don't Tread On Me";
EXPECT_LE(absl::strings_internal::EncodeUTF8Char(buf, 0x00110000),
absl::strings_internal::kMaxEncodedUTF8Size);
char buf2[32] = "Negative is invalid but sane";
EXPECT_LE(absl::strings_internal::EncodeUTF8Char(buf2, -1),
absl::strings_internal::kMaxEncodedUTF8Size);
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif
} |
2,566 | 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 | #ifndef ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_NAVIGATOR_H_
#define ABSL_STRINGS_INTERNAL_CORD_REP_BTREE_NAVIGATOR_H_
#include <cassert>
#include <iostream>
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
class CordRepBtreeNavigator {
public:
struct Position {
CordRep* edge;
size_t offset;
};
struct ReadResult {
CordRep* tree;
size_t n;
};
explicit operator bool() const;
CordRepBtree* btree() const;
CordRep* Current() const;
CordRep* InitFirst(CordRepBtree* tree);
CordRep* InitLast(CordRepBtree* tree);
Position InitOffset(CordRepBtree* tree, size_t offset);
CordRep* Next();
CordRep* Previous();
Position Seek(size_t offset);
ReadResult Read(size_t edge_offset, size_t n);
Position Skip(size_t n);
void Reset();
private:
CordRep* NextUp();
CordRep* PreviousUp();
template <CordRepBtree::EdgeType edge_type>
CordRep* Init(CordRepBtree* tree);
int height_ = -1;
uint8_t index_[CordRepBtree::kMaxDepth];
CordRepBtree* node_[CordRepBtree::kMaxDepth];
};
inline CordRepBtreeNavigator::operator bool() const { return height_ >= 0; }
inline CordRepBtree* CordRepBtreeNavigator::btree() const {
return height_ >= 0 ? node_[height_] : nullptr;
}
inline CordRep* CordRepBtreeNavigator::Current() const {
assert(height_ >= 0);
return node_[0]->Edge(index_[0]);
}
inline void CordRepBtreeNavigator::Reset() { height_ = -1; }
inline CordRep* CordRepBtreeNavigator::InitFirst(CordRepBtree* tree) {
return Init<CordRepBtree::kFront>(tree);
}
inline CordRep* CordRepBtreeNavigator::InitLast(CordRepBtree* tree) {
return Init<CordRepBtree::kBack>(tree);
}
template <CordRepBtree::EdgeType edge_type>
inline CordRep* CordRepBtreeNavigator::Init(CordRepBtree* tree) {
assert(tree != nullptr);
assert(tree->size() > 0);
assert(tree->height() <= CordRepBtree::kMaxHeight);
int height = height_ = tree->height();
size_t index = tree->index(edge_type);
node_[height] = tree;
index_[height] = static_cast<uint8_t>(index);
while (--height >= 0) {
tree = tree->Edge(index)->btree();
node_[height] = tree;
index = tree->index(edge_type);
index_[height] = static_cast<uint8_t>(index);
}
return node_[0]->Edge(index);
}
inline CordRepBtreeNavigator::Position CordRepBtreeNavigator::Seek(
size_t offset) {
assert(btree() != nullptr);
int height = height_;
CordRepBtree* edge = node_[height];
if (ABSL_PREDICT_FALSE(offset >= edge->length)) return {nullptr, 0};
CordRepBtree::Position index = edge->IndexOf(offset);
index_[height] = static_cast<uint8_t>(index.index);
while (--height >= 0) {
edge = edge->Edge(index.index)->btree();
node_[height] = edge;
index = edge->IndexOf(index.n);
index_[height] = static_cast<uint8_t>(index.index);
}
return {edge->Edge(index.index), index.n};
}
inline CordRepBtreeNavigator::Position CordRepBtreeNavigator::InitOffset(
CordRepBtree* tree, size_t offset) {
assert(tree != nullptr);
assert(tree->height() <= CordRepBtree::kMaxHeight);
if (ABSL_PREDICT_FALSE(offset >= tree->length)) return {nullptr, 0};
height_ = tree->height();
node_[height_] = tree;
return Seek(offset);
}
inline CordRep* CordRepBtreeNavigator::Next() {
CordRepBtree* edge = node_[0];
return index_[0] == edge->back() ? NextUp() : edge->Edge(++index_[0]);
}
inline CordRep* CordRepBtreeNavigator::Previous() {
CordRepBtree* edge = node_[0];
return index_[0] == edge->begin() ? PreviousUp() : edge->Edge(--index_[0]);
}
inline CordRep* CordRepBtreeNavigator::NextUp() {
assert(index_[0] == node_[0]->back());
CordRepBtree* edge;
size_t index;
int height = 0;
do {
if (++height > height_) return nullptr;
edge = node_[height];
index = index_[height] + 1;
} while (index == edge->end());
index_[height] = static_cast<uint8_t>(index);
do {
node_[--height] = edge = edge->Edge(index)->btree();
index_[height] = static_cast<uint8_t>(index = edge->begin());
} while (height > 0);
return edge->Edge(index);
}
inline CordRep* CordRepBtreeNavigator::PreviousUp() {
assert(index_[0] == node_[0]->begin());
CordRepBtree* edge;
size_t index;
int height = 0;
do {
if (++height > height_) return nullptr;
edge = node_[height];
index = index_[height];
} while (index == edge->begin());
index_[height] = static_cast<uint8_t>(--index);
do {
node_[--height] = edge = edge->Edge(index)->btree();
index_[height] = static_cast<uint8_t>(index = edge->back());
} while (height > 0);
return edge->Edge(index);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/cord_rep_btree_navigator.h"
#include <cassert>
#include "absl/strings/internal/cord_data_edge.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
using ReadResult = CordRepBtreeNavigator::ReadResult;
namespace {
inline CordRep* Substring(CordRep* rep, size_t offset, size_t n) {
assert(n <= rep->length);
assert(offset < rep->length);
assert(offset <= rep->length - n);
assert(IsDataEdge(rep));
if (n == 0) return nullptr;
if (n == rep->length) return CordRep::Ref(rep);
if (rep->tag == SUBSTRING) {
offset += rep->substring()->start;
rep = rep->substring()->child;
}
assert(rep->IsExternal() || rep->IsFlat());
CordRepSubstring* substring = new CordRepSubstring();
substring->length = n;
substring->tag = SUBSTRING;
substring->start = offset;
substring->child = CordRep::Ref(rep);
return substring;
}
inline CordRep* Substring(CordRep* rep, size_t offset) {
return Substring(rep, offset, rep->length - offset);
}
}
CordRepBtreeNavigator::Position CordRepBtreeNavigator::Skip(size_t n) {
int height = 0;
size_t index = index_[0];
CordRepBtree* node = node_[0];
CordRep* edge = node->Edge(index);
while (n >= edge->length) {
n -= edge->length;
while (++index == node->end()) {
if (++height > height_) return {nullptr, n};
node = node_[height];
index = index_[height];
}
edge = node->Edge(index);
}
while (height > 0) {
node = edge->btree();
index_[height] = static_cast<uint8_t>(index);
node_[--height] = node;
index = node->begin();
edge = node->Edge(index);
while (n >= edge->length) {
n -= edge->length;
++index;
assert(index != node->end());
edge = node->Edge(index);
}
}
index_[0] = static_cast<uint8_t>(index);
return {edge, n};
}
ReadResult CordRepBtreeNavigator::Read(size_t edge_offset, size_t n) {
int height = 0;
size_t length = edge_offset + n;
size_t index = index_[0];
CordRepBtree* node = node_[0];
CordRep* edge = node->Edge(index);
assert(edge_offset < edge->length);
if (length < edge->length) {
return {Substring(edge, edge_offset, n), length};
}
CordRepBtree* subtree = CordRepBtree::New(Substring(edge, edge_offset));
size_t subtree_end = 1;
do {
length -= edge->length;
while (++index == node->end()) {
index_[height] = static_cast<uint8_t>(index);
if (++height > height_) {
subtree->set_end(subtree_end);
if (length == 0) return {subtree, 0};
CordRep::Unref(subtree);
return {nullptr, length};
}
if (length != 0) {
subtree->set_end(subtree_end);
subtree = CordRepBtree::New(subtree);
subtree_end = 1;
}
node = node_[height];
index = index_[height];
}
edge = node->Edge(index);
if (length >= edge->length) {
subtree->length += edge->length;
subtree->edges_[subtree_end++] = CordRep::Ref(edge);
}
} while (length >= edge->length);
CordRepBtree* tree = subtree;
subtree->length += length;
while (height > 0) {
node = edge->btree();
index_[height] = static_cast<uint8_t>(index);
node_[--height] = node;
index = node->begin();
edge = node->Edge(index);
if (length != 0) {
CordRepBtree* right = CordRepBtree::New(height);
right->length = length;
subtree->edges_[subtree_end++] = right;
subtree->set_end(subtree_end);
subtree = right;
subtree_end = 0;
while (length >= edge->length) {
subtree->edges_[subtree_end++] = CordRep::Ref(edge);
length -= edge->length;
edge = node->Edge(++index);
}
}
}
if (length != 0) {
subtree->edges_[subtree_end++] = Substring(edge, 0, length);
}
subtree->set_end(subtree_end);
index_[0] = static_cast<uint8_t>(index);
return {tree, length};
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/cord_rep_btree_navigator.h"
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_test_util.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::Eq;
using ::testing::Ne;
using ::absl::cordrep_testing::CordRepBtreeFromFlats;
using ::absl::cordrep_testing::CordToString;
using ::absl::cordrep_testing::CreateFlatsFromString;
using ::absl::cordrep_testing::CreateRandomString;
using ::absl::cordrep_testing::MakeFlat;
using ::absl::cordrep_testing::MakeSubstring;
using ReadResult = CordRepBtreeNavigator::ReadResult;
using Position = CordRepBtreeNavigator::Position;
class CordRepBtreeNavigatorTest : public testing::TestWithParam<size_t> {
public:
using Flats = std::vector<CordRep*>;
static constexpr size_t kCharsPerFlat = 3;
CordRepBtreeNavigatorTest() {
data_ = CreateRandomString(count() * kCharsPerFlat);
flats_ = CreateFlatsFromString(data_, kCharsPerFlat);
if (count() > 1) {
CordRep::Unref(flats_[1]);
flats_[1] = MakeSubstring(kCharsPerFlat, kCharsPerFlat, MakeFlat(data_));
} else {
CordRep::Unref(flats_[0]);
flats_[0] = MakeSubstring(0, kCharsPerFlat, MakeFlat(data_));
}
tree_ = CordRepBtreeFromFlats(flats_);
}
~CordRepBtreeNavigatorTest() override { CordRep::Unref(tree_); }
size_t count() const { return GetParam(); }
CordRepBtree* tree() { return tree_; }
const std::string& data() const { return data_; }
const std::vector<CordRep*>& flats() const { return flats_; }
static std::string ToString(testing::TestParamInfo<size_t> param) {
return absl::StrCat(param.param, "_Flats");
}
private:
std::string data_;
Flats flats_;
CordRepBtree* tree_;
};
INSTANTIATE_TEST_SUITE_P(
WithParam, CordRepBtreeNavigatorTest,
testing::Values(1, CordRepBtree::kMaxCapacity - 1,
CordRepBtree::kMaxCapacity,
CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity - 1,
CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity,
CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity + 1,
CordRepBtree::kMaxCapacity* CordRepBtree::kMaxCapacity * 2 +
17),
CordRepBtreeNavigatorTest::ToString);
TEST(CordRepBtreeNavigatorTest, Uninitialized) {
CordRepBtreeNavigator nav;
EXPECT_FALSE(nav);
EXPECT_THAT(nav.btree(), Eq(nullptr));
#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
EXPECT_DEATH(nav.Current(), ".*");
#endif
}
TEST_P(CordRepBtreeNavigatorTest, InitFirst) {
CordRepBtreeNavigator nav;
CordRep* edge = nav.InitFirst(tree());
EXPECT_TRUE(nav);
EXPECT_THAT(nav.btree(), Eq(tree()));
EXPECT_THAT(nav.Current(), Eq(flats().front()));
EXPECT_THAT(edge, Eq(flats().front()));
}
TEST_P(CordRepBtreeNavigatorTest, InitLast) {
CordRepBtreeNavigator nav;
CordRep* edge = nav.InitLast(tree());
EXPECT_TRUE(nav);
EXPECT_THAT(nav.btree(), Eq(tree()));
EXPECT_THAT(nav.Current(), Eq(flats().back()));
EXPECT_THAT(edge, Eq(flats().back()));
}
TEST_P(CordRepBtreeNavigatorTest, NextPrev) {
CordRepBtreeNavigator nav;
nav.InitFirst(tree());
const Flats& flats = this->flats();
EXPECT_THAT(nav.Previous(), Eq(nullptr));
EXPECT_THAT(nav.Current(), Eq(flats.front()));
for (size_t i = 1; i < flats.size(); ++i) {
ASSERT_THAT(nav.Next(), Eq(flats[i]));
EXPECT_THAT(nav.Current(), Eq(flats[i]));
}
EXPECT_THAT(nav.Next(), Eq(nullptr));
EXPECT_THAT(nav.Current(), Eq(flats.back()));
for (size_t i = flats.size() - 1; i > 0; --i) {
ASSERT_THAT(nav.Previous(), Eq(flats[i - 1]));
EXPECT_THAT(nav.Current(), Eq(flats[i - 1]));
}
EXPECT_THAT(nav.Previous(), Eq(nullptr));
EXPECT_THAT(nav.Current(), Eq(flats.front()));
}
TEST_P(CordRepBtreeNavigatorTest, PrevNext) {
CordRepBtreeNavigator nav;
nav.InitLast(tree());
const Flats& flats = this->flats();
EXPECT_THAT(nav.Next(), Eq(nullptr));
EXPECT_THAT(nav.Current(), Eq(flats.back()));
for (size_t i = flats.size() - 1; i > 0; --i) {
ASSERT_THAT(nav.Previous(), Eq(flats[i - 1]));
EXPECT_THAT(nav.Current(), Eq(flats[i - 1]));
}
EXPECT_THAT(nav.Previous(), Eq(nullptr));
EXPECT_THAT(nav.Current(), Eq(flats.front()));
for (size_t i = 1; i < flats.size(); ++i) {
ASSERT_THAT(nav.Next(), Eq(flats[i]));
EXPECT_THAT(nav.Current(), Eq(flats[i]));
}
EXPECT_THAT(nav.Next(), Eq(nullptr));
EXPECT_THAT(nav.Current(), Eq(flats.back()));
}
TEST(CordRepBtreeNavigatorTest, Reset) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
CordRepBtreeNavigator nav;
nav.InitFirst(tree);
nav.Reset();
EXPECT_FALSE(nav);
EXPECT_THAT(nav.btree(), Eq(nullptr));
#if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG)
EXPECT_DEATH(nav.Current(), ".*");
#endif
CordRep::Unref(tree);
}
TEST_P(CordRepBtreeNavigatorTest, Skip) {
size_t count = this->count();
const Flats& flats = this->flats();
CordRepBtreeNavigator nav;
nav.InitFirst(tree());
for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) {
Position pos = nav.Skip(char_offset);
EXPECT_THAT(pos.edge, Eq(nav.Current()));
EXPECT_THAT(pos.edge, Eq(flats[0]));
EXPECT_THAT(pos.offset, Eq(char_offset));
}
for (size_t index1 = 0; index1 < count; ++index1) {
for (size_t index2 = index1; index2 < count; ++index2) {
for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) {
CordRepBtreeNavigator nav;
nav.InitFirst(tree());
size_t length1 = index1 * kCharsPerFlat;
Position pos1 = nav.Skip(length1 + char_offset);
ASSERT_THAT(pos1.edge, Eq(flats[index1]));
ASSERT_THAT(pos1.edge, Eq(nav.Current()));
ASSERT_THAT(pos1.offset, Eq(char_offset));
size_t length2 = index2 * kCharsPerFlat;
Position pos2 = nav.Skip(length2 - length1 + char_offset);
ASSERT_THAT(pos2.edge, Eq(flats[index2]));
ASSERT_THAT(pos2.edge, Eq(nav.Current()));
ASSERT_THAT(pos2.offset, Eq(char_offset));
}
}
}
}
TEST_P(CordRepBtreeNavigatorTest, Seek) {
size_t count = this->count();
const Flats& flats = this->flats();
CordRepBtreeNavigator nav;
nav.InitFirst(tree());
for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) {
Position pos = nav.Seek(char_offset);
EXPECT_THAT(pos.edge, Eq(nav.Current()));
EXPECT_THAT(pos.edge, Eq(flats[0]));
EXPECT_THAT(pos.offset, Eq(char_offset));
}
for (size_t index = 0; index < count; ++index) {
for (size_t char_offset = 0; char_offset < kCharsPerFlat; ++char_offset) {
size_t offset = index * kCharsPerFlat + char_offset;
Position pos1 = nav.Seek(offset);
ASSERT_THAT(pos1.edge, Eq(flats[index]));
ASSERT_THAT(pos1.edge, Eq(nav.Current()));
ASSERT_THAT(pos1.offset, Eq(char_offset));
}
}
}
TEST(CordRepBtreeNavigatorTest, InitOffset) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
tree = CordRepBtree::Append(tree, MakeFlat("def"));
CordRepBtreeNavigator nav;
Position pos = nav.InitOffset(tree, 5);
EXPECT_TRUE(nav);
EXPECT_THAT(nav.btree(), Eq(tree));
EXPECT_THAT(pos.edge, Eq(tree->Edges()[1]));
EXPECT_THAT(pos.edge, Eq(nav.Current()));
EXPECT_THAT(pos.offset, Eq(2u));
CordRep::Unref(tree);
}
TEST(CordRepBtreeNavigatorTest, InitOffsetAndSeekBeyondLength) {
CordRepBtree* tree1 = CordRepBtree::Create(MakeFlat("abc"));
CordRepBtree* tree2 = CordRepBtree::Create(MakeFlat("def"));
CordRepBtreeNavigator nav;
nav.InitFirst(tree1);
EXPECT_THAT(nav.Seek(3).edge, Eq(nullptr));
EXPECT_THAT(nav.Seek(100).edge, Eq(nullptr));
EXPECT_THAT(nav.btree(), Eq(tree1));
EXPECT_THAT(nav.Current(), Eq(tree1->Edges().front()));
EXPECT_THAT(nav.InitOffset(tree2, 3).edge, Eq(nullptr));
EXPECT_THAT(nav.InitOffset(tree2, 100).edge, Eq(nullptr));
EXPECT_THAT(nav.btree(), Eq(tree1));
EXPECT_THAT(nav.Current(), Eq(tree1->Edges().front()));
CordRep::Unref(tree1);
CordRep::Unref(tree2);
}
TEST_P(CordRepBtreeNavigatorTest, Read) {
const Flats& flats = this->flats();
const std::string& data = this->data();
for (size_t offset = 0; offset < data.size(); ++offset) {
for (size_t length = 1; length <= data.size() - offset; ++length) {
CordRepBtreeNavigator nav;
nav.InitFirst(tree());
size_t edge_offset = nav.Skip(offset).offset;
ReadResult result = nav.Read(edge_offset, length);
ASSERT_THAT(result.tree, Ne(nullptr));
EXPECT_THAT(result.tree->length, Eq(length));
if (result.tree->tag == BTREE) {
ASSERT_TRUE(CordRepBtree::IsValid(result.tree->btree()));
}
std::string value = CordToString(result.tree);
EXPECT_THAT(value, Eq(data.substr(offset, length)));
size_t partial = (offset + length) % kCharsPerFlat;
ASSERT_THAT(result.n, Eq(partial));
if (offset + length < data.size()) {
size_t index = (offset + length) / kCharsPerFlat;
EXPECT_THAT(nav.Current(), Eq(flats[index]));
}
CordRep::Unref(result.tree);
}
}
}
TEST_P(CordRepBtreeNavigatorTest, ReadBeyondLengthOfTree) {
CordRepBtreeNavigator nav;
nav.InitFirst(tree());
ReadResult result = nav.Read(2, tree()->length);
ASSERT_THAT(result.tree, Eq(nullptr));
}
TEST(CordRepBtreeNavigatorTest, NavigateMaximumTreeDepth) {
CordRepFlat* flat1 = MakeFlat("Hello world");
CordRepFlat* flat2 = MakeFlat("World Hello");
CordRepBtree* node = CordRepBtree::Create(flat1);
node = CordRepBtree::Append(node, flat2);
while (node->height() < CordRepBtree::kMaxHeight) {
node = CordRepBtree::New(node);
}
CordRepBtreeNavigator nav;
CordRep* edge = nav.InitFirst(node);
EXPECT_THAT(edge, Eq(flat1));
EXPECT_THAT(nav.Next(), Eq(flat2));
EXPECT_THAT(nav.Next(), Eq(nullptr));
EXPECT_THAT(nav.Previous(), Eq(flat1));
EXPECT_THAT(nav.Previous(), Eq(nullptr));
CordRep::Unref(node);
}
}
}
ABSL_NAMESPACE_END
} |
2,567 | cpp | abseil/abseil-cpp | cord_rep_crc | absl/strings/internal/cord_rep_crc.cc | absl/strings/internal/cord_rep_crc_test.cc | #ifndef ABSL_STRINGS_INTERNAL_CORD_REP_CRC_H_
#define ABSL_STRINGS_INTERNAL_CORD_REP_CRC_H_
#include <cassert>
#include <cstdint>
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#include "absl/crc/internal/crc_cord_state.h"
#include "absl/strings/internal/cord_internal.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
struct CordRepCrc : public CordRep {
CordRep* child;
absl::crc_internal::CrcCordState crc_cord_state;
static CordRepCrc* New(CordRep* child, crc_internal::CrcCordState state);
static void Destroy(CordRepCrc* node);
};
inline CordRep* RemoveCrcNode(CordRep* rep) {
assert(rep != nullptr);
if (ABSL_PREDICT_FALSE(rep->IsCrc())) {
CordRep* child = rep->crc()->child;
if (rep->refcount.IsOne()) {
delete rep->crc();
} else {
CordRep::Ref(child);
CordRep::Unref(rep);
}
return child;
}
return rep;
}
inline CordRep* SkipCrcNode(CordRep* rep) {
assert(rep != nullptr);
if (ABSL_PREDICT_FALSE(rep->IsCrc())) {
return rep->crc()->child;
} else {
return rep;
}
}
inline const CordRep* SkipCrcNode(const CordRep* rep) {
assert(rep != nullptr);
if (ABSL_PREDICT_FALSE(rep->IsCrc())) {
return rep->crc()->child;
} else {
return rep;
}
}
inline CordRepCrc* CordRep::crc() {
assert(IsCrc());
return static_cast<CordRepCrc*>(this);
}
inline const CordRepCrc* CordRep::crc() const {
assert(IsCrc());
return static_cast<const CordRepCrc*>(this);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/cord_rep_crc.h"
#include <cassert>
#include <cstdint>
#include <utility>
#include "absl/base/config.h"
#include "absl/strings/internal/cord_internal.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
CordRepCrc* CordRepCrc::New(CordRep* child, crc_internal::CrcCordState state) {
if (child != nullptr && child->IsCrc()) {
if (child->refcount.IsOne()) {
child->crc()->crc_cord_state = std::move(state);
return child->crc();
}
CordRep* old = child;
child = old->crc()->child;
CordRep::Ref(child);
CordRep::Unref(old);
}
auto* new_cordrep = new CordRepCrc;
new_cordrep->length = child != nullptr ? child->length : 0;
new_cordrep->tag = cord_internal::CRC;
new_cordrep->child = child;
new_cordrep->crc_cord_state = std::move(state);
return new_cordrep;
}
void CordRepCrc::Destroy(CordRepCrc* node) {
if (node->child != nullptr) {
CordRep::Unref(node->child);
}
delete node;
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/cord_rep_crc.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/crc/internal/crc_cord_state.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_test_util.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::absl::cordrep_testing::MakeFlat;
using ::testing::Eq;
using ::testing::IsNull;
using ::testing::Ne;
#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
TEST(CordRepCrc, RemoveCrcWithNullptr) {
EXPECT_DEATH(RemoveCrcNode(nullptr), "");
}
#endif
absl::crc_internal::CrcCordState MakeCrcCordState(uint32_t crc) {
crc_internal::CrcCordState state;
state.mutable_rep()->prefix_crc.push_back(
crc_internal::CrcCordState::PrefixCrc(42, crc32c_t{crc}));
return state;
}
TEST(CordRepCrc, NewDestroy) {
CordRep* rep = cordrep_testing::MakeFlat("Hello world");
CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345));
EXPECT_TRUE(crc->refcount.IsOne());
EXPECT_THAT(crc->child, Eq(rep));
EXPECT_THAT(crc->crc_cord_state.Checksum(), Eq(crc32c_t{12345u}));
EXPECT_TRUE(rep->refcount.IsOne());
CordRepCrc::Destroy(crc);
}
TEST(CordRepCrc, NewExistingCrcNotShared) {
CordRep* rep = cordrep_testing::MakeFlat("Hello world");
CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345));
CordRepCrc* new_crc = CordRepCrc::New(crc, MakeCrcCordState(54321));
EXPECT_THAT(new_crc, Eq(crc));
EXPECT_TRUE(new_crc->refcount.IsOne());
EXPECT_THAT(new_crc->child, Eq(rep));
EXPECT_THAT(new_crc->crc_cord_state.Checksum(), Eq(crc32c_t{54321u}));
EXPECT_TRUE(rep->refcount.IsOne());
CordRepCrc::Destroy(new_crc);
}
TEST(CordRepCrc, NewExistingCrcShared) {
CordRep* rep = cordrep_testing::MakeFlat("Hello world");
CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345));
CordRep::Ref(crc);
CordRepCrc* new_crc = CordRepCrc::New(crc, MakeCrcCordState(54321));
EXPECT_THAT(new_crc, Ne(crc));
EXPECT_TRUE(new_crc->refcount.IsOne());
EXPECT_TRUE(crc->refcount.IsOne());
EXPECT_FALSE(rep->refcount.IsOne());
EXPECT_THAT(crc->child, Eq(rep));
EXPECT_THAT(new_crc->child, Eq(rep));
EXPECT_THAT(crc->crc_cord_state.Checksum(), Eq(crc32c_t{12345u}));
EXPECT_THAT(new_crc->crc_cord_state.Checksum(), Eq(crc32c_t{54321u}));
CordRep::Unref(crc);
CordRep::Unref(new_crc);
}
TEST(CordRepCrc, NewEmpty) {
CordRepCrc* crc = CordRepCrc::New(nullptr, MakeCrcCordState(12345));
EXPECT_TRUE(crc->refcount.IsOne());
EXPECT_THAT(crc->child, IsNull());
EXPECT_THAT(crc->length, Eq(0u));
EXPECT_THAT(crc->crc_cord_state.Checksum(), Eq(crc32c_t{12345u}));
EXPECT_TRUE(crc->refcount.IsOne());
CordRepCrc::Destroy(crc);
}
TEST(CordRepCrc, RemoveCrcNotCrc) {
CordRep* rep = cordrep_testing::MakeFlat("Hello world");
CordRep* nocrc = RemoveCrcNode(rep);
EXPECT_THAT(nocrc, Eq(rep));
CordRep::Unref(nocrc);
}
TEST(CordRepCrc, RemoveCrcNotShared) {
CordRep* rep = cordrep_testing::MakeFlat("Hello world");
CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345));
CordRep* nocrc = RemoveCrcNode(crc);
EXPECT_THAT(nocrc, Eq(rep));
EXPECT_TRUE(rep->refcount.IsOne());
CordRep::Unref(nocrc);
}
TEST(CordRepCrc, RemoveCrcShared) {
CordRep* rep = cordrep_testing::MakeFlat("Hello world");
CordRepCrc* crc = CordRepCrc::New(rep, MakeCrcCordState(12345));
CordRep::Ref(crc);
CordRep* nocrc = RemoveCrcNode(crc);
EXPECT_THAT(nocrc, Eq(rep));
EXPECT_FALSE(rep->refcount.IsOne());
CordRep::Unref(nocrc);
CordRep::Unref(crc);
}
}
}
ABSL_NAMESPACE_END
} |
2,568 | cpp | abseil/abseil-cpp | extension | absl/strings/internal/str_format/extension.cc | absl/strings/internal/str_format/extension_test.cc | #ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_EXTENSION_H_
#define ABSL_STRINGS_INTERNAL_STR_FORMAT_EXTENSION_H_
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <ostream>
#include <string>
#include "absl/base/config.h"
#include "absl/strings/internal/str_format/output.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
enum class FormatConversionChar : uint8_t;
enum class FormatConversionCharSet : uint64_t;
enum class LengthMod : std::uint8_t { h, hh, l, ll, L, j, z, t, q, none };
namespace str_format_internal {
class FormatRawSinkImpl {
public:
template <typename T, decltype(str_format_internal::InvokeFlush(
std::declval<T*>(), string_view()))* = nullptr>
FormatRawSinkImpl(T* raw)
: sink_(raw), write_(&FormatRawSinkImpl::Flush<T>) {}
void Write(string_view s) { write_(sink_, s); }
template <typename T>
static FormatRawSinkImpl Extract(T s) {
return s.sink_;
}
private:
template <typename T>
static void Flush(void* r, string_view s) {
str_format_internal::InvokeFlush(static_cast<T*>(r), s);
}
void* sink_;
void (*write_)(void*, string_view);
};
class FormatSinkImpl {
public:
explicit FormatSinkImpl(FormatRawSinkImpl raw) : raw_(raw) {}
~FormatSinkImpl() { Flush(); }
void Flush() {
raw_.Write(string_view(buf_, static_cast<size_t>(pos_ - buf_)));
pos_ = buf_;
}
void Append(size_t n, char c) {
if (n == 0) return;
size_ += n;
auto raw_append = [&](size_t count) {
memset(pos_, c, count);
pos_ += count;
};
while (n > Avail()) {
n -= Avail();
if (Avail() > 0) {
raw_append(Avail());
}
Flush();
}
raw_append(n);
}
void Append(string_view v) {
size_t n = v.size();
if (n == 0) return;
size_ += n;
if (n >= Avail()) {
Flush();
raw_.Write(v);
return;
}
memcpy(pos_, v.data(), n);
pos_ += n;
}
size_t size() const { return size_; }
bool PutPaddedString(string_view v, int width, int precision, bool left);
template <typename T>
T Wrap() {
return T(this);
}
template <typename T>
static FormatSinkImpl* Extract(T* s) {
return s->sink_;
}
private:
size_t Avail() const {
return static_cast<size_t>(buf_ + sizeof(buf_) - pos_);
}
FormatRawSinkImpl raw_;
size_t size_ = 0;
char* pos_ = buf_;
char buf_[1024];
};
enum class Flags : uint8_t {
kBasic = 0,
kLeft = 1 << 0,
kShowPos = 1 << 1,
kSignCol = 1 << 2,
kAlt = 1 << 3,
kZero = 1 << 4,
kNonBasic = 1 << 5,
};
constexpr Flags operator|(Flags a, Flags b) {
return static_cast<Flags>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b));
}
constexpr bool FlagsContains(Flags haystack, Flags needle) {
return (static_cast<uint8_t>(haystack) & static_cast<uint8_t>(needle)) ==
static_cast<uint8_t>(needle);
}
std::string FlagsToString(Flags v);
inline std::ostream& operator<<(std::ostream& os, Flags v) {
return os << FlagsToString(v);
}
#define ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(X_VAL, X_SEP) \
\
X_VAL(c) X_SEP X_VAL(s) X_SEP \
\
X_VAL(d) X_SEP X_VAL(i) X_SEP X_VAL(o) X_SEP \
X_VAL(u) X_SEP X_VAL(x) X_SEP X_VAL(X) X_SEP \
\
X_VAL(f) X_SEP X_VAL(F) X_SEP X_VAL(e) X_SEP X_VAL(E) X_SEP \
X_VAL(g) X_SEP X_VAL(G) X_SEP X_VAL(a) X_SEP X_VAL(A) X_SEP \
\
X_VAL(n) X_SEP X_VAL(p) X_SEP X_VAL(v)
struct FormatConversionCharInternal {
FormatConversionCharInternal() = delete;
private:
enum class Enum : uint8_t {
c, s,
d, i, o, u, x, X,
f, F, e, E, g, G, a, A,
n, p, v,
kNone
};
public:
#define ABSL_INTERNAL_X_VAL(id) \
static constexpr FormatConversionChar id = \
static_cast<FormatConversionChar>(Enum::id);
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL, )
#undef ABSL_INTERNAL_X_VAL
static constexpr FormatConversionChar kNone =
static_cast<FormatConversionChar>(Enum::kNone);
};
inline FormatConversionChar FormatConversionCharFromChar(char c) {
switch (c) {
#define ABSL_INTERNAL_X_VAL(id) \
case #id[0]: \
return FormatConversionCharInternal::id;
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL, )
#undef ABSL_INTERNAL_X_VAL
}
return FormatConversionCharInternal::kNone;
}
inline bool FormatConversionCharIsUpper(FormatConversionChar c) {
if (c == FormatConversionCharInternal::X ||
c == FormatConversionCharInternal::F ||
c == FormatConversionCharInternal::E ||
c == FormatConversionCharInternal::G ||
c == FormatConversionCharInternal::A) {
return true;
} else {
return false;
}
}
inline bool FormatConversionCharIsFloat(FormatConversionChar c) {
if (c == FormatConversionCharInternal::a ||
c == FormatConversionCharInternal::e ||
c == FormatConversionCharInternal::f ||
c == FormatConversionCharInternal::g ||
c == FormatConversionCharInternal::A ||
c == FormatConversionCharInternal::E ||
c == FormatConversionCharInternal::F ||
c == FormatConversionCharInternal::G) {
return true;
} else {
return false;
}
}
inline char FormatConversionCharToChar(FormatConversionChar c) {
if (c == FormatConversionCharInternal::kNone) {
return '\0';
#define ABSL_INTERNAL_X_VAL(e) \
} else if (c == FormatConversionCharInternal::e) { \
return #e[0];
#define ABSL_INTERNAL_X_SEP
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL,
ABSL_INTERNAL_X_SEP)
} else {
return '\0';
}
#undef ABSL_INTERNAL_X_VAL
#undef ABSL_INTERNAL_X_SEP
}
inline std::ostream& operator<<(std::ostream& os, FormatConversionChar v) {
char c = FormatConversionCharToChar(v);
if (!c) c = '?';
return os << c;
}
struct FormatConversionSpecImplFriend;
class FormatConversionSpecImpl {
public:
bool is_basic() const { return flags_ == Flags::kBasic; }
bool has_left_flag() const { return FlagsContains(flags_, Flags::kLeft); }
bool has_show_pos_flag() const {
return FlagsContains(flags_, Flags::kShowPos);
}
bool has_sign_col_flag() const {
return FlagsContains(flags_, Flags::kSignCol);
}
bool has_alt_flag() const { return FlagsContains(flags_, Flags::kAlt); }
bool has_zero_flag() const { return FlagsContains(flags_, Flags::kZero); }
LengthMod length_mod() const { return length_mod_; }
FormatConversionChar conversion_char() const {
static_assert(offsetof(FormatConversionSpecImpl, conv_) == 0, "");
return conv_;
}
void set_conversion_char(FormatConversionChar c) { conv_ = c; }
int width() const { return width_; }
int precision() const { return precision_; }
template <typename T>
T Wrap() {
return T(*this);
}
private:
friend struct str_format_internal::FormatConversionSpecImplFriend;
FormatConversionChar conv_ = FormatConversionCharInternal::kNone;
Flags flags_;
LengthMod length_mod_ = LengthMod::none;
int width_;
int precision_;
};
struct FormatConversionSpecImplFriend final {
static void SetFlags(Flags f, FormatConversionSpecImpl* conv) {
conv->flags_ = f;
}
static void SetLengthMod(LengthMod l, FormatConversionSpecImpl* conv) {
conv->length_mod_ = l;
}
static void SetConversionChar(FormatConversionChar c,
FormatConversionSpecImpl* conv) {
conv->conv_ = c;
}
static void SetWidth(int w, FormatConversionSpecImpl* conv) {
conv->width_ = w;
}
static void SetPrecision(int p, FormatConversionSpecImpl* conv) {
conv->precision_ = p;
}
static std::string FlagsToString(const FormatConversionSpecImpl& spec) {
return str_format_internal::FlagsToString(spec.flags_);
}
};
constexpr FormatConversionCharSet FormatConversionCharSetUnion(
FormatConversionCharSet a) {
return a;
}
template <typename... CharSet>
constexpr FormatConversionCharSet FormatConversionCharSetUnion(
FormatConversionCharSet a, CharSet... rest) {
return static_cast<FormatConversionCharSet>(
static_cast<uint64_t>(a) |
static_cast<uint64_t>(FormatConversionCharSetUnion(rest...)));
}
constexpr uint64_t FormatConversionCharToConvInt(FormatConversionChar c) {
return uint64_t{1} << (1 + static_cast<uint8_t>(c));
}
constexpr uint64_t FormatConversionCharToConvInt(char conv) {
return
#define ABSL_INTERNAL_CHAR_SET_CASE(c) \
conv == #c[0] \
? FormatConversionCharToConvInt(FormatConversionCharInternal::c) \
:
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_CHAR_SET_CASE, )
#undef ABSL_INTERNAL_CHAR_SET_CASE
conv == '*'
? 1
: 0;
}
constexpr FormatConversionCharSet FormatConversionCharToConvValue(char conv) {
return static_cast<FormatConversionCharSet>(
FormatConversionCharToConvInt(conv));
}
struct FormatConversionCharSetInternal {
#define ABSL_INTERNAL_CHAR_SET_CASE(c) \
static constexpr FormatConversionCharSet c = \
FormatConversionCharToConvValue(#c[0]);
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_CHAR_SET_CASE, )
#undef ABSL_INTERNAL_CHAR_SET_CASE
static constexpr FormatConversionCharSet kStar =
FormatConversionCharToConvValue('*');
static constexpr FormatConversionCharSet kIntegral =
FormatConversionCharSetUnion(d, i, u, o, x, X);
static constexpr FormatConversionCharSet kFloating =
FormatConversionCharSetUnion(a, e, f, g, A, E, F, G);
static constexpr FormatConversionCharSet kNumeric =
FormatConversionCharSetUnion(kIntegral, kFloating);
static constexpr FormatConversionCharSet kPointer = p;
};
constexpr FormatConversionCharSet operator|(FormatConversionCharSet a,
FormatConversionCharSet b) {
return FormatConversionCharSetUnion(a, b);
}
constexpr FormatConversionCharSet ToFormatConversionCharSet(char c) {
return static_cast<FormatConversionCharSet>(
FormatConversionCharToConvValue(c));
}
constexpr FormatConversionCharSet ToFormatConversionCharSet(
FormatConversionCharSet c) {
return c;
}
template <typename T>
void ToFormatConversionCharSet(T) = delete;
constexpr bool Contains(FormatConversionCharSet set, char c) {
return (static_cast<uint64_t>(set) &
static_cast<uint64_t>(FormatConversionCharToConvValue(c))) != 0;
}
constexpr bool Contains(FormatConversionCharSet set,
FormatConversionCharSet c) {
return (static_cast<uint64_t>(set) & static_cast<uint64_t>(c)) ==
static_cast<uint64_t>(c);
}
constexpr bool Contains(FormatConversionCharSet set, FormatConversionChar c) {
return (static_cast<uint64_t>(set) & FormatConversionCharToConvInt(c)) != 0;
}
inline size_t Excess(size_t used, size_t capacity) {
return used < capacity ? capacity - used : 0;
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/str_format/extension.h"
#include <errno.h>
#include <algorithm>
#include <string>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
std::string FlagsToString(Flags v) {
std::string s;
s.append(FlagsContains(v, Flags::kLeft) ? "-" : "");
s.append(FlagsContains(v, Flags::kShowPos) ? "+" : "");
s.append(FlagsContains(v, Flags::kSignCol) ? " " : "");
s.append(FlagsContains(v, Flags::kAlt) ? "#" : "");
s.append(FlagsContains(v, Flags::kZero) ? "0" : "");
return s;
}
#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
#define ABSL_INTERNAL_X_VAL(id) \
constexpr absl::FormatConversionChar FormatConversionCharInternal::id;
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_X_VAL, )
#undef ABSL_INTERNAL_X_VAL
constexpr absl::FormatConversionChar FormatConversionCharInternal::kNone;
#define ABSL_INTERNAL_CHAR_SET_CASE(c) \
constexpr FormatConversionCharSet FormatConversionCharSetInternal::c;
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(ABSL_INTERNAL_CHAR_SET_CASE, )
#undef ABSL_INTERNAL_CHAR_SET_CASE
constexpr FormatConversionCharSet FormatConversionCharSetInternal::kStar;
constexpr FormatConversionCharSet FormatConversionCharSetInternal::kIntegral;
constexpr FormatConversionCharSet FormatConversionCharSetInternal::kFloating;
constexpr FormatConversionCharSet FormatConversionCharSetInternal::kNumeric;
constexpr FormatConversionCharSet FormatConversionCharSetInternal::kPointer;
#endif
bool FormatSinkImpl::PutPaddedString(string_view value, int width,
int precision, bool left) {
size_t space_remaining = 0;
if (width >= 0)
space_remaining = static_cast<size_t>(width);
size_t n = value.size();
if (precision >= 0) n = std::min(n, static_cast<size_t>(precision));
string_view shown(value.data(), n);
space_remaining = Excess(shown.size(), space_remaining);
if (!left) Append(space_remaining, ' ');
Append(shown);
if (left) Append(space_remaining, ' ');
return true;
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/str_format/extension.h"
#include <random>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
namespace my_namespace {
class UserDefinedType {
public:
UserDefinedType() = default;
void Append(absl::string_view str) { value_.append(str.data(), str.size()); }
const std::string& Value() const { return value_; }
friend void AbslFormatFlush(UserDefinedType* x, absl::string_view str) {
x->Append(str);
}
private:
std::string value_;
};
}
namespace {
std::string MakeRandomString(size_t len) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis('a', 'z');
std::string s(len, '0');
for (char& c : s) {
c = dis(gen);
}
return s;
}
TEST(FormatExtensionTest, SinkAppendSubstring) {
for (size_t chunk_size : {1, 10, 100, 1000, 10000}) {
std::string expected, actual;
absl::str_format_internal::FormatSinkImpl sink(&actual);
for (size_t chunks = 0; chunks < 10; ++chunks) {
std::string rand = MakeRandomString(chunk_size);
expected += rand;
sink.Append(rand);
}
sink.Flush();
EXPECT_EQ(actual, expected);
}
}
TEST(FormatExtensionTest, SinkAppendChars) {
for (size_t chunk_size : {1, 10, 100, 1000, 10000}) {
std::string expected, actual;
absl::str_format_internal::FormatSinkImpl sink(&actual);
for (size_t chunks = 0; chunks < 10; ++chunks) {
std::string rand = MakeRandomString(1);
expected.append(chunk_size, rand[0]);
sink.Append(chunk_size, rand[0]);
}
sink.Flush();
EXPECT_EQ(actual, expected);
}
}
TEST(FormatExtensionTest, VerifyEnumEquality) {
#define X_VAL(id) \
EXPECT_EQ(absl::FormatConversionChar::id, \
absl::str_format_internal::FormatConversionCharInternal::id);
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(X_VAL, );
#undef X_VAL
#define X_VAL(id) \
EXPECT_EQ(absl::FormatConversionCharSet::id, \
absl::str_format_internal::FormatConversionCharSetInternal::id);
ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(X_VAL, );
#undef X_VAL
}
TEST(FormatExtensionTest, SetConversionChar) {
absl::str_format_internal::FormatConversionSpecImpl spec;
EXPECT_EQ(spec.conversion_char(),
absl::str_format_internal::FormatConversionCharInternal::kNone);
spec.set_conversion_char(
absl::str_format_internal::FormatConversionCharInternal::d);
EXPECT_EQ(spec.conversion_char(),
absl::str_format_internal::FormatConversionCharInternal::d);
}
} |
2,569 | cpp | abseil/abseil-cpp | bind | absl/strings/internal/str_format/bind.cc | absl/strings/internal/str_format/bind_test.cc | #ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_BIND_H_
#define ABSL_STRINGS_INTERNAL_STR_FORMAT_BIND_H_
#include <cassert>
#include <cstdio>
#include <ostream>
#include <string>
#include "absl/base/config.h"
#include "absl/container/inlined_vector.h"
#include "absl/strings/internal/str_format/arg.h"
#include "absl/strings/internal/str_format/checker.h"
#include "absl/strings/internal/str_format/constexpr_parser.h"
#include "absl/strings/internal/str_format/extension.h"
#include "absl/strings/internal/str_format/parser.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "absl/utility/utility.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class UntypedFormatSpec;
namespace str_format_internal {
class BoundConversion : public FormatConversionSpecImpl {
public:
const FormatArgImpl* arg() const { return arg_; }
void set_arg(const FormatArgImpl* a) { arg_ = a; }
private:
const FormatArgImpl* arg_;
};
class UntypedFormatSpecImpl {
public:
UntypedFormatSpecImpl() = delete;
explicit UntypedFormatSpecImpl(string_view s)
: data_(s.data()), size_(s.size()) {}
explicit UntypedFormatSpecImpl(
const str_format_internal::ParsedFormatBase* pc)
: data_(pc), size_(~size_t{}) {}
bool has_parsed_conversion() const { return size_ == ~size_t{}; }
string_view str() const {
assert(!has_parsed_conversion());
return string_view(static_cast<const char*>(data_), size_);
}
const str_format_internal::ParsedFormatBase* parsed_conversion() const {
assert(has_parsed_conversion());
return static_cast<const str_format_internal::ParsedFormatBase*>(data_);
}
template <typename T>
static const UntypedFormatSpecImpl& Extract(const T& s) {
return s.spec_;
}
private:
const void* data_;
size_t size_;
};
template <typename T, FormatConversionCharSet...>
struct MakeDependent {
using type = T;
};
template <FormatConversionCharSet... Args>
class FormatSpecTemplate
: public MakeDependent<UntypedFormatSpec, Args...>::type {
using Base = typename MakeDependent<UntypedFormatSpec, Args...>::type;
template <bool res>
struct ErrorMaker {
constexpr bool operator()(int) const { return res; }
};
template <int i, int j>
static constexpr bool CheckArity(ErrorMaker<true> SpecifierCount = {},
ErrorMaker<i == j> ParametersPassed = {}) {
static_assert(SpecifierCount(i) == ParametersPassed(j),
"Number of arguments passed must match the number of "
"conversion specifiers.");
return true;
}
template <FormatConversionCharSet specified, FormatConversionCharSet passed,
int arg>
static constexpr bool CheckMatch(
ErrorMaker<Contains(specified, passed)> MismatchedArgumentNumber = {}) {
static_assert(MismatchedArgumentNumber(arg),
"Passed argument must match specified format.");
return true;
}
template <FormatConversionCharSet... C, size_t... I>
static bool CheckMatches(absl::index_sequence<I...>) {
bool res[] = {true, CheckMatch<Args, C, I + 1>()...};
(void)res;
return true;
}
public:
#ifdef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER
FormatSpecTemplate(...)
__attribute__((unavailable("Format string is not constexpr.")));
template <typename = void>
FormatSpecTemplate(const char* s)
__attribute__((
enable_if(str_format_internal::EnsureConstexpr(s), "constexpr trap"),
unavailable(
"Format specified does not match the arguments passed.")));
template <typename T = void>
FormatSpecTemplate(string_view s)
__attribute__((enable_if(str_format_internal::EnsureConstexpr(s),
"constexpr trap")))
: Base("to avoid noise in the compiler error") {
static_assert(sizeof(T*) == 0,
"Format specified does not match the arguments passed.");
}
FormatSpecTemplate(const char* s)
__attribute__((enable_if(ValidFormatImpl<Args...>(s), "bad format trap")))
: Base(s) {}
FormatSpecTemplate(string_view s)
__attribute__((enable_if(ValidFormatImpl<Args...>(s), "bad format trap")))
: Base(s) {}
#else
FormatSpecTemplate(const char* s) : Base(s) {}
FormatSpecTemplate(string_view s) : Base(s) {}
#endif
template <FormatConversionCharSet... C>
FormatSpecTemplate(const ExtendedParsedFormat<C...>& pc)
: Base(&pc) {
CheckArity<sizeof...(C), sizeof...(Args)>();
CheckMatches<C...>(absl::make_index_sequence<sizeof...(C)>{});
}
};
class Streamable {
public:
Streamable(const UntypedFormatSpecImpl& format,
absl::Span<const FormatArgImpl> args)
: format_(format), args_(args.begin(), args.end()) {}
std::ostream& Print(std::ostream& os) const;
friend std::ostream& operator<<(std::ostream& os, const Streamable& l) {
return l.Print(os);
}
private:
const UntypedFormatSpecImpl& format_;
absl::InlinedVector<FormatArgImpl, 4> args_;
};
std::string Summarize(UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args);
bool BindWithPack(const UnboundConversion* props,
absl::Span<const FormatArgImpl> pack, BoundConversion* bound);
bool FormatUntyped(FormatRawSinkImpl raw_sink, UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args);
std::string& AppendPack(std::string* out, UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args);
std::string FormatPack(UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args);
int FprintF(std::FILE* output, UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args);
int SnprintF(char* output, size_t size, UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args);
template <typename T>
class StreamedWrapper {
public:
explicit StreamedWrapper(const T& v) : v_(v) {}
private:
template <typename S>
friend ArgConvertResult<FormatConversionCharSetUnion(
FormatConversionCharSetInternal::s, FormatConversionCharSetInternal::v)>
FormatConvertImpl(const StreamedWrapper<S>& v, FormatConversionSpecImpl conv,
FormatSinkImpl* out);
const T& v_;
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/str_format/bind.h"
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstddef>
#include <cstdio>
#include <ios>
#include <limits>
#include <ostream>
#include <sstream>
#include <string>
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#include "absl/strings/internal/str_format/arg.h"
#include "absl/strings/internal/str_format/constexpr_parser.h"
#include "absl/strings/internal/str_format/extension.h"
#include "absl/strings/internal/str_format/output.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
inline bool BindFromPosition(int position, int* value,
absl::Span<const FormatArgImpl> pack) {
assert(position > 0);
if (static_cast<size_t>(position) > pack.size()) {
return false;
}
return FormatArgImplFriend::ToInt(pack[static_cast<size_t>(position) - 1],
value);
}
class ArgContext {
public:
explicit ArgContext(absl::Span<const FormatArgImpl> pack) : pack_(pack) {}
bool Bind(const UnboundConversion* unbound, BoundConversion* bound);
private:
absl::Span<const FormatArgImpl> pack_;
};
inline bool ArgContext::Bind(const UnboundConversion* unbound,
BoundConversion* bound) {
const FormatArgImpl* arg = nullptr;
int arg_position = unbound->arg_position;
if (static_cast<size_t>(arg_position - 1) >= pack_.size()) return false;
arg = &pack_[static_cast<size_t>(arg_position - 1)];
if (unbound->flags != Flags::kBasic) {
int width = unbound->width.value();
bool force_left = false;
if (unbound->width.is_from_arg()) {
if (!BindFromPosition(unbound->width.get_from_arg(), &width, pack_))
return false;
if (width < 0) {
force_left = true;
width = -std::max(width, -std::numeric_limits<int>::max());
}
}
int precision = unbound->precision.value();
if (unbound->precision.is_from_arg()) {
if (!BindFromPosition(unbound->precision.get_from_arg(), &precision,
pack_))
return false;
}
FormatConversionSpecImplFriend::SetWidth(width, bound);
FormatConversionSpecImplFriend::SetPrecision(precision, bound);
if (force_left) {
FormatConversionSpecImplFriend::SetFlags(unbound->flags | Flags::kLeft,
bound);
} else {
FormatConversionSpecImplFriend::SetFlags(unbound->flags, bound);
}
FormatConversionSpecImplFriend::SetLengthMod(unbound->length_mod, bound);
} else {
FormatConversionSpecImplFriend::SetFlags(unbound->flags, bound);
FormatConversionSpecImplFriend::SetWidth(-1, bound);
FormatConversionSpecImplFriend::SetPrecision(-1, bound);
}
FormatConversionSpecImplFriend::SetConversionChar(unbound->conv, bound);
bound->set_arg(arg);
return true;
}
template <typename Converter>
class ConverterConsumer {
public:
ConverterConsumer(Converter converter, absl::Span<const FormatArgImpl> pack)
: converter_(converter), arg_context_(pack) {}
bool Append(string_view s) {
converter_.Append(s);
return true;
}
bool ConvertOne(const UnboundConversion& conv, string_view conv_string) {
BoundConversion bound;
if (!arg_context_.Bind(&conv, &bound)) return false;
return converter_.ConvertOne(bound, conv_string);
}
private:
Converter converter_;
ArgContext arg_context_;
};
template <typename Converter>
bool ConvertAll(const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args, Converter converter) {
if (format.has_parsed_conversion()) {
return format.parsed_conversion()->ProcessFormat(
ConverterConsumer<Converter>(converter, args));
} else {
return ParseFormatString(format.str(),
ConverterConsumer<Converter>(converter, args));
}
}
class DefaultConverter {
public:
explicit DefaultConverter(FormatSinkImpl* sink) : sink_(sink) {}
void Append(string_view s) const { sink_->Append(s); }
bool ConvertOne(const BoundConversion& bound, string_view ) const {
return FormatArgImplFriend::Convert(*bound.arg(), bound, sink_);
}
private:
FormatSinkImpl* sink_;
};
class SummarizingConverter {
public:
explicit SummarizingConverter(FormatSinkImpl* sink) : sink_(sink) {}
void Append(string_view s) const { sink_->Append(s); }
bool ConvertOne(const BoundConversion& bound, string_view ) const {
UntypedFormatSpecImpl spec("%d");
std::ostringstream ss;
ss << "{" << Streamable(spec, {*bound.arg()}) << ":"
<< FormatConversionSpecImplFriend::FlagsToString(bound);
if (bound.width() >= 0) ss << bound.width();
if (bound.precision() >= 0) ss << "." << bound.precision();
ss << bound.conversion_char() << "}";
Append(ss.str());
return true;
}
private:
FormatSinkImpl* sink_;
};
}
bool BindWithPack(const UnboundConversion* props,
absl::Span<const FormatArgImpl> pack,
BoundConversion* bound) {
return ArgContext(pack).Bind(props, bound);
}
std::string Summarize(const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
typedef SummarizingConverter Converter;
std::string out;
{
FormatSinkImpl sink(&out);
if (!ConvertAll(format, args, Converter(&sink))) {
return "";
}
}
return out;
}
bool FormatUntyped(FormatRawSinkImpl raw_sink,
const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
FormatSinkImpl sink(raw_sink);
using Converter = DefaultConverter;
return ConvertAll(format, args, Converter(&sink));
}
std::ostream& Streamable::Print(std::ostream& os) const {
if (!FormatUntyped(&os, format_, args_)) os.setstate(std::ios::failbit);
return os;
}
std::string& AppendPack(std::string* out, const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
size_t orig = out->size();
if (ABSL_PREDICT_FALSE(!FormatUntyped(out, format, args))) {
out->erase(orig);
}
return *out;
}
std::string FormatPack(UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
std::string out;
if (ABSL_PREDICT_FALSE(!FormatUntyped(&out, format, args))) {
out.clear();
}
return out;
}
int FprintF(std::FILE* output, const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
FILERawSink sink(output);
if (!FormatUntyped(&sink, format, args)) {
errno = EINVAL;
return -1;
}
if (sink.error()) {
errno = sink.error();
return -1;
}
if (sink.count() > static_cast<size_t>(std::numeric_limits<int>::max())) {
errno = EFBIG;
return -1;
}
return static_cast<int>(sink.count());
}
int SnprintF(char* output, size_t size, const UntypedFormatSpecImpl format,
absl::Span<const FormatArgImpl> args) {
BufferRawSink sink(output, size ? size - 1 : 0);
if (!FormatUntyped(&sink, format, args)) {
errno = EINVAL;
return -1;
}
size_t total = sink.total_written();
if (size) output[std::min(total, size - 1)] = 0;
return static_cast<int>(total);
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/str_format/bind.h"
#include <string.h>
#include <limits>
#include "gtest/gtest.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
class FormatBindTest : public ::testing::Test {
public:
bool Extract(const char *s, UnboundConversion *props, int *next) const {
return ConsumeUnboundConversion(s, s + strlen(s), props, next) ==
s + strlen(s);
}
};
TEST_F(FormatBindTest, BindSingle) {
struct Expectation {
int line;
const char *fmt;
int ok_phases;
const FormatArgImpl *arg;
int width;
int precision;
int next_arg;
};
const int no = -1;
const int ia[] = { 10, 20, 30, 40};
const FormatArgImpl args[] = {FormatArgImpl(ia[0]), FormatArgImpl(ia[1]),
FormatArgImpl(ia[2]), FormatArgImpl(ia[3])};
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
const Expectation kExpect[] = {
{__LINE__, "d", 2, &args[0], no, no, 2},
{__LINE__, "4d", 2, &args[0], 4, no, 2},
{__LINE__, ".5d", 2, &args[0], no, 5, 2},
{__LINE__, "4.5d", 2, &args[0], 4, 5, 2},
{__LINE__, "*d", 2, &args[1], 10, no, 3},
{__LINE__, ".*d", 2, &args[1], no, 10, 3},
{__LINE__, "*.*d", 2, &args[2], 10, 20, 4},
{__LINE__, "1$d", 2, &args[0], no, no, 0},
{__LINE__, "2$d", 2, &args[1], no, no, 0},
{__LINE__, "3$d", 2, &args[2], no, no, 0},
{__LINE__, "4$d", 2, &args[3], no, no, 0},
{__LINE__, "2$*1$d", 2, &args[1], 10, no, 0},
{__LINE__, "2$*2$d", 2, &args[1], 20, no, 0},
{__LINE__, "2$*3$d", 2, &args[1], 30, no, 0},
{__LINE__, "2$.*1$d", 2, &args[1], no, 10, 0},
{__LINE__, "2$.*2$d", 2, &args[1], no, 20, 0},
{__LINE__, "2$.*3$d", 2, &args[1], no, 30, 0},
{__LINE__, "2$*3$.*1$d", 2, &args[1], 30, 10, 0},
{__LINE__, "2$*2$.*2$d", 2, &args[1], 20, 20, 0},
{__LINE__, "2$*1$.*3$d", 2, &args[1], 10, 30, 0},
{__LINE__, "2$*3$.*1$d", 2, &args[1], 30, 10, 0},
{__LINE__, "1$*d", 0},
{__LINE__, "*2$d", 0},
{__LINE__, "6$d", 1},
{__LINE__, "1$6$d", 0},
{__LINE__, "1$.6$d", 0},
{__LINE__, "1$*6$d", 1},
{__LINE__, "1$.*6$d", 1},
};
#pragma GCC diagnostic pop
for (const Expectation &e : kExpect) {
SCOPED_TRACE(e.line);
SCOPED_TRACE(e.fmt);
UnboundConversion props;
BoundConversion bound;
int ok_phases = 0;
int next = 0;
if (Extract(e.fmt, &props, &next)) {
++ok_phases;
if (BindWithPack(&props, args, &bound)) {
++ok_phases;
}
}
EXPECT_EQ(e.ok_phases, ok_phases);
if (e.ok_phases < 2) continue;
if (e.arg != nullptr) {
EXPECT_EQ(e.arg, bound.arg());
}
EXPECT_EQ(e.width, bound.width());
EXPECT_EQ(e.precision, bound.precision());
}
}
TEST_F(FormatBindTest, WidthUnderflowRegression) {
UnboundConversion props;
BoundConversion bound;
int next = 0;
const int args_i[] = {std::numeric_limits<int>::min(), 17};
const FormatArgImpl args[] = {FormatArgImpl(args_i[0]),
FormatArgImpl(args_i[1])};
ASSERT_TRUE(Extract("*d", &props, &next));
ASSERT_TRUE(BindWithPack(&props, args, &bound));
EXPECT_EQ(bound.width(), std::numeric_limits<int>::max());
EXPECT_EQ(bound.arg(), args + 1);
}
TEST_F(FormatBindTest, FormatPack) {
struct Expectation {
int line;
const char *fmt;
const char *summary;
};
const int ia[] = { 10, 20, 30, 40, -10 };
const FormatArgImpl args[] = {FormatArgImpl(ia[0]), FormatArgImpl(ia[1]),
FormatArgImpl(ia[2]), FormatArgImpl(ia[3]),
FormatArgImpl(ia[4])};
const Expectation kExpect[] = {
{__LINE__, "a%4db%dc", "a{10:4d}b{20:d}c"},
{__LINE__, "a%.4db%dc", "a{10:.4d}b{20:d}c"},
{__LINE__, "a%4.5db%dc", "a{10:4.5d}b{20:d}c"},
{__LINE__, "a%db%4.5dc", "a{10:d}b{20:4.5d}c"},
{__LINE__, "a%db%*.*dc", "a{10:d}b{40:20.30d}c"},
{__LINE__, "a%.*fb", "a{20:.10f}b"},
{__LINE__, "a%1$db%2$*3$.*4$dc", "a{10:d}b{20:30.40d}c"},
{__LINE__, "a%4$db%3$*2$.*1$dc", "a{40:d}b{30:20.10d}c"},
{__LINE__, "a%04ldb", "a{10:04d}b"},
{__LINE__, "a%-#04lldb", "a{10:-#04d}b"},
{__LINE__, "a%1$*5$db", "a{10:-10d}b"},
{__LINE__, "a%1$.*5$db", "a{10:d}b"},
};
for (const Expectation &e : kExpect) {
absl::string_view fmt = e.fmt;
SCOPED_TRACE(e.line);
SCOPED_TRACE(e.fmt);
UntypedFormatSpecImpl format(fmt);
EXPECT_EQ(e.summary,
str_format_internal::Summarize(format, absl::MakeSpan(args)))
<< "line:" << e.line;
}
}
}
}
ABSL_NAMESPACE_END
} |
2,570 | cpp | abseil/abseil-cpp | arg | absl/strings/internal/str_format/arg.cc | absl/strings/internal/str_format/arg_test.cc | #ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_ARG_H_
#define ABSL_STRINGS_INTERNAL_STR_FORMAT_ARG_H_
#include <string.h>
#include <wchar.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#include "absl/meta/type_traits.h"
#include "absl/numeric/int128.h"
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/internal/str_format/extension.h"
#include "absl/strings/string_view.h"
#if defined(ABSL_HAVE_STD_STRING_VIEW)
#include <string_view>
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
class Cord;
class FormatCountCapture;
class FormatSink;
template <absl::FormatConversionCharSet C>
struct FormatConvertResult;
class FormatConversionSpec;
namespace str_format_internal {
template <FormatConversionCharSet C>
struct ArgConvertResult {
bool value;
};
using IntegralConvertResult = ArgConvertResult<FormatConversionCharSetUnion(
FormatConversionCharSetInternal::c,
FormatConversionCharSetInternal::kNumeric,
FormatConversionCharSetInternal::kStar,
FormatConversionCharSetInternal::v)>;
using FloatingConvertResult = ArgConvertResult<FormatConversionCharSetUnion(
FormatConversionCharSetInternal::kFloating,
FormatConversionCharSetInternal::v)>;
using CharConvertResult = ArgConvertResult<FormatConversionCharSetUnion(
FormatConversionCharSetInternal::c,
FormatConversionCharSetInternal::kNumeric,
FormatConversionCharSetInternal::kStar)>;
template <typename T, typename = void>
struct HasUserDefinedConvert : std::false_type {};
template <typename T>
struct HasUserDefinedConvert<T, void_t<decltype(AbslFormatConvert(
std::declval<const T&>(),
std::declval<const FormatConversionSpec&>(),
std::declval<FormatSink*>()))>>
: std::true_type {};
void AbslFormatConvert();
void AbslStringify();
template <typename T>
bool ConvertIntArg(T v, FormatConversionSpecImpl conv, FormatSinkImpl* sink);
extern template bool ConvertIntArg<char>(char v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<signed char>(signed char v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<unsigned char>(unsigned char v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<wchar_t>(wchar_t v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<short>(short v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<unsigned short>(
unsigned short v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<int>(int v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<unsigned int>(unsigned int v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<long>(
long v, FormatConversionSpecImpl conv, FormatSinkImpl* sink);
extern template bool ConvertIntArg<unsigned long>(unsigned long v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<long long>(long long v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
extern template bool ConvertIntArg<unsigned long long>(
unsigned long long v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
template <typename T>
auto FormatConvertImpl(const T& v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink)
-> decltype(AbslFormatConvert(v,
std::declval<const FormatConversionSpec&>(),
std::declval<FormatSink*>())) {
using FormatConversionSpecT =
absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatConversionSpec>;
using FormatSinkT =
absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatSink>;
auto fcs = conv.Wrap<FormatConversionSpecT>();
auto fs = sink->Wrap<FormatSinkT>();
return AbslFormatConvert(v, fcs, &fs);
}
template <typename T>
auto FormatConvertImpl(const T& v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink)
-> std::enable_if_t<std::is_enum<T>::value &&
std::is_void<decltype(AbslStringify(
std::declval<FormatSink&>(), v))>::value,
IntegralConvertResult> {
if (conv.conversion_char() == FormatConversionCharInternal::v) {
using FormatSinkT =
absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatSink>;
auto fs = sink->Wrap<FormatSinkT>();
AbslStringify(fs, v);
return {true};
} else {
return {ConvertIntArg(
static_cast<typename std::underlying_type<T>::type>(v), conv, sink)};
}
}
template <typename T>
auto FormatConvertImpl(const T& v, FormatConversionSpecImpl,
FormatSinkImpl* sink)
-> std::enable_if_t<!std::is_enum<T>::value &&
!std::is_same<T, absl::Cord>::value &&
std::is_void<decltype(AbslStringify(
std::declval<FormatSink&>(), v))>::value,
ArgConvertResult<FormatConversionCharSetInternal::v>> {
using FormatSinkT =
absl::enable_if_t<sizeof(const T& (*)()) != 0, FormatSink>;
auto fs = sink->Wrap<FormatSinkT>();
AbslStringify(fs, v);
return {true};
}
template <typename T>
class StreamedWrapper;
struct VoidPtr {
VoidPtr() = default;
template <typename T,
decltype(reinterpret_cast<uintptr_t>(std::declval<T*>())) = 0>
VoidPtr(T* ptr)
: value(ptr ? reinterpret_cast<uintptr_t>(ptr) : 0) {}
uintptr_t value;
};
template <FormatConversionCharSet C>
constexpr FormatConversionCharSet ExtractCharSet(FormatConvertResult<C>) {
return C;
}
template <FormatConversionCharSet C>
constexpr FormatConversionCharSet ExtractCharSet(ArgConvertResult<C>) {
return C;
}
ArgConvertResult<FormatConversionCharSetInternal::p> FormatConvertImpl(
VoidPtr v, FormatConversionSpecImpl conv, FormatSinkImpl* sink);
using StringConvertResult = ArgConvertResult<FormatConversionCharSetUnion(
FormatConversionCharSetInternal::s,
FormatConversionCharSetInternal::v)>;
StringConvertResult FormatConvertImpl(const std::string& v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
StringConvertResult FormatConvertImpl(const std::wstring& v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
StringConvertResult FormatConvertImpl(string_view v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
#if defined(ABSL_HAVE_STD_STRING_VIEW)
StringConvertResult FormatConvertImpl(std::wstring_view v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
#if !defined(ABSL_USES_STD_STRING_VIEW)
inline StringConvertResult FormatConvertImpl(std::string_view v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink) {
return FormatConvertImpl(absl::string_view(v.data(), v.size()), conv, sink);
}
#endif
#endif
using StringPtrConvertResult = ArgConvertResult<FormatConversionCharSetUnion(
FormatConversionCharSetInternal::s,
FormatConversionCharSetInternal::p)>;
StringPtrConvertResult FormatConvertImpl(const char* v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
StringPtrConvertResult FormatConvertImpl(const wchar_t* v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
StringPtrConvertResult FormatConvertImpl(std::nullptr_t,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
template <class AbslCord, typename std::enable_if<std::is_same<
AbslCord, absl::Cord>::value>::type* = nullptr>
StringConvertResult FormatConvertImpl(const AbslCord& value,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink) {
bool is_left = conv.has_left_flag();
size_t space_remaining = 0;
int width = conv.width();
if (width >= 0) space_remaining = static_cast<size_t>(width);
size_t to_write = value.size();
int precision = conv.precision();
if (precision >= 0)
to_write = (std::min)(to_write, static_cast<size_t>(precision));
space_remaining = Excess(to_write, space_remaining);
if (space_remaining > 0 && !is_left) sink->Append(space_remaining, ' ');
for (string_view piece : value.Chunks()) {
if (piece.size() > to_write) {
piece.remove_suffix(piece.size() - to_write);
to_write = 0;
} else {
to_write -= piece.size();
}
sink->Append(piece);
if (to_write == 0) {
break;
}
}
if (space_remaining > 0 && is_left) sink->Append(space_remaining, ' ');
return {true};
}
bool ConvertBoolArg(bool v, FormatSinkImpl* sink);
FloatingConvertResult FormatConvertImpl(float v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
FloatingConvertResult FormatConvertImpl(double v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
FloatingConvertResult FormatConvertImpl(long double v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
CharConvertResult FormatConvertImpl(char v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
CharConvertResult FormatConvertImpl(wchar_t v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(signed char v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(unsigned char v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(short v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(unsigned short v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(int v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(unsigned v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(long v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(unsigned long v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(long long v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(unsigned long long v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(int128 v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
IntegralConvertResult FormatConvertImpl(uint128 v,
FormatConversionSpecImpl conv,
FormatSinkImpl* sink);
template <typename T, enable_if_t<std::is_same<T, bool>::value, int> = 0>
IntegralConvertResult FormatConvertImpl(T v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink) {
if (conv.conversion_char() == FormatConversionCharInternal::v) {
return {ConvertBoolArg(v, sink)};
}
return FormatConvertImpl(static_cast<int>(v), conv, sink);
}
template <typename T>
typename std::enable_if<std::is_enum<T>::value &&
!HasUserDefinedConvert<T>::value &&
!HasAbslStringify<T>::value,
IntegralConvertResult>::type
FormatConvertImpl(T v, FormatConversionSpecImpl conv, FormatSinkImpl* sink);
template <typename T>
StringConvertResult FormatConvertImpl(const StreamedWrapper<T>& v,
FormatConversionSpecImpl conv,
FormatSinkImpl* out) {
std::ostringstream oss;
oss << v.v_;
if (!oss) return {false};
return str_format_internal::FormatConvertImpl(oss.str(), conv, out);
}
struct FormatCountCaptureHelper {
template <class T = int>
static ArgConvertResult<FormatConversionCharSetInternal::n> ConvertHelper(
const FormatCountCapture& v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink) {
const absl::enable_if_t<sizeof(T) != 0, FormatCountCapture>& v2 = v;
if (conv.conversion_char() !=
str_format_internal::FormatConversionCharInternal::n) {
return {false};
}
*v2.p_ = static_cast<int>(sink->size());
return {true};
}
};
template <class T = int>
ArgConvertResult<FormatConversionCharSetInternal::n> FormatConvertImpl(
const FormatCountCapture& v, FormatConversionSpecImpl conv,
FormatSinkImpl* sink) {
return FormatCountCaptureHelper::ConvertHelper(v, conv, sink);
}
struct FormatArgImplFriend {
template <typename Arg>
static bool ToInt(Arg arg, int* out) {
return arg.dispatcher_(arg.data_, {}, out);
}
template <typename Arg>
static bool Convert(Arg arg, FormatConversionSpecImpl conv,
FormatSinkImpl* out) {
return arg.dispatcher_(arg.data_, conv, out);
}
template <typename Arg>
static typename Arg::Dispatcher GetVTablePtrForTest(Arg arg) {
return arg.dispatcher_;
}
};
template <typename Arg>
constexpr FormatConversionCharSet ArgumentToConv() {
using ConvResult = decltype(str_format_internal::FormatConvertImpl(
std::declval<const Arg&>(),
std::declval<const FormatConversionSpecImpl&>(),
std::declval<FormatSinkImpl*>()));
return absl::str_format_internal::ExtractCharSet(ConvResult{});
}
class FormatArgImpl {
private:
enum { kInlinedSpace = 8 };
using VoidPtr = str_format_internal::VoidPtr;
union Data {
const void* ptr;
const volatile void* volatile_ptr;
char buf[kInlinedSpace];
};
using Dispatcher = bool (*)(Data, FormatConversionSpecImpl, void* out);
template <typename T>
struct store_by_value
: std::integral_constant<bool, (sizeof(T) <= kInlinedSpace) &&
(std::is_integral<T>::value ||
std::is_floating_point<T>::value ||
std::is_pointer<T>::value ||
std::is_same<VoidPtr, T>::value)> {};
enum StoragePolicy { ByPointer, ByVolatilePointer, ByValue };
template <typename T>
struct storage_policy
: std::integral_constant<StoragePolicy,
(std::is_volatile<T>::value
? ByVolatilePointer
: (store_by_value<T>::value ? ByValue
: ByPointer))> {
};
template <typename T, typename = void>
struct DecayType {
static constexpr bool kHasUserDefined =
str_format_internal::HasUserDefinedConvert<T>::value ||
HasAbslStringify<T>::value;
using type = typename std::conditional<
!kHasUserDefined && std::is_convertible<T, const char*>::value,
const char*,
typename std::conditional<
!kHasUserDefined && std::is_convertible<T, const wchar_t*>::value,
const wchar_t*,
typename std::conditional<
!kHasUserDefined && std::is_convertible<T, VoidPtr>::value,
VoidPtr,
const T&>::type>::type>::type;
};
template <typename T>
struct DecayType<
T, typename std::enable_if<
!str_format_internal::HasUserDefinedConvert<T>::value &&
!HasAbslStringify<T>::value && std::is_enum<T>::value>::type> {
using type = decltype(+typename std::underlying_type<T>::type());
};
public:
template <typename T>
explicit FormatArgImpl(const T& value) {
using D = typename DecayType<T>::type;
static_assert(
std::is_same<D, const T&>::value || storage_policy<D>::value == ByValue,
"Decayed types must be stored by value");
Init(static_cast<D>(value));
}
private:
friend struct str_format_internal::FormatArgImplFriend;
template <typename T, StoragePolicy = storage_policy<T>::value>
struct Manager;
template <typename T>
struct Manager<T, ByPointer> {
static Data SetValue(const T& value) {
Data data;
data.ptr = std::addressof(value);
return data;
}
static const T& Value(Data arg) { return *static_cast<const T*>(arg.ptr); }
};
template <typename T>
struct Manager<T, ByVolatilePointer> {
static Data SetValue(const T& value) {
Data data;
data.volatile_ptr = &value;
return data;
}
static const T& Value(Data arg) {
return *static_cast<const T*>(arg.volatile_ptr);
}
};
template <typename T>
struct Manager<T, ByValue> {
static Data SetValue(const T& value) {
Data data;
memcpy(data.buf, &value, sizeof(value));
return data;
}
static T Value(Data arg) {
T value;
memcpy(&value, arg.buf, sizeof(T));
return value;
}
};
template <typename T>
void Init(const T& value) {
data_ = Manager<T>::SetValue(value);
dispatcher_ = &Dispatch<T>;
}
template <typename T>
static int ToIntVal(const T& val) {
using CommonType = typename std::conditional<std::is_signed<T>::value,
int64_t, uint64_t>::type;
if (static_cast<CommonType>(val) >
static_cast<CommonType>((std::numeric_limits<int>::max)())) {
return (std::numeric_limits<int>::max)();
} else if (std::is_signed<T>::value &&
static_cast<CommonType>(val) <
static_cast<CommonType>((std::numeric_limits<int>::min)())) {
return (std::numeric_limits<int>::min)();
}
return static_cast<int>(val);
}
template <typename T>
static bool ToInt(Data arg, int* out, std::true_type ,
std::false_type) {
*out = ToIntVal(Manager<T>::Value(arg));
return true;
}
template <typename T>
static bool ToInt(Data arg, int* out, std::false_type,
std::true_type ) {
*out = ToIntVal(static_cast<typename std::underlying_type<T>::type>(
Manager<T>::Value(arg)));
return true;
}
template <typename T>
static bool ToInt(Data, int*, std::false_type, std::false_type) {
return false;
}
template <typename T>
static bool Dispatch(Data arg, FormatConversionSpecImpl spec, void* out) {
if (ABSL_PREDICT_FALSE(spec.conversion_char() ==
FormatConversionCharInternal::kNone)) {
return ToInt<T>(arg, static_cast<int*>(out), std::is_integral<T>(),
std::is_enum<T>());
}
if (ABSL_PREDICT_FALSE(!Contains(ArgumentToConv<T>(),
spec.conversion_char()))) {
return false;
}
return str_format_internal::FormatConvertImpl(
Manager<T>::Value(arg), spec,
static_cast<FormatSinkImpl*>(out))
.value;
}
Data data_;
Dispatcher dispatcher_;
};
#define ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(T, E) \
E template bool FormatArgImpl::Dispatch<T>(Data, FormatConversionSpecImpl, \
void*)
#define ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_NO_WSTRING_VIEW_(...) \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(str_format_internal::VoidPtr, \
__VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(bool, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(char, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(signed char, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned char, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(short, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned short, \
__VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(int, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned int, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(long, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned long, \
__VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(long long, \
__VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(unsigned long long, \
__VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(int128, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(uint128, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(float, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(double, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(long double, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(const char*, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(std::string, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(string_view, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(const wchar_t*, __VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(std::wstring, __VA_ARGS__)
#if defined(ABSL_HAVE_STD_STRING_VIEW)
#define ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_(...) \
ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_NO_WSTRING_VIEW_( \
__VA_ARGS__); \
ABSL_INTERNAL_FORMAT_DISPATCH_INSTANTIATE_(std::wstring_view, __VA_ARGS__)
#else
#define ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_(...) \
ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_NO_WSTRING_VIEW_(__VA_ARGS__)
#endif
ABSL_INTERNAL_FORMAT_DISPATCH_OVERLOADS_EXPAND_(extern);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/str_format/arg.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <string>
#include <type_traits>
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#include "absl/container/fixed_array.h"
#include "absl/numeric/int128.h"
#include "absl/strings/internal/str_format/extension.h"
#include "absl/strings/internal/str_format/float_conversion.h"
#include "absl/strings/numbers.h"
#include "absl/strings/string_view.h"
#if defined(ABSL_HAVE_STD_STRING_VIEW)
#include <string_view>
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
void ReducePadding(string_view s, size_t *capacity) {
*capacity = Excess(s.size(), *capacity);
}
void ReducePadding(size_t n, size_t *capacity) {
*capacity = Excess(n, *capacity);
}
template <typename T>
struct MakeUnsigned : std::make_unsigned<T> {};
template <>
struct MakeUnsigned<absl::int128> {
using type = absl::uint128;
};
template <>
struct MakeUnsigned<absl::uint128> {
using type = absl::uint128;
};
template <typename T>
struct IsSigned : std::is_signed<T> {};
template <>
struct IsSigned<absl::int128> : std::true_type {};
template <>
struct IsSigned<absl::uint128> : std::false_type {};
class IntDigits {
public:
template <typename T>
void PrintAsOct(T v) {
static_assert(!IsSigned<T>::value, "");
char *p = storage_ + sizeof(storage_);
do {
*--p = static_cast<char>('0' + (static_cast<size_t>(v) & 7));
v >>= 3;
} while (v);
start_ = p;
size_ = static_cast<size_t>(storage_ + sizeof(storage_) - p);
}
template <typename T>
void PrintAsDec(T v) {
static_assert(std::is_integral<T>::value, "");
start_ = storage_;
size_ = static_cast<size_t>(numbers_internal::FastIntToBuffer(v, storage_) -
storage_);
}
void PrintAsDec(int128 v) {
auto u = static_cast<uint128>(v);
bool add_neg = false;
if (v < 0) {
add_neg = true;
u = uint128{} - u;
}
PrintAsDec(u, add_neg);
}
void PrintAsDec(uint128 v, bool add_neg = false) {
char *p = storage_ + sizeof(storage_);
do {
p -= 2;
numbers_internal::PutTwoDigits(static_cast<uint32_t>(v % 100), p);
v /= 100;
} while (v);
if (p[0] == '0') {
++p;
}
if (add_neg) {
*--p = '-';
}
size_ = static_cast<size_t>(storage_ + sizeof(storage_) - p);
start_ = p;
}
template <typename T>
void PrintAsHexLower(T v) {
static_assert(!IsSigned<T>::value, "");
char *p = storage_ + sizeof(storage_);
do {
p -= 2;
constexpr const char* table = numbers_internal::kHexTable;
std::memcpy(p, table + 2 * (static_cast<size_t>(v) & 0xFF), 2);
if (sizeof(T) == 1) break;
v >>= 8;
} while (v);
if (p[0] == '0') {
++p;
}
start_ = p;
size_ = static_cast<size_t>(storage_ + sizeof(storage_) - p);
}
template <typename T>
void PrintAsHexUpper(T v) {
static_assert(!IsSigned<T>::value, "");
char *p = storage_ + sizeof(storage_);
do {
*--p = "0123456789ABCDEF"[static_cast<size_t>(v) & 15];
v >>= 4;
} while (v);
start_ = p;
size_ = static_cast<size_t>(storage_ + sizeof | #include "absl/strings/internal/str_format/arg.h"
#include <limits>
#include <string>
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/strings/str_format.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
class FormatArgImplTest : public ::testing::Test {
public:
enum Color { kRed, kGreen, kBlue };
static const char *hi() { return "hi"; }
struct X {};
X x_;
};
inline FormatConvertResult<FormatConversionCharSet{}> AbslFormatConvert(
const FormatArgImplTest::X &, const FormatConversionSpec &, FormatSink *) {
return {false};
}
TEST_F(FormatArgImplTest, ToInt) {
int out = 0;
EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(1), &out));
EXPECT_EQ(1, out);
EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(-1), &out));
EXPECT_EQ(-1, out);
EXPECT_TRUE(
FormatArgImplFriend::ToInt(FormatArgImpl(static_cast<char>(64)), &out));
EXPECT_EQ(64, out);
EXPECT_TRUE(FormatArgImplFriend::ToInt(
FormatArgImpl(static_cast<unsigned long long>(123456)), &out));
EXPECT_EQ(123456, out);
EXPECT_TRUE(FormatArgImplFriend::ToInt(
FormatArgImpl(static_cast<unsigned long long>(
std::numeric_limits<int>::max()) +
1),
&out));
EXPECT_EQ(std::numeric_limits<int>::max(), out);
EXPECT_TRUE(FormatArgImplFriend::ToInt(
FormatArgImpl(static_cast<long long>(
std::numeric_limits<int>::min()) -
10),
&out));
EXPECT_EQ(std::numeric_limits<int>::min(), out);
EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(false), &out));
EXPECT_EQ(0, out);
EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(true), &out));
EXPECT_EQ(1, out);
EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(2.2), &out));
EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(3.2f), &out));
EXPECT_FALSE(FormatArgImplFriend::ToInt(
FormatArgImpl(static_cast<int *>(nullptr)), &out));
EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(hi()), &out));
EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl("hi"), &out));
EXPECT_FALSE(FormatArgImplFriend::ToInt(FormatArgImpl(x_), &out));
EXPECT_TRUE(FormatArgImplFriend::ToInt(FormatArgImpl(kBlue), &out));
EXPECT_EQ(2, out);
}
extern const char kMyArray[];
TEST_F(FormatArgImplTest, CharArraysDecayToCharPtr) {
const char* a = "";
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl("")));
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl("A")));
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl("ABC")));
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(kMyArray)));
}
extern const wchar_t kMyWCharTArray[];
TEST_F(FormatArgImplTest, WCharTArraysDecayToWCharTPtr) {
const wchar_t* a = L"";
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(L"")));
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(L"A")));
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(L"ABC")));
EXPECT_EQ(
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(a)),
FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(kMyWCharTArray)));
}
TEST_F(FormatArgImplTest, OtherPtrDecayToVoidPtr) {
auto expected = FormatArgImplFriend::GetVTablePtrForTest(
FormatArgImpl(static_cast<void *>(nullptr)));
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(
FormatArgImpl(static_cast<int *>(nullptr))),
expected);
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(
FormatArgImpl(static_cast<volatile int *>(nullptr))),
expected);
auto p = static_cast<void (*)()>([] {});
EXPECT_EQ(FormatArgImplFriend::GetVTablePtrForTest(FormatArgImpl(p)),
expected);
}
TEST_F(FormatArgImplTest, WorksWithCharArraysOfUnknownSize) {
std::string s;
FormatSinkImpl sink(&s);
FormatConversionSpecImpl conv;
FormatConversionSpecImplFriend::SetConversionChar(
FormatConversionCharInternal::s, &conv);
FormatConversionSpecImplFriend::SetFlags(Flags(), &conv);
FormatConversionSpecImplFriend::SetWidth(-1, &conv);
FormatConversionSpecImplFriend::SetPrecision(-1, &conv);
EXPECT_TRUE(
FormatArgImplFriend::Convert(FormatArgImpl(kMyArray), conv, &sink));
sink.Flush();
EXPECT_EQ("ABCDE", s);
}
const char kMyArray[] = "ABCDE";
TEST_F(FormatArgImplTest, WorksWithWCharTArraysOfUnknownSize) {
std::string s;
FormatSinkImpl sink(&s);
FormatConversionSpecImpl conv;
FormatConversionSpecImplFriend::SetConversionChar(
FormatConversionCharInternal::s, &conv);
FormatConversionSpecImplFriend::SetFlags(Flags(), &conv);
FormatConversionSpecImplFriend::SetWidth(-1, &conv);
FormatConversionSpecImplFriend::SetPrecision(-1, &conv);
EXPECT_TRUE(
FormatArgImplFriend::Convert(FormatArgImpl(kMyWCharTArray), conv, &sink));
sink.Flush();
EXPECT_EQ("ABCDE", s);
}
const wchar_t kMyWCharTArray[] = L"ABCDE";
}
}
ABSL_NAMESPACE_END
} |
2,571 | cpp | abseil/abseil-cpp | output | absl/strings/internal/str_format/output.cc | absl/strings/internal/str_format/output_test.cc | #ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_OUTPUT_H_
#define ABSL_STRINGS_INTERNAL_STR_FORMAT_OUTPUT_H_
#include <cstdio>
#include <ios>
#include <ostream>
#include <string>
#include "absl/base/port.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
class BufferRawSink {
public:
BufferRawSink(char* buffer, size_t size) : buffer_(buffer), size_(size) {}
size_t total_written() const { return total_written_; }
void Write(string_view v);
private:
char* buffer_;
size_t size_;
size_t total_written_ = 0;
};
class FILERawSink {
public:
explicit FILERawSink(std::FILE* output) : output_(output) {}
void Write(string_view v);
size_t count() const { return count_; }
int error() const { return error_; }
private:
std::FILE* output_;
int error_ = 0;
size_t count_ = 0;
};
inline void AbslFormatFlush(std::string* out, string_view s) {
out->append(s.data(), s.size());
}
inline void AbslFormatFlush(std::ostream* out, string_view s) {
out->write(s.data(), static_cast<std::streamsize>(s.size()));
}
inline void AbslFormatFlush(FILERawSink* sink, string_view v) {
sink->Write(v);
}
inline void AbslFormatFlush(BufferRawSink* sink, string_view v) {
sink->Write(v);
}
template <typename T>
auto InvokeFlush(T* out, string_view s) -> decltype(AbslFormatFlush(out, s)) {
AbslFormatFlush(out, s);
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/str_format/output.h"
#include <errno.h>
#include <cstring>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
struct ClearErrnoGuard {
ClearErrnoGuard() : old_value(errno) { errno = 0; }
~ClearErrnoGuard() {
if (!errno) errno = old_value;
}
int old_value;
};
}
void BufferRawSink::Write(string_view v) {
size_t to_write = std::min(v.size(), size_);
std::memcpy(buffer_, v.data(), to_write);
buffer_ += to_write;
size_ -= to_write;
total_written_ += v.size();
}
void FILERawSink::Write(string_view v) {
while (!v.empty() && !error_) {
ClearErrnoGuard guard;
if (size_t result = std::fwrite(v.data(), 1, v.size(), output_)) {
count_ += result;
v.remove_prefix(result);
} else {
if (errno == EINTR) {
continue;
} else if (errno) {
error_ = errno;
} else if (std::ferror(output_)) {
error_ = EBADF;
} else {
continue;
}
}
}
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/str_format/output.h"
#include <sstream>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/cord.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
TEST(InvokeFlush, String) {
std::string str = "ABC";
str_format_internal::InvokeFlush(&str, "DEF");
EXPECT_EQ(str, "ABCDEF");
}
TEST(InvokeFlush, Stream) {
std::stringstream str;
str << "ABC";
str_format_internal::InvokeFlush(&str, "DEF");
EXPECT_EQ(str.str(), "ABCDEF");
}
TEST(InvokeFlush, Cord) {
absl::Cord str("ABC");
str_format_internal::InvokeFlush(&str, "DEF");
EXPECT_EQ(str, "ABCDEF");
}
TEST(BufferRawSink, Limits) {
char buf[16];
{
std::fill(std::begin(buf), std::end(buf), 'x');
str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1);
str_format_internal::InvokeFlush(&bufsink, "Hello World237");
EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World237xx");
}
{
std::fill(std::begin(buf), std::end(buf), 'x');
str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1);
str_format_internal::InvokeFlush(&bufsink, "Hello World237237");
EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World2372x");
}
{
std::fill(std::begin(buf), std::end(buf), 'x');
str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1);
str_format_internal::InvokeFlush(&bufsink, "Hello World");
str_format_internal::InvokeFlush(&bufsink, "237");
EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World237xx");
}
{
std::fill(std::begin(buf), std::end(buf), 'x');
str_format_internal::BufferRawSink bufsink(buf, sizeof(buf) - 1);
str_format_internal::InvokeFlush(&bufsink, "Hello World");
str_format_internal::InvokeFlush(&bufsink, "237237");
EXPECT_EQ(std::string(buf, sizeof(buf)), "Hello World2372x");
}
}
}
ABSL_NAMESPACE_END
} |
2,572 | cpp | abseil/abseil-cpp | parser | absl/strings/internal/str_format/parser.cc | absl/strings/internal/str_format/parser_test.cc | #ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_PARSER_H_
#define ABSL_STRINGS_INTERNAL_STR_FORMAT_PARSER_H_
#include <stddef.h>
#include <stdlib.h>
#include <cassert>
#include <cstring>
#include <initializer_list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/config.h"
#include "absl/base/optimization.h"
#include "absl/strings/internal/str_format/checker.h"
#include "absl/strings/internal/str_format/constexpr_parser.h"
#include "absl/strings/internal/str_format/extension.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
std::string LengthModToString(LengthMod v);
const char* ConsumeUnboundConversionNoInline(const char* p, const char* end,
UnboundConversion* conv,
int* next_arg);
template <typename Consumer>
bool ParseFormatString(string_view src, Consumer consumer) {
int next_arg = 0;
const char* p = src.data();
const char* const end = p + src.size();
while (p != end) {
const char* percent =
static_cast<const char*>(memchr(p, '%', static_cast<size_t>(end - p)));
if (!percent) {
return consumer.Append(string_view(p, static_cast<size_t>(end - p)));
}
if (ABSL_PREDICT_FALSE(!consumer.Append(
string_view(p, static_cast<size_t>(percent - p))))) {
return false;
}
if (ABSL_PREDICT_FALSE(percent + 1 >= end)) return false;
auto tag = GetTagForChar(percent[1]);
if (tag.is_conv()) {
if (ABSL_PREDICT_FALSE(next_arg < 0)) {
return false;
}
p = percent + 2;
UnboundConversion conv;
conv.conv = tag.as_conv();
conv.arg_position = ++next_arg;
if (ABSL_PREDICT_FALSE(
!consumer.ConvertOne(conv, string_view(percent + 1, 1)))) {
return false;
}
} else if (percent[1] != '%') {
UnboundConversion conv;
p = ConsumeUnboundConversionNoInline(percent + 1, end, &conv, &next_arg);
if (ABSL_PREDICT_FALSE(p == nullptr)) return false;
if (ABSL_PREDICT_FALSE(!consumer.ConvertOne(
conv, string_view(percent + 1,
static_cast<size_t>(p - (percent + 1)))))) {
return false;
}
} else {
if (ABSL_PREDICT_FALSE(!consumer.Append("%"))) return false;
p = percent + 2;
continue;
}
}
return true;
}
constexpr bool EnsureConstexpr(string_view s) {
return s.empty() || s[0] == s[0];
}
class ParsedFormatBase {
public:
explicit ParsedFormatBase(
string_view format, bool allow_ignored,
std::initializer_list<FormatConversionCharSet> convs);
ParsedFormatBase(const ParsedFormatBase& other) { *this = other; }
ParsedFormatBase(ParsedFormatBase&& other) { *this = std::move(other); }
ParsedFormatBase& operator=(const ParsedFormatBase& other) {
if (this == &other) return *this;
has_error_ = other.has_error_;
items_ = other.items_;
size_t text_size = items_.empty() ? 0 : items_.back().text_end;
data_.reset(new char[text_size]);
memcpy(data_.get(), other.data_.get(), text_size);
return *this;
}
ParsedFormatBase& operator=(ParsedFormatBase&& other) {
if (this == &other) return *this;
has_error_ = other.has_error_;
data_ = std::move(other.data_);
items_ = std::move(other.items_);
other.items_.clear();
return *this;
}
template <typename Consumer>
bool ProcessFormat(Consumer consumer) const {
const char* const base = data_.get();
string_view text(base, 0);
for (const auto& item : items_) {
const char* const end = text.data() + text.size();
text =
string_view(end, static_cast<size_t>((base + item.text_end) - end));
if (item.is_conversion) {
if (!consumer.ConvertOne(item.conv, text)) return false;
} else {
if (!consumer.Append(text)) return false;
}
}
return !has_error_;
}
bool has_error() const { return has_error_; }
private:
bool MatchesConversions(
bool allow_ignored,
std::initializer_list<FormatConversionCharSet> convs) const;
struct ParsedFormatConsumer;
struct ConversionItem {
bool is_conversion;
size_t text_end;
UnboundConversion conv;
};
bool has_error_;
std::unique_ptr<char[]> data_;
std::vector<ConversionItem> items_;
};
template <FormatConversionCharSet... C>
class ExtendedParsedFormat : public str_format_internal::ParsedFormatBase {
public:
explicit ExtendedParsedFormat(string_view format)
#ifdef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER
__attribute__((
enable_if(str_format_internal::EnsureConstexpr(format),
"Format string is not constexpr."),
enable_if(str_format_internal::ValidFormatImpl<C...>(format),
"Format specified does not match the template arguments.")))
#endif
: ExtendedParsedFormat(format, false) {
}
static std::unique_ptr<ExtendedParsedFormat> New(string_view format) {
return New(format, false);
}
static std::unique_ptr<ExtendedParsedFormat> NewAllowIgnored(
string_view format) {
return New(format, true);
}
private:
static std::unique_ptr<ExtendedParsedFormat> New(string_view format,
bool allow_ignored) {
std::unique_ptr<ExtendedParsedFormat> conv(
new ExtendedParsedFormat(format, allow_ignored));
if (conv->has_error()) return nullptr;
return conv;
}
ExtendedParsedFormat(string_view s, bool allow_ignored)
: ParsedFormatBase(s, allow_ignored, {C...}) {}
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/strings/internal/str_format/parser.h"
#include <assert.h>
#include <string.h>
#include <wchar.h>
#include <cctype>
#include <cstdint>
#include <algorithm>
#include <initializer_list>
#include <limits>
#include <ostream>
#include <string>
#include <unordered_set>
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
constexpr ConvTag ConvTagHolder::value[256];
ABSL_ATTRIBUTE_NOINLINE const char* ConsumeUnboundConversionNoInline(
const char* p, const char* end, UnboundConversion* conv, int* next_arg) {
return ConsumeUnboundConversion(p, end, conv, next_arg);
}
std::string LengthModToString(LengthMod v) {
switch (v) {
case LengthMod::h:
return "h";
case LengthMod::hh:
return "hh";
case LengthMod::l:
return "l";
case LengthMod::ll:
return "ll";
case LengthMod::L:
return "L";
case LengthMod::j:
return "j";
case LengthMod::z:
return "z";
case LengthMod::t:
return "t";
case LengthMod::q:
return "q";
case LengthMod::none:
return "";
}
return "";
}
struct ParsedFormatBase::ParsedFormatConsumer {
explicit ParsedFormatConsumer(ParsedFormatBase *parsedformat)
: parsed(parsedformat), data_pos(parsedformat->data_.get()) {}
bool Append(string_view s) {
if (s.empty()) return true;
size_t text_end = AppendText(s);
if (!parsed->items_.empty() && !parsed->items_.back().is_conversion) {
parsed->items_.back().text_end = text_end;
} else {
parsed->items_.push_back({false, text_end, {}});
}
return true;
}
bool ConvertOne(const UnboundConversion &conv, string_view s) {
size_t text_end = AppendText(s);
parsed->items_.push_back({true, text_end, conv});
return true;
}
size_t AppendText(string_view s) {
memcpy(data_pos, s.data(), s.size());
data_pos += s.size();
return static_cast<size_t>(data_pos - parsed->data_.get());
}
ParsedFormatBase *parsed;
char* data_pos;
};
ParsedFormatBase::ParsedFormatBase(
string_view format, bool allow_ignored,
std::initializer_list<FormatConversionCharSet> convs)
: data_(format.empty() ? nullptr : new char[format.size()]) {
has_error_ = !ParseFormatString(format, ParsedFormatConsumer(this)) ||
!MatchesConversions(allow_ignored, convs);
}
bool ParsedFormatBase::MatchesConversions(
bool allow_ignored,
std::initializer_list<FormatConversionCharSet> convs) const {
std::unordered_set<int> used;
auto add_if_valid_conv = [&](int pos, char c) {
if (static_cast<size_t>(pos) > convs.size() ||
!Contains(convs.begin()[pos - 1], c))
return false;
used.insert(pos);
return true;
};
for (const ConversionItem &item : items_) {
if (!item.is_conversion) continue;
auto &conv = item.conv;
if (conv.precision.is_from_arg() &&
!add_if_valid_conv(conv.precision.get_from_arg(), '*'))
return false;
if (conv.width.is_from_arg() &&
!add_if_valid_conv(conv.width.get_from_arg(), '*'))
return false;
if (!add_if_valid_conv(conv.arg_position,
FormatConversionCharToChar(conv.conv)))
return false;
}
return used.size() == convs.size() || allow_ignored;
}
}
ABSL_NAMESPACE_END
} | #include "absl/strings/internal/str_format/parser.h"
#include <string.h>
#include <algorithm>
#include <initializer_list>
#include <string>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/strings/internal/str_format/constexpr_parser.h"
#include "absl/strings/internal/str_format/extension.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace str_format_internal {
namespace {
using testing::Pair;
TEST(LengthModTest, Names) {
struct Expectation {
int line;
LengthMod mod;
const char *name;
};
const Expectation kExpect[] = {
{__LINE__, LengthMod::none, "" },
{__LINE__, LengthMod::h, "h" },
{__LINE__, LengthMod::hh, "hh"},
{__LINE__, LengthMod::l, "l" },
{__LINE__, LengthMod::ll, "ll"},
{__LINE__, LengthMod::L, "L" },
{__LINE__, LengthMod::j, "j" },
{__LINE__, LengthMod::z, "z" },
{__LINE__, LengthMod::t, "t" },
{__LINE__, LengthMod::q, "q" },
};
EXPECT_EQ(ABSL_ARRAYSIZE(kExpect), 10);
for (auto e : kExpect) {
SCOPED_TRACE(e.line);
EXPECT_EQ(e.name, LengthModToString(e.mod));
}
}
TEST(ConversionCharTest, Names) {
struct Expectation {
FormatConversionChar id;
char name;
};
const Expectation kExpect[] = {
#define X(c) {FormatConversionCharInternal::c, #c[0]}
X(c), X(s),
X(d), X(i), X(o), X(u), X(x), X(X),
X(f), X(F), X(e), X(E), X(g), X(G), X(a), X(A),
X(n), X(p),
#undef X
{FormatConversionCharInternal::kNone, '\0'},
};
for (auto e : kExpect) {
SCOPED_TRACE(e.name);
FormatConversionChar v = e.id;
EXPECT_EQ(e.name, FormatConversionCharToChar(v));
}
}
class ConsumeUnboundConversionTest : public ::testing::Test {
public:
std::pair<string_view, string_view> Consume(string_view src) {
int next = 0;
o = UnboundConversion();
const char* p = ConsumeUnboundConversion(
src.data(), src.data() + src.size(), &o, &next);
if (!p) return {{}, src};
return {string_view(src.data(), p - src.data()),
string_view(p, src.data() + src.size() - p)};
}
bool Run(const char *fmt, bool force_positional = false) {
int next = force_positional ? -1 : 0;
o = UnboundConversion();
return ConsumeUnboundConversion(fmt, fmt + strlen(fmt), &o, &next) ==
fmt + strlen(fmt);
}
UnboundConversion o;
};
TEST_F(ConsumeUnboundConversionTest, ConsumeSpecification) {
struct Expectation {
int line;
string_view src;
string_view out;
string_view src_post;
};
const Expectation kExpect[] = {
{__LINE__, "", "", "" },
{__LINE__, "b", "", "b" },
{__LINE__, "ba", "", "ba"},
{__LINE__, "l", "", "l" },
{__LINE__, "d", "d", "" },
{__LINE__, "v", "v", "" },
{__LINE__, "d ", "d", " " },
{__LINE__, "dd", "d", "d" },
{__LINE__, "d9", "d", "9" },
{__LINE__, "dzz", "d", "zz"},
{__LINE__, "3v", "", "3v"},
{__LINE__, "hv", "", "hv"},
{__LINE__, "1$v", "1$v", ""},
{__LINE__, "1$*2$d", "1$*2$d", "" },
{__LINE__, "0-14.3hhd", "0-14.3hhd", ""},
{__LINE__, " 0-+#14.3hhd", " 0-+#14.3hhd", ""},
};
for (const auto& e : kExpect) {
SCOPED_TRACE(e.line);
EXPECT_THAT(Consume(e.src), Pair(e.out, e.src_post));
}
}
TEST_F(ConsumeUnboundConversionTest, BasicConversion) {
EXPECT_FALSE(Run(""));
EXPECT_FALSE(Run("z"));
EXPECT_FALSE(Run("dd"));
EXPECT_TRUE(Run("d"));
EXPECT_EQ('d', FormatConversionCharToChar(o.conv));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_LT(o.width.value(), 0);
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_LT(o.precision.value(), 0);
EXPECT_EQ(1, o.arg_position);
}
TEST_F(ConsumeUnboundConversionTest, ArgPosition) {
EXPECT_TRUE(Run("d"));
EXPECT_EQ(1, o.arg_position);
EXPECT_TRUE(Run("3$d"));
EXPECT_EQ(3, o.arg_position);
EXPECT_TRUE(Run("1$d"));
EXPECT_EQ(1, o.arg_position);
EXPECT_TRUE(Run("1$d", true));
EXPECT_EQ(1, o.arg_position);
EXPECT_TRUE(Run("123$d"));
EXPECT_EQ(123, o.arg_position);
EXPECT_TRUE(Run("123$d", true));
EXPECT_EQ(123, o.arg_position);
EXPECT_TRUE(Run("10$d"));
EXPECT_EQ(10, o.arg_position);
EXPECT_TRUE(Run("10$d", true));
EXPECT_EQ(10, o.arg_position);
EXPECT_FALSE(Run("0$d"));
EXPECT_FALSE(Run("0$d", true));
EXPECT_FALSE(Run("1$*0$d"));
EXPECT_FALSE(Run("1$.*0$d"));
EXPECT_FALSE(Run("01$p"));
EXPECT_FALSE(Run("01$p", true));
EXPECT_FALSE(Run("1$*01$p"));
EXPECT_FALSE(Run("1$.*01$p"));
}
TEST_F(ConsumeUnboundConversionTest, WidthAndPrecision) {
EXPECT_TRUE(Run("14d"));
EXPECT_EQ('d', FormatConversionCharToChar(o.conv));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_EQ(14, o.width.value());
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_LT(o.precision.value(), 0);
EXPECT_TRUE(Run("14.d"));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_EQ(14, o.width.value());
EXPECT_EQ(0, o.precision.value());
EXPECT_TRUE(Run(".d"));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_LT(o.width.value(), 0);
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_EQ(0, o.precision.value());
EXPECT_TRUE(Run(".5d"));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_LT(o.width.value(), 0);
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_EQ(5, o.precision.value());
EXPECT_TRUE(Run(".0d"));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_LT(o.width.value(), 0);
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_EQ(0, o.precision.value());
EXPECT_TRUE(Run("14.5d"));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_EQ(14, o.width.value());
EXPECT_EQ(5, o.precision.value());
EXPECT_TRUE(Run("*.*d"));
EXPECT_TRUE(o.width.is_from_arg());
EXPECT_EQ(1, o.width.get_from_arg());
EXPECT_TRUE(o.precision.is_from_arg());
EXPECT_EQ(2, o.precision.get_from_arg());
EXPECT_EQ(3, o.arg_position);
EXPECT_TRUE(Run("*d"));
EXPECT_TRUE(o.width.is_from_arg());
EXPECT_EQ(1, o.width.get_from_arg());
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_LT(o.precision.value(), 0);
EXPECT_EQ(2, o.arg_position);
EXPECT_TRUE(Run(".*d"));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_LT(o.width.value(), 0);
EXPECT_TRUE(o.precision.is_from_arg());
EXPECT_EQ(1, o.precision.get_from_arg());
EXPECT_EQ(2, o.arg_position);
EXPECT_FALSE(Run("*23$.*34$d"));
EXPECT_TRUE(Run("12$*23$.*34$d"));
EXPECT_EQ(12, o.arg_position);
EXPECT_TRUE(o.width.is_from_arg());
EXPECT_EQ(23, o.width.get_from_arg());
EXPECT_TRUE(o.precision.is_from_arg());
EXPECT_EQ(34, o.precision.get_from_arg());
EXPECT_TRUE(Run("2$*5$.*9$d"));
EXPECT_EQ(2, o.arg_position);
EXPECT_TRUE(o.width.is_from_arg());
EXPECT_EQ(5, o.width.get_from_arg());
EXPECT_TRUE(o.precision.is_from_arg());
EXPECT_EQ(9, o.precision.get_from_arg());
EXPECT_FALSE(Run(".*0$d")) << "no arg 0";
EXPECT_TRUE(Run("999999999.999999999d"));
EXPECT_FALSE(o.width.is_from_arg());
EXPECT_EQ(999999999, o.width.value());
EXPECT_FALSE(o.precision.is_from_arg());
EXPECT_EQ(999999999, o.precision.value());
EXPECT_FALSE(Run("1000000000.999999999d"));
EXPECT_FALSE(Run("999999999.1000000000d"));
EXPECT_FALSE(Run("9999999999d"));
EXPECT_FALSE(Run(".9999999999d"));
}
TEST_F(ConsumeUnboundConversionTest, Flags) {
static const char kAllFlags[] = "-+ #0";
static const int kNumFlags = ABSL_ARRAYSIZE(kAllFlags) - 1;
for (int rev = 0; rev < 2; ++rev) {
for (int i = 0; i < 1 << kNumFlags; ++i) {
std::string fmt;
for (int k = 0; k < kNumFlags; ++k)
if ((i >> k) & 1) fmt += kAllFlags[k];
if (rev == 1) {
std::reverse(fmt.begin(), fmt.end());
}
fmt += 'd';
SCOPED_TRACE(fmt);
EXPECT_TRUE(Run(fmt.c_str()));
EXPECT_EQ(fmt.find('-') == std::string::npos,
!FlagsContains(o.flags, Flags::kLeft));
EXPECT_EQ(fmt.find('+') == std::string::npos,
!FlagsContains(o.flags, Flags::kShowPos));
EXPECT_EQ(fmt.find(' ') == std::string::npos,
!FlagsContains(o.flags, Flags::kSignCol));
EXPECT_EQ(fmt.find('#') == std::string::npos,
!FlagsContains(o.flags, Flags::kAlt));
EXPECT_EQ(fmt.find('0') == std::string::npos,
!FlagsContains(o.flags, Flags::kZero));
}
}
}
TEST_F(ConsumeUnboundConversionTest, BasicFlag) {
for (const char* fmt : {"d", "llx", "G", "1$X"}) {
SCOPED_TRACE(fmt);
EXPECT_TRUE(Run(fmt));
EXPECT_EQ(o.flags, Flags::kBasic);
}
for (const char* fmt : {"3d", ".llx", "-G", "1$#X", "lc"}) {
SCOPED_TRACE(fmt);
EXPECT_TRUE(Run(fmt));
EXPECT_NE(o.flags, Flags::kBasic);
}
}
TEST_F(ConsumeUnboundConversionTest, LengthMod) {
EXPECT_TRUE(Run("d"));
EXPECT_EQ(LengthMod::none, o.length_mod);
EXPECT_TRUE(Run("hd"));
EXPECT_EQ(LengthMod::h, o.length_mod);
EXPECT_TRUE(Run("hhd"));
EXPECT_EQ(LengthMod::hh, o.length_mod);
EXPECT_TRUE(Run("ld"));
EXPECT_EQ(LengthMod::l, o.length_mod);
EXPECT_TRUE(Run("lld"));
EXPECT_EQ(LengthMod::ll, o.length_mod);
EXPECT_TRUE(Run("Lf"));
EXPECT_EQ(LengthMod::L, o.length_mod);
EXPECT_TRUE(Run("qf"));
EXPECT_EQ(LengthMod::q, o.length_mod);
EXPECT_TRUE(Run("jd"));
EXPECT_EQ(LengthMod::j, o.length_mod);
EXPECT_TRUE(Run("zd"));
EXPECT_EQ(LengthMod::z, o.length_mod);
EXPECT_TRUE(Run("td"));
EXPECT_EQ(LengthMod::t, o.length_mod);
}
struct SummarizeConsumer {
std::string* out;
explicit SummarizeConsumer(std::string* out) : out(out) {}
bool Append(string_view s) {
*out += "[" + std::string(s) + "]";
return true;
}
bool ConvertOne(const UnboundConversion& conv, string_view s) {
*out += "{";
*out += std::string(s);
*out += ":";
*out += std::to_string(conv.arg_position) + "$";
if (conv.width.is_from_arg()) {
*out += std::to_string(conv.width.get_from_arg()) + "$*";
}
if (conv.precision.is_from_arg()) {
*out += "." + std::to_string(conv.precision.get_from_arg()) + "$*";
}
*out += FormatConversionCharToChar(conv.conv);
*out += "}";
return true;
}
};
std::string SummarizeParsedFormat(const ParsedFormatBase& pc) {
std::string out;
if (!pc.ProcessFormat(SummarizeConsumer(&out))) out += "!";
return out;
}
class ParsedFormatTest : public testing::Test {};
TEST_F(ParsedFormatTest, ValueSemantics) {
ParsedFormatBase p1({}, true, {});
EXPECT_EQ("", SummarizeParsedFormat(p1));
ParsedFormatBase p2 = p1;
EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p2));
p1 = ParsedFormatBase("hello%s", true,
{FormatConversionCharSetInternal::s});
EXPECT_EQ("[hello]{s:1$s}", SummarizeParsedFormat(p1));
ParsedFormatBase p3 = p1;
EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p3));
using std::swap;
swap(p1, p2);
EXPECT_EQ("", SummarizeParsedFormat(p1));
EXPECT_EQ("[hello]{s:1$s}", SummarizeParsedFormat(p2));
swap(p1, p2);
p2 = p1;
EXPECT_EQ(SummarizeParsedFormat(p1), SummarizeParsedFormat(p2));
}
struct ExpectParse {
const char* in;
std::initializer_list<FormatConversionCharSet> conv_set;
const char* out;
};
TEST_F(ParsedFormatTest, Parsing) {
const ExpectParse kExpect[] = {
{"", {}, ""},
{"ab", {}, "[ab]"},
{"a%d", {FormatConversionCharSetInternal::d}, "[a]{d:1$d}"},
{"a%+d", {FormatConversionCharSetInternal::d}, "[a]{+d:1$d}"},
{"a% d", {FormatConversionCharSetInternal::d}, "[a]{ d:1$d}"},
{"a%b %d", {}, "[a]!"},
};
for (const auto& e : kExpect) {
SCOPED_TRACE(e.in);
EXPECT_EQ(e.out,
SummarizeParsedFormat(ParsedFormatBase(e.in, false, e.conv_set)));
}
}
TEST_F(ParsedFormatTest, ParsingFlagOrder) {
const ExpectParse kExpect[] = {
{"a%+ 0d", {FormatConversionCharSetInternal::d}, "[a]{+ 0d:1$d}"},
{"a%+0 d", {FormatConversionCharSetInternal::d}, "[a]{+0 d:1$d}"},
{"a%0+ d", {FormatConversionCharSetInternal::d}, "[a]{0+ d:1$d}"},
{"a% +0d", {FormatConversionCharSetInternal::d}, "[a]{ +0d:1$d}"},
{"a%0 +d", {FormatConversionCharSetInternal::d}, "[a]{0 +d:1$d}"},
{"a% 0+d", {FormatConversionCharSetInternal::d}, "[a]{ 0+d:1$d}"},
{"a%+ 0+d", {FormatConversionCharSetInternal::d}, "[a]{+ 0+d:1$d}"},
};
for (const auto& e : kExpect) {
SCOPED_TRACE(e.in);
EXPECT_EQ(e.out,
SummarizeParsedFormat(ParsedFormatBase(e.in, false, e.conv_set)));
}
}
}
}
ABSL_NAMESPACE_END
} |
2,573 | cpp | abseil/abseil-cpp | int128 | absl/numeric/int128.cc | absl/numeric/int128_test.cc | #ifndef ABSL_NUMERIC_INT128_H_
#define ABSL_NUMERIC_INT128_H_
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <iosfwd>
#include <limits>
#include <string>
#include <utility>
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/base/port.h"
#include "absl/types/compare.h"
#if defined(_MSC_VER)
#define ABSL_INTERNAL_WCHAR_T __wchar_t
#if defined(_M_X64) && !defined(_M_ARM64EC)
#include <intrin.h>
#pragma intrinsic(_umul128)
#endif
#else
#define ABSL_INTERNAL_WCHAR_T wchar_t
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
class int128;
class
#if defined(ABSL_HAVE_INTRINSIC_INT128)
alignas(unsigned __int128)
#endif
uint128 {
public:
uint128() = default;
constexpr uint128(int v);
constexpr uint128(unsigned int v);
constexpr uint128(long v);
constexpr uint128(unsigned long v);
constexpr uint128(long long v);
constexpr uint128(unsigned long long v);
#ifdef ABSL_HAVE_INTRINSIC_INT128
constexpr uint128(__int128 v);
constexpr uint128(unsigned __int128 v);
#endif
constexpr uint128(int128 v);
explicit uint128(float v);
explicit uint128(double v);
explicit uint128(long double v);
uint128& operator=(int v);
uint128& operator=(unsigned int v);
uint128& operator=(long v);
uint128& operator=(unsigned long v);
uint128& operator=(long long v);
uint128& operator=(unsigned long long v);
#ifdef ABSL_HAVE_INTRINSIC_INT128
uint128& operator=(__int128 v);
uint128& operator=(unsigned __int128 v);
#endif
uint128& operator=(int128 v);
constexpr explicit operator bool() const;
constexpr explicit operator char() const;
constexpr explicit operator signed char() const;
constexpr explicit operator unsigned char() const;
constexpr explicit operator char16_t() const;
constexpr explicit operator char32_t() const;
constexpr explicit operator ABSL_INTERNAL_WCHAR_T() const;
constexpr explicit operator short() const;
constexpr explicit operator unsigned short() const;
constexpr explicit operator int() const;
constexpr explicit operator unsigned int() const;
constexpr explicit operator long() const;
constexpr explicit operator unsigned long() const;
constexpr explicit operator long long() const;
constexpr explicit operator unsigned long long() const;
#ifdef ABSL_HAVE_INTRINSIC_INT128
constexpr explicit operator __int128() const;
constexpr explicit operator unsigned __int128() const;
#endif
explicit operator float() const;
explicit operator double() const;
explicit operator long double() const;
uint128& operator+=(uint128 other);
uint128& operator-=(uint128 other);
uint128& operator*=(uint128 other);
uint128& operator/=(uint128 other);
uint128& operator%=(uint128 other);
uint128 operator++(int);
uint128 operator--(int);
uint128& operator<<=(int);
uint128& operator>>=(int);
uint128& operator&=(uint128 other);
uint128& operator|=(uint128 other);
uint128& operator^=(uint128 other);
uint128& operator++();
uint128& operator--();
friend constexpr uint64_t Uint128Low64(uint128 v);
friend constexpr uint64_t Uint128High64(uint128 v);
friend constexpr uint128 MakeUint128(uint64_t high, uint64_t low);
friend constexpr uint128 Uint128Max();
template <typename H>
friend H AbslHashValue(H h, uint128 v) {
return H::combine(std::move(h), Uint128High64(v), Uint128Low64(v));
}
template <typename Sink>
friend void AbslStringify(Sink& sink, uint128 v) {
sink.Append(v.ToString());
}
private:
constexpr uint128(uint64_t high, uint64_t low);
std::string ToString() const;
#if defined(ABSL_IS_LITTLE_ENDIAN)
uint64_t lo_;
uint64_t hi_;
#elif defined(ABSL_IS_BIG_ENDIAN)
uint64_t hi_;
uint64_t lo_;
#else
#error "Unsupported byte order: must be little-endian or big-endian."
#endif
};
std::ostream& operator<<(std::ostream& os, uint128 v);
constexpr uint128 Uint128Max() {
return uint128((std::numeric_limits<uint64_t>::max)(),
(std::numeric_limits<uint64_t>::max)());
}
ABSL_NAMESPACE_END
}
namespace std {
template <>
class numeric_limits<absl::uint128> {
public:
static constexpr bool is_specialized = true;
static constexpr bool is_signed = false;
static constexpr bool is_integer = true;
static constexpr bool is_exact = true;
static constexpr bool has_infinity = false;
static constexpr bool has_quiet_NaN = false;
static constexpr bool has_signaling_NaN = false;
ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
static constexpr float_denorm_style has_denorm = denorm_absent;
ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
static constexpr bool has_denorm_loss = false;
static constexpr float_round_style round_style = round_toward_zero;
static constexpr bool is_iec559 = false;
static constexpr bool is_bounded = true;
static constexpr bool is_modulo = true;
static constexpr int digits = 128;
static constexpr int digits10 = 38;
static constexpr int max_digits10 = 0;
static constexpr int radix = 2;
static constexpr int min_exponent = 0;
static constexpr int min_exponent10 = 0;
static constexpr int max_exponent = 0;
static constexpr int max_exponent10 = 0;
#ifdef ABSL_HAVE_INTRINSIC_INT128
static constexpr bool traps = numeric_limits<unsigned __int128>::traps;
#else
static constexpr bool traps = numeric_limits<uint64_t>::traps;
#endif
static constexpr bool tinyness_before = false;
static constexpr absl::uint128(min)() { return 0; }
static constexpr absl::uint128 lowest() { return 0; }
static constexpr absl::uint128(max)() { return absl::Uint128Max(); }
static constexpr absl::uint128 epsilon() { return 0; }
static constexpr absl::uint128 round_error() { return 0; }
static constexpr absl::uint128 infinity() { return 0; }
static constexpr absl::uint128 quiet_NaN() { return 0; }
static constexpr absl::uint128 signaling_NaN() { return 0; }
static constexpr absl::uint128 denorm_min() { return 0; }
};
}
namespace absl {
ABSL_NAMESPACE_BEGIN
class int128 {
public:
int128() = default;
constexpr int128(int v);
constexpr int128(unsigned int v);
constexpr int128(long v);
constexpr int128(unsigned long v);
constexpr int128(long long v);
constexpr int128(unsigned long long v);
#ifdef ABSL_HAVE_INTRINSIC_INT128
constexpr int128(__int128 v);
constexpr explicit int128(unsigned __int128 v);
#endif
constexpr explicit int128(uint128 v);
explicit int128(float v);
explicit int128(double v);
explicit int128(long double v);
int128& operator=(int v);
int128& operator=(unsigned int v);
int128& operator=(long v);
int128& operator=(unsigned long v);
int128& operator=(long long v);
int128& operator=(unsigned long long v);
#ifdef ABSL_HAVE_INTRINSIC_INT128
int128& operator=(__int128 v);
#endif
constexpr explicit operator bool() const;
constexpr explicit operator char() const;
constexpr explicit operator signed char() const;
constexpr explicit operator unsigned char() const;
constexpr explicit operator char16_t() const;
constexpr explicit operator char32_t() const;
constexpr explicit operator ABSL_INTERNAL_WCHAR_T() const;
constexpr explicit operator short() const;
constexpr explicit operator unsigned short() const;
constexpr explicit operator int() const;
constexpr explicit operator unsigned int() const;
constexpr explicit operator long() const;
constexpr explicit operator unsigned long() const;
constexpr explicit operator long long() const;
constexpr explicit operator unsigned long long() const;
#ifdef ABSL_HAVE_INTRINSIC_INT128
constexpr explicit operator __int128() const;
constexpr explicit operator unsigned __int128() const;
#endif
explicit operator float() const;
explicit operator double() const;
explicit operator long double() const;
int128& operator+=(int128 other);
int128& operator-=(int128 other);
int128& operator*=(int128 other);
int128& operator/=(int128 other);
int128& operator%=(int128 other);
int128 operator++(int);
int128 operator--(int);
int128& operator++();
int128& operator--();
int128& operator&=(int128 other);
int128& operator|=(int128 other);
int128& operator^=(int128 other);
int128& operator<<=(int amount);
int128& operator>>=(int amount);
friend constexpr uint64_t Int128Low64(int128 v);
friend constexpr int64_t Int128High64(int128 v);
friend constexpr int128 MakeInt128(int64_t high, uint64_t low);
friend constexpr int128 Int128Max();
friend constexpr int128 Int128Min();
template <typename H>
friend H AbslHashValue(H h, int128 v) {
return H::combine(std::move(h), Int128High64(v), Int128Low64(v));
}
template <typename Sink>
friend void AbslStringify(Sink& sink, int128 v) {
sink.Append(v.ToString());
}
private:
constexpr int128(int64_t high, uint64_t low);
std::string ToString() const;
#if defined(ABSL_HAVE_INTRINSIC_INT128)
__int128 v_;
#else
#if defined(ABSL_IS_LITTLE_ENDIAN)
uint64_t lo_;
int64_t hi_;
#elif defined(ABSL_IS_BIG_ENDIAN)
int64_t hi_;
uint64_t lo_;
#else
#error "Unsupported byte order: must be little-endian or big-endian."
#endif
#endif
};
std::ostream& operator<<(std::ostream& os, int128 v);
constexpr int128 Int128Max() {
return int128((std::numeric_limits<int64_t>::max)(),
(std::numeric_limits<uint64_t>::max)());
}
constexpr int128 Int128Min() {
return int128((std::numeric_limits<int64_t>::min)(), 0);
}
ABSL_NAMESPACE_END
}
namespace std {
template <>
class numeric_limits<absl::int128> {
public:
static constexpr bool is_specialized = true;
static constexpr bool is_signed = true;
static constexpr bool is_integer = true;
static constexpr bool is_exact = true;
static constexpr bool has_infinity = false;
static constexpr bool has_quiet_NaN = false;
static constexpr bool has_signaling_NaN = false;
ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
static constexpr float_denorm_style has_denorm = denorm_absent;
ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
static constexpr bool has_denorm_loss = false;
static constexpr float_round_style round_style = round_toward_zero;
static constexpr bool is_iec559 = false;
static constexpr bool is_bounded = true;
static constexpr bool is_modulo = false;
static constexpr int digits = 127;
static constexpr int digits10 = 38;
static constexpr int max_digits10 = 0;
static constexpr int radix = 2;
static constexpr int min_exponent = 0;
static constexpr int min_exponent10 = 0;
static constexpr int max_exponent = 0;
static constexpr int max_exponent10 = 0;
#ifdef ABSL_HAVE_INTRINSIC_INT128
static constexpr bool traps = numeric_limits<__int128>::traps;
#else
static constexpr bool traps = numeric_limits<uint64_t>::traps;
#endif
static constexpr bool tinyness_before = false;
static constexpr absl::int128(min)() { return absl::Int128Min(); }
static constexpr absl::int128 lowest() { return absl::Int128Min(); }
static constexpr absl::int128(max)() { return absl::Int128Max(); }
static constexpr absl::int128 epsilon() { return 0; }
static constexpr absl::int128 round_error() { return 0; }
static constexpr absl::int128 infinity() { return 0; }
static constexpr absl::int128 quiet_NaN() { return 0; }
static constexpr absl::int128 signaling_NaN() { return 0; }
static constexpr absl::int128 denorm_min() { return 0; }
};
}
namespace absl {
ABSL_NAMESPACE_BEGIN
constexpr uint128 MakeUint128(uint64_t high, uint64_t low) {
return uint128(high, low);
}
inline uint128& uint128::operator=(int v) { return *this = uint128(v); }
inline uint128& uint128::operator=(unsigned int v) {
return *this = uint128(v);
}
inline uint128& uint128::operator=(long v) {
return *this = uint128(v);
}
inline uint128& uint128::operator=(unsigned long v) {
return *this = uint128(v);
}
inline uint128& uint128::operator=(long long v) { return *this = uint128(v); }
inline uint128& uint128::operator=(unsigned long long v) {
return *this = uint128(v);
}
#ifdef ABSL_HAVE_INTRINSIC_INT128
inline uint128& uint128::operator=(__int128 v) { return *this = uint128(v); }
inline uint128& uint128::operator=(unsigned __int128 v) {
return *this = uint128(v);
}
#endif
inline uint128& uint128::operator=(int128 v) { return *this = uint128(v); }
constexpr uint128 operator<<(uint128 lhs, int amount);
constexpr uint128 operator>>(uint128 lhs, int amount);
constexpr uint128 operator+(uint128 lhs, uint128 rhs);
constexpr uint128 operator-(uint128 lhs, uint128 rhs);
uint128 operator*(uint128 lhs, uint128 rhs);
uint128 operator/(uint128 lhs, uint128 rhs);
uint128 operator%(uint128 lhs, uint128 rhs);
inline uint128& uint128::operator<<=(int amount) {
*this = *this << amount;
return *this;
}
inline uint128& uint128::operator>>=(int amount) {
*this = *this >> amount;
return *this;
}
inline uint128& uint128::operator+=(uint128 other) {
*this = *this + other;
return *this;
}
inline uint128& uint128::operator-=(uint128 other) {
*this = *this - other;
return *this;
}
inline uint128& uint128::operator*=(uint128 other) {
*this = *this * other;
return *this;
}
inline uint128& uint128::operator/=(uint128 other) {
*this = *this / other;
return *this;
}
inline uint128& uint128::operator%=(uint128 other) {
*this = *this % other;
return *this;
}
constexpr uint64_t Uint128Low64(uint128 v) { return v.lo_; }
constexpr uint64_t Uint128High64(uint128 v) { return v.hi_; }
#if defined(ABSL_IS_LITTLE_ENDIAN)
constexpr uint128::uint128(uint64_t high, uint64_t low) : lo_{low}, hi_{high} {}
constexpr uint128::uint128(int v)
: lo_{static_cast<uint64_t>(v)},
hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0} {}
constexpr uint128::uint128(long v)
: lo_{static_cast<uint64_t>(v)},
hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0} {}
constexpr uint128::uint128(long long v)
: lo_{static_cast<uint64_t>(v)},
hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0} {}
constexpr uint128::uint128(unsigned int v) : lo_{v}, hi_{0} {}
constexpr uint128::uint128(unsigned long v) : lo_{v}, hi_{0} {}
constexpr uint128::uint128(unsigned long long v) : lo_{v}, hi_{0} {}
#ifdef ABSL_HAVE_INTRINSIC_INT128
constexpr uint128::uint128(__int128 v)
: lo_{static_cast<uint64_t>(v & ~uint64_t{0})},
hi_{static_cast<uint64_t>(static_cast<unsigned __int128>(v) >> 64)} {}
constexpr uint128::uint128(unsigned __int128 v)
: lo_{static_cast<uint64_t>(v & ~uint64_t{0})},
hi_{static_cast<uint64_t>(v >> 64)} {}
#endif
constexpr uint128::uint128(int128 v)
: lo_{Int128Low64(v)}, hi_{static_cast<uint64_t>(Int128High64(v))} {}
#elif defined(ABSL_IS_BIG_ENDIAN)
constexpr uint128::uint128(uint64_t high, uint64_t low) : hi_{high}, lo_{low} {}
constexpr uint128::uint128(int v)
: hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0},
lo_{static_cast<uint64_t>(v)} {}
constexpr uint128::uint128(long v)
: hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0},
lo_{static_cast<uint64_t>(v)} {}
constexpr uint128::uint128(long long v)
: hi_{v < 0 ? (std::numeric_limits<uint64_t>::max)() : 0},
lo_{static_cast<uint64_t>(v)} {}
constexpr uint128::uint128(unsigned int v) : hi_{0}, lo_{v} {}
constexpr uint128::uint128(unsigned long v) : hi_{0}, lo_{v} {}
constexpr uint128::uint128(unsigned long long v) : hi_{0}, lo_{v} {}
#ifdef ABSL_HAVE_INTRINSIC_INT128
constexpr uint128::uint128(__int128 v)
: hi_{static_cast<uint64_t>(static_cast<unsigned __int128>(v) >> 64)},
lo_{static_cast<uint64_t>(v & ~uint64_t{0})} {}
constexpr uint128::uint128(unsigned __int128 v)
: hi_{static_cast<uint64_t>(v >> 64)},
lo_{static_cast<uint64_t>(v & ~uint64_t{0})} {}
#endif
constexpr uint128::uint128(int128 v)
: hi_{static_cast<uint64_t>(Int128High64(v))}, lo_{Int128Low64(v)} {}
#else
#error "Unsupported byte order: must be little-endian or big-endian."
#endif
constexpr uint128::operator bool() const { return lo_ || hi_; }
constexpr uint128::operator char() const { return static_cast<char>(lo_); }
constexpr uint128::operator signed char() const {
return static_cast<signed char>(lo_);
}
constexpr uint128::operator unsigned char() const {
return static_cast<unsigned char>(lo_);
}
constexpr uint128::operator char16_t() const {
return static_cast<char16_t>(lo_);
}
constexpr uint128::operator char32_t() const {
return static_cast<char32_t>(lo_);
}
constexpr uint128::operator ABSL_INTERNAL_WCHAR_T() const {
return static_cast<ABSL_INTERNAL_WCHAR_T>(lo_);
}
constexpr uint128::operator short() const { return static_cast<short>(lo_); }
constexpr uint128::operator unsigned short() const {
return static_cast<unsigned short>(lo_);
}
constexpr uint128::operator int() const { return static_cast<int>(lo_); }
constexpr uint128::operator unsigned int() const {
return static_cast<unsigned int>(lo_);
}
constexpr uint128::operator long() const { return static_cast<long>(lo_); }
constexpr uint128::operator unsigned long() const {
return static_cast<unsigned long>(lo_);
}
constexpr uint128::operator long long() const {
return static_cast<long long>(lo_);
}
constexpr uint128::operator unsigned long long() const {
return static_cast<unsigned long long>(lo_);
}
#ifdef ABSL_HAVE_INTRINSIC_INT128
constexpr uint128::operator __int128() const {
return (static_cast<__int128>(hi_) << 64) + lo_;
}
constexpr uint128::operator unsigned __int128() const {
return (static_cast<unsigned __int128>(hi_) << 64) + lo_;
}
#endif
inline uint128::operator float() const {
return static_cast<float>(lo_) + std::ldexp(static_cast<float>(hi_), 64);
}
inline uint128::operator double() const {
return static_cast<double>(lo_) + std::ldexp(static_cast<double>(hi_), 64);
}
inline uint128::operator long double() const {
return static_cast<long double>(lo_) +
std::ldexp(static_cast<long double>(hi_), 64);
}
constexpr bool operator==(uint128 lhs, uint128 rhs) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
return static_cast<unsigned __int128>(lhs) ==
static_cast<unsigned __int128>(rhs);
#else
return (Uint128Low64(lhs) == Uint128Low64(rhs) &&
Uint128High64(lhs) == Uint128High64(rhs));
#endif
}
constexpr bool operator!=(uint128 lhs, uint128 rhs) { return !(lhs == rhs); }
constexpr bool operator<(uint128 lhs, uint128 rhs) {
#ifdef ABSL_HAVE_INTRINSIC_INT128
return static_cast<unsigned __int128>(lhs) <
static_cast<unsigned __int128>(rhs);
#else
return (Uint128High64(lhs) == Uint128High64(rhs))
? (Uint128Low64(lhs) < Uint128Low64(rhs))
: (Uint128High64(lhs) < Uint128High64(rhs));
#endif
}
constexpr bool operator>(uint128 lhs, uint128 rhs) { return rhs < lhs; }
constexpr bool operator<=(uint128 lhs, uint128 rhs) { return !(rhs < lhs); }
constexpr bool operator>=(uint128 lhs, uint128 rhs) { return !(lhs < rhs); }
#ifdef __cpp_impl_three_way_comparison
constexpr absl::strong_ordering operator<=>(uint128 lhs, uint128 rhs) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
if (auto lhs_128 = static_cast<unsigned __int128>(lhs),
rhs_128 = static_cast<unsigned __int128>(rhs);
lhs_128 < rhs_128) {
return absl::strong_ordering::less;
} else if (lhs_128 > rhs_128) {
return absl::strong_ordering::greater;
} else {
return absl::strong_ordering::equal;
}
#else
if (uint64_t lhs_high = Uint128High64(lhs), rhs_high = Uint128High64(rhs);
lhs_high < rhs_high) {
return absl::strong_ordering::less;
} else if (lhs_high > rhs_high) {
return absl::strong_ordering::greater;
} else if (uint64_t lhs_low = Uint128Low64(lhs), rhs_low = Uint128Low64(rhs);
lhs_low < rhs_low) {
return absl::strong_ordering::less;
} else if (lhs_low > rhs_low) {
return absl::strong_ordering::greater;
} else {
return absl::strong_ordering::equal;
}
#endif
}
#endif
constexpr inline uint128 operator+(uint128 val) { return val; }
constexpr inline int128 operator+(int128 val) { return val; }
constexpr uint128 operator-(uint128 val) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
return -static_cast<unsigned __int128>(val);
#else
return MakeUint128(
~Uint128High64(val) + static_cast<unsigned long>(Uint128Low64(val) == 0),
~Uint128Low64(val) + 1);
#endif
}
constexpr inline bool operator!(uint128 val) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
return !static_cast<unsigned __int128>(val);
#else
return !Uint128High64(val) && !Uint128Low64(val);
#endif
}
constexpr inline uint128 operator~(uint128 val) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
return ~static_cast<unsigned __int128>(val);
#else
return MakeUint128(~Uint128High64(val), ~Uint128Low64(val));
#endif
}
constexpr inline uint128 operator|(uint128 lhs, uint128 rhs) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
return static_cast<unsigned __int128>(lhs) |
static_cast<unsigned __int128>(rhs);
#else
return MakeUint128(Uint128High64(lhs) | Uint128High64(rhs),
Uint128Low64(lhs) | Uint128Low64(rhs));
#endif
}
constexpr inline uint128 operator&(uint128 lhs, uint128 rhs) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
return static_cast<unsigned __int128>(lhs) &
static_cast<unsigned __int128>(rhs);
#else
return MakeUint128(Uint128High64(lhs) & Uint128High64(rhs),
Uint128Low64(lhs) & Uint128Low64(rhs));
#endif
}
constexpr inline uint128 operator^(uint128 lhs, uint128 rhs) {
#if defined(ABSL_HAVE_INTRINSIC_INT128)
return static_cast<unsigned __int128>(lhs) ^
static_cast<unsigned __int128>(rhs);
#else
return MakeUint128(Uint128High64(lhs) ^ Uint128High64(rhs),
Uint128Low64(lhs) ^ Uint128Low64(rhs));
#endif
}
inline uint128& uint128::operator|=(uint128 other) {
*this = *this | other;
return *this;
}
inline uint128& uint128::operator&=(uint128 other) {
*this = *this & other;
return *this;
}
inline uint128& uint128::operator^=(uint128 other) {
*this = *this ^ other;
return *this;
}
constexpr uint128 operator<<(uint128 lhs, int amount) {
#ifdef ABSL_HAVE_INTRINSIC_INT128
return static_cast<unsigned __int128>(lhs) << amount;
#else
return amount >= 64 ? MakeUint128(Uint128Low64(lhs) << (amount - 64), 0)
: amount == 0 ? lhs
: MakeUint128((Uint128High64(lhs) << amount) |
(Uint128Low64(lhs) >> (64 - amount)),
Uint128Low64(lhs) << amount);
#endif
}
constexpr uint128 operator>>(uint128 lhs, int amount) {
#ifdef ABSL_HAVE_INTRINSIC_INT128
return | #include "absl/numeric/int128.h"
#include <algorithm>
#include <limits>
#include <random>
#include <type_traits>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
#include "absl/base/internal/cycleclock.h"
#include "absl/hash/hash_testing.h"
#include "absl/meta/type_traits.h"
#include "absl/types/compare.h"
#define MAKE_INT128(HI, LO) absl::MakeInt128(static_cast<int64_t>(HI), LO)
namespace {
template <typename T>
class Uint128IntegerTraitsTest : public ::testing::Test {};
typedef ::testing::Types<bool, char, signed char, unsigned char, char16_t,
char32_t, wchar_t,
short,
unsigned short,
int, unsigned int,
long,
unsigned long,
long long,
unsigned long long>
IntegerTypes;
template <typename T>
class Uint128FloatTraitsTest : public ::testing::Test {};
typedef ::testing::Types<float, double, long double> FloatingPointTypes;
TYPED_TEST_SUITE(Uint128IntegerTraitsTest, IntegerTypes);
TYPED_TEST(Uint128IntegerTraitsTest, ConstructAssignTest) {
static_assert(std::is_constructible<absl::uint128, TypeParam>::value,
"absl::uint128 must be constructible from TypeParam");
static_assert(std::is_assignable<absl::uint128&, TypeParam>::value,
"absl::uint128 must be assignable from TypeParam");
static_assert(!std::is_assignable<TypeParam&, absl::uint128>::value,
"TypeParam must not be assignable from absl::uint128");
}
TYPED_TEST_SUITE(Uint128FloatTraitsTest, FloatingPointTypes);
TYPED_TEST(Uint128FloatTraitsTest, ConstructAssignTest) {
static_assert(std::is_constructible<absl::uint128, TypeParam>::value,
"absl::uint128 must be constructible from TypeParam");
static_assert(!std::is_assignable<absl::uint128&, TypeParam>::value,
"absl::uint128 must not be assignable from TypeParam");
static_assert(!std::is_assignable<TypeParam&, absl::uint128>::value,
"TypeParam must not be assignable from absl::uint128");
}
#ifdef ABSL_HAVE_INTRINSIC_INT128
TEST(Uint128, IntrinsicTypeTraitsTest) {
static_assert(std::is_constructible<absl::uint128, __int128>::value,
"absl::uint128 must be constructible from __int128");
static_assert(std::is_assignable<absl::uint128&, __int128>::value,
"absl::uint128 must be assignable from __int128");
static_assert(!std::is_assignable<__int128&, absl::uint128>::value,
"__int128 must not be assignable from absl::uint128");
static_assert(std::is_constructible<absl::uint128, unsigned __int128>::value,
"absl::uint128 must be constructible from unsigned __int128");
static_assert(std::is_assignable<absl::uint128&, unsigned __int128>::value,
"absl::uint128 must be assignable from unsigned __int128");
static_assert(!std::is_assignable<unsigned __int128&, absl::uint128>::value,
"unsigned __int128 must not be assignable from absl::uint128");
}
#endif
TEST(Uint128, TrivialTraitsTest) {
static_assert(absl::is_trivially_default_constructible<absl::uint128>::value,
"");
static_assert(absl::is_trivially_copy_constructible<absl::uint128>::value,
"");
static_assert(absl::is_trivially_copy_assignable<absl::uint128>::value, "");
static_assert(std::is_trivially_destructible<absl::uint128>::value, "");
}
TEST(Uint128, AllTests) {
absl::uint128 zero = 0;
absl::uint128 one = 1;
absl::uint128 one_2arg = absl::MakeUint128(0, 1);
absl::uint128 two = 2;
absl::uint128 three = 3;
absl::uint128 big = absl::MakeUint128(2000, 2);
absl::uint128 big_minus_one = absl::MakeUint128(2000, 1);
absl::uint128 bigger = absl::MakeUint128(2001, 1);
absl::uint128 biggest = absl::Uint128Max();
absl::uint128 high_low = absl::MakeUint128(1, 0);
absl::uint128 low_high =
absl::MakeUint128(0, std::numeric_limits<uint64_t>::max());
EXPECT_LT(one, two);
EXPECT_GT(two, one);
EXPECT_LT(one, big);
EXPECT_LT(one, big);
EXPECT_EQ(one, one_2arg);
EXPECT_NE(one, two);
EXPECT_GT(big, one);
EXPECT_GE(big, two);
EXPECT_GE(big, big_minus_one);
EXPECT_GT(big, big_minus_one);
EXPECT_LT(big_minus_one, big);
EXPECT_LE(big_minus_one, big);
EXPECT_NE(big_minus_one, big);
EXPECT_LT(big, biggest);
EXPECT_LE(big, biggest);
EXPECT_GT(biggest, big);
EXPECT_GE(biggest, big);
EXPECT_EQ(big, ~~big);
EXPECT_EQ(one, one | one);
EXPECT_EQ(big, big | big);
EXPECT_EQ(one, one | zero);
EXPECT_EQ(one, one & one);
EXPECT_EQ(big, big & big);
EXPECT_EQ(zero, one & zero);
EXPECT_EQ(zero, big & ~big);
EXPECT_EQ(zero, one ^ one);
EXPECT_EQ(zero, big ^ big);
EXPECT_EQ(one, one ^ zero);
EXPECT_EQ(big, big << 0);
EXPECT_EQ(big, big >> 0);
EXPECT_GT(big << 1, big);
EXPECT_LT(big >> 1, big);
EXPECT_EQ(big, (big << 10) >> 10);
EXPECT_EQ(big, (big >> 1) << 1);
EXPECT_EQ(one, (one << 80) >> 80);
EXPECT_EQ(zero, (one >> 80) << 80);
absl::uint128 big_copy = big;
EXPECT_EQ(big << 0, big_copy <<= 0);
big_copy = big;
EXPECT_EQ(big >> 0, big_copy >>= 0);
big_copy = big;
EXPECT_EQ(big << 1, big_copy <<= 1);
big_copy = big;
EXPECT_EQ(big >> 1, big_copy >>= 1);
big_copy = big;
EXPECT_EQ(big << 10, big_copy <<= 10);
big_copy = big;
EXPECT_EQ(big >> 10, big_copy >>= 10);
big_copy = big;
EXPECT_EQ(big << 64, big_copy <<= 64);
big_copy = big;
EXPECT_EQ(big >> 64, big_copy >>= 64);
big_copy = big;
EXPECT_EQ(big << 73, big_copy <<= 73);
big_copy = big;
EXPECT_EQ(big >> 73, big_copy >>= 73);
EXPECT_EQ(absl::Uint128High64(biggest), std::numeric_limits<uint64_t>::max());
EXPECT_EQ(absl::Uint128Low64(biggest), std::numeric_limits<uint64_t>::max());
EXPECT_EQ(zero + one, one);
EXPECT_EQ(one + one, two);
EXPECT_EQ(big_minus_one + one, big);
EXPECT_EQ(one - one, zero);
EXPECT_EQ(one - zero, one);
EXPECT_EQ(zero - one, biggest);
EXPECT_EQ(big - big, zero);
EXPECT_EQ(big - one, big_minus_one);
EXPECT_EQ(big + std::numeric_limits<uint64_t>::max(), bigger);
EXPECT_EQ(biggest + 1, zero);
EXPECT_EQ(zero - 1, biggest);
EXPECT_EQ(high_low - one, low_high);
EXPECT_EQ(low_high + one, high_low);
EXPECT_EQ(absl::Uint128High64((absl::uint128(1) << 64) - 1), 0);
EXPECT_EQ(absl::Uint128Low64((absl::uint128(1) << 64) - 1),
std::numeric_limits<uint64_t>::max());
EXPECT_TRUE(!!one);
EXPECT_TRUE(!!high_low);
EXPECT_FALSE(!!zero);
EXPECT_FALSE(!one);
EXPECT_FALSE(!high_low);
EXPECT_TRUE(!zero);
EXPECT_TRUE(zero == 0);
EXPECT_FALSE(zero != 0);
EXPECT_FALSE(one == 0);
EXPECT_TRUE(one != 0);
EXPECT_FALSE(high_low == 0);
EXPECT_TRUE(high_low != 0);
absl::uint128 test = zero;
EXPECT_EQ(++test, one);
EXPECT_EQ(test, one);
EXPECT_EQ(test++, one);
EXPECT_EQ(test, two);
EXPECT_EQ(test -= 2, zero);
EXPECT_EQ(test, zero);
EXPECT_EQ(test += 2, two);
EXPECT_EQ(test, two);
EXPECT_EQ(--test, one);
EXPECT_EQ(test, one);
EXPECT_EQ(test--, one);
EXPECT_EQ(test, zero);
EXPECT_EQ(test |= three, three);
EXPECT_EQ(test &= one, one);
EXPECT_EQ(test ^= three, two);
EXPECT_EQ(test >>= 1, one);
EXPECT_EQ(test <<= 1, two);
EXPECT_EQ(big, +big);
EXPECT_EQ(two, +two);
EXPECT_EQ(absl::Uint128Max(), +absl::Uint128Max());
EXPECT_EQ(zero, +zero);
EXPECT_EQ(big, -(-big));
EXPECT_EQ(two, -((-one) - 1));
EXPECT_EQ(absl::Uint128Max(), -one);
EXPECT_EQ(zero, -zero);
}
TEST(Int128, RightShiftOfNegativeNumbers) {
absl::int128 minus_six = -6;
absl::int128 minus_three = -3;
absl::int128 minus_two = -2;
absl::int128 minus_one = -1;
if ((-6 >> 1) == -3) {
EXPECT_EQ(minus_six >> 1, minus_three);
EXPECT_EQ(minus_six >> 2, minus_two);
EXPECT_EQ(minus_six >> 65, minus_one);
} else {
EXPECT_EQ(minus_six >> 1, absl::int128(absl::uint128(minus_six) >> 1));
EXPECT_EQ(minus_six >> 2, absl::int128(absl::uint128(minus_six) >> 2));
EXPECT_EQ(minus_six >> 65, absl::int128(absl::uint128(minus_six) >> 65));
}
}
TEST(Uint128, ConversionTests) {
EXPECT_TRUE(absl::MakeUint128(1, 0));
#ifdef ABSL_HAVE_INTRINSIC_INT128
unsigned __int128 intrinsic =
(static_cast<unsigned __int128>(0x3a5b76c209de76f6) << 64) +
0x1f25e1d63a2b46c5;
absl::uint128 custom =
absl::MakeUint128(0x3a5b76c209de76f6, 0x1f25e1d63a2b46c5);
EXPECT_EQ(custom, absl::uint128(intrinsic));
EXPECT_EQ(custom, absl::uint128(static_cast<__int128>(intrinsic)));
EXPECT_EQ(intrinsic, static_cast<unsigned __int128>(custom));
EXPECT_EQ(intrinsic, static_cast<__int128>(custom));
#endif
double precise_double = 0x530e * std::pow(2.0, 64.0) + 0xda74000000000000;
absl::uint128 from_precise_double(precise_double);
absl::uint128 from_precise_ints =
absl::MakeUint128(0x530e, 0xda74000000000000);
EXPECT_EQ(from_precise_double, from_precise_ints);
EXPECT_DOUBLE_EQ(static_cast<double>(from_precise_ints), precise_double);
double approx_double =
static_cast<double>(0xffffeeeeddddcccc) * std::pow(2.0, 64.0) +
static_cast<double>(0xbbbbaaaa99998888);
absl::uint128 from_approx_double(approx_double);
EXPECT_DOUBLE_EQ(static_cast<double>(from_approx_double), approx_double);
double round_to_zero = 0.7;
double round_to_five = 5.8;
double round_to_nine = 9.3;
EXPECT_EQ(static_cast<absl::uint128>(round_to_zero), 0);
EXPECT_EQ(static_cast<absl::uint128>(round_to_five), 5);
EXPECT_EQ(static_cast<absl::uint128>(round_to_nine), 9);
absl::uint128 highest_precision_in_long_double =
~absl::uint128{} >> (128 - std::numeric_limits<long double>::digits);
EXPECT_EQ(highest_precision_in_long_double,
static_cast<absl::uint128>(
static_cast<long double>(highest_precision_in_long_double)));
const absl::uint128 arbitrary_mask =
absl::MakeUint128(0xa29f622677ded751, 0xf8ca66add076f468);
EXPECT_EQ(highest_precision_in_long_double & arbitrary_mask,
static_cast<absl::uint128>(static_cast<long double>(
highest_precision_in_long_double & arbitrary_mask)));
EXPECT_EQ(static_cast<absl::uint128>(-0.1L), 0);
}
TEST(Uint128, OperatorAssignReturnRef) {
absl::uint128 v(1);
(v += 4) -= 3;
EXPECT_EQ(2, v);
}
TEST(Uint128, Multiply) {
absl::uint128 a, b, c;
a = 0;
b = 0;
c = a * b;
EXPECT_EQ(0, c);
a = absl::uint128(0) - 1;
b = absl::uint128(0) - 1;
c = a * b;
EXPECT_EQ(1, c);
c = absl::uint128(0) - 1;
c *= c;
EXPECT_EQ(1, c);
for (int i = 0; i < 64; ++i) {
for (int j = 0; j < 64; ++j) {
a = absl::uint128(1) << i;
b = absl::uint128(1) << j;
c = a * b;
EXPECT_EQ(absl::uint128(1) << (i + j), c);
}
}
a = absl::MakeUint128(0xffffeeeeddddcccc, 0xbbbbaaaa99998888);
b = absl::MakeUint128(0x7777666655554444, 0x3333222211110000);
c = a * b;
EXPECT_EQ(absl::MakeUint128(0x530EDA741C71D4C3, 0xBF25975319080000), c);
EXPECT_EQ(0, c - b * a);
EXPECT_EQ(a*a - b*b, (a+b) * (a-b));
a = absl::MakeUint128(0x0123456789abcdef, 0xfedcba9876543210);
b = absl::MakeUint128(0x02468ace13579bdf, 0xfdb97531eca86420);
c = a * b;
EXPECT_EQ(absl::MakeUint128(0x97a87f4f261ba3f2, 0x342d0bbf48948200), c);
EXPECT_EQ(0, c - b * a);
EXPECT_EQ(a*a - b*b, (a+b) * (a-b));
}
TEST(Uint128, AliasTests) {
absl::uint128 x1 = absl::MakeUint128(1, 2);
absl::uint128 x2 = absl::MakeUint128(2, 4);
x1 += x1;
EXPECT_EQ(x2, x1);
absl::uint128 x3 = absl::MakeUint128(1, static_cast<uint64_t>(1) << 63);
absl::uint128 x4 = absl::MakeUint128(3, 0);
x3 += x3;
EXPECT_EQ(x4, x3);
}
TEST(Uint128, DivideAndMod) {
using std::swap;
absl::uint128 a, b, q, r;
a = 0;
b = 123;
q = a / b;
r = a % b;
EXPECT_EQ(0, q);
EXPECT_EQ(0, r);
a = absl::MakeUint128(0x530eda741c71d4c3, 0xbf25975319080000);
q = absl::MakeUint128(0x4de2cab081, 0x14c34ab4676e4bab);
b = absl::uint128(0x1110001);
r = absl::uint128(0x3eb455);
ASSERT_EQ(a, q * b + r);
absl::uint128 result_q, result_r;
result_q = a / b;
result_r = a % b;
EXPECT_EQ(q, result_q);
EXPECT_EQ(r, result_r);
swap(q, b);
result_q = a / b;
result_r = a % b;
EXPECT_EQ(q, result_q);
EXPECT_EQ(r, result_r);
swap(b, q);
swap(a, b);
result_q = a / b;
result_r = a % b;
EXPECT_EQ(0, result_q);
EXPECT_EQ(a, result_r);
swap(a, q);
result_q = a / b;
result_r = a % b;
EXPECT_EQ(0, result_q);
EXPECT_EQ(a, result_r);
swap(q, a);
swap(b, a);
b = a / 2 + 1;
absl::uint128 expected_r =
absl::MakeUint128(0x29876d3a0e38ea61, 0xdf92cba98c83ffff);
ASSERT_EQ(a / 2 - 1, expected_r);
ASSERT_EQ(a, b + expected_r);
result_q = a / b;
result_r = a % b;
EXPECT_EQ(1, result_q);
EXPECT_EQ(expected_r, result_r);
}
TEST(Uint128, DivideAndModRandomInputs) {
const int kNumIters = 1 << 18;
std::minstd_rand random(testing::UnitTest::GetInstance()->random_seed());
std::uniform_int_distribution<uint64_t> uniform_uint64;
for (int i = 0; i < kNumIters; ++i) {
const absl::uint128 a =
absl::MakeUint128(uniform_uint64(random), uniform_uint64(random));
const absl::uint128 b =
absl::MakeUint128(uniform_uint64(random), uniform_uint64(random));
if (b == 0) {
continue;
}
const absl::uint128 q = a / b;
const absl::uint128 r = a % b;
ASSERT_EQ(a, b * q + r);
}
}
TEST(Uint128, ConstexprTest) {
constexpr absl::uint128 zero = absl::uint128();
constexpr absl::uint128 one = 1;
constexpr absl::uint128 minus_two = -2;
EXPECT_EQ(zero, absl::uint128(0));
EXPECT_EQ(one, absl::uint128(1));
EXPECT_EQ(minus_two, absl::MakeUint128(-1, -2));
}
TEST(Uint128, NumericLimitsTest) {
static_assert(std::numeric_limits<absl::uint128>::is_specialized, "");
static_assert(!std::numeric_limits<absl::uint128>::is_signed, "");
static_assert(std::numeric_limits<absl::uint128>::is_integer, "");
EXPECT_EQ(static_cast<int>(128 * std::log10(2)),
std::numeric_limits<absl::uint128>::digits10);
EXPECT_EQ(0, std::numeric_limits<absl::uint128>::min());
EXPECT_EQ(0, std::numeric_limits<absl::uint128>::lowest());
EXPECT_EQ(absl::Uint128Max(), std::numeric_limits<absl::uint128>::max());
}
TEST(Uint128, Hash) {
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({
absl::uint128{0},
absl::uint128{1},
~absl::uint128{},
absl::uint128{std::numeric_limits<int64_t>::max()},
absl::uint128{std::numeric_limits<uint64_t>::max()} + 0,
absl::uint128{std::numeric_limits<uint64_t>::max()} + 1,
absl::uint128{std::numeric_limits<uint64_t>::max()} + 2,
absl::uint128{1} << 62,
absl::uint128{1} << 63,
absl::uint128{1} << 64,
absl::uint128{1} << 65,
std::numeric_limits<absl::uint128>::max(),
std::numeric_limits<absl::uint128>::max() - 1,
std::numeric_limits<absl::uint128>::min() + 1,
std::numeric_limits<absl::uint128>::min(),
}));
}
TEST(Int128Uint128, ConversionTest) {
absl::int128 nonnegative_signed_values[] = {
0,
1,
0xffeeddccbbaa9988,
absl::MakeInt128(0x7766554433221100, 0),
absl::MakeInt128(0x1234567890abcdef, 0xfedcba0987654321),
absl::Int128Max()};
for (absl::int128 value : nonnegative_signed_values) {
EXPECT_EQ(value, absl::int128(absl::uint128(value)));
absl::uint128 assigned_value;
assigned_value = value;
EXPECT_EQ(value, absl::int128(assigned_value));
}
absl::int128 negative_values[] = {
-1, -0x1234567890abcdef,
absl::MakeInt128(-0x5544332211ffeedd, 0),
-absl::MakeInt128(0x76543210fedcba98, 0xabcdef0123456789)};
for (absl::int128 value : negative_values) {
EXPECT_EQ(absl::uint128(-value), -absl::uint128(value));
absl::uint128 assigned_value;
assigned_value = value;
EXPECT_EQ(absl::uint128(-value), -assigned_value);
}
}
template <typename T>
class Int128IntegerTraitsTest : public ::testing::Test {};
TYPED_TEST_SUITE(Int128IntegerTraitsTest, IntegerTypes);
TYPED_TEST(Int128IntegerTraitsTest, ConstructAssignTest) {
static_assert(std::is_constructible<absl::int128, TypeParam>::value,
"absl::int128 must be constructible from TypeParam");
static_assert(std::is_assignable<absl::int128&, TypeParam>::value,
"absl::int128 must be assignable from TypeParam");
static_assert(!std::is_assignable<TypeParam&, absl::int128>::value,
"TypeParam must not be assignable from absl::int128");
}
template <typename T>
class Int128FloatTraitsTest : public ::testing::Test {};
TYPED_TEST_SUITE(Int128FloatTraitsTest, FloatingPointTypes);
TYPED_TEST(Int128FloatTraitsTest, ConstructAssignTest) {
static_assert(std::is_constructible<absl::int128, TypeParam>::value,
"absl::int128 must be constructible from TypeParam");
static_assert(!std::is_assignable<absl::int128&, TypeParam>::value,
"absl::int128 must not be assignable from TypeParam");
static_assert(!std::is_assignable<TypeParam&, absl::int128>::value,
"TypeParam must not be assignable from absl::int128");
}
#ifdef ABSL_HAVE_INTRINSIC_INT128
TEST(Int128, IntrinsicTypeTraitsTest) {
static_assert(std::is_constructible<absl::int128, __int128>::value,
"absl::int128 must be constructible from __int128");
static_assert(std::is_assignable<absl::int128&, __int128>::value,
"absl::int128 must be assignable from __int128");
static_assert(!std::is_assignable<__int128&, absl::int128>::value,
"__int128 must not be assignable from absl::int128");
static_assert(std::is_constructible<absl::int128, unsigned __int128>::value,
"absl::int128 must be constructible from unsigned __int128");
static_assert(!std::is_assignable<absl::int128&, unsigned __int128>::value,
"absl::int128 must be assignable from unsigned __int128");
static_assert(!std::is_assignable<unsigned __int128&, absl::int128>::value,
"unsigned __int128 must not be assignable from absl::int128");
}
#endif
TEST(Int128, TrivialTraitsTest) {
static_assert(absl::is_trivially_default_constructible<absl::int128>::value,
"");
static_assert(absl::is_trivially_copy_constructible<absl::int128>::value, "");
static_assert(absl::is_trivially_copy_assignable<absl::int128>::value, "");
static_assert(std::is_trivially_destructible<absl::int128>::value, "");
}
TEST(Int128, BoolConversionTest) {
EXPECT_FALSE(absl::int128(0));
for (int i = 0; i < 64; ++i) {
EXPECT_TRUE(absl::MakeInt128(0, uint64_t{1} << i));
}
for (int i = 0; i < 63; ++i) {
EXPECT_TRUE(absl::MakeInt128(int64_t{1} << i, 0));
}
EXPECT_TRUE(absl::Int128Min());
EXPECT_EQ(absl::int128(1), absl::int128(true));
EXPECT_EQ(absl::int128(0), absl::int128(false));
}
template <typename T>
class Int128IntegerConversionTest : public ::testing::Test {};
TYPED_TEST_SUITE(Int128IntegerConversionTest, IntegerTypes);
TYPED_TEST(Int128IntegerConversionTest, RoundTripTest) {
EXPECT_EQ(TypeParam{0}, static_cast<TypeParam>(absl::int128(0)));
EXPECT_EQ(std::numeric_limits<TypeParam>::min(),
static_cast<TypeParam>(
absl::int128(std::numeric_limits<TypeParam>::min())));
EXPECT_EQ(std::numeric_limits<TypeParam>::max(),
static_cast<TypeParam>(
absl::int128(std::numeric_limits<TypeParam>::max())));
}
template <typename T>
class Int128FloatConversionTest : public ::testing::Test {};
TYPED_TEST_SUITE(Int128FloatConversionTest, FloatingPointTypes);
TYPED_TEST(Int128FloatConversionTest, ConstructAndCastTest) {
for (int i = 0; i < 110; ++i) {
SCOPED_TRACE(::testing::Message() << "i = " << i);
TypeParam float_value = std::ldexp(static_cast<TypeParam>(0x9f5b), i);
absl::int128 int_value = absl::int128(0x9f5b) << i;
EXPECT_EQ(float_value, static_cast<TypeParam>(int_value));
EXPECT_EQ(-float_value, static_cast<TypeParam>(-int_value));
EXPECT_EQ(int_value, absl::int128(float_value));
EXPECT_EQ(-int_value, absl::int128(-float_value));
}
uint64_t values[] = {0x6d4492c24fb86199, 0x26ead65e4cb359b5,
0x2c43407433ba3fd1, 0x3b574ec668df6b55,
0x1c750e55a29f4f0f};
for (uint64_t value : values) {
for (int i = 0; i <= 64; ++i) {
SCOPED_TRACE(::testing::Message()
<< "value = " << value << "; i = " << i);
TypeParam fvalue = std::ldexp(static_cast<TypeParam>(value), i);
EXPECT_DOUBLE_EQ(fvalue, static_cast<TypeParam>(absl::int128(fvalue)));
EXPECT_DOUBLE_EQ(-fvalue, static_cast<TypeParam>(-absl::int128(fvalue)));
EXPECT_DOUBLE_EQ(-fvalue, static_cast<TypeParam>(absl::int128(-fvalue)));
EXPECT_DOUBLE_EQ(fvalue, static_cast<TypeParam>(-absl::int128(-fvalue)));
}
}
absl::int128 large_values[] = {
absl::MakeInt128(0x5b0640d96c7b3d9f, 0xb7a7189e51d18622),
absl::MakeInt128(0x34bed042c6f65270, 0x73b236570669a089),
absl::MakeInt128(0x43deba9e6da12724, 0xf7f0f83da686797d),
absl::MakeInt128(0x71e8d383be4e5589, 0x75c3f96fb00752b6)};
for (absl::int128 value : large_values) {
value >>= (127 - std::numeric_limits<TypeParam>::digits);
value |= absl::int128(1) << (std::numeric_limits<TypeParam>::digits - 1);
value |= 1;
for (int i = 0; i < 127 - std::numeric_limits<TypeParam>::digits; ++i) {
absl::int128 int_value = value << i;
EXPECT_EQ(int_value,
static_cast<absl::int128>(static_cast<TypeParam>(int_value)));
EXPECT_EQ(-int_value,
static_cast<absl::int128>(static_cast<TypeParam>(-int_value)));
}
}
EXPECT_EQ(0, absl::int128(TypeParam(0.1)));
EXPECT_EQ(17, absl::int128(TypeParam(17.8)));
EXPECT_EQ(0, absl::int128(TypeParam(-0.8)));
EXPECT_EQ(-53, absl::int128(TypeParam(-53.1)));
EXPECT_EQ(0, absl::int128(TypeParam(0.5)));
EXPECT_EQ(0, absl::int128(TypeParam(-0.5)));
TypeParam just_lt_one = std::nexttoward(TypeParam(1), TypeParam(0));
EXPECT_EQ(0, absl::int128(just_lt_one));
TypeParam just_gt_minus_one = std::nexttoward(TypeParam(-1), TypeParam(0));
EXPECT_EQ(0, absl::int128(just_gt_minus_one));
EXPECT_DOUBLE_EQ(std::ldexp(static_cast<TypeParam>(1), 127),
static_cast<TypeParam>(absl::Int128Max()));
EXPECT_DOUBLE_EQ(-std::ldexp(static_cast<TypeParam>(1), 127),
static_cast<TypeParam>(absl::Int128Min()));
}
TEST(Int128, FactoryTest) {
EXPECT_EQ(absl::int128(-1), absl::MakeInt128(-1, -1));
EXPECT_EQ(absl::int128(-31), absl::MakeInt128(-1, -31));
EXPECT_EQ(absl::int128(std::numeric_limits<int64_t>::min()),
absl::MakeInt128(-1, std::numeric_limits<int64_t>::min()));
EXPECT_EQ(absl::int128(0), absl::MakeInt128(0, 0));
EXPECT_EQ(absl::int128(1), absl::MakeInt128(0, 1));
EXPECT_EQ(absl::int128(std::numeric_limits<int64_t>::max()),
absl::MakeInt128(0, std::numeric_limits<int64_t>::max()));
}
TEST(Int128, HighLowTest) {
struct HighLowPair {
int64_t high;
uint64_t low;
};
HighLowPair values[]{{0, 0}, {0, 1}, {1, 0}, {123, 456}, {-654, 321}};
for (const HighLowPair& pair : values) {
absl::int128 value = absl::MakeInt128(pair.high, pair.low);
EXPECT_EQ(pair.low, absl::Int128Low64(value));
EXPECT_EQ(pair.high, absl::Int128High64(value));
}
}
TEST(Int128, LimitsTest) {
EXPECT_EQ(absl::MakeInt128(0x7fffffffffffffff, 0xffffffffffffffff),
absl::Int128Max());
EXPECT_EQ(absl::Int128Max(), ~absl::Int128Min());
}
#if defined(ABSL_HAVE_INTRINSIC_INT128)
TEST(Int128, IntrinsicConversionTest) {
__int128 intrinsic =
(static_cast<__int128>(0x3a5b76c209de76f6) << 64) + 0x1f25e1d63a2b46c5;
absl::int128 custom =
absl::MakeInt128(0x3a5b76c209de76f6, 0x1f25e1d63a2b46c5);
EXPECT_EQ(custom, absl::int128(intrinsic));
EXPECT_EQ(intrinsic, static_cast<__int128>(custom));
}
#endif
TEST(Int128, ConstexprTest) {
constexpr absl::int128 zero = absl::int128();
constexpr absl::int128 one = 1;
constexpr absl::int128 minus_two = -2;
constexpr absl::int128 min = absl::Int128Min();
constexpr absl::int128 max = absl::Int128Max();
EXPECT_EQ(zero, absl::int128(0));
EXPECT_EQ(one, absl::int128(1));
EXPECT_EQ(minus_two, absl::MakeInt128(-1, -2));
EXPECT_GT(max, one);
EXPECT_LT(min, minus_two);
}
TEST(Int128, ComparisonTest) {
struct TestCase {
absl::int128 smaller;
absl::int128 larger;
};
TestCase cases[] = {
{absl::int128(0), absl::int128(123)},
{absl::MakeInt128(-12, 34), absl::MakeInt128(12, 34)},
{absl::MakeInt128(1, 1000), absl::MakeInt128(1000, 1)},
{absl::MakeInt128(-1000, 1000), absl::MakeInt128(-1, 1)},
};
for (const TestCase& pair : cases) {
SCOPED_TRACE(::testing::Message() << "pair.smaller = " << pair.smaller
<< "; pair.larger = " << pair.larger);
EXPECT_TRUE(pair.smaller == pair.smaller);
EXPECT_TRUE(pair.larger == pair.larger);
EXPECT_FALSE(pair.smaller == pair.larger);
EXPECT_TRUE(pair.smaller != pair.larger);
EXPECT_FALSE(pair.smaller != pair.smaller);
EXPECT_FALSE(pair.larger != pair.larger);
EXPECT_TRUE(pair.smaller < pair.larger);
EXPECT_FALSE(pair.larger < pair.smaller);
EXPECT_TRUE(pair.larger > pair.smaller);
EXPECT_FALSE(pair.smaller > pair.larger);
EXPECT_TRUE(pair.smaller <= pair.larger);
EXPECT_FALSE(pair.larger <= pair.smaller);
EXPECT_TRUE(pair.smaller <= pair.smaller);
EXPECT_TRUE(pair.larger <= pair.larger);
EXPECT_TRUE(pair.larger >= pair.smaller);
EXPECT_FALSE(pair.smaller >= pair.larger);
EXPECT_TRUE(pair.smaller >= pair.smaller);
EXPECT_TRUE(pair.larger >= pair.larger);
#ifdef __cpp_impl_three_way_comparison
EXPECT_EQ(pair.smaller <=> pair.larger, absl::strong_ordering::less);
EXPECT_EQ(pair.larger <=> pair.smaller, absl::strong_ordering::greater);
EXPECT_EQ(pair.smaller <=> pair.smaller, absl::strong_ordering::equal);
EXPECT_EQ(pair.larger <=> pair.larger, absl::strong_ordering::equal);
#endif
}
}
TEST(Int128, UnaryPlusTest) {
int64_t values64[] = {0, 1, 12345, 0x4000000000000000,
std::numeric_limits<int64_t>::max()};
for (int64_t value : values64) {
SCOPED_TRACE(::testing::Message() << "value = " << value);
EXPECT_EQ(absl::int128(value), +absl::int128(value));
EXPECT_EQ(absl::int128(-value), +absl::int128(-value));
EXPECT_EQ(absl::MakeInt128(value, 0), +absl::MakeInt128(value, 0));
EXPECT_EQ(absl::MakeInt128(-value, 0), +absl::MakeInt128(-value, 0));
}
}
TEST(Int128, UnaryNegationTest) {
int64_t values64[] = {0, 1, 12345, 0x4000000000000000,
std::numeric_limits<int64_t>::max()};
for (int64_t value : values64) {
SCOPED_TRACE(::testing::Message() << "value = " << value);
EXPECT_EQ(absl::int128(-value), -absl::int128(value));
EXPECT_EQ(absl::int128(value), -absl::int128(-value));
EXPECT_EQ(absl::MakeInt128(-value, 0), -absl::MakeInt128(value, 0));
EXPECT_EQ(absl::MakeInt128(value, 0), -absl::MakeInt128(-value, 0));
}
}
TEST(Int128, LogicalNotTest) {
EXPECT_TRUE(!absl::int128(0));
for (int i = 0; i < 64; ++i) {
EXPECT_FALSE(!absl::MakeInt128(0, uint64_t{1} << i));
}
for (int i = 0; i < 63; ++i) {
EXPECT_FALSE(!absl::MakeInt128(int64_t{1} << i, 0));
}
}
TEST(Int128, AdditionSubtractionTest) {
std::pair<int64_t, int64_t> cases[]{
{0, 0},
{0, 2945781290834},
{1908357619234, 0},
{0, -1204895918245},
{-2957928523560, 0},
{89023982312461, 98346012567134},
{-63454234568239, -23456235230773},
{98263457263502, -21428561935925},
{-88235237438467, 15923659234573},
};
for (const auto& pair : cases) {
SCOPED_TRACE(::testing::Message()
<< "pair = {" << pair.first << ", " << pair.second << '}');
EXPECT_EQ(absl::int128(pair.first + pair.second),
absl::int128(pair.first) + absl::int128(pair.second));
EXPECT_EQ(absl::int128(pair.second + pair.first),
absl::int128(pair.second) += absl::int128(pair.first));
EXPECT_EQ(absl::int128(pair.first - pair.second),
absl::int128(pair.first) - absl::int128(pair.second));
EXPECT_EQ(absl::int128(pair.second - pair.first),
absl::int128(pair.second) -= absl::int128(pair.first));
EXPECT_EQ(
absl::MakeInt128(pair.second + pair.first, 0),
absl::MakeInt128(pair.second, 0) + absl::MakeInt128(pair.first, 0));
EXPECT_EQ(
absl::MakeInt128(pair.first + pair.second, 0),
absl::MakeInt128(pair.first, 0) += absl::MakeInt128(pair.second, 0));
EXPECT_EQ(
absl::MakeInt128(pair.second - pair.first, 0),
absl::MakeInt128(pair.second, 0) - absl::MakeInt128(pair |
2,574 | cpp | abseil/abseil-cpp | blocking_counter | absl/synchronization/blocking_counter.cc | absl/synchronization/blocking_counter_test.cc | #ifndef ABSL_SYNCHRONIZATION_BLOCKING_COUNTER_H_
#define ABSL_SYNCHRONIZATION_BLOCKING_COUNTER_H_
#include <atomic>
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/mutex.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class BlockingCounter {
public:
explicit BlockingCounter(int initial_count);
BlockingCounter(const BlockingCounter&) = delete;
BlockingCounter& operator=(const BlockingCounter&) = delete;
bool DecrementCount();
void Wait();
private:
Mutex lock_;
std::atomic<int> count_;
int num_waiting_ ABSL_GUARDED_BY(lock_);
bool done_ ABSL_GUARDED_BY(lock_);
};
ABSL_NAMESPACE_END
}
#endif
#include "absl/synchronization/blocking_counter.h"
#include <atomic>
#include "absl/base/internal/raw_logging.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
bool IsDone(void *arg) { return *reinterpret_cast<bool *>(arg); }
}
BlockingCounter::BlockingCounter(int initial_count)
: count_(initial_count),
num_waiting_(0),
done_{initial_count == 0 ? true : false} {
ABSL_RAW_CHECK(initial_count >= 0, "BlockingCounter initial_count negative");
}
bool BlockingCounter::DecrementCount() {
int count = count_.fetch_sub(1, std::memory_order_acq_rel) - 1;
ABSL_RAW_CHECK(count >= 0,
"BlockingCounter::DecrementCount() called too many times");
if (count == 0) {
MutexLock l(&lock_);
done_ = true;
return true;
}
return false;
}
void BlockingCounter::Wait() {
MutexLock l(&this->lock_);
ABSL_RAW_CHECK(num_waiting_ == 0, "multiple threads called Wait()");
num_waiting_++;
this->lock_.Await(Condition(IsDone, &this->done_));
}
ABSL_NAMESPACE_END
} | #include "absl/synchronization/blocking_counter.h"
#include <thread>
#include <vector>
#include "gtest/gtest.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
void PauseAndDecreaseCounter(BlockingCounter* counter, int* done) {
absl::SleepFor(absl::Seconds(1));
*done = 1;
counter->DecrementCount();
}
TEST(BlockingCounterTest, BasicFunctionality) {
const int num_workers = 10;
BlockingCounter counter(num_workers);
std::vector<std::thread> workers;
std::vector<int> done(num_workers, 0);
workers.reserve(num_workers);
for (int k = 0; k < num_workers; k++) {
workers.emplace_back(
[&counter, &done, k] { PauseAndDecreaseCounter(&counter, &done[k]); });
}
counter.Wait();
for (int k = 0; k < num_workers; k++) {
EXPECT_EQ(1, done[k]);
}
for (std::thread& w : workers) {
w.join();
}
}
TEST(BlockingCounterTest, WaitZeroInitialCount) {
BlockingCounter counter(0);
counter.Wait();
}
#if GTEST_HAS_DEATH_TEST
TEST(BlockingCounterTest, WaitNegativeInitialCount) {
EXPECT_DEATH(BlockingCounter counter(-1),
"BlockingCounter initial_count negative");
}
#endif
}
ABSL_NAMESPACE_END
} |
2,575 | cpp | abseil/abseil-cpp | barrier | absl/synchronization/barrier.cc | absl/synchronization/barrier_test.cc | #ifndef ABSL_SYNCHRONIZATION_BARRIER_H_
#define ABSL_SYNCHRONIZATION_BARRIER_H_
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/mutex.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Barrier {
public:
explicit Barrier(int num_threads)
: num_to_block_(num_threads), num_to_exit_(num_threads) {}
Barrier(const Barrier&) = delete;
Barrier& operator=(const Barrier&) = delete;
bool Block();
private:
Mutex lock_;
int num_to_block_ ABSL_GUARDED_BY(lock_);
int num_to_exit_ ABSL_GUARDED_BY(lock_);
};
ABSL_NAMESPACE_END
}
#endif
#include "absl/synchronization/barrier.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/synchronization/mutex.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
static bool IsZero(void *arg) {
return 0 == *reinterpret_cast<int *>(arg);
}
bool Barrier::Block() {
MutexLock l(&this->lock_);
this->num_to_block_--;
if (this->num_to_block_ < 0) {
ABSL_RAW_LOG(
FATAL,
"Block() called too many times. num_to_block_=%d out of total=%d",
this->num_to_block_, this->num_to_exit_);
}
this->lock_.Await(Condition(IsZero, &this->num_to_block_));
this->num_to_exit_--;
ABSL_RAW_CHECK(this->num_to_exit_ >= 0, "barrier underflow");
return this->num_to_exit_ == 0;
}
ABSL_NAMESPACE_END
} | #include "absl/synchronization/barrier.h"
#include <thread>
#include <vector>
#include "gtest/gtest.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
TEST(Barrier, SanityTest) {
constexpr int kNumThreads = 10;
absl::Barrier* barrier = new absl::Barrier(kNumThreads);
absl::Mutex mutex;
int counter = 0;
auto thread_func = [&] {
if (barrier->Block()) {
delete barrier;
}
absl::MutexLock lock(&mutex);
++counter;
};
std::vector<std::thread> threads;
for (int i = 0; i < kNumThreads - 1; ++i) {
threads.push_back(std::thread(thread_func));
}
absl::SleepFor(absl::Seconds(1));
{
absl::MutexLock lock(&mutex);
EXPECT_EQ(counter, 0);
}
threads.push_back(std::thread(thread_func));
for (auto& thread : threads) {
thread.join();
}
absl::MutexLock lock(&mutex);
EXPECT_EQ(counter, kNumThreads);
} |
2,576 | cpp | abseil/abseil-cpp | notification | absl/synchronization/notification.cc | absl/synchronization/notification_test.cc | #ifndef ABSL_SYNCHRONIZATION_NOTIFICATION_H_
#define ABSL_SYNCHRONIZATION_NOTIFICATION_H_
#include <atomic>
#include "absl/base/attributes.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Notification {
public:
Notification() : notified_yet_(false) {}
explicit Notification(bool prenotify) : notified_yet_(prenotify) {}
Notification(const Notification&) = delete;
Notification& operator=(const Notification&) = delete;
~Notification();
ABSL_MUST_USE_RESULT bool HasBeenNotified() const {
return HasBeenNotifiedInternal(&this->notified_yet_);
}
void WaitForNotification() const;
bool WaitForNotificationWithTimeout(absl::Duration timeout) const;
bool WaitForNotificationWithDeadline(absl::Time deadline) const;
void Notify();
private:
static inline bool HasBeenNotifiedInternal(
const std::atomic<bool>* notified_yet) {
return notified_yet->load(std::memory_order_acquire);
}
mutable Mutex mutex_;
std::atomic<bool> notified_yet_;
};
ABSL_NAMESPACE_END
}
#endif
#include "absl/synchronization/notification.h"
#include <atomic>
#include "absl/base/internal/raw_logging.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
void Notification::Notify() {
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 {
if (!HasBeenNotifiedInternal(&this->notified_yet_)) {
this->mutex_.LockWhen(Condition(&HasBeenNotifiedInternal,
&this->notified_yet_));
this->mutex_.Unlock();
}
}
bool Notification::WaitForNotificationWithTimeout(
absl::Duration timeout) const {
bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
if (!notified) {
notified = this->mutex_.LockWhenWithTimeout(
Condition(&HasBeenNotifiedInternal, &this->notified_yet_), timeout);
this->mutex_.Unlock();
}
return notified;
}
bool Notification::WaitForNotificationWithDeadline(absl::Time deadline) const {
bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
if (!notified) {
notified = this->mutex_.LockWhenWithDeadline(
Condition(&HasBeenNotifiedInternal, &this->notified_yet_), deadline);
this->mutex_.Unlock();
}
return notified;
}
ABSL_NAMESPACE_END
} | #include "absl/synchronization/notification.h"
#include <thread>
#include <vector>
#include "gtest/gtest.h"
#include "absl/synchronization/mutex.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);
}
ABSL_NAMESPACE_END
} |
2,577 | cpp | abseil/abseil-cpp | mutex | absl/synchronization/mutex.cc | absl/synchronization/mutex_test.cc | #ifndef ABSL_SYNCHRONIZATION_MUTEX_H_
#define ABSL_SYNCHRONIZATION_MUTEX_H_
#include <atomic>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <string>
#include "absl/base/attributes.h"
#include "absl/base/const_init.h"
#include "absl/base/internal/identity.h"
#include "absl/base/internal/low_level_alloc.h"
#include "absl/base/internal/thread_identity.h"
#include "absl/base/internal/tsan_mutex_interface.h"
#include "absl/base/port.h"
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/internal/kernel_timeout.h"
#include "absl/synchronization/internal/per_thread_sem.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Condition;
struct SynchWaitParams;
class ABSL_LOCKABLE ABSL_ATTRIBUTE_WARN_UNUSED Mutex {
public:
Mutex();
explicit constexpr Mutex(absl::ConstInitType);
~Mutex();
void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION();
void Unlock() ABSL_UNLOCK_FUNCTION();
ABSL_MUST_USE_RESULT bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true);
void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK();
void ReaderLock() ABSL_SHARED_LOCK_FUNCTION();
void ReaderUnlock() ABSL_UNLOCK_FUNCTION();
ABSL_MUST_USE_RESULT bool ReaderTryLock() ABSL_SHARED_TRYLOCK_FUNCTION(true);
void AssertReaderHeld() const ABSL_ASSERT_SHARED_LOCK();
void WriterLock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { this->Lock(); }
void WriterUnlock() ABSL_UNLOCK_FUNCTION() { this->Unlock(); }
ABSL_MUST_USE_RESULT bool WriterTryLock()
ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
return this->TryLock();
}
void Await(const Condition& cond) {
AwaitCommon(cond, synchronization_internal::KernelTimeout::Never());
}
void LockWhen(const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION() {
LockWhenCommon(cond, synchronization_internal::KernelTimeout::Never(),
true);
}
void ReaderLockWhen(const Condition& cond) ABSL_SHARED_LOCK_FUNCTION() {
LockWhenCommon(cond, synchronization_internal::KernelTimeout::Never(),
false);
}
void WriterLockWhen(const Condition& cond) ABSL_EXCLUSIVE_LOCK_FUNCTION() {
this->LockWhen(cond);
}
bool AwaitWithTimeout(const Condition& cond, absl::Duration timeout) {
return AwaitCommon(cond, synchronization_internal::KernelTimeout{timeout});
}
bool AwaitWithDeadline(const Condition& cond, absl::Time deadline) {
return AwaitCommon(cond, synchronization_internal::KernelTimeout{deadline});
}
bool LockWhenWithTimeout(const Condition& cond, absl::Duration timeout)
ABSL_EXCLUSIVE_LOCK_FUNCTION() {
return LockWhenCommon(
cond, synchronization_internal::KernelTimeout{timeout}, true);
}
bool ReaderLockWhenWithTimeout(const Condition& cond, absl::Duration timeout)
ABSL_SHARED_LOCK_FUNCTION() {
return LockWhenCommon(
cond, synchronization_internal::KernelTimeout{timeout}, false);
}
bool WriterLockWhenWithTimeout(const Condition& cond, absl::Duration timeout)
ABSL_EXCLUSIVE_LOCK_FUNCTION() {
return this->LockWhenWithTimeout(cond, timeout);
}
bool LockWhenWithDeadline(const Condition& cond, absl::Time deadline)
ABSL_EXCLUSIVE_LOCK_FUNCTION() {
return LockWhenCommon(
cond, synchronization_internal::KernelTimeout{deadline}, true);
}
bool ReaderLockWhenWithDeadline(const Condition& cond, absl::Time deadline)
ABSL_SHARED_LOCK_FUNCTION() {
return LockWhenCommon(
cond, synchronization_internal::KernelTimeout{deadline}, false);
}
bool WriterLockWhenWithDeadline(const Condition& cond, absl::Time deadline)
ABSL_EXCLUSIVE_LOCK_FUNCTION() {
return this->LockWhenWithDeadline(cond, deadline);
}
void EnableInvariantDebugging(void (*invariant)(void*), void* arg);
void EnableDebugLog(const char* name);
void ForgetDeadlockInfo();
void AssertNotHeld() const;
typedef const struct MuHowS* MuHow;
static void InternalAttemptToUseMutexInFatalSignalHandler();
private:
std::atomic<intptr_t> mu_;
static void IncrementSynchSem(Mutex* mu, base_internal::PerThreadSynch* w);
static bool DecrementSynchSem(Mutex* mu, base_internal::PerThreadSynch* w,
synchronization_internal::KernelTimeout t);
void LockSlowLoop(SynchWaitParams* waitp, int flags);
bool LockSlowWithDeadline(MuHow how, const Condition* cond,
synchronization_internal::KernelTimeout t,
int flags);
void LockSlow(MuHow how, const Condition* cond,
int flags) ABSL_ATTRIBUTE_COLD;
void UnlockSlow(SynchWaitParams* waitp) ABSL_ATTRIBUTE_COLD;
bool TryLockSlow();
bool ReaderTryLockSlow();
bool AwaitCommon(const Condition& cond,
synchronization_internal::KernelTimeout t);
bool LockWhenCommon(const Condition& cond,
synchronization_internal::KernelTimeout t, bool write);
void TryRemove(base_internal::PerThreadSynch* s);
void Block(base_internal::PerThreadSynch* s);
base_internal::PerThreadSynch* Wakeup(base_internal::PerThreadSynch* w);
void Dtor();
friend class CondVar;
void Trans(MuHow how);
void Fer(
base_internal::PerThreadSynch* w);
explicit Mutex(const volatile Mutex* ) {}
Mutex(const Mutex&) = delete;
Mutex& operator=(const Mutex&) = delete;
};
class ABSL_SCOPED_LOCKABLE MutexLock {
public:
explicit MutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) {
this->mu_->Lock();
}
explicit MutexLock(Mutex* mu, const Condition& cond)
ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
: mu_(mu) {
this->mu_->LockWhen(cond);
}
MutexLock(const MutexLock&) = delete;
MutexLock(MutexLock&&) = delete;
MutexLock& operator=(const MutexLock&) = delete;
MutexLock& operator=(MutexLock&&) = delete;
~MutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->Unlock(); }
private:
Mutex* const mu_;
};
class ABSL_SCOPED_LOCKABLE ReaderMutexLock {
public:
explicit ReaderMutexLock(Mutex* mu) ABSL_SHARED_LOCK_FUNCTION(mu) : mu_(mu) {
mu->ReaderLock();
}
explicit ReaderMutexLock(Mutex* mu, const Condition& cond)
ABSL_SHARED_LOCK_FUNCTION(mu)
: mu_(mu) {
mu->ReaderLockWhen(cond);
}
ReaderMutexLock(const ReaderMutexLock&) = delete;
ReaderMutexLock(ReaderMutexLock&&) = delete;
ReaderMutexLock& operator=(const ReaderMutexLock&) = delete;
ReaderMutexLock& operator=(ReaderMutexLock&&) = delete;
~ReaderMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->ReaderUnlock(); }
private:
Mutex* const mu_;
};
class ABSL_SCOPED_LOCKABLE WriterMutexLock {
public:
explicit WriterMutexLock(Mutex* mu) ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
: mu_(mu) {
mu->WriterLock();
}
explicit WriterMutexLock(Mutex* mu, const Condition& cond)
ABSL_EXCLUSIVE_LOCK_FUNCTION(mu)
: mu_(mu) {
mu->WriterLockWhen(cond);
}
WriterMutexLock(const WriterMutexLock&) = delete;
WriterMutexLock(WriterMutexLock&&) = delete;
WriterMutexLock& operator=(const WriterMutexLock&) = delete;
WriterMutexLock& operator=(WriterMutexLock&&) = delete;
~WriterMutexLock() ABSL_UNLOCK_FUNCTION() { this->mu_->WriterUnlock(); }
private:
Mutex* const mu_;
};
class Condition {
public:
Condition(bool (*func)(void*), void* arg);
template <typename T>
Condition(bool (*func)(T*), T* arg);
template <typename T, typename = void>
Condition(bool (*func)(T*),
typename absl::internal::type_identity<T>::type* arg);
template <typename T>
Condition(T* object,
bool (absl::internal::type_identity<T>::type::*method)());
template <typename T>
Condition(const T* object,
bool (absl::internal::type_identity<T>::type::*method)() const);
explicit Condition(const bool* cond); | #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();
} |
2,578 | cpp | abseil/abseil-cpp | per_thread_sem | absl/synchronization/internal/per_thread_sem.cc | absl/synchronization/internal/per_thread_sem_test.cc | #ifndef ABSL_SYNCHRONIZATION_INTERNAL_PER_THREAD_SEM_H_
#define ABSL_SYNCHRONIZATION_INTERNAL_PER_THREAD_SEM_H_
#include <atomic>
#include "absl/base/internal/thread_identity.h"
#include "absl/synchronization/internal/create_thread_identity.h"
#include "absl/synchronization/internal/kernel_timeout.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Mutex;
namespace synchronization_internal {
class PerThreadSem {
public:
PerThreadSem() = delete;
PerThreadSem(const PerThreadSem&) = delete;
PerThreadSem& operator=(const PerThreadSem&) = delete;
static void Tick(base_internal::ThreadIdentity* identity);
static void SetThreadBlockedCounter(std::atomic<int> *counter);
static std::atomic<int> *GetThreadBlockedCounter();
private:
static inline void Init(base_internal::ThreadIdentity* identity);
static inline void Post(base_internal::ThreadIdentity* identity);
static inline bool Wait(KernelTimeout t);
friend class PerThreadSemTest;
friend class absl::Mutex;
friend void OneTimeInitThreadIdentity(absl::base_internal::ThreadIdentity*);
};
}
ABSL_NAMESPACE_END
}
extern "C" {
void ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemInit)(
absl::base_internal::ThreadIdentity* identity);
void ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemPost)(
absl::base_internal::ThreadIdentity* identity);
bool ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemWait)(
absl::synchronization_internal::KernelTimeout t);
void ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemPoke)(
absl::base_internal::ThreadIdentity* identity);
}
void absl::synchronization_internal::PerThreadSem::Init(
absl::base_internal::ThreadIdentity* identity) {
ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemInit)(identity);
}
void absl::synchronization_internal::PerThreadSem::Post(
absl::base_internal::ThreadIdentity* identity) {
ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemPost)(identity);
}
bool absl::synchronization_internal::PerThreadSem::Wait(
absl::synchronization_internal::KernelTimeout t) {
return ABSL_INTERNAL_C_SYMBOL(AbslInternalPerThreadSemWait)(t);
}
#endif
#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
} |
2,579 | cpp | abseil/abseil-cpp | kernel_timeout | absl/synchronization/internal/kernel_timeout.cc | absl/synchronization/internal/kernel_timeout_test.cc | #ifndef ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
#define ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
#ifndef _WIN32
#include <sys/types.h>
#endif
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <ctime>
#include <limits>
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace synchronization_internal {
class KernelTimeout {
public:
explicit KernelTimeout(absl::Time t);
explicit KernelTimeout(absl::Duration d);
constexpr KernelTimeout() : rep_(kNoTimeout) {}
static constexpr KernelTimeout Never() { return KernelTimeout(); }
bool has_timeout() const { return rep_ != kNoTimeout; }
bool is_absolute_timeout() const { return (rep_ & 1) == 0; }
bool is_relative_timeout() const { return (rep_ & 1) == 1; }
struct timespec MakeAbsTimespec() const;
struct timespec MakeRelativeTimespec() const;
#ifndef _WIN32
struct timespec MakeClockAbsoluteTimespec(clockid_t c) const;
#endif
int64_t MakeAbsNanos() const;
typedef unsigned long DWord;
DWord InMillisecondsFromNow() const;
std::chrono::time_point<std::chrono::system_clock> ToChronoTimePoint() const;
std::chrono::nanoseconds ToChronoDuration() const;
static constexpr bool SupportsSteadyClock() { return true; }
private:
static int64_t SteadyClockNow();
uint64_t rep_;
int64_t RawAbsNanos() const { return static_cast<int64_t>(rep_ >> 1); }
int64_t InNanosecondsFromNow() const;
static constexpr uint64_t kNoTimeout = (std::numeric_limits<uint64_t>::max)();
static constexpr int64_t kMaxNanos = (std::numeric_limits<int64_t>::max)();
};
}
ABSL_NAMESPACE_END
}
#endif
#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));
}
} |
2,580 | cpp | abseil/abseil-cpp | graphcycles | absl/synchronization/internal/graphcycles.cc | absl/synchronization/internal/graphcycles_test.cc | #ifndef ABSL_SYNCHRONIZATION_INTERNAL_GRAPHCYCLES_H_
#define ABSL_SYNCHRONIZATION_INTERNAL_GRAPHCYCLES_H_
#include <cstdint>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace synchronization_internal {
struct GraphId {
uint64_t handle;
bool operator==(const GraphId& x) const { return handle == x.handle; }
bool operator!=(const GraphId& x) const { return handle != x.handle; }
};
inline GraphId InvalidGraphId() {
return GraphId{0};
}
class GraphCycles {
public:
GraphCycles();
~GraphCycles();
GraphId GetId(void* ptr);
void RemoveNode(void* ptr);
void* Ptr(GraphId id);
bool InsertEdge(GraphId source_node, GraphId dest_node);
void RemoveEdge(GraphId source_node, GraphId dest_node);
bool HasNode(GraphId node);
bool HasEdge(GraphId source_node, GraphId dest_node) const;
bool IsReachable(GraphId source_node, GraphId dest_node) const;
int FindPath(GraphId source, GraphId dest, int max_path_len,
GraphId path[]) const;
void UpdateStackTrace(GraphId id, int priority,
int (*get_stack_trace)(void**, int));
int GetStackTrace(GraphId id, void*** ptr);
bool CheckInvariants() const;
struct Rep;
private:
Rep *rep_;
GraphCycles(const GraphCycles&) = delete;
GraphCycles& operator=(const GraphCycles&) = delete;
};
}
ABSL_NAMESPACE_END
}
#endif
#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;
}
GraphCycles::GraphCycles() {
InitArenaIfNecessary();
rep_ = new (base_internal::LowLevelAlloc::AllocWithArena(sizeof(Rep), arena))
Rep;
}
GraphCycles::~GraphCycles() {
for (auto* node : rep_->nodes_) {
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 <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_);
}
}
ABSL_NAMESPACE_END
} |
2,581 | cpp | abseil/abseil-cpp | city | absl/hash/internal/city.cc | absl/hash/internal/city_test.cc | #ifndef ABSL_HASH_INTERNAL_CITY_H_
#define ABSL_HASH_INTERNAL_CITY_H_
#include <stdint.h>
#include <stdlib.h>
#include <utility>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace hash_internal {
uint64_t CityHash64(const char *s, size_t len);
uint64_t CityHash64WithSeed(const char *s, size_t len, uint64_t seed);
uint64_t CityHash64WithSeeds(const char *s, size_t len, uint64_t seed0,
uint64_t seed1);
uint32_t CityHash32(const char *s, size_t len);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/hash/internal/city.h"
#include <string.h>
#include <algorithm>
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/internal/unaligned_access.h"
#include "absl/base/optimization.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace hash_internal {
#ifdef ABSL_IS_BIG_ENDIAN
#define uint32_in_expected_order(x) (absl::gbswap_32(x))
#define uint64_in_expected_order(x) (absl::gbswap_64(x))
#else
#define uint32_in_expected_order(x) (x)
#define uint64_in_expected_order(x) (x)
#endif
static uint64_t Fetch64(const char *p) {
return uint64_in_expected_order(ABSL_INTERNAL_UNALIGNED_LOAD64(p));
}
static uint32_t Fetch32(const char *p) {
return uint32_in_expected_order(ABSL_INTERNAL_UNALIGNED_LOAD32(p));
}
static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
static const uint64_t k1 = 0xb492b66fbe98f273ULL;
static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
static const uint32_t c1 = 0xcc9e2d51;
static const uint32_t c2 = 0x1b873593;
static uint32_t fmix(uint32_t h) {
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
static uint32_t Rotate32(uint32_t val, int shift) {
return shift == 0 ? val : ((val >> shift) | (val << (32 - shift)));
}
#undef PERMUTE3
#define PERMUTE3(a, b, c) \
do { \
std::swap(a, b); \
std::swap(a, c); \
} while (0)
static uint32_t Mur(uint32_t a, uint32_t h) {
a *= c1;
a = Rotate32(a, 17);
a *= c2;
h ^= a;
h = Rotate32(h, 19);
return h * 5 + 0xe6546b64;
}
static uint32_t Hash32Len13to24(const char *s, size_t len) {
uint32_t a = Fetch32(s - 4 + (len >> 1));
uint32_t b = Fetch32(s + 4);
uint32_t c = Fetch32(s + len - 8);
uint32_t d = Fetch32(s + (len >> 1));
uint32_t e = Fetch32(s);
uint32_t f = Fetch32(s + len - 4);
uint32_t h = static_cast<uint32_t>(len);
return fmix(Mur(f, Mur(e, Mur(d, Mur(c, Mur(b, Mur(a, h)))))));
}
static uint32_t Hash32Len0to4(const char *s, size_t len) {
uint32_t b = 0;
uint32_t c = 9;
for (size_t i = 0; i < len; i++) {
signed char v = static_cast<signed char>(s[i]);
b = b * c1 + static_cast<uint32_t>(v);
c ^= b;
}
return fmix(Mur(b, Mur(static_cast<uint32_t>(len), c)));
}
static uint32_t Hash32Len5to12(const char *s, size_t len) {
uint32_t a = static_cast<uint32_t>(len), b = a * 5, c = 9, d = b;
a += Fetch32(s);
b += Fetch32(s + len - 4);
c += Fetch32(s + ((len >> 1) & 4));
return fmix(Mur(c, Mur(b, Mur(a, d))));
}
uint32_t CityHash32(const char *s, size_t len) {
if (len <= 24) {
return len <= 12
? (len <= 4 ? Hash32Len0to4(s, len) : Hash32Len5to12(s, len))
: Hash32Len13to24(s, len);
}
uint32_t h = static_cast<uint32_t>(len), g = c1 * h, f = g;
uint32_t a0 = Rotate32(Fetch32(s + len - 4) * c1, 17) * c2;
uint32_t a1 = Rotate32(Fetch32(s + len - 8) * c1, 17) * c2;
uint32_t a2 = Rotate32(Fetch32(s + len - 16) * c1, 17) * c2;
uint32_t a3 = Rotate32(Fetch32(s + len - 12) * c1, 17) * c2;
uint32_t a4 = Rotate32(Fetch32(s + len - 20) * c1, 17) * c2;
h ^= a0;
h = Rotate32(h, 19);
h = h * 5 + 0xe6546b64;
h ^= a2;
h = Rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= a1;
g = Rotate32(g, 19);
g = g * 5 + 0xe6546b64;
g ^= a3;
g = Rotate32(g, 19);
g = g * 5 + 0xe6546b64;
f += a4;
f = Rotate32(f, 19);
f = f * 5 + 0xe6546b64;
size_t iters = (len - 1) / 20;
do {
uint32_t b0 = Rotate32(Fetch32(s) * c1, 17) * c2;
uint32_t b1 = Fetch32(s + 4);
uint32_t b2 = Rotate32(Fetch32(s + 8) * c1, 17) * c2;
uint32_t b3 = Rotate32(Fetch32(s + 12) * c1, 17) * c2;
uint32_t b4 = Fetch32(s + 16);
h ^= b0;
h = Rotate32(h, 18);
h = h * 5 + 0xe6546b64;
f += b1;
f = Rotate32(f, 19);
f = f * c1;
g += b2;
g = Rotate32(g, 18);
g = g * 5 + 0xe6546b64;
h ^= b3 + b1;
h = Rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= b4;
g = absl::gbswap_32(g) * 5;
h += b4 * 5;
h = absl::gbswap_32(h);
f += b0;
PERMUTE3(f, h, g);
s += 20;
} while (--iters != 0);
g = Rotate32(g, 11) * c1;
g = Rotate32(g, 17) * c1;
f = Rotate32(f, 11) * c1;
f = Rotate32(f, 17) * c1;
h = Rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = Rotate32(h, 17) * c1;
h = Rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = Rotate32(h, 17) * c1;
return h;
}
static uint64_t Rotate(uint64_t val, int shift) {
return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
}
static uint64_t ShiftMix(uint64_t val) { return val ^ (val >> 47); }
static uint64_t HashLen16(uint64_t u, uint64_t v, uint64_t mul) {
uint64_t a = (u ^ v) * mul;
a ^= (a >> 47);
uint64_t b = (v ^ a) * mul;
b ^= (b >> 47);
b *= mul;
return b;
}
static uint64_t HashLen16(uint64_t u, uint64_t v) {
const uint64_t kMul = 0x9ddfea08eb382d69ULL;
return HashLen16(u, v, kMul);
}
static uint64_t HashLen0to16(const char *s, size_t len) {
if (len >= 8) {
uint64_t mul = k2 + len * 2;
uint64_t a = Fetch64(s) + k2;
uint64_t b = Fetch64(s + len - 8);
uint64_t c = Rotate(b, 37) * mul + a;
uint64_t d = (Rotate(a, 25) + b) * mul;
return HashLen16(c, d, mul);
}
if (len >= 4) {
uint64_t mul = k2 + len * 2;
uint64_t a = Fetch32(s);
return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul);
}
if (len > 0) {
uint8_t a = static_cast<uint8_t>(s[0]);
uint8_t b = static_cast<uint8_t>(s[len >> 1]);
uint8_t c = static_cast<uint8_t>(s[len - 1]);
uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
uint32_t z = static_cast<uint32_t>(len) + (static_cast<uint32_t>(c) << 2);
return ShiftMix(y * k2 ^ z * k0) * k2;
}
return k2;
}
static uint64_t HashLen17to32(const char *s, size_t len) {
uint64_t mul = k2 + len * 2;
uint64_t a = Fetch64(s) * k1;
uint64_t b = Fetch64(s + 8);
uint64_t c = Fetch64(s + len - 8) * mul;
uint64_t d = Fetch64(s + len - 16) * k2;
return HashLen16(Rotate(a + b, 43) + Rotate(c, 30) + d,
a + Rotate(b + k2, 18) + c, mul);
}
static std::pair<uint64_t, uint64_t> WeakHashLen32WithSeeds(
uint64_t w, uint64_t x, uint64_t y, uint64_t z, uint64_t a, uint64_t b) {
a += w;
b = Rotate(b + a + z, 21);
uint64_t c = a;
a += x;
a += y;
b += Rotate(a, 44);
return std::make_pair(a + z, b + c);
}
static std::pair<uint64_t, uint64_t> WeakHashLen32WithSeeds(const char *s,
uint64_t a,
uint64_t b) {
return WeakHashLen32WithSeeds(Fetch64(s), Fetch64(s + 8), Fetch64(s + 16),
Fetch64(s + 24), a, b);
}
static uint64_t HashLen33to64(const char *s, size_t len) {
uint64_t mul = k2 + len * 2;
uint64_t a = Fetch64(s) * k2;
uint64_t b = Fetch64(s + 8);
uint64_t c = Fetch64(s + len - 24);
uint64_t d = Fetch64(s + len - 32);
uint64_t e = Fetch64(s + 16) * k2;
uint64_t f = Fetch64(s + 24) * 9;
uint64_t g = Fetch64(s + len - 8);
uint64_t h = Fetch64(s + len - 16) * mul;
uint64_t u = Rotate(a + g, 43) + (Rotate(b, 30) + c) * 9;
uint64_t v = ((a + g) ^ d) + f + 1;
uint64_t w = absl::gbswap_64((u + v) * mul) + h;
uint64_t x = Rotate(e + f, 42) + c;
uint64_t y = (absl::gbswap_64((v + w) * mul) + g) * mul;
uint64_t z = e + f + c;
a = absl::gbswap_64((x + z) * mul + y) + b;
b = ShiftMix((z + a) * mul + d + h) * mul;
return b + x;
}
uint64_t CityHash64(const char *s, size_t len) {
if (len <= 32) {
if (len <= 16) {
return HashLen0to16(s, len);
} else {
return HashLen17to32(s, len);
}
} else if (len <= 64) {
return HashLen33to64(s, len);
}
uint64_t x = Fetch64(s + len - 40);
uint64_t y = Fetch64(s + len - 16) + Fetch64(s + len - 56);
uint64_t z = HashLen16(Fetch64(s + len - 48) + len, Fetch64(s + len - 24));
std::pair<uint64_t, uint64_t> v =
WeakHashLen32WithSeeds(s + len - 64, len, z);
std::pair<uint64_t, uint64_t> w =
WeakHashLen32WithSeeds(s + len - 32, y + k1, x);
x = x * k1 + Fetch64(s);
len = (len - 1) & ~static_cast<size_t>(63);
do {
x = Rotate(x + y + v.first + Fetch64(s + 8), 37) * k1;
y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1;
x ^= w.second;
y += v.first + Fetch64(s + 40);
z = Rotate(z + w.first, 33) * k1;
v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first);
w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch64(s + 16));
std::swap(z, x);
s += 64;
len -= 64;
} while (len != 0);
return HashLen16(HashLen16(v.first, w.first) + ShiftMix(y) * k1 + z,
HashLen16(v.second, w.second) + x);
}
uint64_t CityHash64WithSeed(const char *s, size_t len, uint64_t seed) {
return CityHash64WithSeeds(s, len, k2, seed);
}
uint64_t CityHash64WithSeeds(const char *s, size_t len, uint64_t seed0,
uint64_t seed1) {
return HashLen16(CityHash64(s, len) - seed0, seed1);
}
}
ABSL_NAMESPACE_END
} | #include "absl/hash/internal/city.h"
#include <string.h>
#include <cstdio>
#include <iostream>
#include "gtest/gtest.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace hash_internal {
namespace {
static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
static const uint64_t kSeed0 = 1234567;
static const uint64_t kSeed1 = k0;
static const int kDataSize = 1 << 20;
static const int kTestSize = 300;
static char data[kDataSize];
void setup() {
uint64_t a = 9;
uint64_t b = 777;
for (int i = 0; i < kDataSize; i++) {
a += b;
b += a;
a = (a ^ (a >> 41)) * k0;
b = (b ^ (b >> 41)) * k0 + i;
uint8_t u = b >> 37;
memcpy(data + i, &u, 1);
}
}
#define C(x) 0x##x##ULL
static const uint64_t testdata[kTestSize][4] = {
{C(9ae16a3b2f90404f), C(75106db890237a4a), C(3feac5f636039766),
C(dc56d17a)},
{C(541150e87f415e96), C(1aef0d24b3148a1a), C(bacc300e1e82345a),
C(99929334)},
{C(f3786a4b25827c1), C(34ee1a2bf767bd1c), C(2f15ca2ebfb631f2), C(4252edb7)},
{C(ef923a7a1af78eab), C(79163b1e1e9a9b18), C(df3b2aca6e1e4a30),
C(ebc34f3c)},
{C(11df592596f41d88), C(843ec0bce9042f9c), C(cce2ea1e08b1eb30),
C(26f2b463)},
{C(831f448bdc5600b3), C(62a24be3120a6919), C(1b44098a41e010da),
C(b042c047)},
{C(3eca803e70304894), C(d80de767e4a920a), C(a51cfbb292efd53d), C(e73bb0a8)},
{C(1b5a063fb4c7f9f1), C(318dbc24af66dee9), C(10ef7b32d5c719af),
C(91dfdd75)},
{C(a0f10149a0e538d6), C(69d008c20f87419f), C(41b36376185b3e9e),
C(c87f95de)},
{C(fb8d9c70660b910b), C(a45b0cc3476bff1b), C(b28d1996144f0207),
C(3f5538ef)},
{C(236827beae282a46), C(e43970221139c946), C(4f3ac6faa837a3aa),
C(70eb1a1f)},
{C(c385e435136ecf7c), C(d9d17368ff6c4a08), C(1b31eed4e5251a67),
C(cfd63b83)},
{C(e3f6828b6017086d), C(21b4d1900554b3b0), C(bef38be1809e24f1),
C(894a52ef)},
{C(851fff285561dca0), C(4d1277d73cdf416f), C(28ccffa61010ebe2),
C(9cde6a54)},
{C(61152a63595a96d9), C(d1a3a91ef3a7ba45), C(443b6bb4a493ad0c),
C(6c4898d5)},
{C(44473e03be306c88), C(30097761f872472a), C(9fd1b669bfad82d7),
C(13e1978e)},
{C(3ead5f21d344056), C(fb6420393cfb05c3), C(407932394cbbd303), C(51b4ba8)},
{C(6abbfde37ee03b5b), C(83febf188d2cc113), C(cda7b62d94d5b8ee),
C(b6b06e40)},
{C(943e7ed63b3c080), C(1ef207e9444ef7f8), C(ef4a9f9f8c6f9b4a), C(240a2f2)},
{C(d72ce05171ef8a1a), C(c6bd6bd869203894), C(c760e6396455d23a),
C(5dcefc30)},
{C(4182832b52d63735), C(337097e123eea414), C(b5a72ca0456df910),
C(7a48b105)},
{C(d6cdae892584a2cb), C(58de0fa4eca17dcd), C(43df30b8f5f1cb00),
C(fd55007b)},
{C(5c8e90bc267c5ee4), C(e9ae044075d992d9), C(f234cbfd1f0a1e59),
C(6b95894c)},
{C(bbd7f30ac310a6f3), C(b23b570d2666685f), C(fb13fb08c9814fe7),
C(3360e827)},
{C(36a097aa49519d97), C(8204380a73c4065), C(77c2004bdd9e276a), C(45177e0b)},
{C(dc78cb032c49217), C(112464083f83e03a), C(96ae53e28170c0f5), C(7c6fffe4)},
{C(441593e0da922dfe), C(936ef46061469b32), C(204a1921197ddd87),
C(bbc78da4)},
{C(2ba3883d71cc2133), C(72f2bbb32bed1a3c), C(27e1bd96d4843251),
C(c5c25d39)},
{C(f2b6d2adf8423600), C(7514e2f016a48722), C(43045743a50396ba),
C(b6e5d06e)},
{C(38fffe7f3680d63c), C(d513325255a7a6d1), C(31ed47790f6ca62f),
C(6178504e)},
{C(b7477bf0b9ce37c6), C(63b1c580a7fd02a4), C(f6433b9f10a5dac), C(bd4c3637)},
{C(55bdb0e71e3edebd), C(c7ab562bcf0568bc), C(43166332f9ee684f),
C(6e7ac474)},
{C(782fa1b08b475e7), C(fb7138951c61b23b), C(9829105e234fb11e), C(1fb4b518)},
{C(c5dc19b876d37a80), C(15ffcff666cfd710), C(e8c30c72003103e2),
C(31d13d6d)},
{C(5e1141711d2d6706), C(b537f6dee8de6933), C(3af0a1fbbe027c54),
C(26fa72e3)},
{C(782edf6da001234f), C(f48cbd5c66c48f3), C(808754d1e64e2a32), C(6a7433bf)},
{C(d26285842ff04d44), C(8f38d71341eacca9), C(5ca436f4db7a883c),
C(4e6df758)},
{C(c6ab830865a6bae6), C(6aa8e8dd4b98815c), C(efe3846713c371e5),
C(d57f63ea)},
{C(44b3a1929232892), C(61dca0e914fc217), C(a607cc142096b964), C(52ef73b3)},
{C(4b603d7932a8de4f), C(fae64c464b8a8f45), C(8fafab75661d602a), C(3cb36c3)},
{C(4ec0b54cf1566aff), C(30d2c7269b206bf4), C(77c22e82295e1061),
C(72c39bea)},
{C(ed8b7a4b34954ff7), C(56432de31f4ee757), C(85bd3abaa572b155),
C(a65aa25c)},
{C(5d28b43694176c26), C(714cc8bc12d060ae), C(3437726273a83fe6),
C(74740539)},
{C(6a1ef3639e1d202e), C(919bc1bd145ad928), C(30f3f7e48c28a773),
C(c3ae3c26)},
{C(159f4d9e0307b111), C(3e17914a5675a0c), C(af849bd425047b51), C(f29db8a2)},
{C(cc0a840725a7e25b), C(57c69454396e193a), C(976eaf7eee0b4540),
C(1ef4cbf4)},
{C(a2b27ee22f63c3f1), C(9ebde0ce1b3976b2), C(2fe6a92a257af308),
C(a9be6c41)},
{C(d8f2f234899bcab3), C(b10b037297c3a168), C(debea2c510ceda7f), C(fa31801)},
{C(584f28543864844f), C(d7cee9fc2d46f20d), C(a38dca5657387205),
C(8331c5d8)},
{C(a94be46dd9aa41af), C(a57e5b7723d3f9bd), C(34bf845a52fd2f), C(e9876db8)},
{C(9a87bea227491d20), C(a468657e2b9c43e7), C(af9ba60db8d89ef7),
C(27b0604e)},
{C(27688c24958d1a5c), C(e3b4a1c9429cf253), C(48a95811f70d64bc),
C(dcec07f2)},
{C(5d1d37790a1873ad), C(ed9cd4bcc5fa1090), C(ce51cde05d8cd96a),
C(cff0a82a)},
{C(1f03fd18b711eea9), C(566d89b1946d381a), C(6e96e83fc92563ab),
C(fec83621)},
{C(f0316f286cf527b6), C(f84c29538de1aa5a), C(7612ed3c923d4a71), C(743d8dc)},
{C(297008bcb3e3401d), C(61a8e407f82b0c69), C(a4a35bff0524fa0e),
C(64d41d26)},
{C(43c6252411ee3be), C(b4ca1b8077777168), C(2746dc3f7da1737f), C(acd90c81)},
{C(ce38a9a54fad6599), C(6d6f4a90b9e8755e), C(c3ecc79ff105de3f),
C(7c746a4b)},
{C(270a9305fef70cf), C(600193999d884f3a), C(f4d49eae09ed8a1), C(b1047e99)},
{C(e71be7c28e84d119), C(eb6ace59932736e6), C(70c4397807ba12c5),
C(d1fd1068)},
{C(b5b58c24b53aaa19), C(d2a6ab0773dd897f), C(ef762fe01ecb5b97),
C(56486077)},
{C(44dd59bd301995cf), C(3ccabd76493ada1a), C(540db4c87d55ef23),
C(6069be80)},
{C(b4d4789eb6f2630b), C(bf6973263ce8ef0e), C(d1c75c50844b9d3), C(2078359b)},
{C(12807833c463737c), C(58e927ea3b3776b4), C(72dd20ef1c2f8ad0),
C(9ea21004)},
{C(e88419922b87176f), C(bcf32f41a7ddbf6f), C(d6ebefd8085c1a0f),
C(9c9cfe88)},
{C(105191e0ec8f7f60), C(5918dbfcca971e79), C(6b285c8a944767b9),
C(b70a6ddd)},
{C(a5b88bf7399a9f07), C(fca3ddfd96461cc4), C(ebe738fdc0282fc6),
C(dea37298)},
{C(d08c3f5747d84f50), C(4e708b27d1b6f8ac), C(70f70fd734888606),
C(8f480819)},
{C(2f72d12a40044b4b), C(889689352fec53de), C(f03e6ad87eb2f36), C(30b3b16)},
{C(aa1f61fdc5c2e11e), C(c2c56cd11277ab27), C(a1e73069fdf1f94f),
C(f31bc4e8)},
{C(9489b36fe2246244), C(3355367033be74b8), C(5f57c2277cbce516),
C(419f953b)},
{C(358d7c0476a044cd), C(e0b7b47bcbd8854f), C(ffb42ec696705519),
C(20e9e76d)},
{C(b0c48df14275265a), C(9da4448975905efa), C(d716618e414ceb6d),
C(646f0ff8)},
{C(daa70bb300956588), C(410ea6883a240c6d), C(f5c8239fb5673eb3),
C(eeb7eca8)},
{C(4ec97a20b6c4c7c2), C(5913b1cd454f29fd), C(a9629f9daf06d685), C(8112bb9)},
{C(5c3323628435a2e8), C(1bea45ce9e72a6e3), C(904f0a7027ddb52e),
C(85a6d477)},
{C(c1ef26bea260abdb), C(6ee423f2137f9280), C(df2118b946ed0b43),
C(56f76c84)},
{C(6be7381b115d653a), C(ed046190758ea511), C(de6a45ffc3ed1159),
C(9af45d55)},
{C(ae3eece1711b2105), C(14fd3f4027f81a4a), C(abb7e45177d151db),
C(d1c33760)},
{C(376c28588b8fb389), C(6b045e84d8491ed2), C(4e857effb7d4e7dc),
C(c56bbf69)},
{C(58d943503bb6748f), C(419c6c8e88ac70f6), C(586760cbf3d3d368),
C(abecfb9b)},
{C(dfff5989f5cfd9a1), C(bcee2e7ea3a96f83), C(681c7874adb29017),
C(8de13255)},
{C(7fb19eb1a496e8f5), C(d49e5dfdb5c0833f), C(c0d5d7b2f7c48dc7),
C(a98ee299)},
{C(5dba5b0dadccdbaa), C(4ba8da8ded87fcdc), C(f693fdd25badf2f0),
C(3015f556)},
{C(688bef4b135a6829), C(8d31d82abcd54e8e), C(f95f8a30d55036d7),
C(5a430e29)},
{C(d8323be05433a412), C(8d48fa2b2b76141d), C(3d346f23978336a5),
C(2797add0)},
{C(3b5404278a55a7fc), C(23ca0b327c2d0a81), C(a6d65329571c892c),
C(27d55016)},
{C(2a96a3f96c5e9bbc), C(8caf8566e212dda8), C(904de559ca16e45e),
C(84945a82)},
{C(22bebfdcc26d18ff), C(4b4d8dcb10807ba1), C(40265eee30c6b896),
C(3ef7e224)},
{C(627a2249ec6bbcc2), C(c0578b462a46735a), C(4974b8ee1c2d4f1f),
C(35ed8dc8)},
{C(3abaf1667ba2f3e0), C(ee78476b5eeadc1), C(7e56ac0a6ca4f3f4), C(6a75e43d)},
{C(3931ac68c5f1b2c9), C(efe3892363ab0fb0), C(40b707268337cd36),
C(235d9805)},
{C(b98fb0606f416754), C(46a6e5547ba99c1e), C(c909d82112a8ed2), C(f7d69572)},
{C(7f7729a33e58fcc4), C(2e4bc1e7a023ead4), C(e707008ea7ca6222),
C(bacd0199)},
{C(42a0aa9ce82848b3), C(57232730e6bee175), C(f89bb3f370782031),
C(e428f50e)},
{C(6b2c6d38408a4889), C(de3ef6f68fb25885), C(20754f456c203361),
C(81eaaad3)},
{C(930380a3741e862a), C(348d28638dc71658), C(89dedcfd1654ea0d),
C(addbd3e3)},
{C(94808b5d2aa25f9a), C(cec72968128195e0), C(d9f4da2bdc1e130f),
C(e66dbca0)},
{C(b31abb08ae6e3d38), C(9eb9a95cbd9e8223), C(8019e79b7ee94ea9),
C(afe11fd5)},
{C(dccb5534a893ea1a), C(ce71c398708c6131), C(fe2396315457c164),
C(a71a406f)},
{C(6369163565814de6), C(8feb86fb38d08c2f), C(4976933485cc9a20),
C(9d90eaf5)},
{C(edee4ff253d9f9b3), C(96ef76fb279ef0ad), C(a4d204d179db2460),
C(6665db10)},
{C(941993df6e633214), C(929bc1beca5b72c6), C(141fc52b8d55572d),
C(9c977cbf)},
{C(859838293f64cd4c), C(484403b39d44ad79), C(bf674e64d64b9339),
C(ee83ddd4)},
{C(c19b5648e0d9f555), C(328e47b2b7562993), C(e756b92ba4bd6a51), C(26519cc)},
{C(f963b63b9006c248), C(9e9bf727ffaa00bc), C(c73bacc75b917e3a),
C(a485a53f)},
{C(6a8aa0852a8c1f3b), C(c8f1e5e206a21016), C(2aa554aed1ebb524),
C(f62bc412)},
{C(740428b4d45e5fb8), C(4c95a4ce922cb0a5), C(e99c3ba78feae796),
C(8975a436)},
{C(658b883b3a872b86), C(2f0e303f0f64827a), C(975337e23dc45e1), C(94ff7f41)},
{C(6df0a977da5d27d4), C(891dd0e7cb19508), C(fd65434a0b71e680), C(760aa031)},
{C(a900275464ae07ef), C(11f2cfda34beb4a3), C(9abf91e5a1c38e4), C(3bda76df)},
{C(810bc8aa0c40bcb0), C(448a019568d01441), C(f60ec52f60d3aeae),
C(498e2e65)},
{C(22036327deb59ed7), C(adc05ceb97026a02), C(48bff0654262672b),
C(d38deb48)},
{C(7d14dfa9772b00c8), C(595735efc7eeaed7), C(29872854f94c3507),
C(82b3fb6b)},
{C(2d777cddb912675d), C(278d7b10722a13f9), C(f5c02bfb7cc078af),
C(e500e25f)},
{C(f2ec98824e8aa613), C(5eb7e3fb53fe3bed), C(12c22860466e1dd4),
C(bd2bb07c)},
{C(5e763988e21f487f), C(24189de8065d8dc5), C(d1519d2403b62aa0),
C(3a2b431d)},
{C(48949dc327bb96ad), C(e1fd21636c5c50b4), C(3f6eb7f13a8712b4),
C(7322a83d)},
{C(b7c4209fb24a85c5), C(b35feb319c79ce10), C(f0d3de191833b922),
C(a645ca1c)},
{C(9c9e5be0943d4b05), C(b73dc69e45201cbb), C(aab17180bfe5083d),
C(8909a45a)},
{C(3898bca4dfd6638d), C(f911ff35efef0167), C(24bdf69e5091fc88),
C(bd30074c)},
{C(5b5d2557400e68e7), C(98d610033574cee), C(dfd08772ce385deb), C(c17cf001)},
{C(a927ed8b2bf09bb6), C(606e52f10ae94eca), C(71c2203feb35a9ee),
C(26ffd25a)},
{C(8d25746414aedf28), C(34b1629d28b33d3a), C(4d5394aea5f82d7b),
C(f1d8ce3c)},
{C(b5bbdb73458712f2), C(1ff887b3c2a35137), C(7f7231f702d0ace9),
C(3ee8fb17)},
{C(3d32a26e3ab9d254), C(fc4070574dc30d3a), C(f02629579c2b27c9),
C(a77acc2a)},
{C(9371d3c35fa5e9a5), C(42967cf4d01f30), C(652d1eeae704145c), C(f4556dee)},
{C(cbaa3cb8f64f54e0), C(76c3b48ee5c08417), C(9f7d24e87e61ce9), C(de287a64)},
{C(b2e23e8116c2ba9f), C(7e4d9c0060101151), C(3310da5e5028f367),
C(878e55b9)},
{C(8aa77f52d7868eb9), C(4d55bd587584e6e2), C(d2db37041f495f5), C(7648486)},
{C(858fea922c7fe0c3), C(cfe8326bf733bc6f), C(4e5e2018cf8f7dfc),
C(57ac0fb1)},
{C(46ef25fdec8392b1), C(e48d7b6d42a5cd35), C(56a6fe1c175299ca),
C(d01967ca)},
{C(8d078f726b2df464), C(b50ee71cdcabb299), C(f4af300106f9c7ba),
C(96ecdf74)},
{C(35ea86e6960ca950), C(34fe1fe234fc5c76), C(a00207a3dc2a72b7),
C(779f5506)},
{C(8aee9edbc15dd011), C(51f5839dc8462695), C(b2213e17c37dca2d),
C(3c94c2de)},
{C(c3e142ba98432dda), C(911d060cab126188), C(b753fbfa8365b844),
C(39f98faf)},
{C(123ba6b99c8cd8db), C(448e582672ee07c4), C(cebe379292db9e65),
C(7af31199)},
{C(ba87acef79d14f53), C(b3e0fcae63a11558), C(d5ac313a593a9f45),
C(e341a9d6)},
{C(bcd3957d5717dc3), C(2da746741b03a007), C(873816f4b1ece472), C(ca24aeeb)},
{C(61442ff55609168e), C(6447c5fc76e8c9cf), C(6a846de83ae15728),
C(b2252b57)},
{C(dbe4b1b2d174757f), C(506512da18712656), C(6857f3e0b8dd95f), C(72c81da1)},
{C(531e8e77b363161c), C(eece0b43e2dae030), C(8294b82c78f34ed1),
C(6b9fce95)},
{C(f71e9c926d711e2b), C(d77af2853a4ceaa1), C(9aa0d6d76a36fae7),
C(19399857)},
{C(cb20ac28f52df368), C(e6705ee7880996de), C(9b665cc3ec6972f2),
C(3c57a994)},
{C(e4a794b4acb94b55), C(89795358057b661b), C(9c4cdcec176d7a70),
C(c053e729)},
{C(cb942e91443e7208), C(e335de8125567c2a), C(d4d74d268b86df1f),
C(51cbbba7)},
{C(ecca7563c203f7ba), C(177ae2423ef34bb2), C(f60b7243400c5731),
C(1acde79a)},
{C(1652cb940177c8b5), C(8c4fe7d85d2a6d6d), C(f6216ad097e54e72),
C(2d160d13)},
{C(31fed0fc04c13ce8), C(3d5d03dbf7ff240a), C(727c5c9b51581203),
C(787f5801)},
{C(e7b668947590b9b3), C(baa41ad32938d3fa), C(abcbc8d4ca4b39e4),
C(c9629828)},
{C(1de2119923e8ef3c), C(6ab27c096cf2fe14), C(8c3658edca958891),
C(be139231)},
{C(1269df1e69e14fa7), C(992f9d58ac5041b7), C(e97fcf695a7cbbb4),
C(7df699ef)},
{C(820826d7aba567ff), C(1f73d28e036a52f3), C(41c4c5a73f3b0893),
C(8ce6b96d)},
{C(ffe0547e4923cef9), C(3534ed49b9da5b02), C(548a273700fba03d),
C(6f9ed99c)},
{C(72da8d1b11d8bc8b), C(ba94b56b91b681c6), C(4e8cc51bd9b0fc8c),
C(e0244796)},
{C(d62ab4e3f88fc797), C(ea86c7aeb6283ae4), C(b5b93e09a7fe465), C(4ccf7e75)},
{C(d0f06c28c7b36823), C(1008cb0874de4bb8), C(d6c7ff816c7a737b),
C(915cef86)},
{C(99b7042460d72ec6), C(2a53e5e2b8e795c2), C(53a78132d9e1b3e3),
C(5cb59482)},
{C(4f4dfcfc0ec2bae5), C(841233148268a1b8), C(9248a76ab8be0d3), C(6ca3f532)},
{C(fe86bf9d4422b9ae), C(ebce89c90641ef9c), C(1c84e2292c0b5659),
C(e24f3859)},
{C(a90d81060932dbb0), C(8acfaa88c5fbe92b), C(7c6f3447e90f7f3f),
C(adf5a9c7)},
{C(17938a1b0e7f5952), C(22cadd2f56f8a4be), C(84b0d1183d5ed7c1),
C(32264b75)},
{C(de9e0cb0e16f6e6d), C(238e6283aa4f6594), C(4fb9c914c2f0a13b),
C(a64b3376)},
{C(6d4b876d9b146d1a), C(aab2d64ce8f26739), C(d315f93600e83fe5), C(d33890e)},
{C(e698fa3f54e6ea22), C(bd28e20e7455358c), C(9ace161f6ea76e66),
C(926d4b63)},
{C(7bc0deed4fb349f7), C(1771aff25dc722fa), C(19ff0644d9681917),
C(d51ba539)},
{C(db4b15e88533f622), C(256d6d2419b41ce9), C(9d7c5378396765d5),
C(7f37636d)},
{C(922834735e86ecb2), C(363382685b88328e), C(e9c92960d7144630),
C(b98026c0)},
{C(30f1d72c812f1eb8), C(b567cd4a69cd8989), C(820b6c992a51f0bc),
C(b877767e)},
{C(168884267f3817e9), C(5b376e050f637645), C(1c18314abd34497a), C(aefae77)},
{C(82e78596ee3e56a7), C(25697d9c87f30d98), C(7600a8342834924d), C(f686911)},
{C(aa2d6cf22e3cc252), C(9b4dec4f5e179f16), C(76fb0fba1d99a99a),
C(3deadf12)},
{C(7bf5ffd7f69385c7), C(fc077b1d8bc82879), C(9c04e36f9ed83a24),
C(ccf02a4e)},
{C(e89c8ff9f9c6e34b), C(f54c0f669a49f6c4), C(fc3e46f5d846adef),
C(176c1722)},
{C(a18fbcdccd11e1f4), C(8248216751dfd65e), C(40c089f208d89d7c), C(26f82ad)},
{C(2d54f40cc4088b17), C(59d15633b0cd1399), C(a8cc04bb1bffd15b),
C(b5244f42)},
{C(69276946cb4e87c7), C(62bdbe6183be6fa9), C(3ba9773dac442a1a),
C(49a689e5)},
{C(668174a3f443df1d), C(407299392da1ce86), C(c2a3f7d7f2c5be28), C(59fcdd3)},
{C(5e29be847bd5046), C(b561c7f19c8f80c3), C(5e5abd5021ccaeaf), C(4f4b04e9)},
{C(cd0d79f2164da014), C(4c386bb5c5d6ca0c), C(8e771b03647c3b63),
C(8b00f891)},
{C(e0e6fc0b1628af1d), C(29be5fb4c27a2949), C(1c3f781a604d3630),
C(16e114f3)},
{C(2058927664adfd93), C(6e8f968c7963baa5), C(af3dced6fff7c394),
C(d6b6dadc)},
{C(dc107285fd8e1af7), C(a8641a0609321f3f), C(db06e89ffdc54466),
C(897e20ac)},
{C(fbba1afe2e3280f1), C(755a5f392f07fce), C(9e44a9a15402809a), C(f996e05d)},
{C(bfa10785ddc1011b), C(b6e1c4d2f670f7de), C(517d95604e4fcc1f),
C(c4306af6)},
{C(534cc35f0ee1eb4e), C(b703820f1f3b3dce), C(884aa164cf22363), C(6dcad433)},
{C(7ca6e3933995dac), C(fd118c77daa8188), C(3aceb7b5e7da6545), C(3c07374d)},
{C(f0d6044f6efd7598), C(e044d6ba4369856e), C(91968e4f8c8a1a4c),
C(f0f4602c)},
{C(3d69e52049879d61), C(76610636ea9f74fe), C(e9bf5602f89310c0),
C(3e1ea071)},
{C(79da242a16acae31), C(183c5f438e29d40), C(6d351710ae92f3de), C(67580f0c)},
{C(461c82656a74fb57), C(d84b491b275aa0f7), C(8f262cb29a6eb8b2),
C(4e109454)},
{C(53c1a66d0b13003), C(731f060e6fe797fc), C(daa56811791371e3), C(88a474a7)},
{C(d3a2efec0f047e9), C(1cabce58853e58ea), C(7a17b2eae3256be4), C(5b5bedd)},
{C(43c64d7484f7f9b2), C(5da002b64aafaeb7), C(b576c1e45800a716),
C(1aaddfa7)},
{C(a7dec6ad81cf7fa1), C(180c1ab708683063), C(95e0fd7008d67cff),
C(5be07fd8)},
{C(5408a1df99d4aff), C(b9565e588740f6bd), C(abf241813b08006e), C(cbca8606)},
{C(a8b27a6bcaeeed4b), C(aec1eeded6a87e39), C(9daf246d6fed8326),
C(bde64d01)},
{C(9a952a8246fdc269), C(d0dcfcac74ef278c), C(250f7139836f0f1f),
C(ee90cf33)},
{C(c930841d1d88684f), C(5eb66eb18b7f9672), C(e455d413008a2546),
C(4305c3ce)},
{C(94dc6971e3cf071a), C(994c7003b73b2b34), C(ea16e85978694e5), C(4b3a1d76)},
{C(7fc98006e25cac9), C(77fee0484cda86a7), C(376ec3d447060456), C(a8bb6d80)},
{C(bd781c4454103f6), C(612197322f49c931), C(b9cf17fd7e5462d5), C(1f9fa607)},
{C(da60e6b14479f9df), C(3bdccf69ece16792), C(18ebf45c4fecfdc9),
C(8d0e4ed2)},
{C(4ca56a348b6c4d3), C(60618537c3872514), C(2fbb9f0e65871b09), C(1bf31347)},
{C(ebd22d4b70946401), C(6863602bf7139017), C(c0b1ac4e11b00666),
C(1ae3fc5b)},
{C(3cc4693d6cbcb0c), C(501689ea1c70ffa), C(10a4353e9c89e364), C(459c3930)},
{C(38908e43f7ba5ef0), C(1ab035d4e7781e76), C(41d133e8c0a68ff7),
C(e00c4184)},
{C(34983ccc6aa40205), C(21802cad34e72bc4), C(1943e8fb3c17bb8), C(ffc7a781)},
{C(86215c45dcac9905), C(ea546afe851cae4b), C(d85b6457e489e374),
C(6a125480)},
{C(420fc255c38db175), C(d503cd0f3c1208d1), C(d4684e74c825a0bc),
C(88a1512b)},
{C(1d7a31f5bc8fe2f9), C(4763991092dcf836), C(ed695f55b97416f4),
C(549bbbe5)},
{C(94129a84c376a26e), C(c245e859dc231933), C(1b8f74fecf917453),
C(c133d38c)},
{C(1d3a9809dab05c8d), C(adddeb4f71c93e8), C(ef342eb36631edb), C(fcace348)},
{C(90fa3ccbd60848da), C(dfa6e0595b569e11), C(e585d067a1f5135d),
C(ed7b6f9a)},
{C(2dbb4fc71b554514), C(9650e04b86be0f82), C(60f2304fba9274d3),
C(6d907dda)},
{C(b98bf4274d18374a), C(1b669fd4c7f9a19a), C(b1f5972b88ba2b7a),
C(7a4d48d5)},
{C(d6781d0b5e18eb68), C(b992913cae09b533), C(58f6021caaee3a40),
C(e686f3db)},
{C(226651cf18f4884c), C(595052a874f0f51c), C(c9b75162b23bab42), C(cce7c55)},
{C(a734fb047d3162d6), C(e523170d240ba3a5), C(125a6972809730e8), C(f58b96b)},
{C(c6df6364a24f75a3), C(c294e2c84c4f5df8), C(a88df65c6a89313b),
C(1bbf6f60)},
{C(d8d1364c1fbcd10), C(2d7cc7f54832deaa), C(4e22c876a7c57625), C(ce5e0cc2)},
{C(aae06f9146db885f), C(3598736441e280d9), C(fba339b117083e55),
C(584cfd6f)},
{C(8955ef07631e3bcc), C(7d70965ea3926f83), C(39aed4134f8b2db6),
C(8f9bbc33)},
{C(ad611c609cfbe412), C(d3c00b18bf253877), C(90b2172e1f3d0bfd),
C(d7640d95)},
{C(d5339adc295d5d69), C(b633cc1dcb8b586a), C(ee84184cf5b1aeaf), C(3d12a2b)},
{C(40d0aeff521375a8), C(77ba1ad7ecebd506), C(547c6f1a7d9df427),
C(aaeafed0)},
{C(8b2d54ae1a3df769), C(11e7adaee3216679), C(3483781efc563e03),
C(95b9b814)},
{C(99c175819b4eae28), C(932e8ff9f7a40043), C(ec78dcab07ca9f7c),
C(45fbe66e)},
{C(2a418335779b82fc), C(af0295987849a76b), C(c12bc5ff0213f46e),
C(b4baa7a8)},
{C(3b1fc6a3d279e67d), C(70ea1e49c226396), C(25505adcf104697c), C(83e962fe)},
{C(d97eacdf10f1c3c9), C(b54f4654043a36e0), C(b128f6eb09d1234), C(aac3531c)},
{C(293a5c1c4e203cd4), C(6b3329f1c130cefe), C(f2e32f8ec76aac91),
C(2b1db7cc)},
{C(4290e018ffaedde7), C(a14948545418eb5e), C(72d851b202284636),
C(cf00cd31)},
{C(f919a59cbde8bf2f), C(a56d04203b2dc5a5), C(38b06753ac871e48),
C(7d3c43b8)},
{C(1d70a3f5521d7fa4), C(fb97b3fdc5891965), C(299d49bbbe3535af),
C(cbd5fac6)},
{C(6af98d7b656d0d7c), C(d2e99ae96d6b5c0c), C(f63bd1603ef80627),
C(76d0fec4)},
{C(395b7a8adb96ab75), C(582df7165b20f4a), C(e52bd30e9ff657f9), C(405e3402)},
{C(3822dd82c7df012f), C(b9029b40bd9f122b), C(fd25b988468266c4),
C(c732c481)},
{C(79f7efe4a80b951a), C(dd3a3fddfc6c9c41), C(ab4c812f9e27aa40),
C(a8d123c9)},
{C(ae6e59f5f055921a), C(e9d9b7bf68e82), C(5ce4e4a5b269cc59), C(1e80ad7d)},
{C(8959dbbf07387d36), C(b4658afce48ea35d), C(8f3f82437d8cb8d6),
C(52aeb863)},
{C(4739613234278a49), C(99ea5bcd340bf663), C(258640912e712b12),
C(ef7c0c18)},
{C(420e6c926bc54841), C(96dbbf6f4e7c75cd), C(d8d40fa70c3c67bb),
C(b6ad4b68)},
{C(c8601bab561bc1b7), C(72b26272a0ff869a), C(56fdfc986d6bc3c4),
C(c1e46b17)},
{C(b2d294931a0e20eb), C(284ffd9a0815bc38), C(1f8a103aac9bbe6), C(57b8df25)},
{C(7966f53c37b6c6d7), C(8e6abcfb3aa2b88f), C(7f2e5e0724e5f345),
C(e9fa36d6)},
{C(be9bb0abd03b7368), C(13bca93a3031be55), C(e864f4f52b55b472),
C(8f8daefc)},
{C(a08d128c5f1649be), C(a8166c3dbbe19aad), C(cb9f914f829ec62c), C(6e1bb7e)},
{C(7c386f0ffe0465ac), C(530419c9d843dbf3), C(7450e3a4f72b8d8c),
C(fd0076f0)},
{C(bb362094e7ef4f8), C(ff3c2a48966f9725), C(55152803acd4a7fe), C(899b17b6)},
{C(cd80dea24321eea4), C(52b4fdc8130c2b15), C(f3ea100b154bfb82),
C(e3e84e31)},
{C(d599a04125372c3a), C(313136c56a56f363), C(1e993c3677625832),
C(eef79b6b)},
{C(dbbf541e9dfda0a), C(1479fceb6db4f844), C(31ab576b59062534), C(868e3315)},
{C(c2ee3288be4fe2bf), C(c65d2f5ddf32b92), C(af6ecdf121ba5485), C(4639a426)},
{C(d86603ced1ed4730), C(f9de718aaada7709), C(db8b9755194c6535),
C(f3213646)},
{C(915263c671b28809), C(a815378e7ad762fd), C(abec6dc9b669f559),
C(17f148e9)},
{C(2b67cdd38c307a5e), C(cb1d45bb5c9fe1c), C(800baf2a02ec18ad), C(bfd94880)},
{C(2d107419073b9cd0), C(a96db0740cef8f54), C(ec41ee91b3ecdc1b),
C(bb1fa7f3)},
{C(f3e9487ec0e26dfc), C(1ab1f63224e837fa), C(119983bb5a8125d8), C(88816b1)},
{C(1160987c8fe86f7d), C(879e6db1481eb91b), C(d7dcb802bfe6885d),
C(5c2faeb3)},
{C(eab8112c560b967b), C(97f550b58e89dbae), C(846ed506d304051f),
C(51b5fc6f)},
{C(1addcf0386d35351), C(b5f436561f8f1484), C(85d38e22181c9bb1),
C(33d94752)},
{C(d445ba84bf803e09), C(1216c2497038f804), C(2293216ea2237207),
C(b0c92948)},
{C(37235a096a8be435), C(d9b73130493589c2), C(3b1024f59378d3be),
C(c7171590)},
{C(763ad6ea2fe1c99d), C(cf7af5368ac1e26b), C(4d5e451b3bb8d3d4),
C(240a67fb)},
{C(ea627fc84cd1b857), C(85e372494520071f), C(69ec61800845780b),
C(e1843cd5)},
{C(1f2ffd79f2cdc0c8), C(726a1bc31b337aaa), C(678b7f275ef96434),
C(fda1452b)},
{C(39a9e146ec4b3210), C(f63f75802a78b1ac), C(e2e22539c94741c3),
C(a2cad330)},
{C(74cba303e2dd9d6d), C(692699b83289fad1), C(dfb9aa7874678480),
C(53467e16)},
{C(4cbc2b73a43071e0), C(56c5db4c4ca4e0b7), C(1b275a162f46bd3d),
C(da14a8d0)},
{C(875638b9715d2221), C(d9ba0615c0c58740), C(616d4be2dfe825aa),
C(67333551)},
{C(fb686b2782994a8d), C(edee60693756bb48), C(e6bc3cae0ded2ef5),
C(a0ebd66e)},
{C(ab21d81a911e6723), C(4c31b07354852f59), C(835da384c9384744),
C(4b769593)},
{C(33d013cc0cd46ecf), C(3de726423aea122c), C(116af51117fe21a9),
C(6aa75624)},
{C(8ca92c7cd39fae5d), C(317e620e1bf20f1), C(4f0b33bf2194b97f), C(602a3f96)},
{C(fdde3b03f018f43e), C(38f932946c78660), C(c84084ce946851ee), C(cd183c4d)},
{C(9c8502050e9c9458), C(d6d2a1a69964beb9), C(1675766f480229b5),
C(960a4d07)},
{C(348176ca2fa2fdd2), C(3a89c514cc360c2d), C(9f90b8afb318d6d0),
C(9ae998c4)},
{C(4a3d3dfbbaea130b), C(4e221c920f61ed01), C(553fd6cd1304531f),
C(74e2179d)},
{C(b371f768cdf4edb9), C(bdef2ace6d2de0f0), C(e05b4100f7f1baec),
C(ee9bae25)},
{C(7a1d2e96934f61f), C(eb1760ae6af7d961), C(887eb0da063005df), C(b66edf10)},
{C(8be53d466d4728f2), C(86a5ac8e0d416640), C(984aa464cdb5c8bb),
C(d6209737)},
{C(829677eb03abf042), C(43cad004b6bc2c0), C(f2f224756803971a), C(b994a88)},
{C(754435bae3496fc), C(5707fc006f094dcf), C(8951c86ab19d8e40), C(a05d43c0)},
{C(fda9877ea8e3805f), C(31e868b6ffd521b7), C(b08c90681fb6a0fd),
C(c79f73a8)},
{C(2e36f523ca8f5eb5), C(8b22932f89b27513), C(331cd6ecbfadc1bb),
C(a490aff5)},
{C(21a378ef76828208), C(a5c13037fa841da2), C(506d22a53fbe9812),
C(dfad65b4)},
{C(ccdd5600054b16ca), C(f78846e84204cb7b), C(1f9faec82c24eac9), C(1d07dfb)},
{C(7854468f4e0cabd0), C(3a3f6b4f098d0692), C(ae2423ec7799d30d),
C(416df9a0)},
{C(7f88db5346d8f997), C(88eac9aacc653798), C(68a4d0295f8eefa1),
C(1f8fb9cc)},
{C(bb3fb5fb01d60fcf), C(1b7cc0847a215eb6), C(1246c994437990a1),
C(7abf48e3)},
{C(2e783e1761acd84d), C(39158042bac975a0), C(1cd21c5a8071188d),
C(dea4e3dd)},
{C(392058251cf22acc), C(944ec4475ead4620), C(b330a10b5cb94166),
C(c6064f22)},
{C(adf5c1e5d6419947), C(2a9747bc659d28aa), C(95c5b8cb1f5d62c), C(743bed9c)},
{C(6bc1db2c2bee5aba), C(e63b0ed635307398), C(7b2eca111f30dbbc),
C(fce254d5)},
{C(b00f898229efa508), C(83b7590ad7f6985c), C(2780e70a0592e41d),
C(e47ec9d1)},
{C(b56eb769ce0d9a8c), C(ce196117bfbcaf04), C(b26c3c3797d66165),
C(334a145c)},
{C(70c0637675b94150), C(259e1669305b0a15), C(46e1dd9fd387a58d),
C(adec1e3c)},
{C(74c0b8a6821faafe), C(abac39d7491370e7), C(faf0b2a48a4e6aed),
C(f6a9fbf8)},
{C(5fb5e48ac7b7fa4f), C(a96170f08f5acbc7), C(bbf5c63d4f52a1e5),
C(5398210c)},
};
void TestUnchanging(const uint64_t* expected, int offset, int len) {
EXPECT_EQ(expected[0], CityHash64(data + offset, len));
EXPECT_EQ(expected[3], CityHash32(data + offset, len));
EXPECT_EQ(expected[1], CityHash64WithSeed(data + offset, len, kSeed0));
EXPECT_EQ(expected[2],
CityHash64WithSeeds(data + offset, len, kSeed0, kSeed1));
}
TEST(CityHashTest, Unchanging) {
setup();
int i = 0;
for (; i < kTestSize - 1; i++) {
TestUnchanging(testdata[i], i * i, i);
}
TestUnchanging(testdata[i], 0, kDataSize);
}
}
}
ABSL_NAMESPACE_END
} |
2,582 | cpp | abseil/abseil-cpp | low_level_hash | absl/hash/internal/low_level_hash.cc | absl/hash/internal/low_level_hash_test.cc | #ifndef ABSL_HASH_INTERNAL_LOW_LEVEL_HASH_H_
#define ABSL_HASH_INTERNAL_LOW_LEVEL_HASH_H_
#include <stdint.h>
#include <stdlib.h>
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace hash_internal {
uint64_t LowLevelHash(const void* data, size_t len, uint64_t seed,
const uint64_t salt[5]);
uint64_t LowLevelHashLenGt16(const void* data, size_t len, uint64_t seed,
const uint64_t salt[5]);
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/hash/internal/low_level_hash.h"
#include <cstddef>
#include <cstdint>
#include "absl/base/internal/unaligned_access.h"
#include "absl/base/prefetch.h"
#include "absl/numeric/int128.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace hash_internal {
static uint64_t Mix(uint64_t v0, uint64_t v1) {
absl::uint128 p = v0;
p *= v1;
return absl::Uint128Low64(p) ^ absl::Uint128High64(p);
}
uint64_t LowLevelHashLenGt16(const void* data, size_t len, uint64_t seed,
const uint64_t salt[5]) {
PrefetchToLocalCache(data);
const uint8_t* ptr = static_cast<const uint8_t*>(data);
uint64_t starting_length = static_cast<uint64_t>(len);
const uint8_t* last_16_ptr = ptr + starting_length - 16;
uint64_t current_state = seed ^ salt[0];
if (len > 64) {
uint64_t duplicated_state0 = current_state;
uint64_t duplicated_state1 = current_state;
uint64_t duplicated_state2 = current_state;
do {
PrefetchToLocalCache(ptr + ABSL_CACHELINE_SIZE);
uint64_t a = absl::base_internal::UnalignedLoad64(ptr);
uint64_t b = absl::base_internal::UnalignedLoad64(ptr + 8);
uint64_t c = absl::base_internal::UnalignedLoad64(ptr + 16);
uint64_t d = absl::base_internal::UnalignedLoad64(ptr + 24);
uint64_t e = absl::base_internal::UnalignedLoad64(ptr + 32);
uint64_t f = absl::base_internal::UnalignedLoad64(ptr + 40);
uint64_t g = absl::base_internal::UnalignedLoad64(ptr + 48);
uint64_t h = absl::base_internal::UnalignedLoad64(ptr + 56);
current_state = Mix(a ^ salt[1], b ^ current_state);
duplicated_state0 = Mix(c ^ salt[2], d ^ duplicated_state0);
duplicated_state1 = Mix(e ^ salt[3], f ^ duplicated_state1);
duplicated_state2 = Mix(g ^ salt[4], h ^ duplicated_state2);
ptr += 64;
len -= 64;
} while (len > 64);
current_state = (current_state ^ duplicated_state0) ^
(duplicated_state1 + duplicated_state2);
}
if (len > 32) {
uint64_t a = absl::base_internal::UnalignedLoad64(ptr);
uint64_t b = absl::base_internal::UnalignedLoad64(ptr + 8);
uint64_t c = absl::base_internal::UnalignedLoad64(ptr + 16);
uint64_t d = absl::base_internal::UnalignedLoad64(ptr + 24);
uint64_t cs0 = Mix(a ^ salt[1], b ^ current_state);
uint64_t cs1 = Mix(c ^ salt[2], d ^ current_state);
current_state = cs0 ^ cs1;
ptr += 32;
len -= 32;
}
if (len > 16) {
uint64_t a = absl::base_internal::UnalignedLoad64(ptr);
uint64_t b = absl::base_internal::UnalignedLoad64(ptr + 8);
current_state = Mix(a ^ salt[1], b ^ current_state);
}
uint64_t a = absl::base_internal::UnalignedLoad64(last_16_ptr);
uint64_t b = absl::base_internal::UnalignedLoad64(last_16_ptr + 8);
return Mix(a ^ salt[1] ^ starting_length, b ^ current_state);
}
uint64_t LowLevelHash(const void* data, size_t len, uint64_t seed,
const uint64_t salt[5]) {
if (len > 16) return LowLevelHashLenGt16(data, len, seed, salt);
PrefetchToLocalCache(data);
const uint8_t* ptr = static_cast<const uint8_t*>(data);
uint64_t starting_length = static_cast<uint64_t>(len);
uint64_t current_state = seed ^ salt[0];
if (len == 0) return current_state;
uint64_t a = 0;
uint64_t b = 0;
if (len > 8) {
a = absl::base_internal::UnalignedLoad64(ptr);
b = absl::base_internal::UnalignedLoad64(ptr + len - 8);
} else if (len > 3) {
a = absl::base_internal::UnalignedLoad32(ptr);
b = absl::base_internal::UnalignedLoad32(ptr + len - 4);
} else {
a = static_cast<uint64_t>((ptr[0] << 8) | ptr[len - 1]);
b = static_cast<uint64_t>(ptr[len >> 1]);
}
return Mix(a ^ salt[1] ^ starting_length, b ^ current_state);
}
}
ABSL_NAMESPACE_END
} | #include "absl/hash/internal/low_level_hash.h"
#include <cinttypes>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/escaping.h"
#define UPDATE_GOLDEN 0
namespace {
static const uint64_t kSalt[5] = {0xa0761d6478bd642f, 0xe7037ed1a0b428dbl,
0x8ebc6af09c88c6e3, 0x589965cc75374cc3l,
0x1d8e4e27c47d124f};
TEST(LowLevelHashTest, VerifyGolden) {
constexpr size_t kNumGoldenOutputs = 134;
static struct {
absl::string_view base64_data;
uint64_t seed;
} cases[] = {
{"", uint64_t{0xec42b7ab404b8acb}},
{"ICAg", uint64_t{0}},
{"YWFhYQ==", uint64_t{0}},
{"AQID", uint64_t{0}},
{"AQIDBA==", uint64_t{0}},
{"dGhpcmRfcGFydHl8d3loYXNofDY0", uint64_t{0}},
{"Zw==", uint64_t{0xeeee074043a3ee0f}},
{"xmk=", uint64_t{0x857902089c393de}},
{"c1H/", uint64_t{0x993df040024ca3af}},
{"SuwpzQ==", uint64_t{0xc4e4c2acea740e96}},
{"uqvy++M=", uint64_t{0x6a214b3db872d0cf}},
{"RnzCVPgb", uint64_t{0x44343db6a89dba4d}},
{"6OeNdlouYw==", uint64_t{0x77b5d6d1ae1dd483}},
{"M5/JmmYyDbc=", uint64_t{0x89ab8ecb44d221f1}},
{"MVijWiVdBRdY", uint64_t{0x60244b17577ca81b}},
{"6V7Uq7LNxpu0VA==", uint64_t{0x59a08dcee0717067}},
{"EQ6CdEEhPdyHcOk=", uint64_t{0xf5f20db3ade57396}},
{"PqFB4fxnPgF+l+rc", uint64_t{0xbf8dee0751ad3efb}},
{"a5aPOFwq7LA7+zKvPA==", uint64_t{0x6b7a06b268d63e30}},
{"VOwY21wCGv5D+/qqOvs=", uint64_t{0xb8c37f0ae0f54c82}},
{"KdHmBTx8lHXYvmGJ+Vy7", uint64_t{0x9fcbed0c38e50eef}},
{"qJkPlbHr8bMF7/cA6aE65Q==", uint64_t{0x2af4bade1d8e3a1d}},
{"ygvL0EhHZL0fIx6oHHtkxRQ=", uint64_t{0x714e3aa912da2f2c}},
{"c1rFXkt5YztwZCQRngncqtSs", uint64_t{0xf5ee75e3cbb82c1c}},
{"8hsQrzszzeNQSEcVXLtvIhm6mw==", uint64_t{0x620e7007321b93b9}},
{"ffUL4RocfyP4KfikGxO1yk7omDI=", uint64_t{0xc08528cac2e551fc}},
{"OOB5TT00vF9Od/rLbAWshiErqhpV", uint64_t{0x6a1debf9cc3ad39}},
{"or5wtXM7BFzTNpSzr+Lw5J5PMhVJ/Q==", uint64_t{0x7e0a3c88111fc226}},
{"gk6pCHDUsoopVEiaCrzVDhioRKxb844=", uint64_t{0x1301fef15df39edb}},
{"TNctmwlC5QbEM6/No4R/La3UdkfeMhzs", uint64_t{0x64e181f3d5817ab}},
{"SsQw9iAjhWz7sgcE9OwLuSC6hsM+BfHs2Q==", uint64_t{0xafafc44961078ecb}},
{"ZzO3mVCj4xTT2TT3XqDyEKj2BZQBvrS8RHg=", uint64_t{0x4f7bb45549250094}},
{"+klp5iPQGtppan5MflEls0iEUzqU+zGZkDJX", uint64_t{0xa30061abaa2818c}},
{"RO6bvOnlJc8I9eniXlNgqtKy0IX6VNg16NRmgg==",
uint64_t{0xd902ee3e44a5705f}},
{"ZJjZqId1ZXBaij9igClE3nyliU5XWdNRrayGlYA=", uint64_t{0x316d36da516f583}},
{"7BfkhfGMDGbxfMB8uyL85GbaYQtjr2K8g7RpLzr/",
uint64_t{0x402d83f9f834f616}},
{"rycWk6wHH7htETQtje9PidS2YzXBx+Qkg2fY7ZYS7A==",
uint64_t{0x9c604164c016b72c}},
{"RTkC2OUK+J13CdGllsH0H5WqgspsSa6QzRZouqx6pvI=",
uint64_t{0x3f4507e01f9e73ba}},
{"tKjKmbLCNyrLCM9hycOAXm4DKNpM12oZ7dLTmUx5iwAi",
uint64_t{0xc3fe0d5be8d2c7c7}},
{"VprUGNH+5NnNRaORxgH/ySrZFQFDL+4VAodhfBNinmn8cg==",
uint64_t{0x531858a40bfa7ea1}},
{"gc1xZaY+q0nPcUvOOnWnT3bqfmT/geth/f7Dm2e/DemMfk4=",
uint64_t{0x86689478a7a7e8fa}},
{"Mr35fIxqx1ukPAL0su1yFuzzAU3wABCLZ8+ZUFsXn47UmAph",
uint64_t{0x4ec948b8e7f27288}},
{"A9G8pw2+m7+rDtWYAdbl8tb2fT7FFo4hLi2vAsa5Y8mKH3CX3g==",
uint64_t{0xce46c7213c10032}},
{"DFaJGishGwEHDdj9ixbCoaTjz9KS0phLNWHVVdFsM93CvPft3hM=",
uint64_t{0xf63e96ee6f32a8b6}},
{"7+Ugx+Kr3aRNgYgcUxru62YkTDt5Hqis+2po81hGBkcrJg4N0uuy",
uint64_t{0x1cfe85e65fc5225}},
{"H2w6O8BUKqu6Tvj2xxaecxEI2wRgIgqnTTG1WwOgDSINR13Nm4d4Vg==",
uint64_t{0x45c474f1cee1d2e8}},
{"1XBMnIbqD5jy65xTDaf6WtiwtdtQwv1dCVoqpeKj+7cTR1SaMWMyI04=",
uint64_t{0x6e024e14015f329c}},
{"znZbdXG2TSFrKHEuJc83gPncYpzXGbAebUpP0XxzH0rpe8BaMQ17nDbt",
uint64_t{0x760c40502103ae1c}},
{"ylu8Atu13j1StlcC1MRMJJXIl7USgDDS22HgVv0WQ8hx/8pNtaiKB17hCQ==",
uint64_t{0x17fd05c3c560c320}},
{"M6ZVVzsd7vAvbiACSYHioH/440dp4xG2mLlBnxgiqEvI/aIEGpD0Sf4VS0g=",
uint64_t{0x8b34200a6f8e90d9}},
{"li3oFSXLXI+ubUVGJ4blP6mNinGKLHWkvGruun85AhVn6iuMtocbZPVhqxzn",
uint64_t{0x6be89e50818bdf69}},
{"kFuQHuUCqBF3Tc3hO4dgdIp223ShaCoog48d5Do5zMqUXOh5XpGK1t5XtxnfGA==",
uint64_t{0xfb389773315b47d8}},
{"jWmOad0v0QhXVJd1OdGuBZtDYYS8wBVHlvOeTQx9ZZnm8wLEItPMeihj72E0nWY=",
uint64_t{0x4f2512a23f61efee}},
{"z+DHU52HaOQdW4JrZwDQAebEA6rm13Zg/9lPYA3txt3NjTBqFZlOMvTRnVzRbl23",
uint64_t{0x59ccd92fc16c6fda}},
{"MmBiGDfYeTayyJa/tVycg+rN7f9mPDFaDc+23j0TlW9094er0ADigsl4QX7V3gG/qw==",
uint64_t{0x25c5a7f5bd330919}},
{"774RK+9rOL4iFvs1q2qpo/JVc/I39buvNjqEFDtDvyoB0FXxPI2vXqOrk08VPfIHkmU=",
uint64_t{0x51df4174d34c97d7}},
{"+slatXiQ7/2lK0BkVUI1qzNxOOLP3I1iK6OfHaoxgqT63FpzbElwEXSwdsryq3UlHK0I",
uint64_t{0x80ce6d76f89cb57}},
{"64mVTbQ47dHjHlOHGS/hjJwr/"
"K2frCNpn87exOqMzNUVYiPKmhCbfS7vBUce5tO6Ec9osQ==",
uint64_t{0x20961c911965f684}},
{"fIsaG1r530SFrBqaDj1kqE0AJnvvK8MNEZbII2Yw1OK77v0V59xabIh0B5axaz/"
"+a2V5WpA=",
uint64_t{0x4e5b926ec83868e7}},
{"PGih0zDEOWCYGxuHGDFu9Ivbff/"
"iE7BNUq65tycTR2R76TerrXALRosnzaNYO5fjFhTi+CiS",
uint64_t{0x3927b30b922eecef}},
{"RnpA/"
"zJnEnnLjmICORByRVb9bCOgxF44p3VMiW10G7PvW7IhwsWajlP9kIwNA9FjAD2GoQHk2Q="
"=",
uint64_t{0xbd0291284a49b61c}},
{"qFklMceaTHqJpy2qavJE+EVBiNFOi6OxjOA3LeIcBop1K7w8xQi3TrDk+"
"BrWPRIbfprszSaPfrI=",
uint64_t{0x73a77c575bcc956}},
{"cLbfUtLl3EcQmITWoTskUR8da/VafRDYF/ylPYwk7/"
"zazk6ssyrzxMN3mmSyvrXR2yDGNZ3WDrTT",
uint64_t{0x766a0e2ade6d09a6}},
{"s/"
"Jf1+"
"FbsbCpXWPTUSeWyMH6e4CvTFvPE5Fs6Z8hvFITGyr0dtukHzkI84oviVLxhM1xMxrMAy1db"
"w==",
uint64_t{0x2599f4f905115869}},
{"FvyQ00+j7nmYZVQ8hI1Edxd0AWplhTfWuFGiu34AK5X8u2hLX1bE97sZM0CmeLe+"
"7LgoUT1fJ/axybE=",
uint64_t{0xd8256e5444d21e53}},
{"L8ncxMaYLBH3g9buPu8hfpWZNlOF7nvWLNv9IozH07uQsIBWSKxoPy8+"
"LW4tTuzC6CIWbRGRRD1sQV/4",
uint64_t{0xf664a91333fb8dfd}},
{"CDK0meI07yrgV2kQlZZ+"
"wuVqhc2NmzqeLH7bmcA6kchsRWFPeVF5Wqjjaj556ABeUoUr3yBmfU3kWOakkg==",
uint64_t{0x9625b859be372cd1}},
{"d23/vc5ONh/"
"HkMiq+gYk4gaCNYyuFKwUkvn46t+dfVcKfBTYykr4kdvAPNXGYLjM4u1YkAEFpJP+"
"nX7eOvs=",
uint64_t{0x7b99940782e29898}},
{"NUR3SRxBkxTSbtQORJpu/GdR6b/h6sSGfsMj/KFd99ahbh+9r7LSgSGmkGVB/"
"mGoT0pnMTQst7Lv2q6QN6Vm",
uint64_t{0x4fe12fa5383b51a8}},
{"2BOFlcI3Z0RYDtS9T9Ie9yJoXlOdigpPeeT+CRujb/"
"O39Ih5LPC9hP6RQk1kYESGyaLZZi3jtabHs7DiVx/VDg==",
uint64_t{0xe2ccb09ac0f5b4b6}},
{"FF2HQE1FxEvWBpg6Z9zAMH+Zlqx8S1JD/"
"wIlViL6ZDZY63alMDrxB0GJQahmAtjlm26RGLnjW7jmgQ4Ie3I+014=",
uint64_t{0x7d0a37adbd7b753b}},
{"tHmO7mqVL/PX11nZrz50Hc+M17Poj5lpnqHkEN+4bpMx/"
"YGbkrGOaYjoQjgmt1X2QyypK7xClFrjeWrCMdlVYtbW",
uint64_t{0xd3ae96ef9f7185f2}},
{"/WiHi9IQcxRImsudkA/KOTqGe8/"
"gXkhKIHkjddv5S9hi02M049dIK3EUyAEjkjpdGLUs+BN0QzPtZqjIYPOgwsYE9g==",
uint64_t{0x4fb88ea63f79a0d8}},
{"qds+1ExSnU11L4fTSDz/QE90g4Jh6ioqSh3KDOTOAo2pQGL1k/"
"9CCC7J23YF27dUTzrWsCQA2m4epXoCc3yPHb3xElA=",
uint64_t{0xed564e259bb5ebe9}},
{"8FVYHx40lSQPTHheh08Oq0/"
"pGm2OlG8BEf8ezvAxHuGGdgCkqpXIueJBF2mQJhTfDy5NncO8ntS7vaKs7sCNdDaNGOEi",
uint64_t{0x3e3256b60c428000}},
{"4ZoEIrJtstiCkeew3oRzmyJHVt/pAs2pj0HgHFrBPztbQ10NsQ/"
"lM6DM439QVxpznnBSiHMgMQJhER+70l72LqFTO1JiIQ==",
uint64_t{0xfb05bad59ec8705}},
{"hQPtaYI+wJyxXgwD5n8jGIKFKaFA/"
"P83KqCKZfPthnjwdOFysqEOYwAaZuaaiv4cDyi9TyS8hk5cEbNP/jrI7q6pYGBLbsM=",
uint64_t{0xafdc251dbf97b5f8}},
{"S4gpMSKzMD7CWPsSfLeYyhSpfWOntyuVZdX1xSBjiGvsspwOZcxNKCRIOqAA0moUfOh3I5+"
"juQV4rsqYElMD/gWfDGpsWZKQ",
uint64_t{0x10ec9c92ddb5dcbc}},
{"oswxop+"
"bthuDLT4j0PcoSKby4LhF47ZKg8K17xxHf74UsGCzTBbOz0MM8hQEGlyqDT1iUiAYnaPaUp"
"L2mRK0rcIUYA4qLt5uOw==",
uint64_t{0x9a767d5822c7dac4}},
{"0II/"
"697p+"
"BtLSjxj5989OXI004TogEb94VUnDzOVSgMXie72cuYRvTFNIBgtXlKfkiUjeqVpd4a+"
"n5bxNOD1TGrjQtzKU5r7obo=",
uint64_t{0xee46254080d6e2db}},
{"E84YZW2qipAlMPmctrg7TKlwLZ68l4L+c0xRDUfyyFrA4MAti0q9sHq3TDFviH0Y+"
"Kq3tEE5srWFA8LM9oomtmvm5PYxoaarWPLc",
uint64_t{0xbbb669588d8bf398}},
{"x3pa4HIElyZG0Nj7Vdy9IdJIR4izLmypXw5PCmZB5y68QQ4uRaVVi3UthsoJROvbjDJkP2D"
"Q6L/eN8pFeLFzNPKBYzcmuMOb5Ull7w==",
uint64_t{0xdc2afaa529beef44}},
{"jVDKGYIuWOP/"
"QKLdd2wi8B2VJA8Wh0c8PwrXJVM8FOGM3voPDVPyDJOU6QsBDPseoR8uuKd19OZ/"
"zAvSCB+zlf6upAsBlheUKgCfKww=",
uint64_t{0xf1f67391d45013a8}},
{"mkquunhmYe1aR2wmUz4vcvLEcKBoe6H+kjUok9VUn2+eTSkWs4oDDtJvNCWtY5efJwg/"
"j4PgjRYWtqnrCkhaqJaEvkkOwVfgMIwF3e+d",
uint64_t{0x16fce2b8c65a3429}},
{"fRelvKYonTQ+s+rnnvQw+JzGfFoPixtna0vzcSjiDqX5s2Kg2
"UGrK+AVCyMUhO98WoB1DDbrsOYSw2QzrcPe0+3ck9sePvb+Q/IRaHbw==",
uint64_t{0xf4b096699f49fe67}},
{"DUwXFJzagljo44QeJ7/"
"6ZKw4QXV18lhkYT2jglMr8WB3CHUU4vdsytvw6AKv42ZcG6fRkZkq9fpnmXy6xG0aO3WPT1"
"eHuyFirAlkW+zKtwg=",
uint64_t{0xca584c4bc8198682}},
{"cYmZCrOOBBongNTr7e4nYn52uQUy2mfe48s50JXx2AZ6cRAt/"
"xRHJ5QbEoEJOeOHsJyM4nbzwFm++SlT6gFZZHJpkXJ92JkR86uS/eV1hJUR",
uint64_t{0xed269fc3818b6aad}},
{"EXeHBDfhwzAKFhsMcH9+2RHwV+mJaN01+9oacF6vgm8mCXRd6jeN9U2oAb0of5c5cO4i+"
"Vb/LlHZSMI490SnHU0bejhSCC2gsC5d2K30ER3iNA==",
uint64_t{0x33f253cbb8fe66a8}},
{"FzkzRYoNjkxFhZDso94IHRZaJUP61nFYrh5MwDwv9FNoJ5jyNCY/"
"eazPZk+tbmzDyJIGw2h3GxaWZ9bSlsol/vK98SbkMKCQ/wbfrXRLcDzdd/8=",
uint64_t{0xd0b76b2c1523d99c}},
{"Re4aXISCMlYY/XsX7zkIFR04ta03u4zkL9dVbLXMa/q6hlY/CImVIIYRN3VKP4pnd0AUr/"
"ugkyt36JcstAInb4h9rpAGQ7GMVOgBniiMBZ/MGU7H",
uint64_t{0xfd28f0811a2a237f}},
{"ueLyMcqJXX+MhO4UApylCN9WlTQ+"
"ltJmItgG7vFUtqs2qNwBMjmAvr5u0sAKd8jpzV0dDPTwchbIeAW5zbtkA2NABJV6hFM48ib"
"4/J3A5mseA3cS8w==",
uint64_t{0x6261fb136482e84}},
{"6Si7Yi11L+jZMkwaN+GUuzXMrlvEqviEkGOilNq0h8TdQyYKuFXzkYc/"
"q74gP3pVCyiwz9KpVGMM9vfnq36riMHRknkmhQutxLZs5fbmOgEO69HglCU=",
uint64_t{0x458efc750bca7c3a}},
{"Q6AbOofGuTJOegPh9Clm/"
"9crtUMQqylKrTc1fhfJo1tqvpXxhU4k08kntL1RG7woRnFrVh2UoMrL1kjin+s9CanT+"
"y4hHwLqRranl9FjvxfVKm3yvg68",
uint64_t{0xa7e69ff84e5e7c27}},
{"ieQEbIPvqY2YfIjHnqfJiO1/MIVRk0RoaG/WWi3kFrfIGiNLCczYoklgaecHMm/"
"1sZ96AjO+a5stQfZbJQwS7Sc1ODABEdJKcTsxeW2hbh9A6CFzpowP1A==",
uint64_t{0x3c59bfd0c29efe9e}},
{"zQUv8hFB3zh2GGl3KTvCmnfzE+"
"SUgQPVaSVIELFX5H9cE3FuVFGmymkPQZJLAyzC90Cmi8GqYCvPqTuAAB
"XTJxy4bCcVArgZG9zJXpjowpNBfr3ngWrSE=",
uint64_t{0x10befacc6afd298d}},
{"US4hcC1+op5JKGC7eIs8CUgInjKWKlvKQkapulxW262E/"
"B2ye79QxOexf188u2mFwwe3WTISJHRZzS61IwljqAWAWoBAqkUnW8SHmIDwHUP31J0p5sGd"
"P47L",
uint64_t{0x41d5320b0a38efa7}},
{"9bHUWFna2LNaGF6fQLlkx1Hkt24nrkLE2CmFdWgTQV3FFbUe747SSqYw6ebpTa07MWSpWRP"
"sHesVo2B9tqHbe7eQmqYebPDFnNqrhSdZwFm9arLQVs+7a3Ic6A==",
uint64_t{0x58db1c7450fe17f3}},
{"Kb3DpHRUPhtyqgs3RuXjzA08jGb59hjKTOeFt1qhoINfYyfTt2buKhD6YVffRCPsgK9SeqZ"
"qRPJSyaqsa0ovyq1WnWW8jI/NhvAkZTVHUrX2pC+cD3OPYT05Dag=",
uint64_t{0x6098c055a335b7a6}},
{"gzxyMJIPlU+bJBwhFUCHSofZ/"
"319LxqMoqnt3+L6h2U2+ZXJCSsYpE80xmR0Ta77Jq54o92SMH87HV8dGOaCTuAYF+"
"lDL42SY1P316Cl0sZTS2ow3ZqwGbcPNs/1",
uint64_t{0x1bbacec67845a801}},
{"uR7V0TW+FGVMpsifnaBAQ3IGlr1wx5sKd7TChuqRe6OvUXTlD4hKWy8S+"
"8yyOw8lQabism19vOQxfmocEOW/"
"vzY0pEa87qHrAZy4s9fH2Bltu8vaOIe+agYohhYORQ==",
uint64_t{0xc419cfc7442190}},
{"1UR5eoo2aCwhacjZHaCh9bkOsITp6QunUxHQ2SfeHv0imHetzt/"
"Z70mhyWZBalv6eAx+YfWKCUib2SHDtz/"
"A2dc3hqUWX5VfAV7FQsghPUAtu6IiRatq4YSLpDvKZBQ=",
uint64_t{0xc95e510d94ba270c}},
{"opubR7H63BH7OtY+Avd7QyQ25UZ8kLBdFDsBTwZlY6gA/"
"u+x+"
"czC9AaZMgmQrUy15DH7YMGsvdXnviTtI4eVI4aF1H9Rl3NXMKZgwFOsdTfdcZeeHVRzBBKX"
"8jUfh1il",
uint64_t{0xff1ae05c98089c3f}},
{"DC0kXcSXtfQ9FbSRwirIn5tgPri0sbzHSa78aDZVDUKCMaBGyFU6BmrulywYX8yzvwprdLs"
"oOwTWN2wMjHlPDqrvVHNEjnmufRDblW+nSS+xtKNs3N5xsxXdv6JXDrAB/Q==",
uint64_t{0x90c02b8dceced493}},
{"BXRBk+3wEP3Lpm1y75wjoz+PgB0AMzLe8tQ1AYU2/"
"oqrQB2YMC6W+9QDbcOfkGbeH+b7IBkt/"
"gwCMw2HaQsRFEsurXtcQ3YwRuPz5XNaw5NAvrNa67Fm7eRzdE1+hWLKtA8=",
uint64_t{0x9f8a76697ab1aa36}},
{"RRBSvEGYnzR9E45Aps/+WSnpCo/X7gJLO4DRnUqFrJCV/kzWlusLE/"
"6ZU6RoUf2ROwcgEvUiXTGjLs7ts3t9SXnJHxC1KiOzxHdYLMhVvgNd3hVSAXODpKFSkVXND"
"55G2L1W",
uint64_t{0x6ba1bf3d811a531d}},
{"jeh6Qazxmdi57pa9S3XSnnZFIRrnc6s8QLrah5OX3SB/V2ErSPoEAumavzQPkdKF1/"
"SfvmdL+qgF1C+Yawy562QaFqwVGq7+tW0yxP8FStb56ZRgNI4IOmI30s1Ei7iops9Uuw==",
uint64_t{0x6a418974109c67b4}},
{"6QO5nnDrY2/"
"wrUXpltlKy2dSBcmK15fOY092CR7KxAjNfaY+"
"aAmtWbbzQk3MjBg03x39afSUN1fkrWACdyQKRaGxgwq6MGNxI6W+8DLWJBHzIXrntrE/"
"ml6fnNXEpxplWJ1vEs4=",
uint64_t{0x8472f1c2b3d230a3}},
{"0oPxeEHhqhcFuwonNfLd5jF3RNATGZS6NPoS0WklnzyokbTqcl4BeBkMn07+fDQv83j/"
"BpGUwcWO05f3+DYzocfnizpFjLJemFGsls3gxcBYxcbqWYev51tG3lN9EvRE+X9+Pwww",
uint64_t{0x5e06068f884e73a7}},
{"naSBSjtOKgAOg8XVbR5cHAW3Y+QL4Pb/JO9/"
"oy6L08wvVRZqo0BrssMwhzBP401Um7A4ppAupbQeJFdMrysY34AuSSNvtNUy5VxjNECwiNt"
"gwYHw7yakDUv8WvonctmnoSPKENegQg==",
uint64_t{0x55290b1a8f170f59}},
{"vPyl8DxVeRe1OpilKb9KNwpGkQRtA94UpAHetNh+"
"95V7nIW38v7PpzhnTWIml5kw3So1Si0TXtIUPIbsu32BNhoH7QwFvLM+"
"JACgSpc5e3RjsL6Qwxxi11npwxRmRUqATDeMUfRAjxg=",
uint64_t{0x5501cfd83dfe706a}},
{"QC9i2GjdTMuNC1xQJ74ngKfrlA4w3o58FhvNCltdIpuMhHP1YsDA78scQPLbZ3OCUgeQguY"
"f/vw6zAaVKSgwtaykqg5ka/4vhz4hYqWU5ficdXqClHl+zkWEY26slCNYOM5nnDlly8Cj",
uint64_t{0xe43ed13d13a66990}},
{"7CNIgQhAHX27nxI0HeB5oUTnTdgKpRDYDKwRcXfSFGP1XeT9nQF6WKCMjL1tBV6x7KuJ91G"
"Zz11F4c+8s+MfqEAEpd4FHzamrMNjGcjCyrVtU6y+7HscMVzr7Q/"
"ODLcPEFztFnwjvCjmHw==",
uint64_t{0xdf43bc375cf5283f}},
{"Qa/hC2RPXhANSospe+gUaPfjdK/yhQvfm4cCV6/pdvCYWPv8p1kMtKOX3h5/"
"8oZ31fsmx4Axphu5qXJokuhZKkBUJueuMpxRyXpwSWz2wELx5glxF7CM0Fn+"
"OevnkhUn5jsPlG2r5jYlVn8=",
uint64_t{0x8112b806d288d7b5}},
{"kUw/0z4l3a89jTwN5jpG0SHY5km/"
"IVhTjgM5xCiPRLncg40aqWrJ5vcF891AOq5hEpSq0bUCJUMFXgct7kvnys905HjerV7Vs1G"
"y84tgVJ70/2+pAZTsB/PzNOE/G6sOj4+GbTzkQu819OLB",
uint64_t{0xd52a18abb001cb46}},
{"VDdfSDbO8Tdj3T5W0XM3EI7iHh5xpIutiM6dvcJ/fhe23V/srFEkDy5iZf/"
"VnA9kfi2C79ENnFnbOReeuZW1b3MUXB9lgC6U4pOTuC+"
"jHK3Qnpyiqzj7h3ISJSuo2pob7vY6VHZo6Fn7exEqHg==",
uint64_t{0xe12b76a2433a1236}},
{"Ldfvy3ORdquM/R2fIkhH/ONi69mcP1AEJ6n/"
"oropwecAsLJzQSgezSY8bEiEs0VnFTBBsW+RtZY6tDj03fnb3amNUOq1b7jbqyQkL9hpl+"
"2Z2J8IaVSeownWl+bQcsR5/xRktIMckC5AtF4YHfU=",
uint64_t{0x175bf7319cf1fa00}},
{"BrbNpb42+"
"VzZAjJw6QLirXzhweCVRfwlczzZ0VX2xluskwBqyfnGovz5EuX79JJ31VNXa5hTkAyQat3l"
"YKRADTdAdwE5PqM1N7YaMqqsqoAAAeuYVXuk5eWCykYmClNdSspegwgCuT+403JigBzi",
uint64_t{0xd63d57b3f67525ae}},
{"gB3NGHJJvVcuPyF0ZSvHwnWSIfmaI7La24VMPQVoIIWF7Z74NltPZZpx2f+cocESM+"
"ILzQW9p+BC8x5IWz7N4Str2WLGKMdgmaBfNkEhSHQDU0IJEOnpUt0HmjhFaBlx0/"
"LTmhua+rQ6Wup8ezLwfg==",
uint64_t{0x933faea858832b73}},
{"hTKHlRxx6Pl4gjG+6ksvvj0CWFicUg3WrPdSJypDpq91LUWRni2KF6+"
"81ZoHBFhEBrCdogKqeK+hy9bLDnx7g6rAFUjtn1+cWzQ2YjiOpz4+"
"ROBB7lnwjyTGWzJD1rXtlso1g2qVH8XJVigC5M9AIxM=",
uint64_t{0x53d061e5f8e7c04f}},
{"IWQBelSQnhrr0F3BhUpXUIDauhX6f95Qp+A0diFXiUK7irwPG1oqBiqHyK/SH/"
"9S+"
"rln9DlFROAmeFdH0OCJi2tFm4afxYzJTFR4HnR4cG4x12JqHaZLQx6iiu6CE3rtWBVz99oA"
"wCZUOEXIsLU24o2Y",
uint64_t{0xdb4124556dd515e0}},
{"TKo+l+"
"1dOXdLvIrFqeLaHdm0HZnbcdEgOoLVcGRiCbAMR0j5pIFw8D36tefckAS1RCFOH5IgP8yiF"
"T0Gd0a2hI3+"
"fTKA7iK96NekxWeoeqzJyctc6QsoiyBlkZerRxs5RplrxoeNg29kKDTM0K94mnhD9g==",
uint64_t{0x4fb31a0dd681ee71}},
{"YU4e7G6EfQYvxCFoCrrT0EFgVLHFfOWRTJQJ5gxM3G2b+"
"1kJf9YPrpsxF6Xr6nYtS8reEEbDoZJYqnlk9lXSkVArm88Cqn6d25VCx3+"
"49MqC0trIlXtb7SXUUhwpJK16T0hJUfPH7s5cMZXc6YmmbFuBNPE=",
uint64_t{0x27cc72eefa138e4c}},
{"/I/"
"eImMwPo1U6wekNFD1Jxjk9XQVi1D+"
"FPdqcHifYXQuP5aScNQfxMAmaPR2XhuOQhADV5tTVbBKwCDCX4E3jcDNHzCiPvViZF1W27t"
"xaf2BbFQdwKrNCmrtzcluBFYu0XZfc7RU1RmxK/RtnF1qHsq/O4pp",
uint64_t{0x44bc2dfba4bd3ced}},
{"CJTT9WGcY2XykTdo8KodRIA29qsqY0iHzWZRjKHb9alwyJ7RZAE3V5Juv4MY3MeYEr1EPCC"
"MxO7yFXqT8XA8YTjaMp3bafRt17Pw8JC4iKJ1zN+WWKOESrj+"
"3aluGQqn8z1EzqY4PH7rLG575PYeWsP98BugdA==",
uint64_t{0x242da1e3a439bed8}},
{"ZlhyQwLhXQyIUEnMH/"
"AEW27vh9xrbNKJxpWGtrEmKhd+nFqAfbeNBQjW0SfG1YI0xQkQMHXjuTt4P/"
"EpZRtA47ibZDVS8TtaxwyBjuIDwqcN09eCtpC+Ls+"
"vWDTLmBeDM3u4hmzz4DQAYsLiZYSJcldg9Q3wszw=",
uint64_t{0xdc559c746e35c139}},
{"v2KU8y0sCrBghmnm8lzGJlwo6D6ObccAxCf10heoDtYLosk4ztTpLlpSFEyu23MLA1tJkcg"
"Rko04h19QMG0mOw/"
"wc93EXAweriBqXfvdaP85sZABwiKO+6rtS9pacRVpYYhHJeVTQ5NzrvBvi1huxAr+"
"xswhVMfL",
uint64_t{0xd0b0350275b9989}},
{"QhKlnIS6BuVCTQsnoE67E/"
"yrgogE8EwO7xLaEGei26m0gEU4OksefJgppDh3X0x0Cs78Dr9IHK5b977CmZlrTRmwhlP8p"
"M+UzXPNRNIZuN3ntOum/QhUWP8SGpirheXENWsXMQ/"
"nxtxakyEtrNkKk471Oov9juP8oQ==",
uint64_t{0xb04489e41d17730c}},
{"/ZRMgnoRt+Uo6fUPr9FqQvKX7syhgVqWu+"
"WUSsiQ68UlN0efSP6Eced5gJZL6tg9gcYJIkhjuQNITU0Q3TjVAnAcobgbJikCn6qZ6pRxK"
"BY4MTiAlfGD3T7R7hwJwx554MAy++Zb/YUFlnCaCJiwQMnowF7aQzwYFCo=",
uint64_t{0x2217285eb4572156}},
{"NB7tU5fNE8nI+SXGfipc7sRkhnSkUF1krjeo6k+8FITaAtdyz+"
"o7mONgXmGLulBPH9bEwyYhKNVY0L+njNQrZ9YC2aXsFD3PdZsxAFaBT3VXEzh+"
"NGBTjDASNL3mXyS8Yv1iThGfHoY7T4aR0NYGJ+k+pR6f+KrPC96M",
uint64_t{0x12c2e8e68aede73b}},
{"8T6wrqCtEO6/rwxF6lvMeyuigVOLwPipX/FULvwyu+1wa5sQGav/"
"2FsLHUVn6cGSi0LlFwLewGHPFJDLR0u4t7ZUyM
"x6da0sWgOa5hzDqjsVGmjxEHXiaXKW3i4iSZNuxoNbMQkIbVML+"
"DkYu9ND0O2swg4itGeVSzXA==",
uint64_t{0x4d612125bdc4fd00}},
{"Ntf1bMRdondtMv1CYr3G80iDJ4WSAlKy5H34XdGruQiCrnRGDBa+"
"eUi7vKp4gp3BBcVGl8eYSasVQQjn7MLvb3BjtXx6c/"
"bCL7JtpzQKaDnPr9GWRxpBXVxKREgMM7d8lm35EODv0w+"
"hQLfVSh8OGs7fsBb68nNWPLeeSOo=",
uint64_t{0x81826b553954464e}},
{"VsSAw72Ro6xks02kaiLuiTEIWBC5bgqr4WDnmP8vglXzAhixk7td926rm9jNimL+"
"kroPSygZ9gl63aF5DCPOACXmsbmhDrAQuUzoh9ZKhWgElLQsrqo1KIjWoZT5b5QfVUXY9lS"
"IBg3U75SqORoTPq7HalxxoIT5diWOcJQi",
uint64_t{0xc2e5d345dc0ddd2d}},
{"j+loZ+C87+"
"bJxNVebg94gU0mSLeDulcHs84tQT7BZM2rzDSLiCNxUedHr1ZWJ9ejTiBa0dqy2I2ABc++"
"xzOLcv+
"O6xO+XOBhOWAQ+IHJVHf7wZnDxIXB8AUHsnjEISKj7823biqXjyP3g==",
uint64_t{0x3da6830a9e32631e}},
{"f3LlpcPElMkspNtDq5xXyWU62erEaKn7RWKlo540gR6mZsNpK1czV/"
"sOmqaq8XAQLEn68LKj6/"
"cFkJukxRzCa4OF1a7cCAXYFp9+wZDu0bw4y63qbpjhdCl8GO6Z2lkcXy7KOzbPE01ukg7+"
"gN+7uKpoohgAhIwpAKQXmX5xtd0=",
uint64_t{0xc9ae5c8759b4877a}},
};
#if defined(ABSL_IS_BIG_ENDIAN)
constexpr uint64_t kGolden[kNumGoldenOutputs] = {
0x4c34aacf38f6eee4, 0x88b1366815e50b88, 0x1a36bd0c6150fb9c,
0xa783aba8a67366c7, 0x5e4a92123ae874f2, 0x0cc9ecf27067ee9a,
0xbe77aa94940527f9, 0x7ea5c12f2669fe31, 0xa33eed8737d946b9,
0x310aec5b1340bb36, 0x354e400861c5d8ff, 0x15be98166adcf42f,
0xc51910b62a90ae51, 0x539d47fc7fdf6a1f, 0x3ebba9daa46eef93,
0xd96bcd3a9113c17f, 0xc78eaf6256ded15a, 0x98902ed321c2f0d9,
0x75a4ac96414b954a, 0x2cb90e00a39e307b, 0x46539574626c3637,
0x186ec89a2be3ff45, 0x972a3bf7531519d2, 0xa14df0d25922364b,
0xa351e19d22752109, 0x08bd311d8fed4f82, 0xea2b52ddc6af54f9,
0x5f20549941338336, 0xd43b07422dc2782e, 0x377c68e2acda4835,
0x1b31a0a663b1d7b3, 0x7388ba5d68058a1a, 0xe382794ea816f032,
0xd4c3fe7889276ee0, 0x2833030545582ea9, 0x554d32a55e55df32,
0x8d6d33d7e17b424d, 0xe51a193d03ae1e34, 0xabb6a80835bd66b3,
0x0e4ba5293f9ce9b7, 0x1ebd8642cb762cdf, 0xcb54b555850888ee,
0x1e4195e4717c701f, 0x6235a13937f6532a, 0xd460960741e845c0,
0x2a72168a2d6af7b1, 0x6be38fbbfc5b17de, 0x4ee97cffa0d0fb39,
0xfdf1119ad5e71a55, 0x0dff7f66b3070727, 0x812d791d6ed62744,
0x60962919074b70b8, 0x956fa5c7d6872547, 0xee892daa58aae597,
0xeeda546e998ee369, 0x454481f5eb9b1fa8, 0x1054394634c98b1b,
0x55bb425415f591fb, 0x9601fa97416232c4, 0xd7a18506519daad7,
0x90935cb5de039acf, 0xe64054c5146ed359, 0xe5b323fb1e866c09,
0x10a472555f5ba1bc, 0xe3c0cd57d26e0972, 0x7ca3db7c121da3e8,
0x7004a89c800bb466, 0x865f69c1a1ff7f39, 0xbe0edd48f0cf2b99,
0x10e5e4ba3cc400f5, 0xafc2b91a220eef50, 0x6f04a259289b24f1,
0x2179a8070e880ef0, 0xd6a9a3d023a740c2, 0x96e6d7954755d9b8,
0xc8e4bddecce5af9f, 0x93941f0fbc724c92, 0xbef5fb15bf76a479,
0x534dca8f5da86529, 0x70789790feec116b, 0x2a296e167eea1fe9,
0x54cb1efd2a3ec7ea, 0x357b43897dfeb9f7, 0xd1eda89bc7ff89d3,
0x434f2e10cbb83c98, 0xeec4cdac46ca69ce, 0xd46aafd52a303206,
0x4bf05968ff50a5c9, 0x71c533747a6292df, 0xa40bd0d16a36118c,
0x597b4ee310c395ab, 0xc5b3e3e386172583, 0x12ca0b32284e6c70,
0xb48995fadcf35630, 0x0646368454cd217d, 0xa21c168e40d765b5,
0x4260d3811337da30, 0xb72728a01cff78e4, 0x8586920947f4756f,
0xc21e5f853cae7dc1, 0xf08c9533be9de285, 0x72df06653b4256d6,
0xf7b7f937f8db1779, 0x976db27dd0418127, 0x9ce863b7bc3f9e00,
0xebb679854fcf3a0a, 0x2ccebabbcf1afa99, 0x44201d6be451dac5,
0xb4af71c0e9a537d1, 0xad8fe9bb33ed2681, 0xcb30128bb68df43b,
0x154d8328903e8d07, 0x5844276dabeabdff, 0xd99017d7d36d930b,
0xabb0b4774fb261ca, 0x0a43f075d62e67e0, 0x8df7b371355ada6b,
0xf4c7a40d06513dcf, 0x257a3615955a0372, 0x987ac410bba74c06,
0xa011a46f25a632a2, 0xa14384b963ddd995, 0xf51b6b8cf9d50ba7,
0x3acdb91ee3abf18d, 0x34e799be08920e8c, 0x8766748a31304b36,
0x0aa239d5d0092f2e, 0xadf473ed26628594, 0xc4094b798eb4b79b,
0xe04ee5f33cd130f4, 0x85045d098c341d46, 0xf936cdf115a890ec,
0x51d137b6d8d2eb4f, 0xd10738bb2fccc1ef,
};
#else
constexpr uint64_t kGolden[kNumGoldenOutputs] = {
0x4c34aacf38f6eee4, 0x88b1366815e50b88, 0x1a36bd0c6150fb9c,
0xa783aba8a67366c7, 0xbc89ebdc622314e4, 0x632bc3cfcc7544d8,
0xbe77aa94940527f9, 0x7ea5c12f2669fe31, 0xa33eed8737d946b9,
0x74d832ea11fd18ab, 0x49c0487486246cdc, 0x3fdd986c87ddb0a0,
0xac3fa52a64d7c09a, 0xbff0e330196e7ed2, 0x8c8138d3ad7d3cce,
0x968c7d4b48e93778, 0xa04c78d3a421f529, 0x8854bc9c3c3c0241,
0xcccfcdf5a41113fe, 0xe6fc63dc543d984d, 0x00a39ff89e903c05,
0xaf7e9da25f9a26f9, 0x6e269a13d01a43df, 0x846d2300ce2ecdf8,
0xe7ea8c8f08478260, 0x9a2db0d62f6232f3, 0x6f66c761d168c59f,
0x55f9feacaae82043, 0x518084043700f614, 0xb0c8cfc11bead99f,
0xe4a68fdab6359d80, 0x97b17caa8f92236e, 0x96edf5e8363643dc,
0x9b3fbcd8d5b254cd, 0x22a263621d9b3a8b, 0xde90bf6f81800a6d,
0x1b51cae38c2e9513, 0x689215b3c414ef21, 0x064dc85afae8f557,
0xa2f3a8b51f408378, 0x6907c197ec1f6a3b, 0xfe83a42ef5c1cf13,
0x9b8b1d8f7a20cc13, 0x1f1681d52ca895d0, 0xd7b1670bf28e0f96,
0xb32f20f82d8b038a, 0x6a61d030fb2f5253, 0x8eb2bb0bc29ebb39,
0x144f36f7a9eef95c, 0xe77aa47d29808d8c, 0xf14d34c1fc568bad,
0x9796dcd4383f3c73, 0xa2f685fc1be7225b, 0xf3791295b16068b1,
0xb6b8f63424618948, 0x8ac4fd587045db19, 0x7e2aec2c34feb72e,
0x72e135a6910ccbb1, 0x661ff16f3c904e6f, 0xdf92cf9d67ca092d,
0x98a9953d79722eef, 0xe0649ed2181d1707, 0xcd8b8478636a297b,
0x9516258709c8471b, 0xc703b675b51f4394, 0xdb740eae020139f3,
0x57d1499ac4212ff2, 0x355cc03713d43825, 0x0e71ac9b8b1e101e,
0x8029fa72258ff559, 0xa2159726b4c16a50, 0x04e61582fba43007,
0xdab25af835be8cce, 0x13510b1b184705ee, 0xabdbc9e53666fdeb,
0x94a788fcb8173cef, 0x750d5e031286e722, 0x02559e72f4f5b497,
0x7d6e0e5996a646fa, 0x66e871b73b014132, 0x2ec170083f8b784f,
0x34ac9540cfce3fd9, 0x75c5622c6aad1295, 0xf799a6bb2651acc1,
0x8f6bcd3145bdc452, 0xddd9d326eb584a04, 0x5411af1e3532f8dc,
0xeb34722f2ad0f509, 0x835bc952a82298cc, 0xeb3839ff60ea92ad,
0x70bddf1bcdc8a4bc, 0x4bfb3ee86fcde525, 0xc7b3b93b81dfa386,
0xe66db544d57997e8, 0xf68a1b83fd363187, 0xe9b99bec615b171b,
0x093fba04d04ad28a, 0xba6117ed4231a303, 0x594bef25f9d4e206,
0x0a8cba60578b8f67, 0x88f6c7ca10b06019, 0x32a74082aef17b08,
0xe758222f971e22df, 0x4af14ff4a593e51e, 0xdba651e16cb09044,
0x3f3ac837d181eaac, 0xa5589a3f89610c01, 0xd409a7c3a18d5643,
0x8a89444f82962f26, 0x22eb62a13b9771b9, 0xd3a617615256ddd8,
0x7089b990c4bba297, 0x7d752893783eac4f, 0x1f2fcbb79372c915,
0x67a4446b17eb9839, 0x70d11df5cae46788, 0x52621e1780b47d0f,
0xcf63b93a6e590ee6, 0xb6bc96b58ee064b8, 0x2587f8d635ca9c75,
0xc6bddd62ec5e5d01, 0x957398ad3009cdb7, 0x05b6890b20bcd0d3,
0xbe6e965ff837222e, 0x47383a87d2b04b1a, 0x7d42207e6d8d7950,
0x7e981ed12a7f4aa3, 0xdebb05b30769441a, 0xaac5d86f4ff76c49,
0x384f195ca3248331, 0xec4c4b855e909ca1, 0x6a7eeb5a657d73d5,
0x9efbebe2fa9c2791, 0x19e7fa0546900c4d,
};
#endif
#if UPDATE_GOLDEN
(void)kGolden;
for (size_t i = 0; i < kNumGoldenOutputs; ++i) {
std::string str;
ASSERT_TRUE(absl::Base64Unescape(cases[i].base64_data, &str));
uint64_t h = absl::hash_internal::LowLevelHash(str.data(), str.size(),
cases[i].seed, kSalt);
printf("0x%016" PRIx64 ", ", h);
if (i % 3 == 2) {
printf("\n");
}
}
printf("\n\n\n");
EXPECT_FALSE(true);
#else
for (size_t i = 0; i < kNumGoldenOutputs; ++i) {
SCOPED_TRACE(::testing::Message()
<< "i = " << i << "; input = " << cases[i].base64_data);
std::string str;
ASSERT_TRUE(absl::Base64Unescape(cases[i].base64_data, &str));
EXPECT_EQ(absl::hash_internal::LowLevelHash(str.data(), str.size(),
cases[i].seed, kSalt),
kGolden[i]);
}
#endif
}
} |
2,583 | cpp | abseil/abseil-cpp | hash | absl/hash/internal/hash.cc | absl/hash/hash_test.cc | #ifndef ABSL_HASH_INTERNAL_HASH_H_
#define ABSL_HASH_INTERNAL_HASH_H_
#ifdef __APPLE__
#include <Availability.h>
#include <TargetConditionals.h>
#endif
#include "absl/base/config.h"
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
#include <version>
#else
#include <ciso646>
#endif
#include <algorithm>
#include <array>
#include <bitset>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <deque>
#include <forward_list>
#include <functional>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "absl/base/internal/unaligned_access.h"
#include "absl/base/port.h"
#include "absl/container/fixed_array.h"
#include "absl/hash/internal/city.h"
#include "absl/hash/internal/low_level_hash.h"
#include "absl/meta/type_traits.h"
#include "absl/numeric/bits.h"
#include "absl/numeric/int128.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#include "absl/utility/utility.h"
#if defined(__cpp_lib_filesystem) && __cpp_lib_filesystem >= 201703L && \
!defined(_LIBCPP_HAS_NO_FILESYSTEM_LIBRARY)
#include <filesystem>
#endif
#ifdef ABSL_HAVE_STD_STRING_VIEW
#include <string_view>
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
class HashState;
namespace hash_internal {
constexpr size_t PiecewiseChunkSize() { return 1024; }
class PiecewiseCombiner {
public:
PiecewiseCombiner() : position_(0) {}
PiecewiseCombiner(const PiecewiseCombiner&) = delete;
PiecewiseCombiner& operator=(const PiecewiseCombiner&) = delete;
template <typename H>
H add_buffer(H state, const unsigned char* data, size_t size);
template <typename H>
H add_buffer(H state, const char* data, size_t size) {
return add_buffer(std::move(state),
reinterpret_cast<const unsigned char*>(data), size);
}
template <typename H>
H finalize(H state);
private:
unsigned char buf_[PiecewiseChunkSize()];
size_t position_;
};
template <typename T>
struct is_hashable;
template <typename H>
class HashStateBase {
public:
template <typename T, typename... Ts>
static H combine(H state, const T& value, const Ts&... values);
static H combine(H state) { return state; }
template <typename T>
static H combine_contiguous(H state, const T* data, size_t size);
template <typename I>
static H combine_unordered(H state, I begin, I end);
using AbslInternalPiecewiseCombiner = PiecewiseCombiner;
template <typename T>
using is_hashable = absl::hash_internal::is_hashable<T>;
private:
template <typename I>
struct CombineUnorderedCallback {
I begin;
I end;
template <typename InnerH, typename ElementStateConsumer>
void operator()(InnerH inner_state, ElementStateConsumer cb) {
for (; begin != end; ++begin) {
inner_state = H::combine(std::move(inner_state), *begin);
cb(inner_state);
}
}
};
};
template <typename T, typename Enable = void>
struct is_uniquely_represented : std::false_type {};
template <>
struct is_uniquely_represented<unsigned char> : std::true_type {};
template <typename Integral>
struct is_uniquely_represented<
Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>
: std::true_type {};
template <>
struct is_uniquely_represented<bool> : std::false_type {};
template <typename H, typename T>
H hash_bytes(H hash_state, const T& value) {
const unsigned char* start = reinterpret_cast<const unsigned char*>(&value);
return H::combine_contiguous(std::move(hash_state), start, sizeof(value));
}
template <typename H, typename B>
typename std::enable_if<std::is_same<B, bool>::value, H>::type AbslHashValue(
H hash_state, B value) {
return H::combine(std::move(hash_state),
static_cast<unsigned char>(value ? 1 : 0));
}
template <typename H, typename Enum>
typename std::enable_if<std::is_enum<Enum>::value, H>::type AbslHashValue(
H hash_state, Enum e) {
return H::combine(std::move(hash_state),
static_cast<typename std::underlying_type<Enum>::type>(e));
}
template <typename H, typename Float>
typename std::enable_if<std::is_same<Float, float>::value ||
std::is_same<Float, double>::value,
H>::type
AbslHashValue(H hash_state, Float value) {
return hash_internal::hash_bytes(std::move(hash_state),
value == 0 ? 0 : value);
}
template <typename H, typename LongDouble>
typename std::enable_if<std::is_same<LongDouble, long double>::value, H>::type
AbslHashValue(H hash_state, LongDouble value) {
const int category = std::fpclassify(value);
switch (category) {
case FP_INFINITE:
hash_state = H::combine(std::move(hash_state), std::signbit(value));
break;
case FP_NAN:
case FP_ZERO:
default:
break;
case FP_NORMAL:
case FP_SUBNORMAL:
int exp;
auto mantissa = static_cast<double>(std::frexp(value, &exp));
hash_state = H::combine(std::move(hash_state), mantissa, exp);
}
return H::combine(std::move(hash_state), category);
}
template <typename H, typename T, size_t N>
H AbslHashValue(H hash_state, T (&)[N]) {
static_assert(
sizeof(T) == -1,
"Hashing C arrays is not allowed. For string literals, wrap the literal "
"in absl::string_view(). To hash the array contents, use "
"absl::MakeSpan() or make the array an std::array. To hash the array "
"address, use &array[0].");
return hash_state;
}
template <typename H, typename T>
std::enable_if_t<std::is_pointer<T>::value, H> AbslHashValue(H hash_state,
T ptr) {
auto v = reinterpret_cast<uintptr_t>(ptr);
return H::combine(std::move(hash_state), v, v);
}
template <typename H>
H AbslHashValue(H hash_state, std::nullptr_t) {
return H::combine(std::move(hash_state), static_cast<void*>(nullptr));
}
template <typename H, typename T, typename C>
H AbslHashValue(H hash_state, T C::*ptr) {
auto salient_ptm_size = [](std::size_t n) -> std::size_t {
#if defined(_MSC_VER)
if (alignof(T C::*) == alignof(int)) {
return n;
} else {
return n == 24 ? 20 : n == 16 ? 12 : n;
}
#else
#ifdef __cpp_lib_has_unique_object_representations
static_assert(std::has_unique_object_representations<T C::*>::value);
#endif
return n;
#endif
};
return H::combine_contiguous(std::move(hash_state),
reinterpret_cast<unsigned char*>(&ptr),
salient_ptm_size(sizeof ptr));
}
template <typename H, typename T1, typename T2>
typename std::enable_if<is_hashable<T1>::value && is_hashable<T2>::value,
H>::type
AbslHashValue(H hash_state, const std::pair<T1, T2>& p) {
return H::combine(std::move(hash_state), p.first, p.second);
}
template <typename H, typename Tuple, size_t... Is>
H hash_tuple(H hash_state, const Tuple& t, absl::index_sequence<Is...>) {
return H::combine(std::move(hash_state), std::get<Is>(t)...);
}
template <typename H, typename... Ts>
#if defined(_MSC_VER)
H
#else
typename std::enable_if<absl::conjunction<is_hashable<Ts>...>::value, H>::type
#endif
AbslHashValue(H hash_state, const std::tuple<Ts...>& t) {
return hash_internal::hash_tuple(std::move(hash_state), t,
absl::make_index_sequence<sizeof...(Ts)>());
}
template <typename H, typename T, typename D>
H AbslHashValue(H hash_state, const std::unique_ptr<T, D>& ptr) {
return H::combine(std::move(hash_state), ptr.get());
}
template <typename H, typename T>
H AbslHashValue(H hash_state, const std::shared_ptr<T>& ptr) {
return H::combine(std::move(hash_state), ptr.get());
}
template <typename H>
H AbslHashValue(H hash_state, absl::string_view str) {
return H::combine(
H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
str.size());
}
template <typename Char, typename Alloc, typename H,
typename = absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
std::is_same<Char, char16_t>::value ||
std::is_same<Char, char32_t>::value>>
H AbslHashValue(
H hash_state,
const std::basic_string<Char, std::char_traits<Char>, Alloc>& str) {
return H::combine(
H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
str.size());
}
#ifdef ABSL_HAVE_STD_STRING_VIEW
template <typename Char, typename H,
typename = absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
std::is_same<Char, char16_t>::value ||
std::is_same<Char, char32_t>::value>>
H AbslHashValue(H hash_state, std::basic_string_view<Char> str) {
return H::combine(
H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
str.size());
}
#endif
#if defined(__cpp_lib_filesystem) && __cpp_lib_filesystem >= 201703L && \
!defined(_LIBCPP_HAS_NO_FILESYSTEM_LIBRARY) && \
(!defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) || \
__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 130000) && \
(!defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) || \
__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101500)
#define ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE 1
template <typename Path, typename H,
typename = absl::enable_if_t<
std::is_same_v<Path, std::filesystem::path>>>
H AbslHashValue(H hash_state, const Path& path) {
return H::combine(std::move(hash_state), std::filesystem::hash_value(path));
}
#endif
template <typename H, typename T, size_t N>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::array<T, N>& array) {
return H::combine_contiguous(std::move(hash_state), array.data(),
array.size());
}
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::deque<T, Allocator>& deque) {
for (const auto& t : deque) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), deque.size());
}
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::forward_list<T, Allocator>& list) {
size_t size = 0;
for (const T& t : list) {
hash_state = H::combine(std::move(hash_state), t);
++size;
}
return H::combine(std::move(hash_state), size);
}
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
H hash_state, const std::list<T, Allocator>& list) {
for (const auto& t : list) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), list.size());
}
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value && !std::is_same<T, bool>::value,
H>::type
AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
return H::combine(H::combine_contiguous(std::move(hash_state), vector.data(),
vector.size()),
vector.size());
}
#if defined(ABSL_IS_BIG_ENDIAN) && \
(defined(__GLIBCXX__) || defined(__GLIBCPP__))
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
H>::type
AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
typename H::AbslInternalPiecewiseCombiner combiner;
for (const auto& i : vector) {
unsigned char c = static_cast<unsigned char>(i);
hash_state = combiner.add_buffer(std::move(hash_state), &c, sizeof(c));
}
return H::combine(combiner.finalize(std::move(hash_state)), vector.size());
}
#else
template <typename H, typename T, typename Allocator>
typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
H>::type
AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
return H::combine(std::move(hash_state),
std::hash<std::vector<T, Allocator>>{}(vector),
vector.size());
}
#endif
template <typename H, typename Key, typename T, typename Compare,
typename Allocator>
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
H>::type
AbslHashValue(H hash_state, const std::map<Key, T, Compare, Allocator>& map) {
for (const auto& t : map) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), map.size());
}
template <typename H, typename Key, typename T, typename Compare,
typename Allocator>
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
H>::type
AbslHashValue(H hash_state,
const std::multimap<Key, T, Compare, Allocator>& map) {
for (const auto& t : map) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), map.size());
}
template <typename H, typename Key, typename Compare, typename Allocator>
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
H hash_state, const std::set<Key, Compare, Allocator>& set) {
for (const auto& t : set) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), set.size());
}
template <typename H, typename Key, typename Compare, typename Allocator>
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
H hash_state, const std::multiset<Key, Compare, Allocator>& set) {
for (const auto& t : set) {
hash_state = H::combine(std::move(hash_state), t);
}
return H::combine(std::move(hash_state), set.size());
}
template <typename H, typename Key, typename Hash, typename KeyEqual,
typename Alloc>
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
H hash_state, const std::unordered_set<Key, Hash, KeyEqual, Alloc>& s) {
return H::combine(
H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
s.size());
}
template <typename H, typename Key, typename Hash, typename KeyEqual,
typename Alloc>
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
H hash_state,
const std::unordered_multiset<Key, Hash, KeyEqual, Alloc>& s) {
return H::combine(
H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
s.size());
}
template <typename H, typename Key, typename T, typename Hash,
typename KeyEqual, typename Alloc>
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
H>::type
AbslHashValue(H hash_state,
const std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& s) {
return H::combine(
H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
s.size());
}
template <typename H, typename Key, typename T, typename Hash,
typename KeyEqual, typename Alloc>
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
H>::type
AbslHashValue(H hash_state,
const std::unordered_multimap<Key, T, Hash, KeyEqual, Alloc>& s) {
return H::combine(
H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
s.size());
} | #include "absl/hash/hash.h"
#include <algorithm>
#include <array>
#include <bitset>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <ios>
#include <limits>
#include <memory>
#include <ostream>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/container/flat_hash_set.h"
#include "absl/hash/hash_testing.h"
#include "absl/hash/internal/hash_test.h"
#include "absl/hash/internal/spy_hash_state.h"
#include "absl/memory/memory.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/cord_test_helpers.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"
#ifdef ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE
#include <filesystem>
#endif
#ifdef ABSL_HAVE_STD_STRING_VIEW
#include <string_view>
#endif
namespace {
using ::absl::hash_test_internal::is_hashable;
using ::absl::hash_test_internal::TypeErasedContainer;
using ::absl::hash_test_internal::TypeErasedValue;
template <typename T>
using TypeErasedVector = TypeErasedContainer<std::vector<T>>;
using absl::Hash;
using absl::hash_internal::SpyHashState;
template <typename T>
class HashValueIntTest : public testing::Test {
};
TYPED_TEST_SUITE_P(HashValueIntTest);
template <typename T>
SpyHashState SpyHash(const T& value) {
return SpyHashState::combine(SpyHashState(), value);
}
TYPED_TEST_P(HashValueIntTest, BasicUsage) {
EXPECT_TRUE((is_hashable<TypeParam>::value));
TypeParam n = 42;
EXPECT_EQ(SpyHash(n), SpyHash(TypeParam{42}));
EXPECT_NE(SpyHash(n), SpyHash(TypeParam{0}));
EXPECT_NE(SpyHash(std::numeric_limits<TypeParam>::max()),
SpyHash(std::numeric_limits<TypeParam>::min()));
}
TYPED_TEST_P(HashValueIntTest, FastPath) {
TypeParam n = 42;
EXPECT_EQ(absl::Hash<TypeParam>{}(n),
absl::Hash<std::tuple<TypeParam>>{}(std::tuple<TypeParam>(n)));
}
REGISTER_TYPED_TEST_SUITE_P(HashValueIntTest, BasicUsage, FastPath);
using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t,
uint32_t, uint64_t, size_t>;
INSTANTIATE_TYPED_TEST_SUITE_P(My, HashValueIntTest, IntTypes);
enum LegacyEnum { kValue1, kValue2, kValue3 };
enum class EnumClass { kValue4, kValue5, kValue6 };
TEST(HashValueTest, EnumAndBool) {
EXPECT_TRUE((is_hashable<LegacyEnum>::value));
EXPECT_TRUE((is_hashable<EnumClass>::value));
EXPECT_TRUE((is_hashable<bool>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
LegacyEnum::kValue1, LegacyEnum::kValue2, LegacyEnum::kValue3)));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
EnumClass::kValue4, EnumClass::kValue5, EnumClass::kValue6)));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(true, false)));
}
TEST(HashValueTest, FloatingPoint) {
EXPECT_TRUE((is_hashable<float>::value));
EXPECT_TRUE((is_hashable<double>::value));
EXPECT_TRUE((is_hashable<long double>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(42.f, 0.f, -0.f, std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity())));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(42., 0., -0., std::numeric_limits<double>::infinity(),
-std::numeric_limits<double>::infinity())));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
.5L, 1.L, 2.L, 4.L, 42.L, 0.L, -0.L,
17 * static_cast<long double>(std::numeric_limits<double>::max()),
std::numeric_limits<long double>::infinity(),
-std::numeric_limits<long double>::infinity())));
}
TEST(HashValueTest, Pointer) {
EXPECT_TRUE((is_hashable<int*>::value));
EXPECT_TRUE((is_hashable<int(*)(char, float)>::value));
EXPECT_TRUE((is_hashable<void(*)(int, int, ...)>::value));
int i;
int* ptr = &i;
int* n = nullptr;
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(&i, ptr, nullptr, ptr + 1, n)));
}
TEST(HashValueTest, PointerAlignment) {
constexpr size_t kTotalSize = 1 << 20;
std::unique_ptr<char[]> data(new char[kTotalSize]);
constexpr size_t kLog2NumValues = 5;
constexpr size_t kNumValues = 1 << kLog2NumValues;
for (size_t align = 1; align < kTotalSize / kNumValues;
align < 8 ? align += 1 : align < 1024 ? align += 8 : align += 32) {
SCOPED_TRACE(align);
ASSERT_LE(align * kNumValues, kTotalSize);
size_t bits_or = 0;
size_t bits_and = ~size_t{};
for (size_t i = 0; i < kNumValues; ++i) {
size_t hash = absl::Hash<void*>()(data.get() + i * align);
bits_or |= hash;
bits_and &= hash;
}
constexpr size_t kMask = (1 << (kLog2NumValues + 7)) - 1;
size_t stuck_bits = (~bits_or | bits_and) & kMask;
EXPECT_EQ(stuck_bits, 0u) << "0x" << std::hex << stuck_bits;
}
}
TEST(HashValueTest, PointerToMember) {
struct Bass {
void q() {}
};
struct A : Bass {
virtual ~A() = default;
virtual void vfa() {}
static auto pq() -> void (A::*)() { return &A::q; }
};
struct B : Bass {
virtual ~B() = default;
virtual void vfb() {}
static auto pq() -> void (B::*)() { return &B::q; }
};
struct Foo : A, B {
void f1() {}
void f2() const {}
int g1() & { return 0; }
int g2() const & { return 0; }
int g3() && { return 0; }
int g4() const && { return 0; }
int h1() & { return 0; }
int h2() const & { return 0; }
int h3() && { return 0; }
int h4() const && { return 0; }
int a;
int b;
const int c = 11;
const int d = 22;
};
EXPECT_TRUE((is_hashable<float Foo::*>::value));
EXPECT_TRUE((is_hashable<double (Foo::*)(int, int)&&>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(&Foo::a, &Foo::b, static_cast<int Foo::*>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(&Foo::c, &Foo::d, static_cast<const int Foo::*>(nullptr),
&Foo::a, &Foo::b)));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
&Foo::f1, static_cast<void (Foo::*)()>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
&Foo::f2, static_cast<void (Foo::*)() const>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
&Foo::g1, &Foo::h1, static_cast<int (Foo::*)() &>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
&Foo::g2, &Foo::h2, static_cast<int (Foo::*)() const &>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
&Foo::g3, &Foo::h3, static_cast<int (Foo::*)() &&>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
&Foo::g4, &Foo::h4, static_cast<int (Foo::*)() const &&>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(static_cast<void (Foo::*)()>(&Foo::vfa),
static_cast<void (Foo::*)()>(&Foo::vfb),
static_cast<void (Foo::*)()>(nullptr))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(static_cast<void (Foo::*)()>(Foo::A::pq()),
static_cast<void (Foo::*)()>(Foo::B::pq()),
static_cast<void (Foo::*)()>(nullptr))));
}
TEST(HashValueTest, PairAndTuple) {
EXPECT_TRUE((is_hashable<std::pair<int, int>>::value));
EXPECT_TRUE((is_hashable<std::pair<const int&, const int&>>::value));
EXPECT_TRUE((is_hashable<std::tuple<int&, int&>>::value));
EXPECT_TRUE((is_hashable<std::tuple<int&&, int&&>>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::make_pair(0, 42), std::make_pair(0, 42), std::make_pair(42, 0),
std::make_pair(0, 0), std::make_pair(42, 42), std::make_pair(1, 42))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(std::make_tuple(0, 0, 0), std::make_tuple(0, 0, 42),
std::make_tuple(0, 23, 0), std::make_tuple(17, 0, 0),
std::make_tuple(42, 0, 0), std::make_tuple(3, 9, 9),
std::make_tuple(0, 0, -42))));
int a = 0, b = 1, c = 17, d = 23;
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::tie(a, a), std::tie(a, b), std::tie(b, c), std::tie(c, d))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::forward_as_tuple(0, 0, 0), std::forward_as_tuple(0, 0, 42),
std::forward_as_tuple(0, 23, 0), std::forward_as_tuple(17, 0, 0),
std::forward_as_tuple(42, 0, 0), std::forward_as_tuple(3, 9, 9),
std::forward_as_tuple(0, 0, -42))));
}
TEST(HashValueTest, CombineContiguousWorks) {
std::vector<std::tuple<int>> v1 = {std::make_tuple(1), std::make_tuple(3)};
std::vector<std::tuple<int>> v2 = {std::make_tuple(1), std::make_tuple(2)};
auto vh1 = SpyHash(v1);
auto vh2 = SpyHash(v2);
EXPECT_NE(vh1, vh2);
}
struct DummyDeleter {
template <typename T>
void operator() (T* ptr) {}
};
struct SmartPointerEq {
template <typename T, typename U>
bool operator()(const T& t, const U& u) const {
return GetPtr(t) == GetPtr(u);
}
template <typename T>
static auto GetPtr(const T& t) -> decltype(&*t) {
return t ? &*t : nullptr;
}
static std::nullptr_t GetPtr(std::nullptr_t) { return nullptr; }
};
TEST(HashValueTest, SmartPointers) {
EXPECT_TRUE((is_hashable<std::unique_ptr<int>>::value));
EXPECT_TRUE((is_hashable<std::unique_ptr<int, DummyDeleter>>::value));
EXPECT_TRUE((is_hashable<std::shared_ptr<int>>::value));
int i, j;
std::unique_ptr<int, DummyDeleter> unique1(&i);
std::unique_ptr<int, DummyDeleter> unique2(&i);
std::unique_ptr<int, DummyDeleter> unique_other(&j);
std::unique_ptr<int, DummyDeleter> unique_null;
std::shared_ptr<int> shared1(&i, DummyDeleter());
std::shared_ptr<int> shared2(&i, DummyDeleter());
std::shared_ptr<int> shared_other(&j, DummyDeleter());
std::shared_ptr<int> shared_null;
ASSERT_TRUE(SmartPointerEq{}(unique1, shared1));
ASSERT_FALSE(SmartPointerEq{}(unique1, shared_other));
ASSERT_TRUE(SmartPointerEq{}(unique_null, nullptr));
ASSERT_FALSE(SmartPointerEq{}(shared2, nullptr));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::forward_as_tuple(&i, nullptr,
unique1, unique2, unique_null,
absl::make_unique<int>(),
shared1, shared2, shared_null,
std::make_shared<int>()),
SmartPointerEq{}));
}
TEST(HashValueTest, FunctionPointer) {
using Func = int (*)();
EXPECT_TRUE(is_hashable<Func>::value);
Func p1 = [] { return 2; }, p2 = [] { return 1; };
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(p1, p2, nullptr)));
}
struct WrapInTuple {
template <typename T>
std::tuple<int, T, size_t> operator()(const T& t) const {
return std::make_tuple(7, t, 0xdeadbeef);
}
};
absl::Cord FlatCord(absl::string_view sv) {
absl::Cord c(sv);
c.Flatten();
return c;
}
absl::Cord FragmentedCord(absl::string_view sv) {
if (sv.size() < 2) {
return absl::Cord(sv);
}
size_t halfway = sv.size() / 2;
std::vector<absl::string_view> parts = {sv.substr(0, halfway),
sv.substr(halfway)};
return absl::MakeFragmentedCord(parts);
}
TEST(HashValueTest, Strings) {
EXPECT_TRUE((is_hashable<std::string>::value));
const std::string small = "foo";
const std::string dup = "foofoo";
const std::string large = std::string(2048, 'x');
const std::string huge = std::string(5000, 'a');
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::string(), absl::string_view(), absl::Cord(),
std::string(""), absl::string_view(""), absl::Cord(""),
std::string(small), absl::string_view(small), absl::Cord(small),
std::string(dup), absl::string_view(dup), absl::Cord(dup),
std::string(large), absl::string_view(large), absl::Cord(large),
std::string(huge), absl::string_view(huge), FlatCord(huge),
FragmentedCord(huge))));
const WrapInTuple t{};
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
t(std::string()), t(absl::string_view()), t(absl::Cord()),
t(std::string("")), t(absl::string_view("")), t(absl::Cord("")),
t(std::string(small)), t(absl::string_view(small)),
t(absl::Cord(small)),
t(std::string(dup)), t(absl::string_view(dup)), t(absl::Cord(dup)),
t(std::string(large)), t(absl::string_view(large)),
t(absl::Cord(large)),
t(std::string(huge)), t(absl::string_view(huge)),
t(FlatCord(huge)), t(FragmentedCord(huge)))));
EXPECT_NE(SpyHash(static_cast<const char*>("ABC")),
SpyHash(absl::string_view("ABC")));
}
TEST(HashValueTest, WString) {
EXPECT_TRUE((is_hashable<std::wstring>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::wstring(), std::wstring(L"ABC"), std::wstring(L"ABC"),
std::wstring(L"Some other different string"),
std::wstring(L"Iñtërnâtiônàlizætiøn"))));
}
TEST(HashValueTest, U16String) {
EXPECT_TRUE((is_hashable<std::u16string>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::u16string(), std::u16string(u"ABC"), std::u16string(u"ABC"),
std::u16string(u"Some other different string"),
std::u16string(u"Iñtërnâtiônàlizætiøn"))));
}
TEST(HashValueTest, U32String) {
EXPECT_TRUE((is_hashable<std::u32string>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::u32string(), std::u32string(U"ABC"), std::u32string(U"ABC"),
std::u32string(U"Some other different string"),
std::u32string(U"Iñtërnâtiônàlizætiøn"))));
}
TEST(HashValueTest, WStringView) {
#ifndef ABSL_HAVE_STD_STRING_VIEW
GTEST_SKIP();
#else
EXPECT_TRUE((is_hashable<std::wstring_view>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
std::wstring_view(), std::wstring_view(L"ABC"), std::wstring_view(L"ABC"),
std::wstring_view(L"Some other different string_view"),
std::wstring_view(L"Iñtërnâtiônàlizætiøn"))));
#endif
}
TEST(HashValueTest, U16StringView) {
#ifndef ABSL_HAVE_STD_STRING_VIEW
GTEST_SKIP();
#else
EXPECT_TRUE((is_hashable<std::u16string_view>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(std::u16string_view(), std::u16string_view(u"ABC"),
std::u16string_view(u"ABC"),
std::u16string_view(u"Some other different string_view"),
std::u16string_view(u"Iñtërnâtiônàlizætiøn"))));
#endif
}
TEST(HashValueTest, U32StringView) {
#ifndef ABSL_HAVE_STD_STRING_VIEW
GTEST_SKIP();
#else
EXPECT_TRUE((is_hashable<std::u32string_view>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(std::u32string_view(), std::u32string_view(U"ABC"),
std::u32string_view(U"ABC"),
std::u32string_view(U"Some other different string_view"),
std::u32string_view(U"Iñtërnâtiônàlizætiøn"))));
#endif
}
TEST(HashValueTest, StdFilesystemPath) {
#ifndef ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE
GTEST_SKIP() << "std::filesystem::path is unavailable on this platform";
#else
EXPECT_TRUE((is_hashable<std::filesystem::path>::value));
const auto kTestCases = std::make_tuple(
std::filesystem::path(),
std::filesystem::path("/"),
#ifndef __GLIBCXX__
std::filesystem::path("
#endif
std::filesystem::path("/a/b"),
std::filesystem::path("/a
std::filesystem::path("a/b"),
std::filesystem::path("a/b/"),
std::filesystem::path("a
std::filesystem::path("a
std::filesystem::path("c:/"),
std::filesystem::path("c:\\"),
std::filesystem::path("c:\\/"),
std::filesystem::path("c:\\
std::filesystem::path("c:
std::filesystem::path("c:
std::filesystem::path("/e/p"),
std::filesystem::path("/s/../e/p"),
std::filesystem::path("e/p"),
std::filesystem::path("s/../e/p"));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(kTestCases));
#endif
}
TEST(HashValueTest, StdArray) {
EXPECT_TRUE((is_hashable<std::array<int, 3>>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(std::array<int, 3>{}, std::array<int, 3>{{0, 23, 42}})));
}
TEST(HashValueTest, StdBitset) {
EXPECT_TRUE((is_hashable<std::bitset<257>>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
{std::bitset<2>("00"), std::bitset<2>("01"), std::bitset<2>("10"),
std::bitset<2>("11")}));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
{std::bitset<5>("10101"), std::bitset<5>("10001"), std::bitset<5>()}));
constexpr int kNumBits = 256;
std::array<std::string, 6> bit_strings;
bit_strings.fill(std::string(kNumBits, '1'));
bit_strings[1][0] = '0';
bit_strings[2][1] = '0';
bit_strings[3][kNumBits / 3] = '0';
bit_strings[4][kNumBits - 2] = '0';
bit_strings[5][kNumBits - 1] = '0';
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
{std::bitset<kNumBits>(bit_strings[0].c_str()),
std::bitset<kNumBits>(bit_strings[1].c_str()),
std::bitset<kNumBits>(bit_strings[2].c_str()),
std::bitset<kNumBits>(bit_strings[3].c_str()),
std::bitset<kNumBits>(bit_strings[4].c_str()),
std::bitset<kNumBits>(bit_strings[5].c_str())}));
}
struct Private {
int i;
template <typename H>
friend H AbslHashValue(H h, Private p) {
return H::combine(std::move(h), std::abs(p.i));
}
friend bool operator==(Private a, Private b) {
return std::abs(a.i) == std::abs(b.i);
}
friend std::ostream& operator<<(std::ostream& o, Private p) {
return o << p.i;
}
};
class PiecewiseHashTester {
public:
explicit PiecewiseHashTester(absl::string_view buf)
: buf_(buf), piecewise_(false), split_locations_() {}
PiecewiseHashTester(absl::string_view buf, std::set<size_t> split_locations)
: buf_(buf),
piecewise_(true),
split_locations_(std::move(split_locations)) {}
template <typename H>
friend H AbslHashValue(H h, const PiecewiseHashTester& p) {
if (!p.piecewise_) {
return H::combine_contiguous(std::move(h), p.buf_.data(), p.buf_.size());
}
absl::hash_internal::PiecewiseCombiner combiner;
if (p.split_locations_.empty()) {
h = combiner.add_buffer(std::move(h), p.buf_.data(), p.buf_.size());
return combiner.finalize(std::move(h));
}
size_t begin = 0;
for (size_t next : p.split_locations_) {
absl::string_view chunk = p.buf_.substr(begin, next - begin);
h = combiner.add_buffer(std::move(h), chunk.data(), chunk.size());
begin = next;
}
absl::string_view last_chunk = p.buf_.substr(begin);
if (!last_chunk.empty()) {
h = combiner.add_buffer(std::move(h), last_chunk.data(),
last_chunk.size());
}
return combiner.finalize(std::move(h));
}
private:
absl::string_view buf_;
bool piecewise_;
std::set<size_t> split_locations_;
};
struct DummyFooBar {
template <typename H>
friend H AbslHashValue(H h, const DummyFooBar&) {
const char* foo = "foo";
const char* bar = "bar";
h = H::combine_contiguous(std::move(h), foo, 3);
h = H::combine_contiguous(std::move(h), bar, 3);
return h;
}
};
TEST(HashValueTest, CombinePiecewiseBuffer) {
absl::Hash<PiecewiseHashTester> hash;
EXPECT_EQ(hash(PiecewiseHashTester("")), hash(PiecewiseHashTester("", {})));
EXPECT_EQ(hash(PiecewiseHashTester("foobar")),
hash(PiecewiseHashTester("foobar", {})));
EXPECT_EQ(hash(PiecewiseHashTester("foobar")),
hash(PiecewiseHashTester("foobar", {3})));
EXPECT_NE(hash(PiecewiseHashTester("foobar", {3})),
absl::Hash<DummyFooBar>()(DummyFooBar{}));
for (size_t big_buffer_size : {1024u * 2 + 512u, 1024u * 3}) {
SCOPED_TRACE(big_buffer_size);
std::string big_buffer;
for (size_t i = 0; i < big_buffer_size; ++i) {
big_buffer.push_back(32 + (i * (i / 3)) % 64);
}
auto big_buffer_hash = hash(PiecewiseHashTester(big_buffer));
const int possible_breaks = 9;
size_t breaks[possible_breaks] = {1, 512, 1023, 1024, 1025,
1536, 2047, 2048, 2049};
for (unsigned test_mask = 0; test_mask < (1u << possible_breaks);
++test_mask) {
SCOPED_TRACE(test_mask);
std::set<size_t> break_locations;
for (int j = 0; j < possible_breaks; ++j) {
if (test_mask & (1u << j)) {
break_locations.insert(breaks[j]);
}
}
EXPECT_EQ(
hash(PiecewiseHashTester(big_buffer, std::move(break_locations))),
big_buffer_hash);
}
}
}
TEST(HashValueTest, PrivateSanity) {
EXPECT_TRUE(is_hashable<Private>::value);
EXPECT_NE(SpyHash(Private{0}), SpyHash(Private{1}));
EXPECT_EQ(SpyHash(Private{1}), SpyHash(Private{1}));
}
TEST(HashValueTest, Optional) {
EXPECT_TRUE(is_hashable<absl::optional<Private>>::value);
using O = absl::optional<Private>;
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(O{}, O{{1}}, O{{-1}}, O{{10}})));
}
TEST(HashValueTest, Variant) {
using V = absl::variant<Private, std::string>;
EXPECT_TRUE(is_hashable<V>::value);
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
V(Private{1}), V(Private{-1}), V(Private{2}), V("ABC"), V("BCD"))));
#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
struct S {};
EXPECT_FALSE(is_hashable<absl::variant<S>>::value);
#endif
}
TEST(HashValueTest, ReferenceWrapper) {
EXPECT_TRUE(is_hashable<std::reference_wrapper<Private>>::value);
Private p1{1}, p10{10};
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
p1, p10, std::ref(p1), std::ref(p10), std::cref(p1), std::cref(p10))));
EXPECT_TRUE(is_hashable<std::reference_wrapper<int>>::value);
int one = 1, ten = 10;
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
one, ten, std::ref(one), std::ref(ten), std::cref(one), std::cref(ten))));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(std::tuple<std::reference_wrapper<int>>(std::ref(one)),
std::tuple<std::reference_wrapper<int>>(std::ref(ten)),
std::tuple<int>(one), std::tuple<int>(ten))));
}
template <typename T, typename = void>
struct IsHashCallable : std::false_type {};
template <typename T>
struct IsHashCallable<T, absl::void_t<decltype(std::declval<absl::Hash<T>>()(
std::declval<const T&>()))>> : std::true_type {};
template <typename T, typename = void>
struct IsAggregateInitializable : std::false_type {};
template <typename T>
struct IsAggregateInitializable<T, absl::void_t<decltype(T{})>>
: std::true_type {};
TEST(IsHashableTest, ValidHash) {
EXPECT_TRUE((is_hashable<int>::value));
EXPECT_TRUE(std::is_default_constructible<absl::Hash<int>>::value);
EXPECT_TRUE(std::is_copy_constructible<absl::Hash<int>>::value);
EXPECT_TRUE(std::is_move_constructible<absl::Hash<int>>::value);
EXPECT_TRUE(absl::is_copy_assignable<absl::Hash<int>>::value);
EXPECT_TRUE(absl::is_move_assignable<absl::Hash<int>>::value);
EXPECT_TRUE(IsHashCallable<int>::value);
EXPECT_TRUE(IsAggregateInitializable<absl::Hash<int>>::value);
}
#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
TEST(IsHashableTest, PoisonHash) {
struct X {};
EXPECT_FALSE((is_hashable<X>::value));
EXPECT_FALSE(std::is_default_constructible<absl::Hash<X>>::value);
EXPECT_FALSE(std::is_copy_constructible<absl::Hash<X>>::value);
EXPECT_FALSE(std::is_move_constructible<absl::Hash<X>>::value);
EXPECT_FALSE(absl::is_copy_assignable<absl::Hash<X>>::value);
EXPECT_FALSE(absl::is_move_assignable<absl::Hash<X>>::value);
EXPECT_FALSE(IsHashCallable<X>::value);
#if !defined(__GNUC__) || defined(__clang__)
EXPECT_FALSE(IsAggregateInitializable<absl::Hash<X>>::value);
#endif
}
#endif
struct NoOp {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, NoOp n) {
return h;
}
};
struct EmptyCombine {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, EmptyCombine e) {
return HashCode::combine(std::move(h));
}
};
template <typename Int>
struct CombineIterative {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, CombineIterative c) {
for (int i = 0; i < 5; ++i) {
h = HashCode::combine(std::move(h), Int(i));
}
return h;
}
};
template <typename Int>
struct CombineVariadic {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, CombineVariadic c) {
return HashCode::combine(std::move(h), Int(0), Int(1), Int(2), Int(3),
Int(4));
}
};
enum class InvokeTag {
kUniquelyRepresented,
kHashValue,
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
kLegacyHash,
#endif
kStdHash,
kNone
};
template <InvokeTag T>
using InvokeTagConstant = std::integral_constant<InvokeTag, T>;
template <InvokeTag... Tags>
struct MinTag;
template <InvokeTag a, InvokeTag b, InvokeTag... Tags>
struct MinTag<a, b, Tags...> : MinTag<(a < b ? a : b), Tags...> {};
template <InvokeTag a>
struct MinTag<a> : InvokeTagConstant<a> {};
template <InvokeTag... Tags>
struct CustomHashType {
explicit CustomHashType(size_t val) : value(val) {}
size_t value;
};
template <InvokeTag allowed, InvokeTag... tags>
struct EnableIfContained
: std::enable_if<absl::disjunction<
std::integral_constant<bool, allowed == tags>...>::value> {};
template <
typename H, InvokeTag... Tags,
typename = typename EnableIfContained<InvokeTag::kHashValue, Tags...>::type>
H AbslHashValue(H state, CustomHashType<Tags...> t) {
static_assert(MinTag<Tags...>::value == InvokeTag::kHashValue, "");
return H::combine(std::move(state),
t.value + static_cast<int>(InvokeTag::kHashValue));
}
}
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace hash_internal {
template <InvokeTag... Tags>
struct is_uniquely_represented<
CustomHashType<Tags...>,
typename EnableIfContained<InvokeTag::kUniquelyRepresented, Tags...>::type>
: std::true_type {};
}
ABSL_NAMESPACE_END
}
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE {
template <InvokeTag... Tags>
struct hash<CustomHashType<Tags...>> {
template <InvokeTag... TagsIn, typename = typename EnableIfContained<
InvokeTag::kLegacyHash, TagsIn...>::type>
size_t operator()(CustomHashType<TagsIn...> t) const {
static_assert(MinTag<Tags...>::value == InvokeTag::kLegacyHash, "");
return t.value + static_cast<int>(InvokeTag::kLegacyHash);
}
};
}
#endif
namespace std {
template <InvokeTag... Tags>
struct hash<CustomHashType<Tags...>> {
template <InvokeTag... TagsIn, typename = typename EnableIfContained<
InvokeTag::kStdHash, TagsIn...>::type>
size_t operator()(CustomHashType<TagsIn...> t) const {
static_assert(MinTag<Tags...>::value == InvokeTag::kStdHash, "");
return t.value + static_cast<int>(InvokeTag::kStdHash);
}
};
}
namespace {
template <typename... T>
void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>, T...) {
using type = CustomHashType<T::value...>;
SCOPED_TRACE(testing::PrintToString(std::vector<InvokeTag>{T::value...}));
EXPECT_TRUE(is_hashable<type>());
EXPECT_TRUE(is_hashable<const type>());
EXPECT_TRUE(is_hashable<const type&>());
const size_t offset = static_cast<int>(std::min({T::value...}));
EXPECT_EQ(SpyHash(type(7)), SpyHash(size_t{7 + offset}));
}
void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>) {
#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
using type = CustomHashType<>;
EXPECT_FALSE(is_hashable<type>());
EXPECT_FALSE(is_hashable<const type>());
EXPECT_FALSE(is_hashable<const type&>());
#endif
}
template <InvokeTag Tag, typename... T>
void TestCustomHashType(InvokeTagConstant<Tag> tag, T... t) {
constexpr auto next = static_cast<InvokeTag>(static_cast<int>(Tag) + 1);
TestCustomHashType(InvokeTagConstant<next>(), tag, t...);
TestCustomHashType(InvokeTagConstant<next>(), t...);
}
TEST(HashTest, CustomHashType) {
TestCustomHa |
2,584 | cpp | abseil/abseil-cpp | civil_time | absl/time/civil_time.cc | absl/time/internal/cctz/src/civil_time_test.cc | #ifndef ABSL_TIME_INTERNAL_CCTZ_CIVIL_TIME_H_
#define ABSL_TIME_INTERNAL_CCTZ_CIVIL_TIME_H_
#include "absl/base/config.h"
#include "absl/time/internal/cctz/include/cctz/civil_time_detail.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace time_internal {
namespace cctz {
using civil_year = detail::civil_year;
using civil_month = detail::civil_month;
using civil_day = detail::civil_day;
using civil_hour = detail::civil_hour;
using civil_minute = detail::civil_minute;
using civil_second = detail::civil_second;
using detail::weekday;
using detail::get_weekday;
using detail::next_weekday;
using detail::prev_weekday;
using detail::get_yearday;
}
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/time/civil_time.h"
#include <cstdlib>
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
inline civil_year_t NormalizeYear(civil_year_t year) {
return 2400 + year % 400;
}
std::string FormatYearAnd(string_view fmt, CivilSecond cs) {
const CivilSecond ncs(NormalizeYear(cs.year()), cs.month(), cs.day(),
cs.hour(), cs.minute(), cs.second());
const TimeZone utc = UTCTimeZone();
return StrCat(cs.year(), FormatTime(fmt, FromCivil(ncs, utc), utc));
}
template <typename CivilT>
bool ParseYearAnd(string_view fmt, string_view s, CivilT* c) {
const std::string ss = std::string(s);
const char* const np = ss.c_str();
char* endp;
errno = 0;
const civil_year_t y =
std::strtoll(np, &endp, 10);
if (endp == np || errno == ERANGE) return false;
const std::string norm = StrCat(NormalizeYear(y), endp);
const TimeZone utc = UTCTimeZone();
Time t;
if (ParseTime(StrCat("%Y", fmt), norm, utc, &t, nullptr)) {
const auto cs = ToCivilSecond(t, utc);
*c = CivilT(y, cs.month(), cs.day(), cs.hour(), cs.minute(), cs.second());
return true;
}
return false;
}
template <typename CivilT1, typename CivilT2>
bool ParseAs(string_view s, CivilT2* c) {
CivilT1 t1;
if (ParseCivilTime(s, &t1)) {
*c = CivilT2(t1);
return true;
}
return false;
}
template <typename CivilT>
bool ParseLenient(string_view s, CivilT* c) {
if (ParseCivilTime(s, c)) return true;
if (ParseAs<CivilDay>(s, c)) return true;
if (ParseAs<CivilSecond>(s, c)) return true;
if (ParseAs<CivilHour>(s, c)) return true;
if (ParseAs<CivilMonth>(s, c)) return true;
if (ParseAs<CivilMinute>(s, c)) return true;
if (ParseAs<CivilYear>(s, c)) return true;
return false;
}
}
std::string FormatCivilTime(CivilSecond c) {
return FormatYearAnd("-%m-%d%ET%H:%M:%S", c);
}
std::string FormatCivilTime(CivilMinute c) {
return FormatYearAnd("-%m-%d%ET%H:%M", c);
}
std::string FormatCivilTime(CivilHour c) {
return FormatYearAnd("-%m-%d%ET%H", c);
}
std::string FormatCivilTime(CivilDay c) { return FormatYearAnd("-%m-%d", c); }
std::string FormatCivilTime(CivilMonth c) { return FormatYearAnd("-%m", c); }
std::string FormatCivilTime(CivilYear c) { return FormatYearAnd("", c); }
bool ParseCivilTime(string_view s, CivilSecond* c) {
return ParseYearAnd("-%m-%d%ET%H:%M:%S", s, c);
}
bool ParseCivilTime(string_view s, CivilMinute* c) {
return ParseYearAnd("-%m-%d%ET%H:%M", s, c);
}
bool ParseCivilTime(string_view s, CivilHour* c) {
return ParseYearAnd("-%m-%d%ET%H", s, c);
}
bool ParseCivilTime(string_view s, CivilDay* c) {
return ParseYearAnd("-%m-%d", s, c);
}
bool ParseCivilTime(string_view s, CivilMonth* c) {
return ParseYearAnd("-%m", s, c);
}
bool ParseCivilTime(string_view s, CivilYear* c) {
return ParseYearAnd("", s, c);
}
bool ParseLenientCivilTime(string_view s, CivilSecond* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, CivilMinute* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, CivilHour* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, CivilDay* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, CivilMonth* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, CivilYear* c) {
return ParseLenient(s, c);
}
namespace time_internal {
std::ostream& operator<<(std::ostream& os, CivilYear y) {
return os << FormatCivilTime(y);
}
std::ostream& operator<<(std::ostream& os, CivilMonth m) {
return os << FormatCivilTime(m);
}
std::ostream& operator<<(std::ostream& os, CivilDay d) {
return os << FormatCivilTime(d);
}
std::ostream& operator<<(std::ostream& os, CivilHour h) {
return os << FormatCivilTime(h);
}
std::ostream& operator<<(std::ostream& os, CivilMinute m) {
return os << FormatCivilTime(m);
}
std::ostream& operator<<(std::ostream& os, CivilSecond s) {
return os << FormatCivilTime(s);
}
bool AbslParseFlag(string_view s, CivilSecond* c, std::string*) {
return ParseLenientCivilTime(s, c);
}
bool AbslParseFlag(string_view s, CivilMinute* c, std::string*) {
return ParseLenientCivilTime(s, c);
}
bool AbslParseFlag(string_view s, CivilHour* c, std::string*) {
return ParseLenientCivilTime(s, c);
}
bool AbslParseFlag(string_view s, CivilDay* c, std::string*) {
return ParseLenientCivilTime(s, c);
}
bool AbslParseFlag(string_view s, CivilMonth* c, std::string*) {
return ParseLenientCivilTime(s, c);
}
bool AbslParseFlag(string_view s, CivilYear* c, std::string*) {
return ParseLenientCivilTime(s, c);
}
std::string AbslUnparseFlag(CivilSecond c) { return FormatCivilTime(c); }
std::string AbslUnparseFlag(CivilMinute c) { return FormatCivilTime(c); }
std::string AbslUnparseFlag(CivilHour c) { return FormatCivilTime(c); }
std::string AbslUnparseFlag(CivilDay c) { return FormatCivilTime(c); }
std::string AbslUnparseFlag(CivilMonth c) { return FormatCivilTime(c); }
std::string AbslUnparseFlag(CivilYear c) { return FormatCivilTime(c); }
}
ABSL_NAMESPACE_END
} | #include "absl/time/internal/cctz/include/cctz/civil_time.h"
#include <iomanip>
#include <limits>
#include <sstream>
#include <string>
#include <type_traits>
#include "gtest/gtest.h"
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace time_internal {
namespace cctz {
namespace {
template <typename T>
std::string Format(const T& t) {
std::stringstream ss;
ss << t;
return ss.str();
}
}
#if __cpp_constexpr >= 201304 || (defined(_MSC_VER) && _MSC_VER >= 1910)
TEST(CivilTime, Normal) {
constexpr civil_second css(2016, 1, 28, 17, 14, 12);
static_assert(css.second() == 12, "Normal.second");
constexpr civil_minute cmm(2016, 1, 28, 17, 14);
static_assert(cmm.minute() == 14, "Normal.minute");
constexpr civil_hour chh(2016, 1, 28, 17);
static_assert(chh.hour() == 17, "Normal.hour");
constexpr civil_day cd(2016, 1, 28);
static_assert(cd.day() == 28, "Normal.day");
constexpr civil_month cm(2016, 1);
static_assert(cm.month() == 1, "Normal.month");
constexpr civil_year cy(2016);
static_assert(cy.year() == 2016, "Normal.year");
}
TEST(CivilTime, Conversion) {
constexpr civil_year cy(2016);
static_assert(cy.year() == 2016, "Conversion.year");
constexpr civil_month cm(cy);
static_assert(cm.month() == 1, "Conversion.month");
constexpr civil_day cd(cm);
static_assert(cd.day() == 1, "Conversion.day");
constexpr civil_hour chh(cd);
static_assert(chh.hour() == 0, "Conversion.hour");
constexpr civil_minute cmm(chh);
static_assert(cmm.minute() == 0, "Conversion.minute");
constexpr civil_second css(cmm);
static_assert(css.second() == 0, "Conversion.second");
}
TEST(CivilTime, Normalized) {
constexpr civil_second cs(2016, 1, 28, 17, 14, 12);
static_assert(cs.year() == 2016, "Normalized.year");
static_assert(cs.month() == 1, "Normalized.month");
static_assert(cs.day() == 28, "Normalized.day");
static_assert(cs.hour() == 17, "Normalized.hour");
static_assert(cs.minute() == 14, "Normalized.minute");
static_assert(cs.second() == 12, "Normalized.second");
}
TEST(CivilTime, SecondOverflow) {
constexpr civil_second cs(2016, 1, 28, 17, 14, 121);
static_assert(cs.year() == 2016, "SecondOverflow.year");
static_assert(cs.month() == 1, "SecondOverflow.month");
static_assert(cs.day() == 28, "SecondOverflow.day");
static_assert(cs.hour() == 17, "SecondOverflow.hour");
static_assert(cs.minute() == 16, "SecondOverflow.minute");
static_assert(cs.second() == 1, "SecondOverflow.second");
}
TEST(CivilTime, SecondUnderflow) {
constexpr civil_second cs(2016, 1, 28, 17, 14, -121);
static_assert(cs.year() == 2016, "SecondUnderflow.year");
static_assert(cs.month() == 1, "SecondUnderflow.month");
static_assert(cs.day() == 28, "SecondUnderflow.day");
static_assert(cs.hour() == 17, "SecondUnderflow.hour");
static_assert(cs.minute() == 11, "SecondUnderflow.minute");
static_assert(cs.second() == 59, "SecondUnderflow.second");
}
TEST(CivilTime, MinuteOverflow) {
constexpr civil_second cs(2016, 1, 28, 17, 121, 12);
static_assert(cs.year() == 2016, "MinuteOverflow.year");
static_assert(cs.month() == 1, "MinuteOverflow.month");
static_assert(cs.day() == 28, "MinuteOverflow.day");
static_assert(cs.hour() == 19, "MinuteOverflow.hour");
static_assert(cs.minute() == 1, "MinuteOverflow.minute");
static_assert(cs.second() == 12, "MinuteOverflow.second");
}
TEST(CivilTime, MinuteUnderflow) {
constexpr civil_second cs(2016, 1, 28, 17, -121, 12);
static_assert(cs.year() == 2016, "MinuteUnderflow.year");
static_assert(cs.month() == 1, "MinuteUnderflow.month");
static_assert(cs.day() == 28, "MinuteUnderflow.day");
static_assert(cs.hour() == 14, "MinuteUnderflow.hour");
static_assert(cs.minute() == 59, "MinuteUnderflow.minute");
static_assert(cs.second() == 12, "MinuteUnderflow.second");
}
TEST(CivilTime, HourOverflow) {
constexpr civil_second cs(2016, 1, 28, 49, 14, 12);
static_assert(cs.year() == 2016, "HourOverflow.year");
static_assert(cs.month() == 1, "HourOverflow.month");
static_assert(cs.day() == 30, "HourOverflow.day");
static_assert(cs.hour() == 1, "HourOverflow.hour");
static_assert(cs.minute() == 14, "HourOverflow.minute");
static_assert(cs.second() == 12, "HourOverflow.second");
}
TEST(CivilTime, HourUnderflow) {
constexpr civil_second cs(2016, 1, 28, -49, 14, 12);
static_assert(cs.year() == 2016, "HourUnderflow.year");
static_assert(cs.month() == 1, "HourUnderflow.month");
static_assert(cs.day() == 25, "HourUnderflow.day");
static_assert(cs.hour() == 23, "HourUnderflow.hour");
static_assert(cs.minute() == 14, "HourUnderflow.minute");
static_assert(cs.second() == 12, "HourUnderflow.second");
}
TEST(CivilTime, MonthOverflow) {
constexpr civil_second cs(2016, 25, 28, 17, 14, 12);
static_assert(cs.year() == 2018, "MonthOverflow.year");
static_assert(cs.month() == 1, "MonthOverflow.month");
static_assert(cs.day() == 28, "MonthOverflow.day");
static_assert(cs.hour() == 17, "MonthOverflow.hour");
static_assert(cs.minute() == 14, "MonthOverflow.minute");
static_assert(cs.second() == 12, "MonthOverflow.second");
}
TEST(CivilTime, MonthUnderflow) {
constexpr civil_second cs(2016, -25, 28, 17, 14, 12);
static_assert(cs.year() == 2013, "MonthUnderflow.year");
static_assert(cs.month() == 11, "MonthUnderflow.month");
static_assert(cs.day() == 28, "MonthUnderflow.day");
static_assert(cs.hour() == 17, "MonthUnderflow.hour");
static_assert(cs.minute() == 14, "MonthUnderflow.minute");
static_assert(cs.second() == 12, "MonthUnderflow.second");
}
TEST(CivilTime, C4Overflow) {
constexpr civil_second cs(2016, 1, 292195, 17, 14, 12);
static_assert(cs.year() == 2816, "C4Overflow.year");
static_assert(cs.month() == 1, "C4Overflow.month");
static_assert(cs.day() == 1, "C4Overflow.day");
static_assert(cs.hour() == 17, "C4Overflow.hour");
static_assert(cs.minute() == 14, "C4Overflow.minute");
static_assert(cs.second() == 12, "C4Overflow.second");
}
TEST(CivilTime, C4Underflow) {
constexpr civil_second cs(2016, 1, -292195, 17, 14, 12);
static_assert(cs.year() == 1215, "C4Underflow.year");
static_assert(cs.month() == 12, "C4Underflow.month");
static_assert(cs.day() == 30, "C4Underflow.day");
static_assert(cs.hour() == 17, "C4Underflow.hour");
static_assert(cs.minute() == 14, "C4Underflow.minute");
static_assert(cs.second() == 12, "C4Underflow.second");
}
TEST(CivilTime, MixedNormalization) {
constexpr civil_second cs(2016, -42, 122, 99, -147, 4949);
static_assert(cs.year() == 2012, "MixedNormalization.year");
static_assert(cs.month() == 10, "MixedNormalization.month");
static_assert(cs.day() == 4, "MixedNormalization.day");
static_assert(cs.hour() == 1, "MixedNormalization.hour");
static_assert(cs.minute() == 55, "MixedNormalization.minute");
static_assert(cs.second() == 29, "MixedNormalization.second");
}
TEST(CivilTime, Less) {
constexpr civil_second cs1(2016, 1, 28, 17, 14, 12);
constexpr civil_second cs2(2016, 1, 28, 17, 14, 13);
constexpr bool less = cs1 < cs2;
static_assert(less, "Less");
}
TEST(CivilTime, Addition) {
constexpr civil_second cs1(2016, 1, 28, 17, 14, 12);
constexpr civil_second cs2 = cs1 + 50;
static_assert(cs2.year() == 2016, "Addition.year");
static_assert(cs2.month() == 1, "Addition.month");
static_assert(cs2.day() == 28, "Addition.day");
static_assert(cs2.hour() == 17, "Addition.hour");
static_assert(cs2.minute() == 15, "Addition.minute");
static_assert(cs2.second() == 2, "Addition.second");
}
TEST(CivilTime, Subtraction) {
constexpr civil_second cs1(2016, 1, 28, 17, 14, 12);
constexpr civil_second cs2 = cs1 - 50;
static_assert(cs2.year() == 2016, "Subtraction.year");
static_assert(cs2.month() == 1, "Subtraction.month");
static_assert(cs2.day() == 28, "Subtraction.day");
static_assert(cs2.hour() == 17, "Subtraction.hour");
static_assert(cs2.minute() == 13, "Subtraction.minute");
static_assert(cs2.second() == 22, "Subtraction.second");
}
TEST(CivilTime, Difference) {
constexpr civil_day cd1(2016, 1, 28);
constexpr civil_day cd2(2015, 1, 28);
constexpr int diff = cd1 - cd2;
static_assert(diff == 365, "Difference");
}
TEST(CivilTime, ConstructionWithHugeYear) {
constexpr civil_hour h(-9223372036854775807, 1, 1, -1);
static_assert(h.year() == -9223372036854775807 - 1,
"ConstructionWithHugeYear");
static_assert(h.month() == 12, "ConstructionWithHugeYear");
static_assert(h.day() == 31, "ConstructionWithHugeYear");
static_assert(h.hour() == 23, "ConstructionWithHugeYear");
}
TEST(CivilTime, DifferenceWithHugeYear) {
{
constexpr civil_day d1(9223372036854775807, 1, 1);
constexpr civil_day d2(9223372036854775807, 12, 31);
static_assert(d2 - d1 == 364, "DifferenceWithHugeYear");
}
{
constexpr civil_day d1(-9223372036854775807 - 1, 1, 1);
constexpr civil_day d2(-9223372036854775807 - 1, 12, 31);
static_assert(d2 - d1 == 365, "DifferenceWithHugeYear");
}
{
constexpr civil_day d1(9223372036854775807, 1, 1);
constexpr civil_day d2(9198119301927009252, 6, 6);
static_assert(d1 - d2 == 9223372036854775807, "DifferenceWithHugeYear");
static_assert((d2 - 1) - d1 == -9223372036854775807 - 1,
"DifferenceWithHugeYear");
}
{
constexpr civil_day d1(-9223372036854775807 - 1, 1, 1);
constexpr civil_day d2(-9198119301927009254, 7, 28);
static_assert(d2 - d1 == 9223372036854775807, "DifferenceWithHugeYear");
static_assert(d1 - (d2 + 1) == -9223372036854775807 - 1,
"DifferenceWithHugeYear");
}
{
constexpr civil_day d1(-12626367463883278, 9, 3);
constexpr civil_day d2(12626367463883277, 3, 28);
static_assert(d2 - d1 == 9223372036854775807, "DifferenceWithHugeYear");
static_assert(d1 - (d2 + 1) == -9223372036854775807 - 1,
"DifferenceWithHugeYear");
}
}
TEST(CivilTime, DifferenceNoIntermediateOverflow) {
{
constexpr civil_second s1(-292277022657, 1, 27, 8, 29 - 1, 52);
constexpr civil_second s2(1970, 1, 1, 0, 0 - 1, 0);
static_assert(s1 - s2 == -9223372036854775807 - 1,
"DifferenceNoIntermediateOverflow");
}
{
constexpr civil_second s1(292277026596, 12, 4, 15, 30, 7 - 7);
constexpr civil_second s2(1970, 1, 1, 0, 0, 0 - 7);
static_assert(s1 - s2 == 9223372036854775807,
"DifferenceNoIntermediateOverflow");
}
}
TEST(CivilTime, WeekDay) {
constexpr civil_day cd(2016, 1, 28);
constexpr weekday wd = get_weekday(cd);
static_assert(wd == weekday::thursday, "Weekday");
}
TEST(CivilTime, NextWeekDay) {
constexpr civil_day cd(2016, 1, 28);
constexpr civil_day next = next_weekday(cd, weekday::thursday);
static_assert(next.year() == 2016, "NextWeekDay.year");
static_assert(next.month() == 2, "NextWeekDay.month");
static_assert(next.day() == 4, "NextWeekDay.day");
}
TEST(CivilTime, PrevWeekDay) {
constexpr civil_day cd(2016, 1, 28);
constexpr civil_day prev = prev_weekday(cd, weekday::thursday);
static_assert(prev.year() == 2016, "PrevWeekDay.year");
static_assert(prev.month() == 1, "PrevWeekDay.month");
static_assert(prev.day() == 21, "PrevWeekDay.day");
}
TEST(CivilTime, YearDay) {
constexpr civil_day cd(2016, 1, 28);
constexpr int yd = get_yearday(cd);
static_assert(yd == 28, "YearDay");
}
#endif
TEST(CivilTime, DefaultConstruction) {
civil_second ss;
EXPECT_EQ("1970-01-01T00:00:00", Format(ss));
civil_minute mm;
EXPECT_EQ("1970-01-01T00:00", Format(mm));
civil_hour hh;
EXPECT_EQ("1970-01-01T00", Format(hh));
civil_day d;
EXPECT_EQ("1970-01-01", Format(d));
civil_month m;
EXPECT_EQ("1970-01", Format(m));
civil_year y;
EXPECT_EQ("1970", Format(y));
}
TEST(CivilTime, StructMember) {
struct S {
civil_day day;
};
S s = {};
EXPECT_EQ(civil_day{}, s.day);
}
TEST(CivilTime, FieldsConstruction) {
EXPECT_EQ("2015-01-02T03:04:05", Format(civil_second(2015, 1, 2, 3, 4, 5)));
EXPECT_EQ("2015-01-02T03:04:00", Format(civil_second(2015, 1, 2, 3, 4)));
EXPECT_EQ("2015-01-02T03:00:00", Format(civil_second(2015, 1, 2, 3)));
EXPECT_EQ("2015-01-02T00:00:00", Format(civil_second(2015, 1, 2)));
EXPECT_EQ("2015-01-01T00:00:00", Format(civil_second(2015, 1)));
EXPECT_EQ("2015-01-01T00:00:00", Format(civil_second(2015)));
EXPECT_EQ("2015-01-02T03:04", Format(civil_minute(2015, 1, 2, 3, 4, 5)));
EXPECT_EQ("2015-01-02T03:04", Format(civil_minute(2015, 1, 2, 3, 4)));
EXPECT_EQ("2015-01-02T03:00", Format(civil_minute(2015, 1, 2, 3)));
EXPECT_EQ("2015-01-02T00:00", Format(civil_minute(2015, 1, 2)));
EXPECT_EQ("2015-01-01T00:00", Format(civil_minute(2015, 1)));
EXPECT_EQ("2015-01-01T00:00", Format(civil_minute(2015)));
EXPECT_EQ("2015-01-02T03", Format(civil_hour(2015, 1, 2, 3, 4, 5)));
EXPECT_EQ("2015-01-02T03", Format(civil_hour(2015, 1, 2, 3, 4)));
EXPECT_EQ("2015-01-02T03", Format(civil_hour(2015, 1, 2, 3)));
EXPECT_EQ("2015-01-02T00", Format(civil_hour(2015, 1, 2)));
EXPECT_EQ("2015-01-01T00", Format(civil_hour(2015, 1)));
EXPECT_EQ("2015-01-01T00", Format(civil_hour(2015)));
EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2, 3, 4, 5)));
EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2, 3, 4)));
EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2, 3)));
EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2)));
EXPECT_EQ("2015-01-01", Format(civil_day(2015, 1)));
EXPECT_EQ("2015-01-01", Format(civil_day(2015)));
EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2, 3, 4, 5)));
EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2, 3, 4)));
EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2, 3)));
EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2)));
EXPECT_EQ("2015-01", Format(civil_month(2015, 1)));
EXPECT_EQ("2015-01", Format(civil_month(2015)));
EXPECT_EQ("2015", Format(civil_year(2015, 1, 2, 3, 4, 5)));
EXPECT_EQ("2015", Format(civil_year(2015, 1, 2, 3, 4)));
EXPECT_EQ("2015", Format(civil_year(2015, 1, 2, 3)));
EXPECT_EQ("2015", Format(civil_year(2015, 1, 2)));
EXPECT_EQ("2015", Format(civil_year(2015, 1)));
EXPECT_EQ("2015", Format(civil_year(2015)));
}
TEST(CivilTime, FieldsConstructionLimits) {
const int kIntMax = std::numeric_limits<int>::max();
EXPECT_EQ("2038-01-19T03:14:07",
Format(civil_second(1970, 1, 1, 0, 0, kIntMax)));
EXPECT_EQ("6121-02-11T05:21:07",
Format(civil_second(1970, 1, 1, 0, kIntMax, kIntMax)));
EXPECT_EQ("251104-11-20T12:21:07",
Format(civil_second(1970, 1, 1, kIntMax, kIntMax, kIntMax)));
EXPECT_EQ("6130715-05-30T12:21:07",
Format(civil_second(1970, 1, kIntMax, kIntMax, kIntMax, kIntMax)));
EXPECT_EQ(
"185087685-11-26T12:21:07",
Format(civil_second(1970, kIntMax, kIntMax, kIntMax, kIntMax, kIntMax)));
const int kIntMin = std::numeric_limits<int>::min();
EXPECT_EQ("1901-12-13T20:45:52",
Format(civil_second(1970, 1, 1, 0, 0, kIntMin)));
EXPECT_EQ("-2182-11-20T18:37:52",
Format(civil_second(1970, 1, 1, 0, kIntMin, kIntMin)));
EXPECT_EQ("-247165-02-11T10:37:52",
Format(civil_second(1970, 1, 1, kIntMin, kIntMin, kIntMin)));
EXPECT_EQ("-6126776-08-01T10:37:52",
Format(civil_second(1970, 1, kIntMin, kIntMin, kIntMin, kIntMin)));
EXPECT_EQ(
"-185083747-10-31T10:37:52",
Format(civil_second(1970, kIntMin, kIntMin, kIntMin, kIntMin, kIntMin)));
}
TEST(CivilTime, ImplicitCrossAlignment) {
civil_year year(2015);
civil_month month = year;
civil_day day = month;
civil_hour hour = day;
civil_minute minute = hour;
civil_second second = minute;
second = year;
EXPECT_EQ(second, year);
second = month;
EXPECT_EQ(second, month);
second = day;
EXPECT_EQ(second, day);
second = hour;
EXPECT_EQ(second, hour);
second = minute;
EXPECT_EQ(second, minute);
minute = year;
EXPECT_EQ(minute, year);
minute = month;
EXPECT_EQ(minute, month);
minute = day;
EXPECT_EQ(minute, day);
minute = hour;
EXPECT_EQ(minute, hour);
hour = year;
EXPECT_EQ(hour, year);
hour = month;
EXPECT_EQ(hour, month);
hour = day;
EXPECT_EQ(hour, day);
day = year;
EXPECT_EQ(day, year);
day = month;
EXPECT_EQ(day, month);
month = year;
EXPECT_EQ(month, year);
EXPECT_FALSE((std::is_convertible<civil_second, civil_minute>::value));
EXPECT_FALSE((std::is_convertible<civil_second, civil_hour>::value));
EXPECT_FALSE((std::is_convertible<civil_second, civil_day>::value));
EXPECT_FALSE((std::is_convertible<civil_second, civil_month>::value));
EXPECT_FALSE((std::is_convertible<civil_second, civil_year>::value));
EXPECT_FALSE((std::is_convertible<civil_minute, civil_hour>::value));
EXPECT_FALSE((std::is_convertible<civil_minute, civil_day>::value));
EXPECT_FALSE((std::is_convertible<civil_minute, civil_month>::value));
EXPECT_FALSE((std::is_convertible<civil_minute, civil_year>::value));
EXPECT_FALSE((std::is_convertible<civil_hour, civil_day>::value));
EXPECT_FALSE((std::is_convertible<civil_hour, civil_month>::value));
EXPECT_FALSE((std::is_convertible<civil_hour, civil_year>::value));
EXPECT_FALSE((std::is_convertible<civil_day, civil_month>::value));
EXPECT_FALSE((std::is_convertible<civil_day, civil_year>::value));
EXPECT_FALSE((std::is_convertible<civil_month, civil_year>::value));
}
TEST(CivilTime, ExplicitCrossAlignment) {
civil_second second(2015, 1, 2, 3, 4, 5);
EXPECT_EQ("2015-01-02T03:04:05", Format(second));
civil_minute minute(second);
EXPECT_EQ("2015-01-02T03:04", Format(minute));
civil_hour hour(minute);
EXPECT_EQ("2015-01-02T03", Format(hour));
civil_day day(hour);
EXPECT_EQ("2015-01-02", Format(day));
civil_month month(day);
EXPECT_EQ("2015-01", Format(month));
civil_year year(month);
EXPECT_EQ("2015", Format(year));
month = civil_month(year);
EXPECT_EQ("2015-01", Format(month));
day = civil_day(month);
EXPECT_EQ("2015-01-01", Format(day));
hour = civil_hour(day);
EXPECT_EQ("2015-01-01T00", Format(hour));
minute = civil_minute(hour);
EXPECT_EQ("2015-01-01T00:00", Format(minute));
second = civil_second(minute);
EXPECT_EQ("2015-01-01T00:00:00", Format(second));
}
template <typename T1, typename T2>
struct HasDifference {
template <typename U1, typename U2>
static std::false_type test(...);
template <typename U1, typename U2>
static std::true_type test(decltype(std::declval<U1>() - std::declval<U2>()));
static constexpr bool value = decltype(test<T1, T2>(0))::value;
};
TEST(CivilTime, DisallowCrossAlignedDifference) {
static_assert(HasDifference<civil_second, civil_second>::value, "");
static_assert(HasDifference<civil_minute, civil_minute>::value, "");
static_assert(HasDifference<civil_hour, civil_hour>::value, "");
static_assert(HasDifference<civil_day, civil_day>::value, "");
static_assert(HasDifference<civil_month, civil_month>::value, "");
static_assert(HasDifference<civil_year, civil_year>::value, "");
static_assert(!HasDifference<civil_second, civil_minute>::value, "");
static_assert(!HasDifference<civil_second, civil_hour>::value, "");
static_assert(!HasDifference<civil_second, civil_day>::value, "");
static_assert(!HasDifference<civil_second, civil_month>::value, "");
static_assert(!HasDifference<civil_second, civil_year>::value, "");
static_assert(!HasDifference<civil_minute, civil_hour>::value, "");
static_assert(!HasDifference<civil_minute, civil_day>::value, "");
static_assert(!HasDifference<civil_minute, civil_month>::value, "");
static_assert(!HasDifference<civil_minute, civil_year>::value, "");
static_assert(!HasDifference<civil_hour, civil_day>::value, "");
static_assert(!HasDifference<civil_hour, civil_month>::value, "");
static_assert(!HasDifference<civil_hour, civil_year>::value, "");
static_assert(!HasDifference<civil_day, civil_month>::value, "");
static_assert(!HasDifference<civil_day, civil_year>::value, "");
static_assert(!HasDifference<civil_month, civil_year>::value, "");
}
TEST(CivilTime, ValueSemantics) {
const civil_hour a(2015, 1, 2, 3);
const civil_hour b = a;
const civil_hour c(b);
civil_hour d;
d = c;
EXPECT_EQ("2015-01-02T03", Format(d));
}
TEST(CivilTime, Relational) {
const civil_year year(2014);
const civil_month month(year);
EXPECT_EQ(year, month);
#define TEST_RELATIONAL(OLDER, YOUNGER) \
do { \
EXPECT_FALSE(OLDER < OLDER); \
EXPECT_FALSE(OLDER > OLDER); \
EXPECT_TRUE(OLDER >= OLDER); \
EXPECT_TRUE(OLDER <= OLDER); \
EXPECT_FALSE(YOUNGER < YOUNGER); \
EXPECT_FALSE(YOUNGER > YOUNGER); \
EXPECT_TRUE(YOUNGER >= YOUNGER); \
EXPECT_TRUE(YOUNGER <= YOUNGER); \
EXPECT_EQ(OLDER, OLDER); \
EXPECT_NE(OLDER, YOUNGER); \
EXPECT_LT(OLDER, YOUNGER); \
EXPECT_LE(OLDER, YOUNGER); \
EXPECT_GT(YOUNGER, OLDER); \
EXPECT_GE(YOUNGER, OLDER); \
} while (0)
TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0),
civil_second(2015, 1, 1, 0, 0, 0));
TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0),
civil_second(2014, 2, 1, 0, 0, 0));
TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0),
civil_second(2014, 1, 2, 0, 0, 0));
TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0),
civil_second(2014, 1, 1, 1, 0, 0));
TEST_RELATIONAL(civil_second(2014, 1, 1, 1, 0, 0),
civil_second(2014, 1, 1, 1, 1, 0));
TEST_RELATIONAL(civil_second(2014, 1, 1, 1, 1, 0),
civil_second(2014, 1, 1, 1, 1, 1));
TEST_RELATIONAL(civil_day(2014, 1, 1), civil_minute(2014, 1, 1, 1, 1));
TEST_RELATIONAL(civil_day(2014, 1, 1), civil_month(2014, 2));
#undef TEST_RELATIONAL
}
TEST(CivilTime, Arithmetic) {
civil_second second(2015, 1, 2, 3, 4, 5);
EXPECT_EQ("2015-01-02T03:04:06", Format(second += 1));
EXPECT_EQ("2015-01-02T03:04:07", Format(second + 1));
EXPECT_EQ("2015-01-02T03:04:08", Format(2 + second));
EXPECT_EQ("2015-01-02T03:04:05", Format(second - 1));
EXPECT_EQ("2015-01-02T03:04:05", Format(second -= 1));
EXPECT_EQ("2015-01-02T03:04:05", Format(second++));
EXPECT_EQ("2015-01-02T03:04:07", Format(++second));
EXPECT_EQ("2015-01-02T03:04:07", Format(second--));
EXPECT_EQ("2015-01-02T03:04:05", Format(--second));
civil_minute minute(2015, 1, 2, 3, 4);
EXPECT_EQ("2015-01-02T03:05", Format(minute += 1));
EXPECT_EQ("2015-01-02T03:06", Format(minute + 1));
EXPECT_EQ("2015-01-02T03:07", Format(2 + minute));
EXPECT_EQ("2015-01-02T03:04", Format(minute - 1));
EXPECT_EQ("2015-01-02T03:04", Format(minute -= 1));
EXPECT_EQ("2015-01-02T03:04", Format(minute++));
EXPECT_EQ("2015-01-02T03:06", Format(++minute));
EXPECT_EQ("2015-01-02T03:06", Format(minute--));
EXPECT_EQ("2015-01-02T03:04", Format(--minute));
civil_hour hour(2015, 1, 2, 3);
EXPECT_EQ("2015-01-02T04", Format(hour += 1));
EXPECT_EQ("2015-01-02T05", Format(hour + 1));
EXPECT_EQ("2015-01-02T06", Format(2 + hour));
EXPECT_EQ("2015-01-02T03", Format(hour - 1));
EXPECT_EQ("2015-01-02T03", Format(hour -= 1));
EXPECT_EQ("2015-01-02T03", Format(hour++));
EXPECT_EQ("2015-01-02T05", Format(++hour));
EXPECT_EQ("2015-01-02T05", Format(hour--));
EXPECT_EQ("2015-01-02T03", Format(--hour));
civil_day day(2015, 1, 2);
EXPECT_EQ("2015-01-03", Format(day += 1));
EXPECT_EQ("2015-01-04", Format(day + 1));
EXPECT_EQ("2015-01-05", Format(2 + day));
EXPECT_EQ("2015-01-02", Format(day - 1));
EXPECT_EQ("2015-01-02", Format(day -= 1));
EXPECT_EQ("2015-01-02", Format(day++));
EXPECT_EQ("2015-01-04", Format(++day));
EXPECT_EQ("2015-01-04", Format(day--));
EXPECT_EQ("2015-01-02", Format(--day));
civil_month month(2015, 1);
EXPECT_EQ("2015-02", Format(month += 1));
EXPECT_EQ("2015-03", Format(month + 1));
EXPECT_EQ("2015-04", Format(2 + month));
EXPECT_EQ("2015-01", Format(month - 1));
EXPECT_EQ("2015-01", Format(month -= 1));
EXPECT_EQ("2015-01", Format(month++));
EXPECT_EQ("2015-03", Format(++month));
EXPECT_EQ("2015-03", Format(month--));
EXPECT_EQ("2015-01", Format(--month));
civil_year year(2015);
EXPECT_EQ("2016", Format(year += 1));
EXPECT_EQ("2017", Format(year + 1));
EXPECT_EQ("2018", Format(2 + year));
EXPECT_EQ("2015", Format(year - 1));
EXPECT_EQ("2015", Format(year -= 1));
EXPECT_EQ("2015", Format(year++));
EXPECT_EQ("2017", Format(++year));
EXPECT_EQ("2017", Format(year--));
EXPECT_EQ("2015", Format(--year));
}
TEST(CivilTime, ArithmeticLimits) {
const int kIntMax = std::numeric_limits<int>::max();
const int kIntMin = std::numeric_limits<int>::min();
civil_second second(1970, 1, 1, 0, 0, 0);
second += kIntMax;
EXPECT_EQ("2038-01-19T03:14:07", Format(second));
second -= kIntMax;
EXPECT_EQ("1970-01-01T00:00:00", Format(second));
second += kIntMin;
EXPECT_EQ("1901-12-13T20:45:52", Format(second));
second -= kIntMin;
EXPECT_EQ("1970-01-01T00:00:00", Format(second));
civil_minute minute(1970, 1, 1, 0, 0);
minute += kIntMax;
EXPECT_EQ("6053-01-23T02:07", Format(minute));
minute -= kIntMax;
EXPECT_EQ("1970-01-01T00:00", Format(minute));
minute += kIntMin;
EXPECT_EQ("-2114-12-08T21:52", Format(minute));
minute -= kIntMin;
EXPECT_EQ("1970-01-01T00:00", Format(minute));
civil_hour hour(1970, 1, 1, 0);
hour += kIntMax;
EXPECT_EQ("246953-10-09T07", Format(hour));
hour -= kIntMax;
EXPECT_EQ("1970-01-01T00", Format(hour));
hour += kIntMin;
EXPECT_EQ("-243014-03-24T16", Format(hour));
hour -= kIntMin;
EXPECT_EQ("1970-01-01T00", Format(hour));
civil_day day(1970, 1, 1);
day += kIntMax;
EXPECT_EQ("5881580-07-11", Format(day));
day -= kIntMax;
EXPECT_EQ("1970-01-01", Format(day));
day += kIntMin;
EXPECT_EQ("-5877641-06-23", Format(day));
day -= kIntMin;
EXPECT_EQ("1970-01-01", Format(day));
civil_month month(1970, 1);
month += kIntMax;
EXPECT_EQ("178958940-08", Format(month));
month -= kIntMax;
EXPECT_EQ("1970-01", Format(month));
month += kIntMin;
EXPECT_EQ("-178955001-05", Format(month));
month -= kIntMin;
EXPECT_EQ("1970-01", Format(month));
civil_year year(0);
year += kIntMax;
EXPECT_EQ("2147483647", Format(year));
year -= kIntMax;
EXPECT_EQ("0", Format(year));
year += kIntMin;
EXPECT_EQ("-2147483648", Format(year));
year -= kIntMin;
EXPECT_EQ("0", Format(year));
}
TEST(CivilTime, ArithmeticDifference) {
civil_second second(2015, 1, 2, 3, 4, 5);
EXPECT_EQ(0, second - second);
EXPECT_EQ(10, (second + 10) - second);
EXPECT_EQ(-10, (second - 10) - second);
civil_minute minute(2015, 1, 2, 3, 4);
EXPECT_EQ(0, minute - minute);
EXPECT_EQ(10, (minute + 10) - minute);
EXPECT_EQ(-10, (minute - 10) - minute);
civil_hour hour(2015, 1, 2, 3);
EXPECT_EQ(0, hour - hour);
EXPECT_EQ(10, (hour + 10) - hour);
EXPECT_EQ(-10, (hour - 10) - hour);
civil_day day(2015, 1, 2);
EXPECT_EQ(0, day - day);
EXPECT_EQ(10, (day + 10) - day);
EXPECT_EQ(-10, (day - 10) - day);
civil_month month(2015, 1);
EXPECT_EQ(0, month - month);
EXPECT_EQ(10, (month + 10) - month);
EXPECT_EQ(-10, (month - 10) - month);
civil_year year(2015);
EXPECT_EQ(0, year - year);
EXPECT_EQ(10, (year + 10) - year);
EXPECT_EQ(-10, (year - 10) - year);
}
TEST(CivilTime, DifferenceLimits) {
const int kIntMax = std::numeric_limits<int>::max();
const int kIntMin = std::numeric_limits<int>::min();
const civil_day max_day(kIntMax, 12, 31);
EXPECT_EQ(1, max_day - (max_day - 1));
EXPECT_EQ(-1, (max_day - 1) - max_day);
const civil_day min_day(kIntMin, 1, 1);
EXPECT_EQ(1, (min_day + 1) - min_day);
EXPECT_EQ(-1, min_day - (min_day + 1));
const civil_day d1(1970, 1, 1);
const civil_day d2(5881580, 7, 11);
EXPECT_EQ(kIntMax, d2 - d1);
EXPECT_EQ(kIntMin, d1 - (d2 + 1));
}
TEST(CivilTime, Properties) {
civil_second ss(2015, 2, 3, 4, 5, 6);
EXPECT_EQ(2015, ss.year());
EXPECT_EQ(2, ss.month());
EXPECT_EQ(3, ss.day());
EXPECT_EQ(4, ss.hour());
EXPECT_EQ(5, ss.minute());
EXPECT_EQ(6, ss.second());
EXPECT_EQ(weekday::tuesday, get_weekday(ss));
EXPECT_EQ(34, get_yearday(ss));
civil_minute mm(2015, 2, 3, 4, 5, 6);
EXPECT_EQ(2015, mm.year());
EXPECT_EQ(2, mm.month());
EXPECT_EQ(3, mm.day());
EXPECT_EQ(4, mm.hour());
EXPECT_EQ(5, mm.minute());
EXPECT_EQ(0, mm.second());
EXPECT_EQ(weekday::tuesday, get_weekday(mm));
EXPECT_EQ(34, get_yearday(mm));
civil_hour hh(2015, 2, 3, 4, 5, 6);
EXPECT_EQ(2015, hh.year());
EXPECT_EQ(2, hh.month());
EXPECT_EQ(3, hh.day());
EXPECT_EQ(4, hh.hour());
EXPECT_EQ(0, hh.minute());
EXPECT_EQ(0, hh.second());
EXPECT_EQ(weekday::tuesday, get_weekday(hh));
EXPECT_EQ(34, get_yearday(hh));
civil_day d(2015, 2, 3, 4, 5, 6);
EXPECT_EQ(2015, d.year());
EXPECT_EQ(2, d.month());
EXPECT_EQ(3, d.day());
EXPECT_EQ(0, d.hour());
EXPECT_EQ(0, d.minute());
EXPECT_EQ(0, d.second());
EXPECT_EQ(weekday::tuesday, get_weekday(d));
EXPECT_EQ(34, get_yearday(d));
civil_month m(2015, 2, 3, 4, 5, 6);
EXPECT_EQ(2015, m.year());
EXPECT_EQ(2, m.month());
EXPECT_EQ(1, m.day());
EXPECT_EQ(0, m.hour());
EXPECT_EQ(0, m.minute());
EXPECT_EQ(0, m.second());
EXPECT_EQ(weekday::sunday, get_weekday(m));
EXPECT_EQ(32, get_yearday(m));
civil_year y(2015, 2, 3, 4, 5, 6);
EXPECT_EQ(2015, y.year());
EXPECT_EQ(1, y.month());
EXPECT_EQ(1, y.day());
EXPECT_EQ(0, y.hour());
EXPECT_EQ(0, y.minute());
EXPECT_EQ(0, y.second());
EXPECT_EQ(weekday::thursday, get_weekday(y));
EXPECT_EQ(1, get_yearday(y));
}
TEST(CivilTime, OutputStream) {
EXPECT_EQ("2016", Format(civil_year(2016)));
EXPECT_EQ("123", Format(civil_year(123)));
EXPECT_EQ("0", Format(civil_year(0)));
EXPECT_EQ("-1", Format(civil_year(-1)));
EXPECT_EQ("2016-02", Format(civil_month(2016, 2)));
EXPECT_EQ("2016-02-03", Format(civil_day(2016, 2, 3)));
EXPECT_EQ("2016-02-03T04", Format(civil_hour(2016, 2, 3, 4)));
EXPECT_EQ("2016-02-03T04:05", Format(civil_minute(2016, 2, 3, 4, 5)));
EXPECT_EQ("2016-02-03T04:05:06 |
2,585 | cpp | abseil/abseil-cpp | time | absl/time/time.cc | absl/time/time_test.cc | #ifndef ABSL_TIME_TIME_H_
#define ABSL_TIME_TIME_H_
#if !defined(_MSC_VER)
#include <sys/time.h>
#else
struct timeval;
#endif
#include <chrono>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <limits>
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
#include "absl/time/civil_time.h"
#include "absl/time/internal/cctz/include/cctz/time_zone.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class Duration;
class Time;
class TimeZone;
namespace time_internal {
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Time FromUnixDuration(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ToUnixDuration(Time t);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr int64_t GetRepHi(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr uint32_t GetRepLo(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
uint32_t lo);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration MakeDuration(int64_t hi,
int64_t lo);
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration MakePosDoubleDuration(double n);
constexpr int64_t kTicksPerNanosecond = 4;
constexpr int64_t kTicksPerSecond = 1000 * 1000 * 1000 * kTicksPerNanosecond;
template <std::intmax_t N>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
std::ratio<1, N>);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
std::ratio<60>);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration FromInt64(int64_t v,
std::ratio<3600>);
template <typename T>
using EnableIfIntegral = typename std::enable_if<
std::is_integral<T>::value || std::is_enum<T>::value, int>::type;
template <typename T>
using EnableIfFloat =
typename std::enable_if<std::is_floating_point<T>::value, int>::type;
}
class Duration {
public:
constexpr Duration() : rep_hi_(0), rep_lo_(0) {}
#if !defined(__clang__) && defined(_MSC_VER) && _MSC_VER < 1930
constexpr Duration(const Duration& d)
: rep_hi_(d.rep_hi_), rep_lo_(d.rep_lo_) {}
#else
constexpr Duration(const Duration& d) = default;
#endif
Duration& operator=(const Duration& d) = default;
Duration& operator+=(Duration d);
Duration& operator-=(Duration d);
Duration& operator*=(int64_t r);
Duration& operator*=(double r);
Duration& operator/=(int64_t r);
Duration& operator/=(double r);
Duration& operator%=(Duration rhs);
template <typename T, time_internal::EnableIfIntegral<T> = 0>
Duration& operator*=(T r) {
int64_t x = r;
return *this *= x;
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
Duration& operator/=(T r) {
int64_t x = r;
return *this /= x;
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
Duration& operator*=(T r) {
double x = r;
return *this *= x;
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
Duration& operator/=(T r) {
double x = r;
return *this /= x;
}
template <typename H>
friend H AbslHashValue(H h, Duration d) {
return H::combine(std::move(h), d.rep_hi_.Get(), d.rep_lo_);
}
private:
friend constexpr int64_t time_internal::GetRepHi(Duration d);
friend constexpr uint32_t time_internal::GetRepLo(Duration d);
friend constexpr Duration time_internal::MakeDuration(int64_t hi,
uint32_t lo);
constexpr Duration(int64_t hi, uint32_t lo) : rep_hi_(hi), rep_lo_(lo) {}
class HiRep {
public:
HiRep() = default;
HiRep(const HiRep&) = default;
HiRep& operator=(const HiRep&) = default;
explicit constexpr HiRep(const int64_t value)
:
#if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
hi_(0),
lo_(0)
#else
lo_(0),
hi_(0)
#endif
{
*this = value;
}
constexpr int64_t Get() const {
const uint64_t unsigned_value =
(static_cast<uint64_t>(hi_) << 32) | static_cast<uint64_t>(lo_);
static_assert(
(static_cast<int64_t>((std::numeric_limits<uint64_t>::max)()) ==
int64_t{-1}) &&
(static_cast<int64_t>(static_cast<uint64_t>(
(std::numeric_limits<int64_t>::max)()) +
1) ==
(std::numeric_limits<int64_t>::min)()),
"static_cast<int64_t>(uint64_t) does not have c++20 semantics");
return static_cast<int64_t>(unsigned_value);
}
constexpr HiRep& operator=(const int64_t value) {
const auto unsigned_value = static_cast<uint64_t>(value);
hi_ = static_cast<uint32_t>(unsigned_value >> 32);
lo_ = static_cast<uint32_t>(unsigned_value);
return *this;
}
private:
#if defined(ABSL_IS_BIG_ENDIAN) && ABSL_IS_BIG_ENDIAN
uint32_t hi_;
uint32_t lo_;
#else
uint32_t lo_;
uint32_t hi_;
#endif
};
HiRep rep_hi_;
uint32_t rep_lo_;
};
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<(Duration lhs,
Duration rhs);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>(Duration lhs,
Duration rhs) {
return rhs < lhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator>=(Duration lhs,
Duration rhs) {
return !(lhs < rhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator<=(Duration lhs,
Duration rhs) {
return !(rhs < lhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator==(Duration lhs,
Duration rhs);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr bool operator!=(Duration lhs,
Duration rhs) {
return !(lhs == rhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration operator-(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator+(Duration lhs,
Duration rhs) {
return lhs += rhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator-(Duration lhs,
Duration rhs) {
return lhs -= rhs;
}
int64_t IDivDuration(Duration num, Duration den, Duration* rem);
ABSL_ATTRIBUTE_CONST_FUNCTION double FDivDuration(Duration num, Duration den);
template <typename T>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(Duration lhs, T rhs) {
return lhs *= rhs;
}
template <typename T>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator*(T lhs, Duration rhs) {
return rhs *= lhs;
}
template <typename T>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration operator/(Duration lhs, T rhs) {
return lhs /= rhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline int64_t operator/(Duration lhs,
Duration rhs) {
return IDivDuration(lhs, rhs,
&lhs);
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration operator%(Duration lhs,
Duration rhs) {
return lhs %= rhs;
}
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration ZeroDuration() {
return Duration();
}
ABSL_ATTRIBUTE_CONST_FUNCTION inline Duration AbsDuration(Duration d) {
return (d < ZeroDuration()) ? -d : d;
}
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Trunc(Duration d, Duration unit);
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Floor(Duration d, Duration unit);
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Ceil(Duration d, Duration unit);
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration InfiniteDuration();
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Nanoseconds(T n) {
return time_internal::FromInt64(n, std::nano{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Microseconds(T n) {
return time_internal::FromInt64(n, std::micro{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Milliseconds(T n) {
return time_internal::FromInt64(n, std::milli{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Seconds(T n) {
return time_internal::FromInt64(n, std::ratio<1>{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Minutes(T n) {
return time_internal::FromInt64(n, std::ratio<60>{});
}
template <typename T, time_internal::EnableIfIntegral<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION constexpr Duration Hours(T n) {
return time_internal::FromInt64(n, std::ratio<3600>{});
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Nanoseconds(T n) {
return n * Nanoseconds(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Microseconds(T n) {
return n * Microseconds(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Milliseconds(T n) {
return n * Milliseconds(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Seconds(T n) {
if (n >= 0) {
if (n >= static_cast<T>((std::numeric_limits<int64_t>::max)())) {
return InfiniteDuration();
}
return time_internal::MakePosDoubleDuration(n);
} else {
if (std::isnan(n))
return std::signbit(n) ? -InfiniteDuration() : InfiniteDuration();
if (n <= (std::numeric_limits<int64_t>::min)()) return -InfiniteDuration();
return -time_internal::MakePosDoubleDuration(-n);
}
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Minutes(T n) {
return n * Minutes(1);
}
template <typename T, time_internal::EnableIfFloat<T> = 0>
ABSL_ATTRIBUTE_CONST_FUNCTION Duration Hours(T n) {
return n * Hours(1);
}
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Nanoseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Microseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Milliseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Seconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Minutes(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION int64_t ToInt64Hours(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleNanoseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMicroseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMilliseconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleSeconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleMinutes(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION double ToDoubleHours(Duration d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::nanoseconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::microseconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::milliseconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::seconds& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::minutes& d);
ABSL_ATTRIBUTE_PURE_FUNCTION constexpr Duration FromChrono(
const std::chrono::hours& d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::nanoseconds ToChronoNanoseconds(
Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::microseconds ToChronoMicroseconds(
Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::milliseconds ToChronoMilliseconds(
Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::seconds ToChronoSeconds(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::minutes ToChronoMinutes(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::chrono::hours ToChronoHours(Duration d);
ABSL_ATTRIBUTE_CONST_FUNCTION std::string FormatDuration(Duration d);
inline std::ostream& operator<<(std::ostream& os, Duration d) {
return os << FormatDuration(d);
}
template <typename Sink>
void AbslStringify(Sink& sink, Duration d) {
sink.Append(FormatDuration(d));
}
bool ParseDuration(absl::string_view dur_string, Duration* d);
bool AbslParseFlag(absl::string_view text, Duration* dst, std::string* error);
std::string AbslUnparseFlag(Duration d);
ABSL_DEPRECATED("Use AbslParseFlag() instead.")
bool ParseFlag(const std::string& text, Duration* dst, std::string* error);
ABSL_DEPRECATED("Use AbslUnparseFlag() instead.")
std::string UnparseFlag(Duration d);
class Time {
public:
constexpr Time() = default;
constexpr Time(const Time& t) = default;
Time& operator=(const Time& t) = default;
Time& operator+=(Duration d) {
rep_ += d;
return *this;
}
Time& operator-=(Duration d) {
rep_ -= d;
return *this;
}
struct ABSL_DEPRECATED("Use `absl::TimeZone::CivilInfo`.") Breakdown {
int64_t year;
int month;
int day;
int hour;
int minute;
int second;
Duration subsecond;
int weekday;
int yearday;
int offset;
bool is_dst;
const char* zone_abbr;
};
ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING
ABSL_DEPRECATED("Use `absl::TimeZone::At(Time)`.")
Breakdown In(TimeZone tz) const;
ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING
template <typename H>
friend H AbslHashValue(H h, Time t) {
return H::combine(std::move(h), t.rep_);
}
private:
friend constexpr Time time_internal::FromUnixDuration(Duration d);
friend constexpr Duration time_internal::ToUnixDuration(Time t);
friend constexpr bool operator<(Time lhs, Time rhs);
friend constexpr bool operator==(Time lhs, Time rhs);
friend Duration operator-(Time lhs, Time rhs);
friend constexpr Time UniversalEpoch();
friend constexpr Time InfiniteFuture();
friend constexpr Time InfinitePast();
constexpr explicit Time(Duration rep) : rep_(rep) {}
Duration rep_;
};
ABSL_ATTRIBUTE_CONST_FUNCTION constex | #include "absl/time/time.h"
#include <cstdint>
#include <ios>
#include "absl/time/civil_time.h"
#if defined(_MSC_VER)
#include <winsock2.h>
#endif
#include <chrono>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <limits>
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/numeric/int128.h"
#include "absl/strings/str_format.h"
#include "absl/time/clock.h"
#include "absl/time/internal/test_util.h"
namespace {
#if defined(GTEST_USES_SIMPLE_RE) && GTEST_USES_SIMPLE_RE
const char kZoneAbbrRE[] = ".*";
#else
const char kZoneAbbrRE[] = "[A-Za-z]{3,4}|[-+][0-9]{2}([0-9]{2})?";
#endif
#define EXPECT_CIVIL_INFO(ci, y, m, d, h, min, s, off, isdst) \
do { \
EXPECT_EQ(y, ci.cs.year()); \
EXPECT_EQ(m, ci.cs.month()); \
EXPECT_EQ(d, ci.cs.day()); \
EXPECT_EQ(h, ci.cs.hour()); \
EXPECT_EQ(min, ci.cs.minute()); \
EXPECT_EQ(s, ci.cs.second()); \
EXPECT_EQ(off, ci.offset); \
EXPECT_EQ(isdst, ci.is_dst); \
EXPECT_THAT(ci.zone_abbr, testing::MatchesRegex(kZoneAbbrRE)); \
} while (0)
MATCHER_P(TimespecMatcher, ts, "") {
if (ts.tv_sec == arg.tv_sec && ts.tv_nsec == arg.tv_nsec) return true;
*result_listener << "expected: {" << ts.tv_sec << ", " << ts.tv_nsec << "} ";
*result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_nsec << "}";
return false;
}
MATCHER_P(TimevalMatcher, tv, "") {
if (tv.tv_sec == arg.tv_sec && tv.tv_usec == arg.tv_usec) return true;
*result_listener << "expected: {" << tv.tv_sec << ", " << tv.tv_usec << "} ";
*result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_usec << "}";
return false;
}
TEST(Time, ConstExpr) {
constexpr absl::Time t0 = absl::UnixEpoch();
static_assert(t0 == absl::UnixEpoch(), "UnixEpoch");
constexpr absl::Time t1 = absl::InfiniteFuture();
static_assert(t1 != absl::UnixEpoch(), "InfiniteFuture");
constexpr absl::Time t2 = absl::InfinitePast();
static_assert(t2 != absl::UnixEpoch(), "InfinitePast");
constexpr absl::Time t3 = absl::FromUnixNanos(0);
static_assert(t3 == absl::UnixEpoch(), "FromUnixNanos");
constexpr absl::Time t4 = absl::FromUnixMicros(0);
static_assert(t4 == absl::UnixEpoch(), "FromUnixMicros");
constexpr absl::Time t5 = absl::FromUnixMillis(0);
static_assert(t5 == absl::UnixEpoch(), "FromUnixMillis");
constexpr absl::Time t6 = absl::FromUnixSeconds(0);
static_assert(t6 == absl::UnixEpoch(), "FromUnixSeconds");
constexpr absl::Time t7 = absl::FromTimeT(0);
static_assert(t7 == absl::UnixEpoch(), "FromTimeT");
}
TEST(Time, ValueSemantics) {
absl::Time a;
absl::Time b = a;
EXPECT_EQ(a, b);
absl::Time c(a);
EXPECT_EQ(a, b);
EXPECT_EQ(a, c);
EXPECT_EQ(b, c);
b = c;
EXPECT_EQ(a, b);
EXPECT_EQ(a, c);
EXPECT_EQ(b, c);
}
TEST(Time, UnixEpoch) {
const auto ci = absl::UTCTimeZone().At(absl::UnixEpoch());
EXPECT_EQ(absl::CivilSecond(1970, 1, 1, 0, 0, 0), ci.cs);
EXPECT_EQ(absl::ZeroDuration(), ci.subsecond);
EXPECT_EQ(absl::Weekday::thursday, absl::GetWeekday(ci.cs));
}
TEST(Time, Breakdown) {
absl::TimeZone tz = absl::time_internal::LoadTimeZone("America/New_York");
absl::Time t = absl::UnixEpoch();
auto ci = tz.At(t);
EXPECT_CIVIL_INFO(ci, 1969, 12, 31, 19, 0, 0, -18000, false);
EXPECT_EQ(absl::ZeroDuration(), ci.subsecond);
EXPECT_EQ(absl::Weekday::wednesday, absl::GetWeekday(ci.cs));
t -= absl::Nanoseconds(1);
ci = tz.At(t);
EXPECT_CIVIL_INFO(ci, 1969, 12, 31, 18, 59, 59, -18000, false);
EXPECT_EQ(absl::Nanoseconds(999999999), ci.subsecond);
EXPECT_EQ(absl::Weekday::wednesday, absl::GetWeekday(ci.cs));
t += absl::Hours(24) * 2735;
t += absl::Hours(18) + absl::Minutes(30) + absl::Seconds(15) +
absl::Nanoseconds(9);
ci = tz.At(t);
EXPECT_CIVIL_INFO(ci, 1977, 6, 28, 14, 30, 15, -14400, true);
EXPECT_EQ(8, ci.subsecond / absl::Nanoseconds(1));
EXPECT_EQ(absl::Weekday::tuesday, absl::GetWeekday(ci.cs));
}
TEST(Time, AdditiveOperators) {
const absl::Duration d = absl::Nanoseconds(1);
const absl::Time t0;
const absl::Time t1 = t0 + d;
EXPECT_EQ(d, t1 - t0);
EXPECT_EQ(-d, t0 - t1);
EXPECT_EQ(t0, t1 - d);
absl::Time t(t0);
EXPECT_EQ(t0, t);
t += d;
EXPECT_EQ(t0 + d, t);
EXPECT_EQ(d, t - t0);
t -= d;
EXPECT_EQ(t0, t);
t = absl::UnixEpoch();
t += absl::Milliseconds(500);
EXPECT_EQ(absl::UnixEpoch() + absl::Milliseconds(500), t);
t += absl::Milliseconds(600);
EXPECT_EQ(absl::UnixEpoch() + absl::Milliseconds(1100), t);
t -= absl::Milliseconds(600);
EXPECT_EQ(absl::UnixEpoch() + absl::Milliseconds(500), t);
t -= absl::Milliseconds(500);
EXPECT_EQ(absl::UnixEpoch(), t);
}
TEST(Time, RelationalOperators) {
constexpr absl::Time t1 = absl::FromUnixNanos(0);
constexpr absl::Time t2 = absl::FromUnixNanos(1);
constexpr absl::Time t3 = absl::FromUnixNanos(2);
static_assert(absl::UnixEpoch() == t1, "");
static_assert(t1 == t1, "");
static_assert(t2 == t2, "");
static_assert(t3 == t3, "");
static_assert(t1 < t2, "");
static_assert(t2 < t3, "");
static_assert(t1 < t3, "");
static_assert(t1 <= t1, "");
static_assert(t1 <= t2, "");
static_assert(t2 <= t2, "");
static_assert(t2 <= t3, "");
static_assert(t3 <= t3, "");
static_assert(t1 <= t3, "");
static_assert(t2 > t1, "");
static_assert(t3 > t2, "");
static_assert(t3 > t1, "");
static_assert(t2 >= t2, "");
static_assert(t2 >= t1, "");
static_assert(t3 >= t3, "");
static_assert(t3 >= t2, "");
static_assert(t1 >= t1, "");
static_assert(t3 >= t1, "");
}
TEST(Time, Infinity) {
constexpr absl::Time ifuture = absl::InfiniteFuture();
constexpr absl::Time ipast = absl::InfinitePast();
static_assert(ifuture == ifuture, "");
static_assert(ipast == ipast, "");
static_assert(ipast < ifuture, "");
static_assert(ifuture > ipast, "");
EXPECT_EQ(ifuture, ifuture + absl::Seconds(1));
EXPECT_EQ(ifuture, ifuture - absl::Seconds(1));
EXPECT_EQ(ipast, ipast + absl::Seconds(1));
EXPECT_EQ(ipast, ipast - absl::Seconds(1));
EXPECT_EQ(absl::InfiniteDuration(), ifuture - ifuture);
EXPECT_EQ(absl::InfiniteDuration(), ifuture - ipast);
EXPECT_EQ(-absl::InfiniteDuration(), ipast - ifuture);
EXPECT_EQ(-absl::InfiniteDuration(), ipast - ipast);
constexpr absl::Time t = absl::UnixEpoch();
static_assert(t < ifuture, "");
static_assert(t > ipast, "");
EXPECT_EQ(ifuture, t + absl::InfiniteDuration());
EXPECT_EQ(ipast, t - absl::InfiniteDuration());
}
TEST(Time, FloorConversion) {
#define TEST_FLOOR_CONVERSION(TO, FROM) \
EXPECT_EQ(1, TO(FROM(1001))); \
EXPECT_EQ(1, TO(FROM(1000))); \
EXPECT_EQ(0, TO(FROM(999))); \
EXPECT_EQ(0, TO(FROM(1))); \
EXPECT_EQ(0, TO(FROM(0))); \
EXPECT_EQ(-1, TO(FROM(-1))); \
EXPECT_EQ(-1, TO(FROM(-999))); \
EXPECT_EQ(-1, TO(FROM(-1000))); \
EXPECT_EQ(-2, TO(FROM(-1001)));
TEST_FLOOR_CONVERSION(absl::ToUnixMicros, absl::FromUnixNanos);
TEST_FLOOR_CONVERSION(absl::ToUnixMillis, absl::FromUnixMicros);
TEST_FLOOR_CONVERSION(absl::ToUnixSeconds, absl::FromUnixMillis);
TEST_FLOOR_CONVERSION(absl::ToTimeT, absl::FromUnixMillis);
#undef TEST_FLOOR_CONVERSION
EXPECT_EQ(1, absl::ToUnixNanos(absl::UnixEpoch() + absl::Nanoseconds(3) / 2));
EXPECT_EQ(1, absl::ToUnixNanos(absl::UnixEpoch() + absl::Nanoseconds(1)));
EXPECT_EQ(0, absl::ToUnixNanos(absl::UnixEpoch() + absl::Nanoseconds(1) / 2));
EXPECT_EQ(0, absl::ToUnixNanos(absl::UnixEpoch() + absl::ZeroDuration()));
EXPECT_EQ(-1,
absl::ToUnixNanos(absl::UnixEpoch() - absl::Nanoseconds(1) / 2));
EXPECT_EQ(-1, absl::ToUnixNanos(absl::UnixEpoch() - absl::Nanoseconds(1)));
EXPECT_EQ(-2,
absl::ToUnixNanos(absl::UnixEpoch() - absl::Nanoseconds(3) / 2));
EXPECT_EQ(1,
absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(101)));
EXPECT_EQ(1,
absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(100)));
EXPECT_EQ(0,
absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(99)));
EXPECT_EQ(0,
absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(1)));
EXPECT_EQ(0,
absl::ToUniversal(absl::UniversalEpoch() + absl::ZeroDuration()));
EXPECT_EQ(-1,
absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-1)));
EXPECT_EQ(-1,
absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-99)));
EXPECT_EQ(
-1, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-100)));
EXPECT_EQ(
-2, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-101)));
const struct {
absl::Time t;
timespec ts;
} to_ts[] = {
{absl::FromUnixSeconds(1) + absl::Nanoseconds(1), {1, 1}},
{absl::FromUnixSeconds(1) + absl::Nanoseconds(1) / 2, {1, 0}},
{absl::FromUnixSeconds(1) + absl::ZeroDuration(), {1, 0}},
{absl::FromUnixSeconds(0) + absl::ZeroDuration(), {0, 0}},
{absl::FromUnixSeconds(0) - absl::Nanoseconds(1) / 2, {-1, 999999999}},
{absl::FromUnixSeconds(0) - absl::Nanoseconds(1), {-1, 999999999}},
{absl::FromUnixSeconds(-1) + absl::Nanoseconds(1), {-1, 1}},
{absl::FromUnixSeconds(-1) + absl::Nanoseconds(1) / 2, {-1, 0}},
{absl::FromUnixSeconds(-1) + absl::ZeroDuration(), {-1, 0}},
{absl::FromUnixSeconds(-1) - absl::Nanoseconds(1) / 2, {-2, 999999999}},
};
for (const auto& test : to_ts) {
EXPECT_THAT(absl::ToTimespec(test.t), TimespecMatcher(test.ts));
}
const struct {
timespec ts;
absl::Time t;
} from_ts[] = {
{{1, 1}, absl::FromUnixSeconds(1) + absl::Nanoseconds(1)},
{{1, 0}, absl::FromUnixSeconds(1) + absl::ZeroDuration()},
{{0, 0}, absl::FromUnixSeconds(0) + absl::ZeroDuration()},
{{0, -1}, absl::FromUnixSeconds(0) - absl::Nanoseconds(1)},
{{-1, 999999999}, absl::FromUnixSeconds(0) - absl::Nanoseconds(1)},
{{-1, 1}, absl::FromUnixSeconds(-1) + absl::Nanoseconds(1)},
{{-1, 0}, absl::FromUnixSeconds(-1) + absl::ZeroDuration()},
{{-1, -1}, absl::FromUnixSeconds(-1) - absl::Nanoseconds(1)},
{{-2, 999999999}, absl::FromUnixSeconds(-1) - absl::Nanoseconds(1)},
};
for (const auto& test : from_ts) {
EXPECT_EQ(test.t, absl::TimeFromTimespec(test.ts));
}
const struct {
absl::Time t;
timeval tv;
} to_tv[] = {
{absl::FromUnixSeconds(1) + absl::Microseconds(1), {1, 1}},
{absl::FromUnixSeconds(1) + absl::Microseconds(1) / 2, {1, 0}},
{absl::FromUnixSeconds(1) + absl::ZeroDuration(), {1, 0}},
{absl::FromUnixSeconds(0) + absl::ZeroDuration(), {0, 0}},
{absl::FromUnixSeconds(0) - absl::Microseconds(1) / 2, {-1, 999999}},
{absl::FromUnixSeconds(0) - absl::Microseconds(1), {-1, 999999}},
{absl::FromUnixSeconds(-1) + absl::Microseconds(1), {-1, 1}},
{absl::FromUnixSeconds(-1) + absl::Microseconds(1) / 2, {-1, 0}},
{absl::FromUnixSeconds(-1) + absl::ZeroDuration(), {-1, 0}},
{absl::FromUnixSeconds(-1) - absl::Microseconds(1) / 2, {-2, 999999}},
};
for (const auto& test : to_tv) {
EXPECT_THAT(absl::ToTimeval(test.t), TimevalMatcher(test.tv));
}
const struct {
timeval tv;
absl::Time t;
} from_tv[] = {
{{1, 1}, absl::FromUnixSeconds(1) + absl::Microseconds(1)},
{{1, 0}, absl::FromUnixSeconds(1) + absl::ZeroDuration()},
{{0, 0}, absl::FromUnixSeconds(0) + absl::ZeroDuration()},
{{0, -1}, absl::FromUnixSeconds(0) - absl::Microseconds(1)},
{{-1, 999999}, absl::FromUnixSeconds(0) - absl::Microseconds(1)},
{{-1, 1}, absl::FromUnixSeconds(-1) + absl::Microseconds(1)},
{{-1, 0}, absl::FromUnixSeconds(-1) + absl::ZeroDuration()},
{{-1, -1}, absl::FromUnixSeconds(-1) - absl::Microseconds(1)},
{{-2, 999999}, absl::FromUnixSeconds(-1) - absl::Microseconds(1)},
};
for (const auto& test : from_tv) {
EXPECT_EQ(test.t, absl::TimeFromTimeval(test.tv));
}
const int64_t min_plus_1 = std::numeric_limits<int64_t>::min() + 1;
EXPECT_EQ(min_plus_1, absl::ToUnixSeconds(absl::FromUnixSeconds(min_plus_1)));
EXPECT_EQ(std::numeric_limits<int64_t>::min(),
absl::ToUnixSeconds(absl::FromUnixSeconds(min_plus_1) -
absl::Nanoseconds(1) / 2));
EXPECT_EQ(std::numeric_limits<int64_t>::max(),
absl::ToUnixSeconds(
absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()) +
absl::Nanoseconds(1) / 2));
EXPECT_EQ(std::numeric_limits<int64_t>::max(),
absl::ToUnixSeconds(
absl::FromUnixSeconds(std::numeric_limits<int64_t>::max())));
EXPECT_EQ(std::numeric_limits<int64_t>::max() - 1,
absl::ToUnixSeconds(
absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()) -
absl::Nanoseconds(1) / 2));
}
TEST(Time, RoundtripConversion) {
#define TEST_CONVERSION_ROUND_TRIP(SOURCE, FROM, TO, MATCHER) \
EXPECT_THAT(TO(FROM(SOURCE)), MATCHER(SOURCE))
int64_t now_ns = absl::GetCurrentTimeNanos();
TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixNanos, absl::ToUnixNanos,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixNanos, absl::ToUnixNanos,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixNanos, absl::ToUnixNanos,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(now_ns, absl::FromUnixNanos, absl::ToUnixNanos,
testing::Eq)
<< now_ns;
int64_t now_us = absl::GetCurrentTimeNanos() / 1000;
TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixMicros, absl::ToUnixMicros,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixMicros, absl::ToUnixMicros,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixMicros, absl::ToUnixMicros,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(now_us, absl::FromUnixMicros, absl::ToUnixMicros,
testing::Eq)
<< now_us;
int64_t now_ms = absl::GetCurrentTimeNanos() / 1000000;
TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixMillis, absl::ToUnixMillis,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixMillis, absl::ToUnixMillis,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixMillis, absl::ToUnixMillis,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(now_ms, absl::FromUnixMillis, absl::ToUnixMillis,
testing::Eq)
<< now_ms;
int64_t now_s = std::time(nullptr);
TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixSeconds, absl::ToUnixSeconds,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixSeconds, absl::ToUnixSeconds,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixSeconds, absl::ToUnixSeconds,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(now_s, absl::FromUnixSeconds, absl::ToUnixSeconds,
testing::Eq)
<< now_s;
time_t now_time_t = std::time(nullptr);
TEST_CONVERSION_ROUND_TRIP(-1, absl::FromTimeT, absl::ToTimeT, testing::Eq);
TEST_CONVERSION_ROUND_TRIP(0, absl::FromTimeT, absl::ToTimeT, testing::Eq);
TEST_CONVERSION_ROUND_TRIP(1, absl::FromTimeT, absl::ToTimeT, testing::Eq);
TEST_CONVERSION_ROUND_TRIP(now_time_t, absl::FromTimeT, absl::ToTimeT,
testing::Eq)
<< now_time_t;
timeval tv;
tv.tv_sec = -1;
tv.tv_usec = 0;
TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval,
TimevalMatcher);
tv.tv_sec = -1;
tv.tv_usec = 999999;
TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval,
TimevalMatcher);
tv.tv_sec = 0;
tv.tv_usec = 0;
TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval,
TimevalMatcher);
tv.tv_sec = 0;
tv.tv_usec = 1;
TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval,
TimevalMatcher);
tv.tv_sec = 1;
tv.tv_usec = 0;
TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval,
TimevalMatcher);
timespec ts;
ts.tv_sec = -1;
ts.tv_nsec = 0;
TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec,
TimespecMatcher);
ts.tv_sec = -1;
ts.tv_nsec = 999999999;
TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec,
TimespecMatcher);
ts.tv_sec = 0;
ts.tv_nsec = 0;
TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec,
TimespecMatcher);
ts.tv_sec = 0;
ts.tv_nsec = 1;
TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec,
TimespecMatcher);
ts.tv_sec = 1;
ts.tv_nsec = 0;
TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec,
TimespecMatcher);
double now_ud = absl::GetCurrentTimeNanos() / 1000000;
TEST_CONVERSION_ROUND_TRIP(-1.5, absl::FromUDate, absl::ToUDate,
testing::DoubleEq);
TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUDate, absl::ToUDate,
testing::DoubleEq);
TEST_CONVERSION_ROUND_TRIP(-0.5, absl::FromUDate, absl::ToUDate,
testing::DoubleEq);
TEST_CONVERSION_ROUND_TRIP(0, absl::FromUDate, absl::ToUDate,
testing::DoubleEq);
TEST_CONVERSION_ROUND_TRIP(0.5, absl::FromUDate, absl::ToUDate,
testing::DoubleEq);
TEST_CONVERSION_ROUND_TRIP(1, absl::FromUDate, absl::ToUDate,
testing::DoubleEq);
TEST_CONVERSION_ROUND_TRIP(1.5, absl::FromUDate, absl::ToUDate,
testing::DoubleEq);
TEST_CONVERSION_ROUND_TRIP(now_ud, absl::FromUDate, absl::ToUDate,
testing::DoubleEq)
<< std::fixed << std::setprecision(17) << now_ud;
int64_t now_uni = ((719162LL * (24 * 60 * 60)) * (1000 * 1000 * 10)) +
(absl::GetCurrentTimeNanos() / 100);
TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUniversal, absl::ToUniversal,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(0, absl::FromUniversal, absl::ToUniversal,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(1, absl::FromUniversal, absl::ToUniversal,
testing::Eq);
TEST_CONVERSION_ROUND_TRIP(now_uni, absl::FromUniversal, absl::ToUniversal,
testing::Eq)
<< now_uni;
#undef TEST_CONVERSION_ROUND_TRIP
}
template <typename Duration>
std::chrono::system_clock::time_point MakeChronoUnixTime(const Duration& d) {
return std::chrono::system_clock::from_time_t(0) + d;
}
TEST(Time, FromChrono) {
EXPECT_EQ(absl::FromTimeT(-1),
absl::FromChrono(std::chrono::system_clock::from_time_t(-1)));
EXPECT_EQ(absl::FromTimeT(0),
absl::FromChrono(std::chrono::system_clock::from_time_t(0)));
EXPECT_EQ(absl::FromTimeT(1),
absl::FromChrono(std::chrono::system_clock::from_time_t(1)));
EXPECT_EQ(
absl::FromUnixMillis(-1),
absl::FromChrono(MakeChronoUnixTime(std::chrono::milliseconds(-1))));
EXPECT_EQ(absl::FromUnixMillis(0),
absl::FromChrono(MakeChronoUnixTime(std::chrono::milliseconds(0))));
EXPECT_EQ(absl::FromUnixMillis(1),
absl::FromChrono(MakeChronoUnixTime(std::chrono::milliseconds(1))));
const auto century_sec = 60 * 60 * 24 * 365 * int64_t{100};
const auto century = std::chrono::seconds(century_sec);
const auto chrono_future = MakeChronoUnixTime(century);
const auto chrono_past = MakeChronoUnixTime(-century);
EXPECT_EQ(absl::FromUnixSeconds(century_sec),
absl::FromChrono(chrono_future));
EXPECT_EQ(absl::FromUnixSeconds(-century_sec), absl::FromChrono(chrono_past));
EXPECT_EQ(chrono_future,
absl::ToChronoTime(absl::FromUnixSeconds(century_sec)));
EXPECT_EQ(chrono_past,
absl::ToChronoTime(absl::FromUnixSeconds(-century_sec)));
}
TEST(Time, ToChronoTime) {
EXPECT_EQ(std::chrono::system_clock::from_time_t(-1),
absl::ToChronoTime(absl::FromTimeT(-1)));
EXPECT_EQ(std::chrono::system_clock::from_time_t(0),
absl::ToChronoTime(absl::FromTimeT(0)));
EXPECT_EQ(std::chrono::system_clock::from_time_t(1),
absl::ToChronoTime(absl::FromTimeT(1)));
EXPECT_EQ(MakeChronoUnixTime(std::chrono::milliseconds(-1)),
absl::ToChronoTime(absl::FromUnixMillis(-1)));
EXPECT_EQ(MakeChronoUnixTime(std::chrono::milliseconds(0)),
absl::ToChronoTime(absl::FromUnixMillis(0)));
EXPECT_EQ(MakeChronoUnixTime(std::chrono::milliseconds(1)),
absl::ToChronoTime(absl::FromUnixMillis(1)));
const auto tick = absl::Nanoseconds(1) / 4;
EXPECT_EQ(std::chrono::system_clock::from_time_t(0) -
std::chrono::system_clock::duration(1),
absl::ToChronoTime(absl::UnixEpoch() - tick));
}
TEST(Time, Chrono128) {
using Timestamp =
std::chrono::time_point<std::chrono::system_clock,
std::chrono::duration<absl::int128, std::atto>>;
for (const auto tp : {std::chrono::system_clock::time_point::min(),
std::chrono::system_clock::time_point::max()}) {
EXPECT_EQ(tp, absl::ToChronoTime(absl::FromChrono(tp)));
EXPECT_EQ(tp, std::chrono::time_point_cast<
std::chrono::system_clock::time_point::duration>(
std::chrono::time_point_cast<Timestamp::duration>(tp)));
}
Timestamp::duration::rep v = std::numeric_limits<int64_t>::min();
v *= Timestamp::duration::period::den;
auto ts = Timestamp(Timestamp::duration(v));
ts += std::chrono::duration<int64_t, std::atto>(0);
EXPECT_EQ(std::numeric_limits<int64_t>::min(),
ts.time_since_epoch().count() / Timestamp::duration::period::den);
EXPECT_EQ(0,
ts.time_since_epoch().count() % Timestamp::duration::period::den);
v = std::numeric_limits<int64_t>::max();
v *= Timestamp::duration::period::den;
ts = Timestamp(Timestamp::duration(v));
ts += std::chrono::duration<int64_t, std::atto>(999999999750000000);
EXPECT_EQ(std::numeric_limits<int64_t>::max(),
ts.time_since_epoch().count() / Timestamp::duration::period::den);
EXPECT_EQ(999999999750000000,
ts.time_since_epoch().count() % Timestamp::duration::period::den);
}
TEST(Time, TimeZoneAt) {
const absl::TimeZone nyc =
absl::time_internal::LoadTimeZone("America/New_York");
const std::string fmt = "%a, %e %b %Y %H:%M:%S %z (%Z)";
absl::CivilSecond nov01(2013, 11, 1, 8, 30, 0);
const auto nov01_ci = nyc.At(nov01);
EXPECT_EQ(absl::TimeZone::TimeInfo::UNIQUE, nov01_ci.kind);
EXPECT_EQ("Fri, 1 Nov 2013 08:30:00 -0400 (EDT)",
absl::FormatTime(fmt, nov01_ci.pre, nyc));
EXPECT_EQ(nov01_ci.pre, nov01_ci.trans);
EXPECT_EQ(nov01_ci.pre, nov01_ci.post);
EXPECT_EQ(nov01_ci.pre, absl::FromCivil(nov01, nyc));
absl::CivilSecond mar13(2011, 3, 13, 2, 15, 0);
const auto mar_ci = nyc.At(mar13);
EXPECT_EQ(absl::TimeZone::TimeInfo::SKIPPED, mar_ci.kind);
EXPECT_EQ("Sun, 13 Mar 2011 03:15:00 -0400 (EDT)",
absl::FormatTime(fmt, mar_ci.pre, nyc));
EXPECT_EQ("Sun, 13 Mar 2011 03:00:00 -0400 (EDT)",
absl::FormatTime(fmt, mar_ci.trans, nyc));
EXPECT_EQ("Sun, 13 Mar 2011 01:15:00 -0500 (EST)",
absl::FormatTime(fmt, mar_ci.post, nyc));
EXPECT_EQ(mar_ci.trans, absl::FromCivil(mar13, nyc));
absl::CivilSecond nov06(2011, 11, 6, 1, 15, 0);
const auto nov06_ci = nyc.At(nov06);
EXPECT_EQ(absl::TimeZone::TimeInfo::REPEATED, nov06_ci.kind);
EXPECT_EQ("Sun, 6 Nov 2011 01:15:00 -0400 (EDT)",
absl::FormatTime(fmt, nov06_ci.pre, nyc));
EXPECT_EQ("Sun, 6 Nov 2011 01:00:00 -0500 (EST)",
absl::FormatTime(fmt, nov06_ci.trans, nyc));
EXPECT_EQ("Sun, 6 Nov 2011 01:15:00 -0500 (EST)",
absl::FormatTime(fmt, nov06_ci.post, nyc));
EXPECT_EQ(nov06_ci.pre, absl::FromCivil(nov06, nyc));
absl::CivilSecond minus1(1969, 12, 31, 18, 59, 59);
const auto minus1_cl = nyc.At(minus1);
EXPECT_EQ(absl::TimeZone::TimeInfo::UNIQUE, minus1_cl.kind);
EXPECT_EQ(-1, absl::ToTimeT(minus1_cl.pre));
EXPECT_EQ("Wed, 31 Dec 1969 18:59:59 -0500 (EST)",
absl::FormatTime(fmt, minus1_cl.pre, nyc));
EXPECT_EQ("Wed, 31 Dec 1969 23:59:59 +0000 (UTC)",
absl::FormatTime(fmt, minus1_cl.pre, absl::UTCTimeZone()));
}
TEST(Time, FromCivilUTC) {
const absl::TimeZone utc = absl::UTCTimeZone();
const std::string fmt = "%a, %e %b %Y %H:%M:%S %z (%Z)";
const int kMax = std::numeric_limits<int>::max();
const int kMin = std::numeric_limits<int>::min();
absl::Time t;
t = absl::FromCivil(
absl::CivilSecond(292091940881, kMax, kMax, kMax, kMax, kMax), utc);
EXPECT_EQ("Fri, 25 Nov 292277026596 12:21:07 +0000 (UTC)",
absl::FormatTime(fmt, t, utc));
t = absl::FromCivil(
absl::CivilSecond(292091940882, kMax, kMax, kMax, kMax, kMax), utc);
EXPECT_EQ("infinite-future", absl::FormatTime(fmt, t, utc));
t = absl::FromCivil(
absl::CivilSecond(-292091936940, kMin, kMin, kMin, kMin, kMin), utc);
EXPECT_EQ("Fri, 1 Nov -292277022657 10:37:52 +0000 (UTC)",
absl::FormatTime(fmt, t, utc));
t = absl::FromCivil(
absl::CivilSecond(-292091936941, kMin, kMin, kMin, kMin, kMin), utc);
EXPECT_EQ("infinite-past", absl::FormatTime(fmt, t, utc));
t = absl::FromCivil(absl::CivilSecond(1900, 2, 28, 23, 59, 59), utc);
EXPECT_EQ("Wed, 28 Feb 1900 23:59:59 +0000 (UTC)",
absl::FormatTime(fmt, t, utc));
t = absl::FromCivil(absl::CivilSecond(1900, 3, 1, 0, 0, 0), utc);
EXPECT_EQ("Thu, 1 Mar 1900 00:00:00 +0000 (UTC)",
absl::FormatTime(fmt, t, utc));
t = absl::FromCivil(absl::CivilSecond(2000, 2, 29, 23, 59, 59), utc);
EXPECT_EQ("Tue, 29 Feb 2000 23:59:59 +0000 (UTC)",
absl::FormatTime(fmt, t, utc));
t = absl::FromCivil(absl::CivilSecond(2000, 3, 1, 0, 0, 0), utc);
EXPECT_EQ("Wed, 1 Mar 2000 00:00:00 +0000 (UTC)",
absl::FormatTime(fmt, t, utc));
}
TEST(Time, ToTM) {
const absl::TimeZone utc = absl::UTCTimeZone();
const absl::Time start =
absl::FromCivil(absl::CivilSecond(2014, 1, 2, 3, 4, 5), utc);
const absl::Time end =
absl::FromCivil(absl::CivilSecond(2014, 1, 5, 3, 4, 5), utc);
for (absl::Time t = start; t < end; t += absl::Seconds(30)) {
const struct tm tm_bt = absl::ToTM(t, utc);
const time_t tt = absl::ToTimeT(t);
struct tm tm_lc;
#ifdef _WIN32
gmtime_s(&tm_lc, &tt);
#else
gmtime_r(&tt, &tm_lc);
#endif
EXPECT_EQ(tm_lc.tm_year, tm_bt.tm_year);
EXPECT_EQ(tm_lc.tm_mon, tm_bt.tm_mon);
EXPECT_EQ(tm_lc.tm_mday, tm_bt.tm_mday);
EXPECT_EQ(tm_lc.tm_hour, tm_bt.tm_hour);
EXPECT_EQ(tm_lc.tm_min, tm_bt.tm_min);
EXPECT_EQ(tm_lc.tm_sec, tm_bt.tm_sec);
EXPECT_EQ(tm_lc.tm_wday, tm_bt.tm_wday);
EXPECT_EQ(tm_lc.tm_yday, tm_bt.tm_yday);
EXPECT_EQ(tm_lc.tm_isdst, tm_bt.tm_isdst);
ASSERT_FALSE(HasFailure());
}
const absl::TimeZone nyc =
absl::time_internal::LoadTimeZone("America/New_York");
absl::Time t = absl::FromCivil(absl::CivilSecond(2014, 3, 1, 0, 0, 0), nyc);
struct tm tm = absl::ToTM(t, nyc);
EXPECT_FALSE(tm.tm_isdst);
t = absl::FromCivil(absl::CivilSecond(2014, 4, 1, 0, 0, 0), nyc);
tm = absl::ToTM(t, nyc);
EXPECT_TRUE(tm.tm_isdst);
tm = absl::ToTM(absl::InfiniteFuture(), nyc);
EXPECT_EQ(std::numeric_limits<int>::max() - 1900, tm.tm_year);
EXPECT_EQ(11, tm.tm_mon);
EXPECT_EQ(31, tm.tm_mday);
EXPECT_EQ(23, tm.tm_hour);
EXPECT_EQ(59, tm.tm_min);
EXPECT_EQ(59, tm.tm_sec);
EXPECT_EQ(4, tm.tm_wday);
EXPECT_EQ(364, tm.tm_yday);
EXPECT_FALSE(tm.tm_isdst);
tm = absl::ToTM(absl::InfinitePast(), nyc);
EXPECT_EQ(std::numeric_limits<int>::min(), tm.tm_year);
EXPECT_EQ(0, tm.tm_mon);
EXPECT_EQ(1, tm.tm_mday);
EXPECT_EQ(0, tm.tm_hour);
EXPECT_EQ(0, tm.tm_min);
EXPECT_ |
2,586 | cpp | abseil/abseil-cpp | clock | absl/time/clock.cc | absl/time/clock_test.cc | #ifndef ABSL_TIME_CLOCK_H_
#define ABSL_TIME_CLOCK_H_
#include <cstdint>
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/time/time.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
absl::Time Now();
int64_t GetCurrentTimeNanos();
void SleepFor(absl::Duration duration);
ABSL_NAMESPACE_END
}
extern "C" {
ABSL_DLL void ABSL_INTERNAL_C_SYMBOL(AbslInternalSleepFor)(
absl::Duration duration);
}
inline void absl::SleepFor(absl::Duration duration) {
ABSL_INTERNAL_C_SYMBOL(AbslInternalSleepFor)(duration);
}
#endif
#include "absl/time/clock.h"
#include "absl/base/attributes.h"
#include "absl/base/optimization.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <cstdint>
#include <ctime>
#include <limits>
#include "absl/base/internal/spinlock.h"
#include "absl/base/internal/unscaledcycleclock.h"
#include "absl/base/macros.h"
#include "absl/base/port.h"
#include "absl/base/thread_annotations.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
Time Now() {
int64_t n = absl::GetCurrentTimeNanos();
if (n >= 0) {
return time_internal::FromUnixDuration(
time_internal::MakeDuration(n / 1000000000, n % 1000000000 * 4));
}
return time_internal::FromUnixDuration(absl::Nanoseconds(n));
}
ABSL_NAMESPACE_END
}
#ifndef ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
#define ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS 0
#endif
#if defined(__APPLE__) || defined(_WIN32)
#include "absl/time/internal/get_current_time_chrono.inc"
#else
#include "absl/time/internal/get_current_time_posix.inc"
#endif
#ifndef GET_CURRENT_TIME_NANOS_FROM_SYSTEM
#define GET_CURRENT_TIME_NANOS_FROM_SYSTEM() \
::absl::time_internal::GetCurrentTimeNanosFromSystem()
#endif
#if !ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS
namespace absl {
ABSL_NAMESPACE_BEGIN
int64_t GetCurrentTimeNanos() { return GET_CURRENT_TIME_NANOS_FROM_SYSTEM(); }
ABSL_NAMESPACE_END
}
#else
#ifndef GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW
#define GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW() \
::absl::time_internal::UnscaledCycleClockWrapperForGetCurrentTime::Now()
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace time_internal {
#if !defined(NDEBUG) && defined(__x86_64__)
constexpr int64_t kCycleClockNowMask = ~int64_t{0xff};
#else
constexpr int64_t kCycleClockNowMask = ~int64_t{0};
#endif
class UnscaledCycleClockWrapperForGetCurrentTime {
public:
static int64_t Now() {
return base_internal::UnscaledCycleClock::Now() & kCycleClockNowMask;
}
};
}
static inline uint64_t SeqAcquire(std::atomic<uint64_t> *seq) {
uint64_t x = seq->fetch_add(1, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
return x + 2;
}
static inline void SeqRelease(std::atomic<uint64_t> *seq, uint64_t x) {
seq->store(x, std::memory_order_release);
}
enum { kScale = 30 };
static const uint64_t kMinNSBetweenSamples = 2000 << 20;
static_assert(((kMinNSBetweenSamples << (kScale + 1)) >> (kScale + 1)) ==
kMinNSBetweenSamples,
"cannot represent kMaxBetweenSamplesNSScaled");
struct TimeSampleAtomic {
std::atomic<uint64_t> raw_ns{0};
std::atomic<uint64_t> base_ns{0};
std::atomic<uint64_t> base_cycles{0};
std::atomic<uint64_t> nsscaled_per_cycle{0};
std::atomic<uint64_t> min_cycles_per_sample{0};
};
struct TimeSample {
uint64_t raw_ns = 0;
uint64_t base_ns = 0;
uint64_t base_cycles = 0;
uint64_t nsscaled_per_cycle = 0;
uint64_t min_cycles_per_sample = 0;
};
struct ABSL_CACHELINE_ALIGNED TimeState {
std::atomic<uint64_t> seq{0};
TimeSampleAtomic last_sample;
int64_t stats_initializations{0};
int64_t stats_reinitializations{0};
int64_t stats_calibrations{0};
int64_t stats_slow_paths{0};
int64_t stats_fast_slow_paths{0};
uint64_t last_now_cycles ABSL_GUARDED_BY(lock){0};
std::atomic<uint64_t> approx_syscall_time_in_cycles{10 * 1000};
std::atomic<uint32_t> kernel_time_seen_smaller{0};
absl::base_internal::SpinLock lock{absl::kConstInit,
base_internal::SCHEDULE_KERNEL_ONLY};
};
ABSL_CONST_INIT static TimeState time_state;
static int64_t GetCurrentTimeNanosFromKernel(uint64_t last_cycleclock,
uint64_t *cycleclock)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(time_state.lock) {
uint64_t local_approx_syscall_time_in_cycles =
time_state.approx_syscall_time_in_cycles.load(std::memory_order_relaxed);
int64_t current_time_nanos_from_system;
uint64_t before_cycles;
uint64_t after_cycles;
uint64_t elapsed_cycles;
int loops = 0;
do {
before_cycles =
static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW());
current_time_nanos_from_system = GET_CURRENT_TIME_NANOS_FROM_SYSTEM();
after_cycles =
static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW());
elapsed_cycles = after_cycles - before_cycles;
if (elapsed_cycles >= local_approx_syscall_time_in_cycles &&
++loops == 20) {
loops = 0;
if (local_approx_syscall_time_in_cycles < 1000 * 1000) {
local_approx_syscall_time_in_cycles =
(local_approx_syscall_time_in_cycles + 1) << 1;
}
time_state.approx_syscall_time_in_cycles.store(
local_approx_syscall_time_in_cycles, std::memory_order_relaxed);
}
} while (elapsed_cycles >= local_approx_syscall_time_in_cycles ||
last_cycleclock - after_cycles < (static_cast<uint64_t>(1) << 16));
if ((local_approx_syscall_time_in_cycles >> 1) < elapsed_cycles) {
time_state.kernel_time_seen_smaller.store(0, std::memory_order_relaxed);
} else if (time_state.kernel_time_seen_smaller.fetch_add(
1, std::memory_order_relaxed) >= 3) {
const uint64_t new_approximation =
local_approx_syscall_time_in_cycles -
(local_approx_syscall_time_in_cycles >> 3);
time_state.approx_syscall_time_in_cycles.store(new_approximation,
std::memory_order_relaxed);
time_state.kernel_time_seen_smaller.store(0, std::memory_order_relaxed);
}
*cycleclock = after_cycles;
return current_time_nanos_from_system;
}
static int64_t GetCurrentTimeNanosSlowPath() ABSL_ATTRIBUTE_COLD;
static void ReadTimeSampleAtomic(const struct TimeSampleAtomic *atomic,
struct TimeSample *sample) {
sample->base_ns = atomic->base_ns.load(std::memory_order_relaxed);
sample->base_cycles = atomic->base_cycles.load(std::memory_order_relaxed);
sample->nsscaled_per_cycle =
atomic->nsscaled_per_cycle.load(std::memory_order_relaxed);
sample->min_cycles_per_sample =
atomic->min_cycles_per_sample.load(std::memory_order_relaxed);
sample->raw_ns = atomic->raw_ns.load(std::memory_order_relaxed);
}
int64_t GetCurrentTimeNanos() {
uint64_t base_ns;
uint64_t base_cycles;
uint64_t nsscaled_per_cycle;
uint64_t min_cycles_per_sample;
uint64_t seq_read0;
uint64_t seq_read1;
uint64_t now_cycles =
static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW());
seq_read0 = time_state.seq.load(std::memory_order_acquire);
base_ns = time_state.last_sample.base_ns.load(std::memory_order_relaxed);
base_cycles =
time_state.last_sample.base_cycles.load(std::memory_order_relaxed);
nsscaled_per_cycle =
time_state.last_sample.nsscaled_per_cycle.load(std::memory_order_relaxed);
min_cycles_per_sample = time_state.last_sample.min_cycles_per_sample.load(
std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
seq_read1 = time_state.seq.load(std::memory_order_relaxed);
uint64_t delta_cycles;
if (seq_read0 == seq_read1 && (seq_read0 & 1) == 0 &&
(delta_cycles = now_cycles - base_cycles) < min_cycles_per_sample) {
return static_cast<int64_t>(
base_ns + ((delta_cycles * nsscaled_per_cycle) >> kScale));
}
return GetCurrentTimeNanosSlowPath();
}
static uint64_t SafeDivideAndScale(uint64_t a, uint64_t b) {
int safe_shift = kScale;
while (((a << safe_shift) >> safe_shift) != a) {
safe_shift--;
}
uint64_t scaled_b = b >> (kScale - safe_shift);
uint64_t quotient = 0;
if (scaled_b != 0) {
quotient = (a << safe_shift) / scaled_b;
}
return quotient;
}
static uint64_t UpdateLastSample(
uint64_t now_cycles, uint64_t now_ns, uint64_t delta_cycles,
const struct TimeSample *sample) ABSL_ATTRIBUTE_COLD;
ABSL_ATTRIBUTE_NOINLINE
static int64_t GetCurrentTimeNanosSlowPath()
ABSL_LOCKS_EXCLUDED(time_state.lock) {
time_state.lock.Lock();
uint64_t now_cycles;
uint64_t now_ns = static_cast<uint64_t>(
GetCurrentTimeNanosFromKernel(time_state.last_now_cycles, &now_cycles));
time_state.last_now_cycles = now_cycles;
uint64_t estimated_base_ns;
struct TimeSample sample;
ReadTimeSampleAtomic(&time_state.last_sample, &sample);
uint64_t delta_cycles = now_cycles - sample.base_cycles;
if (delta_cycles < sample.min_cycles_per_sample) {
estimated_base_ns = sample.base_ns +
((delta_cycles * sample.nsscaled_per_cycle) >> kScale);
time_state.stats_fast_slow_paths++;
} else {
estimated_base_ns =
UpdateLastSample(now_cycles, now_ns, delta_cycles, &sample);
}
time_state.lock.Unlock();
return static_cast<int64_t>(estimated_base_ns);
}
static uint64_t UpdateLastSample(uint64_t now_cycles, uint64_t now_ns,
uint64_t delta_cycles,
const struct TimeSample *sample)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(time_state.lock) {
uint64_t estimated_base_ns = now_ns;
uint64_t lock_value =
SeqAcquire(&time_state.seq);
if (sample->raw_ns == 0 ||
sample->raw_ns + static_cast<uint64_t>(5) * 1000 * 1000 * 1000 < now_ns ||
now_ns < sample->raw_ns || now_cycles < sample->base_cycles) {
time_state.last_sample.raw_ns.store(now_ns, std::memory_order_relaxed);
time_state.last_sample.base_ns.store(estimated_base_ns,
std::memory_order_relaxed);
time_state.last_sample.base_cycles.store(now_cycles,
std::memory_order_relaxed);
time_state.last_sample.nsscaled_per_cycle.store(0,
std::memory_order_relaxed);
time_state.last_sample.min_cycles_per_sample.store(
0, std::memory_order_relaxed);
time_state.stats_initializations++;
} else if (sample->raw_ns + 500 * 1000 * 1000 < now_ns &&
sample->base_cycles + 50 < now_cycles) {
if (sample->nsscaled_per_cycle != 0) {
uint64_t estimated_scaled_ns;
int s = -1;
do {
s++;
estimated_scaled_ns = (delta_cycles >> s) * sample->nsscaled_per_cycle;
} while (estimated_scaled_ns / sample->nsscaled_per_cycle !=
(delta_cycles >> s));
estimated_base_ns = sample->base_ns +
(estimated_scaled_ns >> (kScale - s));
}
uint64_t ns = now_ns - sample->raw_ns;
uint64_t measured_nsscaled_per_cycle = SafeDivideAndScale(ns, delta_cycles);
uint64_t assumed_next_sample_delta_cycles =
SafeDivideAndScale(kMinNSBetweenSamples, measured_nsscaled_per_cycle);
int64_t diff_ns = static_cast<int64_t>(now_ns - estimated_base_ns);
ns = static_cast<uint64_t>(static_cast<int64_t>(kMinNSBetweenSamples) +
diff_ns - (diff_ns / 16));
uint64_t new_nsscaled_per_cycle =
SafeDivideAndScale(ns, assumed_next_sample_delta_cycles);
if (new_nsscaled_per_cycle != 0 &&
diff_ns < 100 * 1000 * 1000 && -diff_ns < 100 * 1000 * 1000) {
time_state.last_sample.nsscaled_per_cycle.store(
new_nsscaled_per_cycle, std::memory_order_relaxed);
uint64_t new_min_cycles_per_sample =
SafeDivideAndScale(kMinNSBetweenSamples, new_nsscaled_per_cycle);
time_state.last_sample.min_cycles_per_sample.store(
new_min_cycles_per_sample, std::memory_order_relaxed);
time_state.stats_calibrations++;
} else {
time_state.last_sample.nsscaled_per_cycle.store(
0, std::memory_order_relaxed);
time_state.last_sample.min_cycles_per_sample.store(
0, std::memory_order_relaxed);
estimated_base_ns = now_ns;
time_state.stats_reinitializations++;
}
time_state.last_sample.raw_ns.store(now_ns, std::memory_order_relaxed);
time_state.last_sample.base_ns.store(estimated_base_ns,
std::memory_order_relaxed);
time_state.last_sample.base_cycles.store(now_cycles,
std::memory_order_relaxed);
} else {
time_state.stats_slow_paths++;
}
SeqRelease(&time_state.seq, lock_value);
return estimated_base_ns;
}
ABSL_NAMESPACE_END
}
#endif
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace {
constexpr absl::Duration MaxSleep() {
#ifdef _WIN32
return absl::Milliseconds(
std::numeric_limits<unsigned long>::max());
#else
return absl::Seconds(std::numeric_limits<time_t>::max());
#endif
}
void SleepOnce(absl::Duration to_sleep) {
#ifdef _WIN32
Sleep(static_cast<DWORD>(to_sleep / absl::Milliseconds(1)));
#else
struct timespec sleep_time = absl::ToTimespec(to_sleep);
while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {
}
#endif
}
}
ABSL_NAMESPACE_END
}
extern "C" {
ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSleepFor)(
absl::Duration duration) {
while (duration > absl::ZeroDuration()) {
absl::Duration to_sleep = std::min(duration, absl::MaxSleep());
absl::SleepOnce(to_sleep);
duration -= to_sleep;
}
}
} | #include "absl/time/clock.h"
#include "absl/base/config.h"
#if defined(ABSL_HAVE_ALARM)
#include <signal.h>
#include <unistd.h>
#ifdef _AIX
typedef void (*sig_t)(int);
#endif
#elif defined(__linux__) || defined(__APPLE__)
#error all known Linux and Apple targets have alarm
#endif
#include "gtest/gtest.h"
#include "absl/time/time.h"
namespace {
TEST(Time, Now) {
const absl::Time before = absl::FromUnixNanos(absl::GetCurrentTimeNanos());
const absl::Time now = absl::Now();
const absl::Time after = absl::FromUnixNanos(absl::GetCurrentTimeNanos());
EXPECT_GE(now, before);
EXPECT_GE(after, now);
}
enum class AlarmPolicy { kWithoutAlarm, kWithAlarm };
#if defined(ABSL_HAVE_ALARM)
bool alarm_handler_invoked = false;
void AlarmHandler(int signo) {
ASSERT_EQ(signo, SIGALRM);
alarm_handler_invoked = true;
}
#endif
bool SleepForBounded(absl::Duration d, absl::Duration lower_bound,
absl::Duration upper_bound, absl::Duration timeout,
AlarmPolicy alarm_policy, int* attempts) {
const absl::Time deadline = absl::Now() + timeout;
while (absl::Now() < deadline) {
#if defined(ABSL_HAVE_ALARM)
sig_t old_alarm = SIG_DFL;
if (alarm_policy == AlarmPolicy::kWithAlarm) {
alarm_handler_invoked = false;
old_alarm = signal(SIGALRM, AlarmHandler);
alarm(absl::ToInt64Seconds(d / 2));
}
#else
EXPECT_EQ(alarm_policy, AlarmPolicy::kWithoutAlarm);
#endif
++*attempts;
absl::Time start = absl::Now();
absl::SleepFor(d);
absl::Duration actual = absl::Now() - start;
#if defined(ABSL_HAVE_ALARM)
if (alarm_policy == AlarmPolicy::kWithAlarm) {
signal(SIGALRM, old_alarm);
if (!alarm_handler_invoked) continue;
}
#endif
if (lower_bound <= actual && actual <= upper_bound) {
return true;
}
}
return false;
}
testing::AssertionResult AssertSleepForBounded(absl::Duration d,
absl::Duration early,
absl::Duration late,
absl::Duration timeout,
AlarmPolicy alarm_policy) {
const absl::Duration lower_bound = d - early;
const absl::Duration upper_bound = d + late;
int attempts = 0;
if (SleepForBounded(d, lower_bound, upper_bound, timeout, alarm_policy,
&attempts)) {
return testing::AssertionSuccess();
}
return testing::AssertionFailure()
<< "SleepFor(" << d << ") did not return within [" << lower_bound
<< ":" << upper_bound << "] in " << attempts << " attempt"
<< (attempts == 1 ? "" : "s") << " over " << timeout
<< (alarm_policy == AlarmPolicy::kWithAlarm ? " with" : " without")
<< " an alarm";
}
TEST(SleepFor, Bounded) {
const absl::Duration d = absl::Milliseconds(2500);
const absl::Duration early = absl::Milliseconds(100);
const absl::Duration late = absl::Milliseconds(300);
const absl::Duration timeout = 48 * d;
EXPECT_TRUE(AssertSleepForBounded(d, early, late, timeout,
AlarmPolicy::kWithoutAlarm));
#if defined(ABSL_HAVE_ALARM)
EXPECT_TRUE(AssertSleepForBounded(d, early, late, timeout,
AlarmPolicy::kWithAlarm));
#endif
}
} |
2,587 | cpp | abseil/abseil-cpp | statusor | absl/status/statusor.cc | absl/status/statusor_test.cc | #ifndef ABSL_STATUS_STATUSOR_H_
#define ABSL_STATUS_STATUSOR_H_
#include <exception>
#include <initializer_list>
#include <new>
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/nullability.h"
#include "absl/base/call_once.h"
#include "absl/meta/type_traits.h"
#include "absl/status/internal/statusor_internal.h"
#include "absl/status/status.h"
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/has_ostream_operator.h"
#include "absl/strings/str_format.h"
#include "absl/types/variant.h"
#include "absl/utility/utility.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
class BadStatusOrAccess : public std::exception {
public:
explicit BadStatusOrAccess(absl::Status status);
~BadStatusOrAccess() override = default;
BadStatusOrAccess(const BadStatusOrAccess& other);
BadStatusOrAccess& operator=(const BadStatusOrAccess& other);
BadStatusOrAccess(BadStatusOrAccess&& other);
BadStatusOrAccess& operator=(BadStatusOrAccess&& other);
absl::Nonnull<const char*> what() const noexcept override;
const absl::Status& status() const;
private:
void InitWhat() const;
absl::Status status_;
mutable absl::once_flag init_what_;
mutable std::string what_;
};
template <typename T>
#if ABSL_HAVE_CPP_ATTRIBUTE(nodiscard)
class [[nodiscard]] StatusOr;
#else
class ABSL_MUST_USE_RESULT StatusOr;
#endif
template <typename T>
class StatusOr : private internal_statusor::StatusOrData<T>,
private internal_statusor::CopyCtorBase<T>,
private internal_statusor::MoveCtorBase<T>,
private internal_statusor::CopyAssignBase<T>,
private internal_statusor::MoveAssignBase<T> {
template <typename U>
friend class StatusOr;
typedef internal_statusor::StatusOrData<T> Base;
public:
typedef T value_type;
explicit StatusOr();
StatusOr(const StatusOr&) = default;
StatusOr& operator=(const StatusOr&) = default;
StatusOr(StatusOr&&) = default;
StatusOr& operator=(StatusOr&&) = default;
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
false, T, U, false, const U&>::value,
int> = 0>
StatusOr(const StatusOr<U>& other)
: Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
false, T, U, true, const U&>::value,
int> = 0>
StatusOr(const StatusOr<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND)
: Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
true, T, U, false, const U&>::value,
int> = 0>
explicit StatusOr(const StatusOr<U>& other)
: Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
true, T, U, true, const U&>::value,
int> = 0>
explicit StatusOr(const StatusOr<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND)
: Base(static_cast<const typename StatusOr<U>::Base&>(other)) {}
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
false, T, U, false, U&&>::value,
int> = 0>
StatusOr(StatusOr<U>&& other)
: Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
false, T, U, true, U&&>::value,
int> = 0>
StatusOr(StatusOr<U>&& other ABSL_ATTRIBUTE_LIFETIME_BOUND)
: Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
true, T, U, false, U&&>::value,
int> = 0>
explicit StatusOr(StatusOr<U>&& other)
: Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
template <typename U, absl::enable_if_t<
internal_statusor::IsConstructionFromStatusOrValid<
true, T, U, true, U&&>::value,
int> = 0>
explicit StatusOr(StatusOr<U>&& other ABSL_ATTRIBUTE_LIFETIME_BOUND)
: Base(static_cast<typename StatusOr<U>::Base&&>(other)) {}
template <typename U,
absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
T, const U&, false>::value,
int> = 0>
StatusOr& operator=(const StatusOr<U>& other) {
this->Assign(other);
return *this;
}
template <typename U,
absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
T, const U&, true>::value,
int> = 0>
StatusOr& operator=(const StatusOr<U>& other ABSL_ATTRIBUTE_LIFETIME_BOUND) {
this->Assign(other);
return *this;
}
template <typename U,
absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
T, U&&, false>::value,
int> = 0>
StatusOr& operator=(StatusOr<U>&& other) {
this->Assign(std::move(other));
return *this;
}
template <typename U,
absl::enable_if_t<internal_statusor::IsStatusOrAssignmentValid<
T, U&&, true>::value,
int> = 0>
StatusOr& operator=(StatusOr<U>&& other ABSL_ATTRIBUTE_LIFETIME_BOUND) {
this->Assign(std::move(other));
return *this;
}
template <typename U = absl::Status,
absl::enable_if_t<internal_statusor::IsConstructionFromStatusValid<
false, T, U>::value,
int> = 0>
StatusOr(U&& v) : Base(std::forward<U>(v)) {}
template <typename U = absl::Status,
absl::enable_if_t<internal_statusor::IsConstructionFromStatusValid<
true, T, U>::value,
int> = 0>
explicit StatusOr(U&& v) : Base(std::forward<U>(v)) {}
template <typename U = absl::Status,
absl::enable_if_t<internal_statusor::IsConstructionFromStatusValid<
false, T, U>::value,
int> = 0>
StatusOr& operator=(U&& v) {
this->AssignStatus(std::forward<U>(v));
return *this;
}
template <typename U = T,
typename std::enable_if<
internal_statusor::IsAssignmentValid<T, U, false>::value,
int>::type = 0>
StatusOr& operator=(U&& v) {
this->Assign(std::forward<U>(v));
return *this;
}
template <typename U = T,
typename std::enable_if<
internal_statusor::IsAssignmentValid<T, U, true>::value,
int>::type = 0>
StatusOr& operator=(U&& v ABSL_ATTRIBUTE_LIFETIME_BOUND) {
this->Assign(std::forward<U>(v));
return *this;
}
template <typename... Args>
explicit StatusOr(absl::in_place_t, Args&&... args);
template <typename U, typename... Args>
explicit StatusOr(absl::in_place_t, std::initializer_list<U> ilist,
Args&&... args);
template <typename U = T,
absl::enable_if_t<internal_statusor::IsConstructionValid<
false, T, U, false>::value,
int> = 0>
StatusOr(U&& u)
: StatusOr(absl::in_place, std::forward<U>(u)) {}
template <typename U = T,
absl::enable_if_t<internal_statusor::IsConstructionValid<
false, T, U, true>::value,
int> = 0>
StatusOr(U&& u ABSL_ATTRIBUTE_LIFETIME_BOUND)
: StatusOr(absl::in_place, std::forward<U>(u)) {}
template <typename U = T,
absl::enable_if_t<internal_statusor::IsConstructionValid<
true, T, U, false>::value,
int> = 0>
explicit StatusOr(U&& u)
: StatusOr(absl::in_place, std::forward<U>(u)) {}
template <typename U = T,
absl::enable_if_t<
internal_statusor::IsConstructionValid<true, T, U, true>::value,
int> = 0>
explicit StatusOr(U&& u ABSL_ATTRIBUTE_LIFETIME_BOUND)
: StatusOr(absl::in_place, std::forward<U>(u)) {}
ABSL_MUST_USE_RESULT bool ok() const { return this->status_.ok(); }
const Status& status() const&;
Status status() &&;
const T& value() const& ABSL_ATTRIBUTE_LIFETIME_BOUND;
T& value() & ABSL_ATTRIBUTE_LIFETIME_BOUND;
const T&& value() const&& ABSL_ATTRIBUTE_LIFETIME_BOUND;
T&& value() && ABSL_ATTRIBUTE_LIFETIME_BOUND;
const T& operator*() const& ABSL_ATTRIBUTE_LIFETIME_BOUND;
T& operator*() & ABSL_ATTRIBUTE_LIFETIME_BOUND;
const T&& operator*() const&& ABSL_ATTRIBUTE_LIFETIME_BOUND;
T&& operator*() && ABSL_ATTRIBUTE_LIFETIME_BOUND;
const T* operator->() const ABSL_ATTRIBUTE_LIFETIME_BOUND;
T* operator->() ABSL_ATTRIBUTE_LIFETIME_BOUND;
template <typename U>
T value_or(U&& default_value) const&;
template <typename U>
T value_or(U&& default_value) &&;
void IgnoreError() const;
template <typename... Args>
T& emplace(Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
if (ok()) {
this->Clear();
this->MakeValue(std::forward<Args>(args)...);
} else {
this->MakeValue(std::forward<Args>(args)...);
this->status_ = absl::OkStatus();
}
return this->data_;
}
template <
typename U, typename... Args,
absl::enable_if_t<
std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value,
int> = 0>
T& emplace(std::initializer_list<U> ilist,
Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
if (ok()) {
this->Clear();
this->MakeValue(ilist, std::forward<Args>(args)...);
} else {
this->MakeValue(ilist, std::forward<Args>(args)...);
this->status_ = absl::OkStatus();
}
return this->data_;
}
using internal_statusor::StatusOrData<T>::AssignStatus;
private:
using internal_statusor::StatusOrData<T>::Assign;
template <typename U>
void Assign(const absl::StatusOr<U>& other);
template <typename U>
void Assign(absl::StatusOr<U>&& other);
};
template <typename T>
bool operator==(const StatusOr<T>& lhs, const StatusOr<T>& rhs) {
if (lhs.ok() && rhs.ok()) return *lhs == *rhs;
return lhs.status() == rhs.status();
}
template <typename T>
bool operator!=(const StatusOr<T>& lhs, const StatusOr<T>& rhs) {
return !(lhs == rhs);
}
template <typename T, typename std::enable_if<
absl::HasOstreamOperator<T>::value, int>::type = 0>
std::ostream& operator<<(std::ostream& os, const StatusOr<T>& status_or) {
if (status_or.ok()) {
os << status_or.value();
} else {
os << internal_statusor::StringifyRandom::OpenBrackets()
<< status_or.status()
<< internal_statusor::StringifyRandom::CloseBrackets();
}
return os;
}
template <
typename Sink, typename T,
typename std::enable_if<absl::HasAbslStringify<T>::value, int>::type = 0>
void AbslStringify(Sink& sink, const StatusOr<T>& status_or) {
if (status_or.ok()) {
absl::Format(&sink, "%v", status_or.value());
} else {
absl::Format(&sink, "%s%v%s",
internal_statusor::StringifyRandom::OpenBrackets(),
status_or.status(),
internal_statusor::StringifyRandom::CloseBrackets());
}
}
template <typename T>
StatusOr<T>::StatusOr() : Base(Status(absl::StatusCode::kUnknown, "")) {}
template <typename T>
template <typename U>
inline void StatusOr<T>::Assign(const StatusOr<U>& other) {
if (other.ok()) {
this->Assign(*other);
} else {
this->AssignStatus(other.status());
}
}
template <typename T>
template <typename U>
inline void StatusOr<T>::Assign(StatusOr<U>&& other) {
if (other.ok()) {
this->Assign(*std::move(other));
} else {
this->AssignStatus(std::move(other).status());
}
}
template <typename T>
template <typename... Args>
StatusOr<T>::StatusOr(absl::in_place_t, Args&&... args)
: Base(absl::in_place, std::forward<Args>(args)...) {}
template <typename T>
template <typename U, typename... Args>
StatusOr<T>::StatusOr(absl::in_place_t, std::initializer_list<U> ilist,
Args&&... args)
: Base(absl::in_place, ilist, std::forward<Args>(args)...) {}
template <typename T>
const Status& StatusOr<T>::status() const& {
return this->status_;
}
template <typename T>
Status StatusOr<T>::status() && {
return ok() ? OkStatus() : std::move(this->status_);
}
template <typename T>
const T& StatusOr<T>::value() const& {
if (!this->ok()) internal_statusor::ThrowBadStatusOrAccess(this->status_);
return this->data_;
}
template <typename T>
T& StatusOr<T>::value() & {
if (!this->ok()) internal_statusor::ThrowBadStatusOrAccess(this->status_);
return this->data_;
}
template <typename T>
const T&& StatusOr<T>::value() const&& {
if (!this->ok()) {
internal_statusor::ThrowBadStatusOrAccess(std::move(this->status_));
}
return std::move(this->data_);
}
template <typename T>
T&& StatusOr<T>::value() && {
if (!this->ok()) {
internal_statusor::ThrowBadStatusOrAccess(std::move(this->status_));
}
return std::move(this->data_);
}
template <typename T>
const T& StatusOr<T>::operator*() const& {
this->EnsureOk();
return this->data_;
}
template <typename T>
T& StatusOr<T>::operator*() & {
this->EnsureOk();
return this->data_;
}
template <typename T>
const T&& StatusOr<T>::operator*() const&& {
this->EnsureOk();
return std::move(this->data_);
}
template <typename T>
T&& StatusOr<T>::operator*() && {
this->EnsureOk();
return std::move(this->data_);
}
template <typename T>
absl::Nonnull<const T*> StatusOr<T>::operator->() const {
this->EnsureOk();
return &this->data_;
}
template <typename T>
absl::Nonnull<T*> StatusOr<T>::operator->() {
this->EnsureOk();
return &this->data_;
}
template <typename T>
template <typename U>
T StatusOr<T>::value_or(U&& default_value) const& {
if (ok()) {
return this->data_;
}
return std::forward<U>(default_value);
}
template <typename T>
template <typename U>
T StatusOr<T>::value_or(U&& default_value) && {
if (ok()) {
return std::move(this->data_);
}
return std::forward<U>(default_value);
}
template <typename T>
void StatusOr<T>::IgnoreError() const {
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/status/statusor.h"
#include <cstdlib>
#include <utility>
#include "absl/base/call_once.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/nullability.h"
#include "absl/status/internal/statusor_internal.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
BadStatusOrAccess::BadStatusOrAccess(absl::Status status)
: status_(std::move(status)) {}
BadStatusOrAccess::BadStatusOrAccess(const BadStatusOrAccess& other)
: status_(other.status_) {}
BadStatusOrAccess& BadStatusOrAccess::operator=(
const BadStatusOrAccess& other) {
other.InitWhat();
status_ = other.status_;
what_ = other.what_;
return *this;
}
BadStatusOrAccess& BadStatusOrAccess::operator=(BadStatusOrAccess&& other) {
other.InitWhat();
status_ = std::move(other.status_);
what_ = std::move(other.what_);
return *this;
}
BadStatusOrAccess::BadStatusOrAccess(BadStatusOrAccess&& other)
: status_(std::move(other.status_)) {}
absl::Nonnull<const char*> BadStatusOrAccess::what() const noexcept {
InitWhat();
return what_.c_str();
}
const absl::Status& BadStatusOrAccess::status() const { return status_; }
void BadStatusOrAccess::InitWhat() const {
absl::call_once(init_what_, [this] {
what_ = absl::StrCat("Bad StatusOr access: ", status_.ToString());
});
}
namespace internal_statusor {
void Helper::HandleInvalidStatusCtorArg(absl::Nonnull<absl::Status*> status) {
const char* kMessage =
"An OK status is not a valid constructor argument to StatusOr<T>";
#ifdef NDEBUG
ABSL_INTERNAL_LOG(ERROR, kMessage);
#else
ABSL_INTERNAL_LOG(FATAL, kMessage);
#endif
*status = absl::InternalError(kMessage);
}
void Helper::Crash(const absl::Status& status) {
ABSL_INTERNAL_LOG(
FATAL,
absl::StrCat("Attempting to fetch value instead of handling error ",
status.ToString()));
}
void ThrowBadStatusOrAccess(absl::Status status) {
#ifdef ABSL_HAVE_EXCEPTIONS
throw absl::BadStatusOrAccess(std::move(status));
#else
ABSL_INTERNAL_LOG(
FATAL,
absl::StrCat("Attempting to fetch value instead of handling error ",
status.ToString())) | #include "absl/status/statusor.h"
#include <array>
#include <cstddef>
#include <initializer_list>
#include <map>
#include <memory>
#include <ostream>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/casts.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/status_matchers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/any.h"
#include "absl/types/variant.h"
#include "absl/utility/utility.h"
namespace {
using ::absl_testing::IsOk;
using ::absl_testing::IsOkAndHolds;
using ::testing::AllOf;
using ::testing::AnyOf;
using ::testing::AnyWith;
using ::testing::ElementsAre;
using ::testing::EndsWith;
using ::testing::Field;
using ::testing::HasSubstr;
using ::testing::Ne;
using ::testing::Not;
using ::testing::Pointee;
using ::testing::StartsWith;
using ::testing::VariantWith;
struct CopyDetector {
CopyDetector() = default;
explicit CopyDetector(int xx) : x(xx) {}
CopyDetector(CopyDetector&& d) noexcept
: x(d.x), copied(false), moved(true) {}
CopyDetector(const CopyDetector& d) : x(d.x), copied(true), moved(false) {}
CopyDetector& operator=(const CopyDetector& c) {
x = c.x;
copied = true;
moved = false;
return *this;
}
CopyDetector& operator=(CopyDetector&& c) noexcept {
x = c.x;
copied = false;
moved = true;
return *this;
}
int x = 0;
bool copied = false;
bool moved = false;
};
testing::Matcher<const CopyDetector&> CopyDetectorHas(int a, bool b, bool c) {
return AllOf(Field(&CopyDetector::x, a), Field(&CopyDetector::moved, b),
Field(&CopyDetector::copied, c));
}
class Base1 {
public:
virtual ~Base1() {}
int pad;
};
class Base2 {
public:
virtual ~Base2() {}
int yetotherpad;
};
class Derived : public Base1, public Base2 {
public:
virtual ~Derived() {}
int evenmorepad;
};
class CopyNoAssign {
public:
explicit CopyNoAssign(int value) : foo(value) {}
CopyNoAssign(const CopyNoAssign& other) : foo(other.foo) {}
int foo;
private:
const CopyNoAssign& operator=(const CopyNoAssign&);
};
absl::StatusOr<std::unique_ptr<int>> ReturnUniquePtr() {
return absl::make_unique<int>(0);
}
TEST(StatusOr, ElementType) {
static_assert(std::is_same<absl::StatusOr<int>::value_type, int>(), "");
static_assert(std::is_same<absl::StatusOr<char>::value_type, char>(), "");
}
TEST(StatusOr, TestMoveOnlyInitialization) {
absl::StatusOr<std::unique_ptr<int>> thing(ReturnUniquePtr());
ASSERT_TRUE(thing.ok());
EXPECT_EQ(0, **thing);
int* previous = thing->get();
thing = ReturnUniquePtr();
EXPECT_TRUE(thing.ok());
EXPECT_EQ(0, **thing);
EXPECT_NE(previous, thing->get());
}
TEST(StatusOr, TestMoveOnlyValueExtraction) {
absl::StatusOr<std::unique_ptr<int>> thing(ReturnUniquePtr());
ASSERT_TRUE(thing.ok());
std::unique_ptr<int> ptr = *std::move(thing);
EXPECT_EQ(0, *ptr);
thing = std::move(ptr);
ptr = std::move(*thing);
EXPECT_EQ(0, *ptr);
}
TEST(StatusOr, TestMoveOnlyInitializationFromTemporaryByValueOrDie) {
std::unique_ptr<int> ptr(*ReturnUniquePtr());
EXPECT_EQ(0, *ptr);
}
TEST(StatusOr, TestValueOrDieOverloadForConstTemporary) {
static_assert(
std::is_same<
const int&&,
decltype(std::declval<const absl::StatusOr<int>&&>().value())>(),
"value() for const temporaries should return const T&&");
}
TEST(StatusOr, TestMoveOnlyConversion) {
absl::StatusOr<std::unique_ptr<const int>> const_thing(ReturnUniquePtr());
EXPECT_TRUE(const_thing.ok());
EXPECT_EQ(0, **const_thing);
const int* const_previous = const_thing->get();
const_thing = ReturnUniquePtr();
EXPECT_TRUE(const_thing.ok());
EXPECT_EQ(0, **const_thing);
EXPECT_NE(const_previous, const_thing->get());
}
TEST(StatusOr, TestMoveOnlyVector) {
std::vector<absl::StatusOr<std::unique_ptr<int>>> vec;
vec.push_back(ReturnUniquePtr());
vec.resize(2);
auto another_vec = std::move(vec);
EXPECT_EQ(0, **another_vec[0]);
EXPECT_EQ(absl::UnknownError(""), another_vec[1].status());
}
TEST(StatusOr, TestDefaultCtor) {
absl::StatusOr<int> thing;
EXPECT_FALSE(thing.ok());
EXPECT_EQ(thing.status().code(), absl::StatusCode::kUnknown);
}
TEST(StatusOr, StatusCtorForwards) {
absl::Status status(absl::StatusCode::kInternal, "Some error");
EXPECT_EQ(absl::StatusOr<int>(status).status().message(), "Some error");
EXPECT_EQ(status.message(), "Some error");
EXPECT_EQ(absl::StatusOr<int>(std::move(status)).status().message(),
"Some error");
EXPECT_NE(status.message(), "Some error");
}
TEST(BadStatusOrAccessTest, CopyConstructionWhatOk) {
absl::Status error =
absl::InternalError("some arbitrary message too big for the sso buffer");
absl::BadStatusOrAccess e1{error};
absl::BadStatusOrAccess e2{e1};
EXPECT_THAT(e1.what(), HasSubstr(error.ToString()));
EXPECT_THAT(e2.what(), HasSubstr(error.ToString()));
}
TEST(BadStatusOrAccessTest, CopyAssignmentWhatOk) {
absl::Status error =
absl::InternalError("some arbitrary message too big for the sso buffer");
absl::BadStatusOrAccess e1{error};
absl::BadStatusOrAccess e2{absl::InternalError("other")};
e2 = e1;
EXPECT_THAT(e1.what(), HasSubstr(error.ToString()));
EXPECT_THAT(e2.what(), HasSubstr(error.ToString()));
}
TEST(BadStatusOrAccessTest, MoveConstructionWhatOk) {
absl::Status error =
absl::InternalError("some arbitrary message too big for the sso buffer");
absl::BadStatusOrAccess e1{error};
absl::BadStatusOrAccess e2{std::move(e1)};
EXPECT_THAT(e2.what(), HasSubstr(error.ToString()));
}
TEST(BadStatusOrAccessTest, MoveAssignmentWhatOk) {
absl::Status error =
absl::InternalError("some arbitrary message too big for the sso buffer");
absl::BadStatusOrAccess e1{error};
absl::BadStatusOrAccess e2{absl::InternalError("other")};
e2 = std::move(e1);
EXPECT_THAT(e2.what(), HasSubstr(error.ToString()));
}
#ifdef ABSL_HAVE_EXCEPTIONS
#define EXPECT_DEATH_OR_THROW(statement, status_) \
EXPECT_THROW( \
{ \
try { \
statement; \
} catch (const absl::BadStatusOrAccess& e) { \
EXPECT_EQ(e.status(), status_); \
EXPECT_THAT(e.what(), HasSubstr(e.status().ToString())); \
throw; \
} \
}, \
absl::BadStatusOrAccess);
#else
#define EXPECT_DEATH_OR_THROW(statement, status) \
EXPECT_DEATH_IF_SUPPORTED(statement, status.ToString());
#endif
TEST(StatusOrDeathTest, TestDefaultCtorValue) {
absl::StatusOr<int> thing;
EXPECT_DEATH_OR_THROW(thing.value(), absl::UnknownError(""));
const absl::StatusOr<int> thing2;
EXPECT_DEATH_OR_THROW(thing2.value(), absl::UnknownError(""));
}
TEST(StatusOrDeathTest, TestValueNotOk) {
absl::StatusOr<int> thing(absl::CancelledError());
EXPECT_DEATH_OR_THROW(thing.value(), absl::CancelledError());
}
TEST(StatusOrDeathTest, TestValueNotOkConst) {
const absl::StatusOr<int> thing(absl::UnknownError(""));
EXPECT_DEATH_OR_THROW(thing.value(), absl::UnknownError(""));
}
TEST(StatusOrDeathTest, TestPointerDefaultCtorValue) {
absl::StatusOr<int*> thing;
EXPECT_DEATH_OR_THROW(thing.value(), absl::UnknownError(""));
}
TEST(StatusOrDeathTest, TestPointerValueNotOk) {
absl::StatusOr<int*> thing(absl::CancelledError());
EXPECT_DEATH_OR_THROW(thing.value(), absl::CancelledError());
}
TEST(StatusOrDeathTest, TestPointerValueNotOkConst) {
const absl::StatusOr<int*> thing(absl::CancelledError());
EXPECT_DEATH_OR_THROW(thing.value(), absl::CancelledError());
}
#if GTEST_HAS_DEATH_TEST
TEST(StatusOrDeathTest, TestStatusCtorStatusOk) {
EXPECT_DEBUG_DEATH(
{
absl::StatusOr<int> thing(absl::OkStatus());
EXPECT_FALSE(thing.ok());
EXPECT_EQ(thing.status().code(), absl::StatusCode::kInternal);
},
"An OK status is not a valid constructor argument");
}
TEST(StatusOrDeathTest, TestPointerStatusCtorStatusOk) {
EXPECT_DEBUG_DEATH(
{
absl::StatusOr<int*> thing(absl::OkStatus());
EXPECT_FALSE(thing.ok());
EXPECT_EQ(thing.status().code(), absl::StatusCode::kInternal);
},
"An OK status is not a valid constructor argument");
}
#endif
TEST(StatusOr, ValueAccessor) {
const int kIntValue = 110;
{
absl::StatusOr<int> status_or(kIntValue);
EXPECT_EQ(kIntValue, status_or.value());
EXPECT_EQ(kIntValue, std::move(status_or).value());
}
{
absl::StatusOr<CopyDetector> status_or(kIntValue);
EXPECT_THAT(status_or,
IsOkAndHolds(CopyDetectorHas(kIntValue, false, false)));
CopyDetector copy_detector = status_or.value();
EXPECT_THAT(copy_detector, CopyDetectorHas(kIntValue, false, true));
copy_detector = std::move(status_or).value();
EXPECT_THAT(copy_detector, CopyDetectorHas(kIntValue, true, false));
}
}
TEST(StatusOr, BadValueAccess) {
const absl::Status kError = absl::CancelledError("message");
absl::StatusOr<int> status_or(kError);
EXPECT_DEATH_OR_THROW(status_or.value(), kError);
}
TEST(StatusOr, TestStatusCtor) {
absl::StatusOr<int> thing(absl::CancelledError());
EXPECT_FALSE(thing.ok());
EXPECT_EQ(thing.status().code(), absl::StatusCode::kCancelled);
}
TEST(StatusOr, TestValueCtor) {
const int kI = 4;
const absl::StatusOr<int> thing(kI);
EXPECT_TRUE(thing.ok());
EXPECT_EQ(kI, *thing);
}
struct Foo {
const int x;
explicit Foo(int y) : x(y) {}
};
TEST(StatusOr, InPlaceConstruction) {
EXPECT_THAT(absl::StatusOr<Foo>(absl::in_place, 10),
IsOkAndHolds(Field(&Foo::x, 10)));
}
struct InPlaceHelper {
InPlaceHelper(std::initializer_list<int> xs, std::unique_ptr<int> yy)
: x(xs), y(std::move(yy)) {}
const std::vector<int> x;
std::unique_ptr<int> y;
};
TEST(StatusOr, InPlaceInitListConstruction) {
absl::StatusOr<InPlaceHelper> status_or(absl::in_place, {10, 11, 12},
absl::make_unique<int>(13));
EXPECT_THAT(status_or, IsOkAndHolds(AllOf(
Field(&InPlaceHelper::x, ElementsAre(10, 11, 12)),
Field(&InPlaceHelper::y, Pointee(13)))));
}
TEST(StatusOr, Emplace) {
absl::StatusOr<Foo> status_or_foo(10);
status_or_foo.emplace(20);
EXPECT_THAT(status_or_foo, IsOkAndHolds(Field(&Foo::x, 20)));
status_or_foo = absl::InvalidArgumentError("msg");
EXPECT_FALSE(status_or_foo.ok());
EXPECT_EQ(status_or_foo.status().code(), absl::StatusCode::kInvalidArgument);
EXPECT_EQ(status_or_foo.status().message(), "msg");
status_or_foo.emplace(20);
EXPECT_THAT(status_or_foo, IsOkAndHolds(Field(&Foo::x, 20)));
}
TEST(StatusOr, EmplaceInitializerList) {
absl::StatusOr<InPlaceHelper> status_or(absl::in_place, {10, 11, 12},
absl::make_unique<int>(13));
status_or.emplace({1, 2, 3}, absl::make_unique<int>(4));
EXPECT_THAT(status_or,
IsOkAndHolds(AllOf(Field(&InPlaceHelper::x, ElementsAre(1, 2, 3)),
Field(&InPlaceHelper::y, Pointee(4)))));
status_or = absl::InvalidArgumentError("msg");
EXPECT_FALSE(status_or.ok());
EXPECT_EQ(status_or.status().code(), absl::StatusCode::kInvalidArgument);
EXPECT_EQ(status_or.status().message(), "msg");
status_or.emplace({1, 2, 3}, absl::make_unique<int>(4));
EXPECT_THAT(status_or,
IsOkAndHolds(AllOf(Field(&InPlaceHelper::x, ElementsAre(1, 2, 3)),
Field(&InPlaceHelper::y, Pointee(4)))));
}
TEST(StatusOr, TestCopyCtorStatusOk) {
const int kI = 4;
const absl::StatusOr<int> original(kI);
const absl::StatusOr<int> copy(original);
EXPECT_THAT(copy.status(), IsOk());
EXPECT_EQ(*original, *copy);
}
TEST(StatusOr, TestCopyCtorStatusNotOk) {
absl::StatusOr<int> original(absl::CancelledError());
absl::StatusOr<int> copy(original);
EXPECT_EQ(copy.status().code(), absl::StatusCode::kCancelled);
}
TEST(StatusOr, TestCopyCtorNonAssignable) {
const int kI = 4;
CopyNoAssign value(kI);
absl::StatusOr<CopyNoAssign> original(value);
absl::StatusOr<CopyNoAssign> copy(original);
EXPECT_THAT(copy.status(), IsOk());
EXPECT_EQ(original->foo, copy->foo);
}
TEST(StatusOr, TestCopyCtorStatusOKConverting) {
const int kI = 4;
absl::StatusOr<int> original(kI);
absl::StatusOr<double> copy(original);
EXPECT_THAT(copy.status(), IsOk());
EXPECT_DOUBLE_EQ(*original, *copy);
}
TEST(StatusOr, TestCopyCtorStatusNotOkConverting) {
absl::StatusOr<int> original(absl::CancelledError());
absl::StatusOr<double> copy(original);
EXPECT_EQ(copy.status(), original.status());
}
TEST(StatusOr, TestAssignmentStatusOk) {
{
const auto p = std::make_shared<int>(17);
absl::StatusOr<std::shared_ptr<int>> source(p);
absl::StatusOr<std::shared_ptr<int>> target;
target = source;
ASSERT_TRUE(target.ok());
EXPECT_THAT(target.status(), IsOk());
EXPECT_EQ(p, *target);
ASSERT_TRUE(source.ok());
EXPECT_THAT(source.status(), IsOk());
EXPECT_EQ(p, *source);
}
{
const auto p = std::make_shared<int>(17);
absl::StatusOr<std::shared_ptr<int>> source(p);
absl::StatusOr<std::shared_ptr<int>> target;
target = std::move(source);
ASSERT_TRUE(target.ok());
EXPECT_THAT(target.status(), IsOk());
EXPECT_EQ(p, *target);
ASSERT_TRUE(source.ok());
EXPECT_THAT(source.status(), IsOk());
EXPECT_EQ(nullptr, *source);
}
}
TEST(StatusOr, TestAssignmentStatusNotOk) {
{
const absl::Status expected = absl::CancelledError();
absl::StatusOr<int> source(expected);
absl::StatusOr<int> target;
target = source;
EXPECT_FALSE(target.ok());
EXPECT_EQ(expected, target.status());
EXPECT_FALSE(source.ok());
EXPECT_EQ(expected, source.status());
}
{
const absl::Status expected = absl::CancelledError();
absl::StatusOr<int> source(expected);
absl::StatusOr<int> target;
target = std::move(source);
EXPECT_FALSE(target.ok());
EXPECT_EQ(expected, target.status());
EXPECT_FALSE(source.ok());
EXPECT_EQ(source.status().code(), absl::StatusCode::kInternal);
}
}
TEST(StatusOr, TestAssignmentStatusOKConverting) {
{
const int kI = 4;
absl::StatusOr<int> source(kI);
absl::StatusOr<double> target;
target = source;
ASSERT_TRUE(target.ok());
EXPECT_THAT(target.status(), IsOk());
EXPECT_DOUBLE_EQ(kI, *target);
ASSERT_TRUE(source.ok());
EXPECT_THAT(source.status(), IsOk());
EXPECT_DOUBLE_EQ(kI, *source);
}
{
const auto p = new int(17);
absl::StatusOr<std::unique_ptr<int>> source(absl::WrapUnique(p));
absl::StatusOr<std::shared_ptr<int>> target;
target = std::move(source);
ASSERT_TRUE(target.ok());
EXPECT_THAT(target.status(), IsOk());
EXPECT_EQ(p, target->get());
ASSERT_TRUE(source.ok());
EXPECT_THAT(source.status(), IsOk());
EXPECT_EQ(nullptr, source->get());
}
}
struct A {
int x;
};
struct ImplicitConstructibleFromA {
int x;
bool moved;
ImplicitConstructibleFromA(const A& a)
: x(a.x), moved(false) {}
ImplicitConstructibleFromA(A&& a)
: x(a.x), moved(true) {}
};
TEST(StatusOr, ImplicitConvertingConstructor) {
EXPECT_THAT(
absl::implicit_cast<absl::StatusOr<ImplicitConstructibleFromA>>(
absl::StatusOr<A>(A{11})),
IsOkAndHolds(AllOf(Field(&ImplicitConstructibleFromA::x, 11),
Field(&ImplicitConstructibleFromA::moved, true))));
absl::StatusOr<A> a(A{12});
EXPECT_THAT(
absl::implicit_cast<absl::StatusOr<ImplicitConstructibleFromA>>(a),
IsOkAndHolds(AllOf(Field(&ImplicitConstructibleFromA::x, 12),
Field(&ImplicitConstructibleFromA::moved, false))));
}
struct ExplicitConstructibleFromA {
int x;
bool moved;
explicit ExplicitConstructibleFromA(const A& a) : x(a.x), moved(false) {}
explicit ExplicitConstructibleFromA(A&& a) : x(a.x), moved(true) {}
};
TEST(StatusOr, ExplicitConvertingConstructor) {
EXPECT_FALSE(
(std::is_convertible<const absl::StatusOr<A>&,
absl::StatusOr<ExplicitConstructibleFromA>>::value));
EXPECT_FALSE(
(std::is_convertible<absl::StatusOr<A>&&,
absl::StatusOr<ExplicitConstructibleFromA>>::value));
EXPECT_THAT(
absl::StatusOr<ExplicitConstructibleFromA>(absl::StatusOr<A>(A{11})),
IsOkAndHolds(AllOf(Field(&ExplicitConstructibleFromA::x, 11),
Field(&ExplicitConstructibleFromA::moved, true))));
absl::StatusOr<A> a(A{12});
EXPECT_THAT(
absl::StatusOr<ExplicitConstructibleFromA>(a),
IsOkAndHolds(AllOf(Field(&ExplicitConstructibleFromA::x, 12),
Field(&ExplicitConstructibleFromA::moved, false))));
}
struct ImplicitConstructibleFromBool {
ImplicitConstructibleFromBool(bool y) : x(y) {}
bool x = false;
};
struct ConvertibleToBool {
explicit ConvertibleToBool(bool y) : x(y) {}
operator bool() const { return x; }
bool x = false;
};
TEST(StatusOr, ImplicitBooleanConstructionWithImplicitCasts) {
EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(true)),
IsOkAndHolds(true));
EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(false)),
IsOkAndHolds(false));
EXPECT_THAT(
absl::implicit_cast<absl::StatusOr<ImplicitConstructibleFromBool>>(
absl::StatusOr<bool>(false)),
IsOkAndHolds(Field(&ImplicitConstructibleFromBool::x, false)));
EXPECT_FALSE((std::is_convertible<
absl::StatusOr<ConvertibleToBool>,
absl::StatusOr<ImplicitConstructibleFromBool>>::value));
}
TEST(StatusOr, BooleanConstructionWithImplicitCasts) {
EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(true)),
IsOkAndHolds(true));
EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(false)),
IsOkAndHolds(false));
EXPECT_THAT(
absl::StatusOr<ImplicitConstructibleFromBool>{
absl::StatusOr<bool>(false)},
IsOkAndHolds(Field(&ImplicitConstructibleFromBool::x, false)));
EXPECT_THAT(
absl::StatusOr<ImplicitConstructibleFromBool>{
absl::StatusOr<bool>(absl::InvalidArgumentError(""))},
Not(IsOk()));
EXPECT_THAT(
absl::StatusOr<ImplicitConstructibleFromBool>{
absl::StatusOr<ConvertibleToBool>(ConvertibleToBool{false})},
IsOkAndHolds(Field(&ImplicitConstructibleFromBool::x, false)));
EXPECT_THAT(
absl::StatusOr<ImplicitConstructibleFromBool>{
absl::StatusOr<ConvertibleToBool>(absl::InvalidArgumentError(""))},
Not(IsOk()));
}
TEST(StatusOr, ConstImplicitCast) {
EXPECT_THAT(absl::implicit_cast<absl::StatusOr<bool>>(
absl::StatusOr<const bool>(true)),
IsOkAndHolds(true));
EXPECT_THAT(absl::implicit_cast<absl::StatusOr<bool>>(
absl::StatusOr<const bool>(false)),
IsOkAndHolds(false));
EXPECT_THAT(absl::implicit_cast<absl::StatusOr<const bool>>(
absl::StatusOr<bool>(true)),
IsOkAndHolds(true));
EXPECT_THAT(absl::implicit_cast<absl::StatusOr<const bool>>(
absl::StatusOr<bool>(false)),
IsOkAndHolds(false));
EXPECT_THAT(absl::implicit_cast<absl::StatusOr<const std::string>>(
absl::StatusOr<std::string>("foo")),
IsOkAndHolds("foo"));
EXPECT_THAT(absl::implicit_cast<absl::StatusOr<std::string>>(
absl::StatusOr<const std::string>("foo")),
IsOkAndHolds("foo"));
EXPECT_THAT(
absl::implicit_cast<absl::StatusOr<std::shared_ptr<const std::string>>>(
absl::StatusOr<std::shared_ptr<std::string>>(
std::make_shared<std::string>("foo"))),
IsOkAndHolds(Pointee(std::string("foo"))));
}
TEST(StatusOr, ConstExplicitConstruction) {
EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<const bool>(true)),
IsOkAndHolds(true));
EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<const bool>(false)),
IsOkAndHolds(false));
EXPECT_THAT(absl::StatusOr<const bool>(absl::StatusOr<bool>(true)),
IsOkAndHolds(true));
EXPECT_THAT(absl::StatusOr<const bool>(absl::StatusOr<bool>(false)),
IsOkAndHolds(false));
}
struct ExplicitConstructibleFromInt {
int x;
explicit ExplicitConstructibleFromInt(int y) : x(y) {}
};
TEST(StatusOr, ExplicitConstruction) {
EXPECT_THAT(absl::StatusOr<ExplicitConstructibleFromInt>(10),
IsOkAndHolds(Field(&ExplicitConstructibleFromInt::x, 10)));
}
TEST(StatusOr, ImplicitConstruction) {
auto status_or =
absl::implicit_cast<absl::StatusOr<absl::variant<int, std::string>>>(10);
EXPECT_THAT(status_or, IsOkAndHolds(VariantWith<int>(10)));
}
TEST(StatusOr, ImplicitConstructionFromInitliazerList) {
auto status_or =
absl::implicit_cast<absl::StatusOr<std::vector<int>>>({{10, 20, 30}});
EXPECT_THAT(status_or, IsOkAndHolds(ElementsAre(10, 20, 30)));
}
TEST(StatusOr, UniquePtrImplicitConstruction) {
auto status_or = absl::implicit_cast<absl::StatusOr<std::unique_ptr<Base1>>>(
absl::make_unique<Derived>());
EXPECT_THAT(status_or, IsOkAndHolds(Ne(nullptr)));
}
TEST(StatusOr, NestedStatusOrCopyAndMoveConstructorTests) {
absl::StatusOr<absl::StatusOr<CopyDetector>> status_or = CopyDetector(10);
absl::StatusOr<absl::StatusOr<CopyDetector>> status_error =
absl::InvalidArgumentError("foo");
EXPECT_THAT(status_or,
IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, true, false))));
absl::StatusOr<absl::StatusOr<CopyDetector>> a = status_or;
EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true))));
absl::StatusOr<absl::StatusOr<CopyDetector>> a_err = status_error;
EXPECT_THAT(a_err, Not(IsOk()));
const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref = status_or;
absl::StatusOr<absl::StatusOr<CopyDetector>> b = cref;
EXPECT_THAT(b, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true))));
const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref_err = status_error;
absl::StatusOr<absl::StatusOr<CopyDetector>> b_err = cref_err;
EXPECT_THAT(b_err, Not(IsOk()));
absl::StatusOr<absl::StatusOr<CopyDetector>> c = std::move(status_or);
EXPECT_THAT(c, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, true, false))));
absl::StatusOr<absl::StatusOr<CopyDetector>> c_err = std::move(status_error);
EXPECT_THAT(c_err, Not(IsOk()));
}
TEST(StatusOr, NestedStatusOrCopyAndMoveAssignment) {
absl::StatusOr<absl::StatusOr<CopyDetector>> status_or = CopyDetector(10);
absl::StatusOr<absl::StatusOr<CopyDetector>> status_error =
absl::InvalidArgumentError("foo");
absl::StatusOr<absl::StatusOr<CopyDetector>> a;
a = status_or;
EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true))));
a = status_error;
EXPECT_THAT(a, Not(IsOk()));
const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref = status_or;
a = cref;
EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true))));
const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref_err = status_error;
a = cref_err;
EXPECT_THAT(a, Not(IsOk()));
a = std::move(status_or);
EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, true, false))));
a = std::move(status_error);
EXPECT_THAT(a, Not(IsOk()));
}
struct Copyable {
Copyable() {}
Copyable(const Copyable&) {}
Copyable& operator=(const Copyable&) { return *this; }
};
struct MoveOnly {
MoveOnly() {}
MoveOnly(MoveOnly&&) {}
MoveOnly& operator=(MoveOnly&&) { return *this; }
};
struct NonMovable {
NonMovable() {}
NonMovable(const NonMovable&) = delete;
NonMovable(NonMovable&&) = delete;
NonMovable& operator=(const NonMovable&) = delete;
NonMovable& operator=(NonMovable&&) = delete;
};
TEST(StatusOr, CopyAndMoveAbility) {
EXPECT_TRUE(std::is_copy_constructible<Copyable>::value);
EXPECT_TRUE(std::is_copy_assignable<Copyable>::value);
EXPECT_TRUE(std::is_move_constructible<Copyable>::value);
EXPECT_TRUE(std::is_move_assignable<Copyable>::value);
EXPECT_FALSE(std::is_copy_constructible<MoveOnly>::value);
EXPECT_FALSE(std::is_copy_assignable<MoveOnly>::value);
EXPECT_TRUE(std::is_move_constructible<MoveOnly>::value);
EXPECT_TRUE(std::is_move_assignable<MoveOnly>::value);
EXPECT_FALSE(std::is_copy_constructible<NonMovable>::value);
EXPECT_FALSE(std::is_copy_assignable<NonMovable>::value);
EXPECT_FALSE(std::is_move_constructible<NonMovable>::value);
EXPECT_FALSE(std::is_move_assignable<NonMovable>::value);
}
TEST(StatusOr, StatusOrAnyCopyAndMoveConstructorTests) {
absl::StatusOr<absl::any> status_or = CopyDetector(10);
absl::StatusOr<absl::any> status_error = absl::InvalidArgumentError("foo");
EXPECT_THAT(
status_or,
IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, true, false))));
absl::StatusOr<absl::any> a = status_or;
EXPECT_THAT(
a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true))));
absl::StatusOr<absl::any> a_err = status_error;
EXPECT_THAT(a_err, Not(IsOk()));
const absl::StatusOr<absl::any>& cref = status_or;
absl::StatusOr<absl::any> b = cref;
EXPECT_THAT(
b, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true))));
const absl::StatusOr<absl::any>& cref_err = status_error;
absl::StatusOr<absl::any> b_err = cref_err;
EXPECT_THAT(b_err, Not(IsOk()));
absl::StatusOr<absl::any> c = std::move(status_or);
EXPECT_THAT(
c, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, true, false))));
absl::StatusOr<absl::any> c_err = std::move(status_error);
EXPECT_THAT(c_err, Not(IsOk()));
}
TEST(StatusOr, StatusOrAnyCopyAndMoveAssignment) {
absl::StatusOr<absl::any> status_or = CopyDetector(10);
absl::StatusOr<absl::any> status_error = absl::InvalidArgumentError("foo");
absl::StatusOr<absl::any> a;
a = status_or;
EXPECT_THAT(
a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true))));
a = status_error;
EXPECT_THAT(a, Not(IsOk()));
const absl::StatusOr<absl::any>& cref = status_or;
a = cref;
EXPECT_THAT(
a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true))));
const absl::StatusOr<absl::any>& cref_err = status_error;
a = cref_err;
EXPECT_THAT(a, Not(IsOk()));
a = std::move(status_or);
EXPECT_THAT(
a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, true, false))));
a = std::move(status_error);
EXPECT_THAT(a, Not(IsOk()));
}
TEST(StatusOr, StatusOrCopyAndMoveTestsConstructor) {
absl::StatusOr<CopyDetector> status_or(10);
ASSERT_THAT(status_or, IsOkAndHolds(CopyDetectorHas(10, false, false)));
absl::StatusOr<CopyDetector> a(status_or);
EXPECT_THAT(a, IsOkAndHolds(CopyDetectorHas(10, false, true)));
const absl::StatusOr<CopyDetector>& cref = status_or;
absl::StatusOr<CopyDetector> b(cref);
EXPECT_THAT(b, IsOkAndHolds(CopyDetectorHas(10, false, true)));
absl::StatusOr<CopyDetector> c(std::move(status_or));
EXPECT_THAT(c, IsOkAndHolds(CopyDetectorHas(10, true, false)));
}
TEST(StatusOr, StatusOrCopyAndMoveTestsAssignment) {
absl::StatusOr<CopyDetector> status_or(10);
ASSERT_THAT(status_or, IsOkAndHolds(CopyDetectorHas(10, false, false)));
absl::StatusOr<CopyDetector> a;
a = status_or;
EXPECT_THAT(a, IsOkAndHolds(CopyDetectorHas(10, false, true)));
const absl::StatusOr<CopyDetector>& cref = status_or;
absl::StatusOr<CopyDetector> b;
b = cref;
EXPECT_THAT(b, IsOkAndHolds(CopyDetectorHas(10, false, true)));
absl::StatusOr<CopyDetector> c;
c = std::move(status_or);
EXPECT_THAT(c, IsOkAndHolds(CopyDetectorHas(10, true, false)));
}
TEST(StatusOr, AbslAnyAssignment) {
EXPECT_FALSE((std::is_assignable<absl::StatusOr<absl::any>,
absl::StatusOr<int>>::value));
absl::StatusOr<absl::any> status_or;
status_or = absl::InvalidArgumentError("foo");
EXPECT_THAT(status_or, Not(IsOk()));
}
TEST(StatusOr, ImplicitAssignment) {
absl::StatusOr<absl::variant<int, std::string>> status_or;
status_or = 10;
EXPECT_THAT(status_or, IsOkAndHolds(VariantWith<int>(10)));
}
TEST(StatusOr, SelfDirectInitAssignment) {
absl::StatusOr<std::vector<int>> status_or = {{10, 20, 30}};
status_or = *status_or;
EXPECT_THAT(status_or, IsOkAndHolds(ElementsAre(10, 20, 30)));
}
TEST(StatusOr, ImplicitCastFromInitializerList) {
absl::StatusOr<std::vector<int>> status_or = {{10, 20, 30}};
EXPECT_THAT(status_or, IsOkAndHolds(ElementsAre(10, 20, 30)));
}
TEST(StatusOr, UniquePtrImplicitAssignment) {
absl::StatusOr<std::unique_ptr<Base1>> status_or;
status_or = absl::make_unique<Derived>();
EXPECT_THAT(status_or, IsOkAndHolds(Ne(nullptr)));
}
TEST(StatusOr, Pointer) {
struct A {};
struct B : public A {};
struct C : private A {};
EXPECT_TRUE((std::is_constructible<absl::StatusOr<A*>, B*>::value));
EXPECT_TRUE((std::is_convertible<B*, absl::StatusOr<A*>>::value));
EXPECT_FALSE((std::is_constructible<absl::StatusOr<A*>, C*>::value));
EXPECT_FALSE((std::is_convertible<C*, absl::StatusOr<A*>>::value));
}
TEST(StatusOr, TestAssignmentStatusNotOkConverting) {
{
const absl::Status expected = absl::CancelledError();
absl::StatusOr<int> source(expected);
absl::StatusOr<double> target;
target = source;
EXPECT_FALSE(target.ok());
EXPECT_EQ(expected, target.status());
EXPECT_FALSE(source.ok());
EXPECT_EQ(expected, source.status());
}
{
const absl::Status expected = absl::CancelledError();
absl::StatusOr<int> source(expected);
absl::StatusOr<double> target;
target = std::move(source);
EXPECT_FALSE(target.ok());
EXPECT_EQ(expected, target.status());
EXPECT_FALSE(source.ok());
EXPECT_EQ(source.status().code(), absl::StatusCode::kInternal);
}
}
TEST(StatusOr, SelfAssignment) {
{
const std::string long_str(128, 'a');
absl::StatusOr<std::string> so = long_str;
so = *&so;
ASSERT_TRUE(so.ok());
EXPECT_THAT(so.status(), IsOk());
EXPECT_EQ(long_str, *so);
}
{
absl::StatusOr<int> so = absl::NotFoundError("taco");
so = *&so;
EXPECT_FALSE(so.ok());
EXPECT_EQ(so.status().code(), absl::StatusCode::kNotFo |
2,588 | cpp | abseil/abseil-cpp | status | absl/status/status.cc | absl/status/status_test.cc | #ifndef ABSL_STATUS_STATUS_H_
#define ABSL_STATUS_STATUS_H_
#include <cassert>
#include <cstdint>
#include <ostream>
#include <string>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/macros.h"
#include "absl/base/nullability.h"
#include "absl/base/optimization.h"
#include "absl/functional/function_ref.h"
#include "absl/status/internal/status_internal.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
enum class StatusCode : int {
kOk = 0,
kCancelled = 1,
kUnknown = 2,
kInvalidArgument = 3,
kDeadlineExceeded = 4,
kNotFound = 5,
kAlreadyExists = 6,
kPermissionDenied = 7,
kResourceExhausted = 8,
kFailedPrecondition = 9,
kAborted = 10,
kOutOfRange = 11,
kUnimplemented = 12,
kInternal = 13,
kUnavailable = 14,
kDataLoss = 15,
kUnauthenticated = 16,
kDoNotUseReservedForFutureExpansionUseDefaultInSwitchInstead_ = 20
};
std::string StatusCodeToString(StatusCode code);
std::ostream& operator<<(std::ostream& os, StatusCode code);
enum class StatusToStringMode : int {
kWithNoExtraData = 0,
kWithPayload = 1 << 0,
kWithEverything = ~kWithNoExtraData,
kDefault = kWithPayload,
};
inline constexpr StatusToStringMode operator&(StatusToStringMode lhs,
StatusToStringMode rhs) {
return static_cast<StatusToStringMode>(static_cast<int>(lhs) &
static_cast<int>(rhs));
}
inline constexpr StatusToStringMode operator|(StatusToStringMode lhs,
StatusToStringMode rhs) {
return static_cast<StatusToStringMode>(static_cast<int>(lhs) |
static_cast<int>(rhs));
}
inline constexpr StatusToStringMode operator^(StatusToStringMode lhs,
StatusToStringMode rhs) {
return static_cast<StatusToStringMode>(static_cast<int>(lhs) ^
static_cast<int>(rhs));
}
inline constexpr StatusToStringMode operator~(StatusToStringMode arg) {
return static_cast<StatusToStringMode>(~static_cast<int>(arg));
}
inline StatusToStringMode& operator&=(StatusToStringMode& lhs,
StatusToStringMode rhs) {
lhs = lhs & rhs;
return lhs;
}
inline StatusToStringMode& operator|=(StatusToStringMode& lhs,
StatusToStringMode rhs) {
lhs = lhs | rhs;
return lhs;
}
inline StatusToStringMode& operator^=(StatusToStringMode& lhs,
StatusToStringMode rhs) {
lhs = lhs ^ rhs;
return lhs;
}
class ABSL_ATTRIBUTE_TRIVIAL_ABI Status final {
public:
Status();
Status(absl::StatusCode code, absl::string_view msg);
Status(const Status&);
Status& operator=(const Status& x);
Status(Status&&) noexcept;
Status& operator=(Status&&) noexcept;
~Status();
void Update(const Status& new_status);
void Update(Status&& new_status);
ABSL_MUST_USE_RESULT bool ok() const;
absl::StatusCode code() const;
int raw_code() const;
absl::string_view message() const;
friend bool operator==(const Status&, const Status&);
friend bool operator!=(const Status&, const Status&);
std::string ToString(
StatusToStringMode mode = StatusToStringMode::kDefault) const;
template <typename Sink>
friend void AbslStringify(Sink& sink, const Status& status) {
sink.Append(status.ToString(StatusToStringMode::kWithEverything));
}
void IgnoreError() const;
friend void swap(Status& a, Status& b) noexcept;
absl::optional<absl::Cord> GetPayload(absl::string_view type_url) const;
void SetPayload(absl::string_view type_url, absl::Cord payload);
bool ErasePayload(absl::string_view type_url);
void ForEachPayload(
absl::FunctionRef<void(absl::string_view, const absl::Cord&)> visitor)
const;
private:
friend Status CancelledError();
explicit Status(absl::StatusCode code);
explicit Status(uintptr_t rep) : rep_(rep) {}
static void Ref(uintptr_t rep);
static void Unref(uintptr_t rep);
static absl::Nonnull<status_internal::StatusRep*> PrepareToModify(
uintptr_t rep);
static constexpr const char kMovedFromString[] =
"Status accessed after move.";
static absl::Nonnull<const std::string*> EmptyString();
static absl::Nonnull<const std::string*> MovedFromString();
static constexpr bool IsInlined(uintptr_t rep);
static constexpr bool IsMovedFrom(uintptr_t rep);
static constexpr uintptr_t MovedFromRep();
static constexpr uintptr_t CodeToInlinedRep(absl::StatusCode code);
static constexpr absl::StatusCode InlinedRepToCode(uintptr_t rep);
static uintptr_t PointerToRep(status_internal::StatusRep* r);
static absl::Nonnull<const status_internal::StatusRep*> RepToPointer(
uintptr_t r);
static std::string ToStringSlow(uintptr_t rep, StatusToStringMode mode);
uintptr_t rep_;
friend class status_internal::StatusRep;
};
Status OkStatus();
std::ostream& operator<<(std::ostream& os, const Status& x);
ABSL_MUST_USE_RESULT bool IsAborted(const Status& status);
ABSL_MUST_USE_RESULT bool IsAlreadyExists(const Status& status);
ABSL_MUST_USE_RESULT bool IsCancelled(const Status& status);
ABSL_MUST_USE_RESULT bool IsDataLoss(const Status& status);
ABSL_MUST_USE_RESULT bool IsDeadlineExceeded(const Status& status);
ABSL_MUST_USE_RESULT bool IsFailedPrecondition(const Status& status);
ABSL_MUST_USE_RESULT bool IsInternal(const Status& status);
ABSL_MUST_USE_RESULT bool IsInvalidArgument(const Status& status);
ABSL_MUST_USE_RESULT bool IsNotFound(const Status& status);
ABSL_MUST_USE_RESULT bool IsOutOfRange(const Status& status);
ABSL_MUST_USE_RESULT bool IsPermissionDenied(const Status& status);
ABSL_MUST_USE_RESULT bool IsResourceExhausted(const Status& status);
ABSL_MUST_USE_RESULT bool IsUnauthenticated(const Status& status);
ABSL_MUST_USE_RESULT bool IsUnavailable(const Status& status);
ABSL_MUST_USE_RESULT bool IsUnimplemented(const Status& status);
ABSL_MUST_USE_RESULT bool IsUnknown(const Status& status);
Status AbortedError(absl::string_view message);
Status AlreadyExistsError(absl::string_view message);
Status CancelledError(absl::string_view message);
Status DataLossError(absl::string_view message);
Status DeadlineExceededError(absl::string_view message);
Status FailedPreconditionError(absl::string_view message);
Status InternalError(absl::string_view message);
Status InvalidArgumentError(absl::string_view message);
Status NotFoundError(absl::string_view message);
Status OutOfRangeError(absl::string_view message);
Status PermissionDeniedError(absl::string_view message);
Status ResourceExhaustedError(absl::string_view message);
Status UnauthenticatedError(absl::string_view message);
Status UnavailableError(absl::string_view message);
Status UnimplementedError(absl::string_view message);
Status UnknownError(absl::string_view message);
absl::StatusCode ErrnoToStatusCode(int error_number);
Status ErrnoToStatus(int error_number, absl::string_view message);
inline Status::Status() : Status(absl::StatusCode::kOk) {}
inline Status::Status(absl::StatusCode code) : Status(CodeToInlinedRep(code)) {}
inline Status::Status(const Status& x) : Status(x.rep_) { Ref(rep_); }
inline Status& Status::operator=(const Status& x) {
uintptr_t old_rep = rep_;
if (x.rep_ != old_rep) {
Ref(x.rep_);
rep_ = x.rep_;
Unref(old_rep);
}
return *this;
}
inline Status::Status(Status&& x) noexcept : Status(x.rep_) {
x.rep_ = MovedFromRep();
}
inline Status& Status::operator=(Status&& x) noexcept {
uintptr_t old_rep = rep_;
if (x.rep_ != old_rep) {
rep_ = x.rep_;
x.rep_ = MovedFromRep();
Unref(old_rep);
}
return *this;
}
inline void Status::Update(const Status& new_status) {
if (ok()) {
*this = new_status;
}
}
inline void Status::Update(Status&& new_status) {
if (ok()) {
*this = std::move(new_status);
}
}
inline Status::~Status() { Unref(rep_); }
inline bool Status::ok() const {
return rep_ == CodeToInlinedRep(absl::StatusCode::kOk);
}
inline absl::StatusCode Status::code() const {
return status_internal::MapToLocalCode(raw_code());
}
inline int Status::raw_code() const {
if (IsInlined(rep_)) return static_cast<int>(InlinedRepToCode(rep_));
return static_cast<int>(RepToPointer(rep_)->code());
}
inli | #include "absl/status/status.h"
#include <errno.h>
#include <array>
#include <cstddef>
#include <sstream>
#include <utility>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
namespace {
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::Optional;
using ::testing::UnorderedElementsAreArray;
TEST(StatusCode, InsertionOperator) {
const absl::StatusCode code = absl::StatusCode::kUnknown;
std::ostringstream oss;
oss << code;
EXPECT_EQ(oss.str(), absl::StatusCodeToString(code));
}
struct ErrorTest {
absl::StatusCode code;
using Creator = absl::Status (*)(
absl::string_view
);
using Classifier = bool (*)(const absl::Status&);
Creator creator;
Classifier classifier;
};
constexpr ErrorTest kErrorTests[]{
{absl::StatusCode::kCancelled, absl::CancelledError, absl::IsCancelled},
{absl::StatusCode::kUnknown, absl::UnknownError, absl::IsUnknown},
{absl::StatusCode::kInvalidArgument, absl::InvalidArgumentError,
absl::IsInvalidArgument},
{absl::StatusCode::kDeadlineExceeded, absl::DeadlineExceededError,
absl::IsDeadlineExceeded},
{absl::StatusCode::kNotFound, absl::NotFoundError, absl::IsNotFound},
{absl::StatusCode::kAlreadyExists, absl::AlreadyExistsError,
absl::IsAlreadyExists},
{absl::StatusCode::kPermissionDenied, absl::PermissionDeniedError,
absl::IsPermissionDenied},
{absl::StatusCode::kResourceExhausted, absl::ResourceExhaustedError,
absl::IsResourceExhausted},
{absl::StatusCode::kFailedPrecondition, absl::FailedPreconditionError,
absl::IsFailedPrecondition},
{absl::StatusCode::kAborted, absl::AbortedError, absl::IsAborted},
{absl::StatusCode::kOutOfRange, absl::OutOfRangeError, absl::IsOutOfRange},
{absl::StatusCode::kUnimplemented, absl::UnimplementedError,
absl::IsUnimplemented},
{absl::StatusCode::kInternal, absl::InternalError, absl::IsInternal},
{absl::StatusCode::kUnavailable, absl::UnavailableError,
absl::IsUnavailable},
{absl::StatusCode::kDataLoss, absl::DataLossError, absl::IsDataLoss},
{absl::StatusCode::kUnauthenticated, absl::UnauthenticatedError,
absl::IsUnauthenticated},
};
TEST(Status, CreateAndClassify) {
for (const auto& test : kErrorTests) {
SCOPED_TRACE(absl::StatusCodeToString(test.code));
std::string message =
absl::StrCat("error code ", test.code, " test message");
absl::Status status = test.creator(
message
);
EXPECT_EQ(test.code, status.code());
EXPECT_EQ(message, status.message());
EXPECT_TRUE(test.classifier(status));
for (const auto& other : kErrorTests) {
if (other.code != test.code) {
EXPECT_FALSE(test.classifier(absl::Status(other.code, "")))
<< " other.code = " << other.code;
}
}
}
}
TEST(Status, DefaultConstructor) {
absl::Status status;
EXPECT_TRUE(status.ok());
EXPECT_EQ(absl::StatusCode::kOk, status.code());
EXPECT_EQ("", status.message());
}
TEST(Status, OkStatus) {
absl::Status status = absl::OkStatus();
EXPECT_TRUE(status.ok());
EXPECT_EQ(absl::StatusCode::kOk, status.code());
EXPECT_EQ("", status.message());
}
TEST(Status, ConstructorWithCodeMessage) {
{
absl::Status status(absl::StatusCode::kCancelled, "");
EXPECT_FALSE(status.ok());
EXPECT_EQ(absl::StatusCode::kCancelled, status.code());
EXPECT_EQ("", status.message());
}
{
absl::Status status(absl::StatusCode::kInternal, "message");
EXPECT_FALSE(status.ok());
EXPECT_EQ(absl::StatusCode::kInternal, status.code());
EXPECT_EQ("message", status.message());
}
}
TEST(Status, StatusMessageCStringTest) {
{
absl::Status status = absl::OkStatus();
EXPECT_EQ(status.message(), "");
EXPECT_STREQ(absl::StatusMessageAsCStr(status), "");
EXPECT_EQ(status.message(), absl::StatusMessageAsCStr(status));
EXPECT_NE(absl::StatusMessageAsCStr(status), nullptr);
}
{
absl::Status status;
EXPECT_EQ(status.message(), "");
EXPECT_NE(absl::StatusMessageAsCStr(status), nullptr);
EXPECT_STREQ(absl::StatusMessageAsCStr(status), "");
}
{
absl::Status status(absl::StatusCode::kInternal, "message");
EXPECT_FALSE(status.ok());
EXPECT_EQ(absl::StatusCode::kInternal, status.code());
EXPECT_EQ("message", status.message());
EXPECT_STREQ("message", absl::StatusMessageAsCStr(status));
}
}
TEST(Status, ConstructOutOfRangeCode) {
const int kRawCode = 9999;
absl::Status status(static_cast<absl::StatusCode>(kRawCode), "");
EXPECT_EQ(absl::StatusCode::kUnknown, status.code());
EXPECT_EQ(kRawCode, status.raw_code());
}
constexpr char kUrl1[] = "url.payload.1";
constexpr char kUrl2[] = "url.payload.2";
constexpr char kUrl3[] = "url.payload.3";
constexpr char kUrl4[] = "url.payload.xx";
constexpr char kPayload1[] = "aaaaa";
constexpr char kPayload2[] = "bbbbb";
constexpr char kPayload3[] = "ccccc";
using PayloadsVec = std::vector<std::pair<std::string, absl::Cord>>;
TEST(Status, TestGetSetPayload) {
absl::Status ok_status = absl::OkStatus();
ok_status.SetPayload(kUrl1, absl::Cord(kPayload1));
ok_status.SetPayload(kUrl2, absl::Cord(kPayload2));
EXPECT_FALSE(ok_status.GetPayload(kUrl1));
EXPECT_FALSE(ok_status.GetPayload(kUrl2));
absl::Status bad_status(absl::StatusCode::kInternal, "fail");
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status.SetPayload(kUrl2, absl::Cord(kPayload2));
EXPECT_THAT(bad_status.GetPayload(kUrl1), Optional(Eq(kPayload1)));
EXPECT_THAT(bad_status.GetPayload(kUrl2), Optional(Eq(kPayload2)));
EXPECT_FALSE(bad_status.GetPayload(kUrl3));
bad_status.SetPayload(kUrl1, absl::Cord(kPayload3));
EXPECT_THAT(bad_status.GetPayload(kUrl1), Optional(Eq(kPayload3)));
bad_status.SetPayload(absl::StrCat(kUrl1, ".1"), absl::Cord(kPayload1));
EXPECT_THAT(bad_status.GetPayload(absl::StrCat(kUrl1, ".1")),
Optional(Eq(kPayload1)));
}
TEST(Status, TestErasePayload) {
absl::Status bad_status(absl::StatusCode::kInternal, "fail");
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status.SetPayload(kUrl3, absl::Cord(kPayload3));
EXPECT_FALSE(bad_status.ErasePayload(kUrl4));
EXPECT_TRUE(bad_status.GetPayload(kUrl2));
EXPECT_TRUE(bad_status.ErasePayload(kUrl2));
EXPECT_FALSE(bad_status.GetPayload(kUrl2));
EXPECT_FALSE(bad_status.ErasePayload(kUrl2));
EXPECT_TRUE(bad_status.ErasePayload(kUrl1));
EXPECT_TRUE(bad_status.ErasePayload(kUrl3));
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_TRUE(bad_status.ErasePayload(kUrl1));
}
TEST(Status, TestComparePayloads) {
absl::Status bad_status1(absl::StatusCode::kInternal, "fail");
bad_status1.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status1.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status1.SetPayload(kUrl3, absl::Cord(kPayload3));
absl::Status bad_status2(absl::StatusCode::kInternal, "fail");
bad_status2.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status2.SetPayload(kUrl3, absl::Cord(kPayload3));
bad_status2.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_EQ(bad_status1, bad_status2);
}
TEST(Status, TestComparePayloadsAfterErase) {
absl::Status payload_status(absl::StatusCode::kInternal, "");
payload_status.SetPayload(kUrl1, absl::Cord(kPayload1));
payload_status.SetPayload(kUrl2, absl::Cord(kPayload2));
absl::Status empty_status(absl::StatusCode::kInternal, "");
EXPECT_NE(payload_status, empty_status);
EXPECT_TRUE(payload_status.ErasePayload(kUrl1));
EXPECT_NE(payload_status, empty_status);
EXPECT_TRUE(payload_status.ErasePayload(kUrl2));
EXPECT_EQ(payload_status, empty_status);
}
PayloadsVec AllVisitedPayloads(const absl::Status& s) {
PayloadsVec result;
s.ForEachPayload([&](absl::string_view type_url, const absl::Cord& payload) {
result.push_back(std::make_pair(std::string(type_url), payload));
});
return result;
}
TEST(Status, TestForEachPayload) {
absl::Status bad_status(absl::StatusCode::kInternal, "fail");
bad_status.SetPayload(kUrl1, absl::Cord(kPayload1));
bad_status.SetPayload(kUrl2, absl::Cord(kPayload2));
bad_status.SetPayload(kUrl3, absl::Cord(kPayload3));
int count = 0;
bad_status.ForEachPayload(
[&count](absl::string_view, const absl::Cord&) { ++count; });
EXPECT_EQ(count, 3);
PayloadsVec expected_payloads = {{kUrl1, absl::Cord(kPayload1)},
{kUrl2, absl::Cord(kPayload2)},
{kUrl3, absl::Cord(kPayload3)}};
PayloadsVec visited_payloads = AllVisitedPayloads(bad_status);
EXPECT_THAT(visited_payloads, UnorderedElementsAreArray(expected_payloads));
std::vector<absl::Status> scratch;
while (true) {
scratch.emplace_back(absl::StatusCode::kInternal, "fail");
scratch.back().SetPayload(kUrl1, absl::Cord(kPayload1));
scratch.back().SetPayload(kUrl2, absl::Cord(kPayload2));
scratch.back().SetPayload(kUrl3, absl::Cord(kPayload3));
if (AllVisitedPayloads(scratch.back()) != visited_payloads) {
break;
}
}
}
TEST(Status, ToString) {
absl::Status status(absl::StatusCode::kInternal, "fail");
EXPECT_EQ("INTERNAL: fail", status.ToString());
status.SetPayload("foo", absl::Cord("bar"));
EXPECT_EQ("INTERNAL: fail [foo='bar']", status.ToString());
status.SetPayload("bar", absl::Cord("\377"));
EXPECT_THAT(status.ToString(),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
}
TEST(Status, ToStringMode) {
absl::Status status(absl::StatusCode::kInternal, "fail");
status.SetPayload("foo", absl::Cord("bar"));
status.SetPayload("bar", absl::Cord("\377"));
EXPECT_EQ("INTERNAL: fail",
status.ToString(absl::StatusToStringMode::kWithNoExtraData));
EXPECT_THAT(status.ToString(absl::StatusToStringMode::kWithPayload),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
EXPECT_THAT(status.ToString(absl::StatusToStringMode::kWithEverything),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
EXPECT_THAT(status.ToString(~absl::StatusToStringMode::kWithPayload),
AllOf(HasSubstr("INTERNAL: fail"), Not(HasSubstr("[foo='bar']")),
Not(HasSubstr("[bar='\\xff']"))));
}
TEST(Status, OstreamOperator) {
absl::Status status(absl::StatusCode::kInternal, "fail");
{ std::stringstream stream;
stream << status;
EXPECT_EQ("INTERNAL: fail", stream.str());
}
status.SetPayload("foo", absl::Cord("bar"));
{ std::stringstream stream;
stream << status;
EXPECT_EQ("INTERNAL: fail [foo='bar']", stream.str());
}
status.SetPayload("bar", absl::Cord("\377"));
{ std::stringstream stream;
stream << status;
EXPECT_THAT(stream.str(),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
}
}
TEST(Status, AbslStringify) {
absl::Status status(absl::StatusCode::kInternal, "fail");
EXPECT_EQ("INTERNAL: fail", absl::StrCat(status));
EXPECT_EQ("INTERNAL: fail", absl::StrFormat("%v", status));
status.SetPayload("foo", absl::Cord("bar"));
EXPECT_EQ("INTERNAL: fail [foo='bar']", absl::StrCat(status));
status.SetPayload("bar", absl::Cord("\377"));
EXPECT_THAT(absl::StrCat(status),
AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"),
HasSubstr("[bar='\\xff']")));
}
TEST(Status, OstreamEqStringify) {
absl::Status status(absl::StatusCode::kUnknown, "fail");
status.SetPayload("foo", absl::Cord("bar"));
std::stringstream stream;
stream << status;
EXPECT_EQ(stream.str(), absl::StrCat(status));
}
absl::Status EraseAndReturn(const absl::Status& base) {
absl::Status copy = base;
EXPECT_TRUE(copy.ErasePayload(kUrl1));
return copy;
}
TEST(Status, CopyOnWriteForErasePayload) {
{
absl::Status base(absl::StatusCode::kInvalidArgument, "fail");
base.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_TRUE(base.GetPayload(kUrl1).has_value());
absl::Status copy = EraseAndReturn(base);
EXPECT_TRUE(base.GetPayload(kUrl1).has_value());
EXPECT_FALSE(copy.GetPayload(kUrl1).has_value());
}
{
absl::Status base(absl::StatusCode::kInvalidArgument, "fail");
base.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy = base;
EXPECT_TRUE(base.GetPayload(kUrl1).has_value());
EXPECT_TRUE(copy.GetPayload(kUrl1).has_value());
EXPECT_TRUE(base.ErasePayload(kUrl1));
EXPECT_FALSE(base.GetPayload(kUrl1).has_value());
EXPECT_TRUE(copy.GetPayload(kUrl1).has_value());
}
}
TEST(Status, CopyConstructor) {
{
absl::Status status;
absl::Status copy(status);
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
absl::Status copy(status);
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy(status);
EXPECT_EQ(copy, status);
}
}
TEST(Status, CopyAssignment) {
absl::Status assignee;
{
absl::Status status;
assignee = status;
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
assignee = status;
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
assignee = status;
EXPECT_EQ(assignee, status);
}
}
TEST(Status, CopyAssignmentIsNotRef) {
const absl::Status status_orig(absl::StatusCode::kInvalidArgument, "message");
absl::Status status_copy = status_orig;
EXPECT_EQ(status_orig, status_copy);
status_copy.SetPayload(kUrl1, absl::Cord(kPayload1));
EXPECT_NE(status_orig, status_copy);
}
TEST(Status, MoveConstructor) {
{
absl::Status status;
absl::Status copy(absl::Status{});
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
absl::Status copy(
absl::Status(absl::StatusCode::kInvalidArgument, "message"));
EXPECT_EQ(copy, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy1(status);
absl::Status copy2(std::move(status));
EXPECT_EQ(copy1, copy2);
}
}
TEST(Status, MoveAssignment) {
absl::Status assignee;
{
absl::Status status;
assignee = absl::Status();
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
assignee = absl::Status(absl::StatusCode::kInvalidArgument, "message");
EXPECT_EQ(assignee, status);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
status.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status copy(status);
assignee = std::move(status);
EXPECT_EQ(assignee, copy);
}
{
absl::Status status(absl::StatusCode::kInvalidArgument, "message");
absl::Status copy(status);
assignee = static_cast<absl::Status&&>(status);
EXPECT_EQ(assignee, copy);
}
}
TEST(Status, Update) {
absl::Status s;
s.Update(absl::OkStatus());
EXPECT_TRUE(s.ok());
const absl::Status a(absl::StatusCode::kCancelled, "message");
s.Update(a);
EXPECT_EQ(s, a);
const absl::Status b(absl::StatusCode::kInternal, "other message");
s.Update(b);
EXPECT_EQ(s, a);
s.Update(absl::OkStatus());
EXPECT_EQ(s, a);
EXPECT_FALSE(s.ok());
}
TEST(Status, Equality) {
absl::Status ok;
absl::Status no_payload = absl::CancelledError("no payload");
absl::Status one_payload = absl::InvalidArgumentError("one payload");
one_payload.SetPayload(kUrl1, absl::Cord(kPayload1));
absl::Status two_payloads = one_payload;
two_payloads.SetPayload(kUrl2, absl::Cord(kPayload2));
const std::array<absl::Status, 4> status_arr = {ok, no_payload, one_payload,
two_payloads};
for (int i = 0; i < status_arr.size(); i++) {
for (int j = 0; j < status_arr.size(); j++) {
if (i == j) {
EXPECT_TRUE(status_arr[i] == status_arr[j]);
EXPECT_FALSE(status_arr[i] != status_arr[j]);
} else {
EXPECT_TRUE(status_arr[i] != status_arr[j]);
EXPECT_FALSE(status_arr[i] == status_arr[j]);
}
}
}
}
TEST(Status, Swap) {
auto test_swap = [](const absl::Status& s1, const absl::Status& s2) {
absl::Status copy1 = s1, copy2 = s2;
swap(copy1, copy2);
EXPECT_EQ(copy1, s2);
EXPECT_EQ(copy2, s1);
};
const absl::Status ok;
const absl::Status no_payload(absl::StatusCode::kAlreadyExists, "no payload");
absl::Status with_payload(absl::StatusCode::kInternal, "with payload");
with_payload.SetPayload(kUrl1, absl::Cord(kPayload1));
test_swap(ok, no_payload);
test_swap(no_payload, ok);
test_swap(ok, with_payload);
test_swap(with_payload, ok);
test_swap(no_payload, with_payload);
test_swap(with_payload, no_payload);
}
TEST(StatusErrno, ErrnoToStatusCode) {
EXPECT_EQ(absl::ErrnoToStatusCode(0), absl::StatusCode::kOk);
EXPECT_EQ(absl::ErrnoToStatusCode(EINVAL),
absl::StatusCode::kInvalidArgument);
EXPECT_EQ(absl::ErrnoToStatusCode(ENOENT), absl::StatusCode::kNotFound);
EXPECT_EQ(absl::ErrnoToStatusCode(19980927), absl::StatusCode::kUnknown);
}
TEST(StatusErrno, ErrnoToStatus) {
absl::Status status = absl::ErrnoToStatus(ENOENT, "Cannot open 'path'");
EXPECT_EQ(status.code(), absl::StatusCode::kNotFound);
EXPECT_EQ(status.message(), "Cannot open 'path': No such file or directory");
}
} |
2,589 | cpp | abseil/abseil-cpp | status_matchers | absl/status/internal/status_matchers.cc | absl/status/status_matchers_test.cc | #ifndef ABSL_STATUS_INTERNAL_STATUS_MATCHERS_H_
#define ABSL_STATUS_INTERNAL_STATUS_MATCHERS_H_
#include <ostream>
#include <string>
#include <type_traits>
#include <utility>
#include "gmock/gmock.h"
#include "absl/base/config.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
namespace absl_testing {
ABSL_NAMESPACE_BEGIN
namespace status_internal {
inline const absl::Status& GetStatus(const absl::Status& status) {
return status;
}
template <typename T>
inline const absl::Status& GetStatus(const absl::StatusOr<T>& status) {
return status.status();
}
template <typename StatusOrType>
class IsOkAndHoldsMatcherImpl
: public ::testing::MatcherInterface<StatusOrType> {
public:
typedef
typename std::remove_reference<StatusOrType>::type::value_type value_type;
template <typename InnerMatcher>
explicit IsOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher)
: inner_matcher_(::testing::SafeMatcherCast<const value_type&>(
std::forward<InnerMatcher>(inner_matcher))) {}
void DescribeTo(std::ostream* os) const override {
*os << "is OK and has a value that ";
inner_matcher_.DescribeTo(os);
}
void DescribeNegationTo(std::ostream* os) const override {
*os << "isn't OK or has a value that ";
inner_matcher_.DescribeNegationTo(os);
}
bool MatchAndExplain(
StatusOrType actual_value,
::testing::MatchResultListener* result_listener) const override {
if (!actual_value.ok()) {
*result_listener << "which has status " << actual_value.status();
return false;
}
return inner_matcher_.MatchAndExplain(*actual_value, result_listener);
}
private:
const ::testing::Matcher<const value_type&> inner_matcher_;
};
template <typename InnerMatcher>
class IsOkAndHoldsMatcher {
public:
explicit IsOkAndHoldsMatcher(InnerMatcher inner_matcher)
: inner_matcher_(std::forward<InnerMatcher>(inner_matcher)) {}
template <typename StatusOrType>
operator ::testing::Matcher<StatusOrType>() const {
return ::testing::Matcher<StatusOrType>(
new IsOkAndHoldsMatcherImpl<const StatusOrType&>(inner_matcher_));
}
private:
const InnerMatcher inner_matcher_;
};
class StatusCode {
public:
StatusCode(int code)
: code_(static_cast<::absl::StatusCode>(code)) {}
StatusCode(::absl::StatusCode code) : code_(code) {}
explicit operator int() const { return static_cast<int>(code_); }
friend inline void PrintTo(const StatusCode& code, std::ostream* os) {
*os << static_cast<int>(code);
}
private:
::absl::StatusCode code_;
};
inline bool operator==(const StatusCode& lhs, const StatusCode& rhs) {
return static_cast<int>(lhs) == static_cast<int>(rhs);
}
inline bool operator!=(const StatusCode& lhs, const StatusCode& rhs) {
return static_cast<int>(lhs) != static_cast<int>(rhs);
}
class StatusIsMatcherCommonImpl {
public:
StatusIsMatcherCommonImpl(
::testing::Matcher<StatusCode> code_matcher,
::testing::Matcher<absl::string_view> message_matcher)
: code_matcher_(std::move(code_matcher)),
message_matcher_(std::move(message_matcher)) {}
void DescribeTo(std::ostream* os) const;
void DescribeNegationTo(std::ostream* os) const;
bool MatchAndExplain(const absl::Status& status,
::testing::MatchResultListener* result_listener) const;
private:
const ::testing::Matcher<StatusCode> code_matcher_;
const ::testing::Matcher<absl::string_view> message_matcher_;
};
template <typename T>
class MonoStatusIsMatcherImpl : public ::testing::MatcherInterface<T> {
public:
explicit MonoStatusIsMatcherImpl(StatusIsMatcherCommonImpl common_impl)
: common_impl_(std::move(common_impl)) {}
void DescribeTo(std::ostream* os) const override {
common_impl_.DescribeTo(os);
}
void DescribeNegationTo(std::ostream* os) const override {
common_impl_.DescribeNegationTo(os);
}
bool MatchAndExplain(
T actual_value,
::testing::MatchResultListener* result_listener) const override {
return common_impl_.MatchAndExplain(GetStatus(actual_value),
result_listener);
}
private:
StatusIsMatcherCommonImpl common_impl_;
};
class StatusIsMatcher {
public:
template <typename StatusCodeMatcher, typename StatusMessageMatcher>
StatusIsMatcher(StatusCodeMatcher&& code_matcher,
StatusMessageMatcher&& message_matcher)
: common_impl_(::testing::MatcherCast<StatusCode>(
std::forward<StatusCodeMatcher>(code_matcher)),
::testing::MatcherCast<absl::string_view>(
std::forward<StatusMessageMatcher>(message_matcher))) {
}
template <typename T>
operator ::testing::Matcher<T>() const {
return ::testing::Matcher<T>(
new MonoStatusIsMatcherImpl<const T&>(common_impl_));
}
private:
const StatusIsMatcherCommonImpl common_impl_;
};
template <typename T>
class MonoIsOkMatcherImpl : public ::testing::MatcherInterface<T> {
public:
void DescribeTo(std::ostream* os) const override { *os << "is OK"; }
void DescribeNegationTo(std::ostream* os) const override {
*os << "is not OK";
}
bool MatchAndExplain(T actual_value,
::testing::MatchResultListener*) const override {
return GetStatus(actual_value).ok();
}
};
class IsOkMatcher {
public:
template <typename T>
operator ::testing::Matcher<T>() const {
return ::testing::Matcher<T>(new MonoIsOkMatcherImpl<const T&>());
}
};
}
ABSL_NAMESPACE_END
}
#endif
#include "absl/status/internal/status_matchers.h"
#include <ostream>
#include <string>
#include "gmock/gmock.h"
#include "absl/base/config.h"
#include "absl/status/status.h"
namespace absl_testing {
ABSL_NAMESPACE_BEGIN
namespace status_internal {
void StatusIsMatcherCommonImpl::DescribeTo(std::ostream* os) const {
*os << ", has a status code that ";
code_matcher_.DescribeTo(os);
*os << ", and has an error message that ";
message_matcher_.DescribeTo(os);
}
void StatusIsMatcherCommonImpl::DescribeNegationTo(std::ostream* os) const {
*os << ", or has a status code that ";
code_matcher_.DescribeNegationTo(os);
*os << ", or has an error message that ";
message_matcher_.DescribeNegationTo(os);
}
bool StatusIsMatcherCommonImpl::MatchAndExplain(
const ::absl::Status& status,
::testing::MatchResultListener* result_listener) const {
::testing::StringMatchResultListener inner_listener;
if (!code_matcher_.MatchAndExplain(status.code(), &inner_listener)) {
*result_listener << (inner_listener.str().empty()
? "whose status code is wrong"
: "which has a status code " +
inner_listener.str());
return false;
}
if (!message_matcher_.Matches(std::string(status.message()))) {
*result_listener << "whose error message is wrong";
return false;
}
return true;
}
}
ABSL_NAMESPACE_END
} | #include "absl/status/status_matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
namespace {
using ::absl_testing::IsOk;
using ::absl_testing::IsOkAndHolds;
using ::absl_testing::StatusIs;
using ::testing::Gt;
TEST(StatusMatcherTest, StatusIsOk) { EXPECT_THAT(absl::OkStatus(), IsOk()); }
TEST(StatusMatcherTest, StatusOrIsOk) {
absl::StatusOr<int> ok_int = {0};
EXPECT_THAT(ok_int, IsOk());
}
TEST(StatusMatcherTest, StatusIsNotOk) {
absl::Status error = absl::UnknownError("Smigla");
EXPECT_NONFATAL_FAILURE(EXPECT_THAT(error, IsOk()), "Smigla");
}
TEST(StatusMatcherTest, StatusOrIsNotOk) {
absl::StatusOr<int> error = absl::UnknownError("Smigla");
EXPECT_NONFATAL_FAILURE(EXPECT_THAT(error, IsOk()), "Smigla");
}
TEST(StatusMatcherTest, IsOkAndHolds) {
absl::StatusOr<int> ok_int = {4};
absl::StatusOr<absl::string_view> ok_str = {"text"};
EXPECT_THAT(ok_int, IsOkAndHolds(4));
EXPECT_THAT(ok_int, IsOkAndHolds(Gt(0)));
EXPECT_THAT(ok_str, IsOkAndHolds("text"));
}
TEST(StatusMatcherTest, IsOkAndHoldsFailure) {
absl::StatusOr<int> ok_int = {502};
absl::StatusOr<int> error = absl::UnknownError("Smigla");
absl::StatusOr<absl::string_view> ok_str = {"actual"};
EXPECT_NONFATAL_FAILURE(EXPECT_THAT(ok_int, IsOkAndHolds(0)), "502");
EXPECT_NONFATAL_FAILURE(EXPECT_THAT(error, IsOkAndHolds(0)), "Smigla");
EXPECT_NONFATAL_FAILURE(EXPECT_THAT(ok_str, IsOkAndHolds("expected")),
"actual");
}
TEST(StatusMatcherTest, StatusIs) {
absl::Status unknown = absl::UnknownError("unbekannt");
absl::Status invalid = absl::InvalidArgumentError("ungueltig");
EXPECT_THAT(absl::OkStatus(), StatusIs(absl::StatusCode::kOk));
EXPECT_THAT(absl::OkStatus(), StatusIs(0));
EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown));
EXPECT_THAT(unknown, StatusIs(2));
EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown, "unbekannt"));
EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(invalid, StatusIs(3));
EXPECT_THAT(invalid,
StatusIs(absl::StatusCode::kInvalidArgument, "ungueltig"));
}
TEST(StatusMatcherTest, StatusOrIs) {
absl::StatusOr<int> ok = {42};
absl::StatusOr<int> unknown = absl::UnknownError("unbekannt");
absl::StatusOr<absl::string_view> invalid =
absl::InvalidArgumentError("ungueltig");
EXPECT_THAT(ok, StatusIs(absl::StatusCode::kOk));
EXPECT_THAT(ok, StatusIs(0));
EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown));
EXPECT_THAT(unknown, StatusIs(2));
EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown, "unbekannt"));
EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kInvalidArgument));
EXPECT_THAT(invalid, StatusIs(3));
EXPECT_THAT(invalid,
StatusIs(absl::StatusCode::kInvalidArgument, "ungueltig"));
}
TEST(StatusMatcherTest, StatusIsFailure) {
absl::Status unknown = absl::UnknownError("unbekannt");
absl::Status invalid = absl::InvalidArgumentError("ungueltig");
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(absl::OkStatus(),
StatusIs(absl::StatusCode::kInvalidArgument)),
"OK");
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kCancelled)), "UNKNOWN");
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown, "inconnu")),
"unbekannt");
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kOutOfRange)), "INVALID");
EXPECT_NONFATAL_FAILURE(
EXPECT_THAT(invalid,
StatusIs(absl::StatusCode::kInvalidArgument, "invalide")),
"ungueltig");
}
} |
2,590 | cpp | google/tsl | scanner | tsl/platform/scanner.cc | tsl/platform/scanner_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_SCANNER_H_
#define TENSORFLOW_TSL_PLATFORM_SCANNER_H_
#include <string>
#include "tsl/platform/macros.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/stringpiece.h"
namespace tsl {
namespace strings {
class Scanner {
public:
enum CharClass {
ALL,
DIGIT,
LETTER,
LETTER_DIGIT,
LETTER_DIGIT_DASH_UNDERSCORE,
LETTER_DIGIT_DASH_DOT_SLASH,
LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE,
LETTER_DIGIT_DOT,
LETTER_DIGIT_DOT_PLUS_MINUS,
LETTER_DIGIT_DOT_UNDERSCORE,
LETTER_DIGIT_UNDERSCORE,
LOWERLETTER,
LOWERLETTER_DIGIT,
LOWERLETTER_DIGIT_UNDERSCORE,
NON_ZERO_DIGIT,
SPACE,
UPPERLETTER,
RANGLE,
};
explicit Scanner(StringPiece source) : cur_(source) { RestartCapture(); }
Scanner& One(CharClass clz) {
if (cur_.empty() || !Matches(clz, cur_[0])) {
return Error();
}
cur_.remove_prefix(1);
return *this;
}
Scanner& ZeroOrOneLiteral(StringPiece s) {
str_util::ConsumePrefix(&cur_, s);
return *this;
}
Scanner& OneLiteral(StringPiece s) {
if (!str_util::ConsumePrefix(&cur_, s)) {
error_ = true;
}
return *this;
}
Scanner& Any(CharClass clz) {
while (!cur_.empty() && Matches(clz, cur_[0])) {
cur_.remove_prefix(1);
}
return *this;
}
Scanner& Many(CharClass clz) { return One(clz).Any(clz); }
Scanner& RestartCapture() {
capture_start_ = cur_.data();
capture_end_ = nullptr;
return *this;
}
Scanner& StopCapture() {
capture_end_ = cur_.data();
return *this;
}
Scanner& Eos() {
if (!cur_.empty()) error_ = true;
return *this;
}
Scanner& AnySpace() { return Any(SPACE); }
Scanner& ScanUntil(char end_ch) {
ScanUntilImpl(end_ch, false);
return *this;
}
Scanner& ScanEscapedUntil(char end_ch) {
ScanUntilImpl(end_ch, true);
return *this;
}
char Peek(char default_value = '\0') const {
return cur_.empty() ? default_value : cur_[0];
}
int empty() const { return cur_.empty(); }
bool GetResult(StringPiece* remaining = nullptr,
StringPiece* capture = nullptr);
private:
void ScanUntilImpl(char end_ch, bool escaped);
Scanner& Error() {
error_ = true;
return *this;
}
static bool IsLetter(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
static bool IsLowerLetter(char ch) { return ch >= 'a' && ch <= 'z'; }
static bool IsDigit(char ch) { return ch >= '0' && ch <= '9'; }
static bool IsSpace(char ch) {
return (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\f' ||
ch == '\r');
}
static bool Matches(CharClass clz, char ch) {
switch (clz) {
case ALL:
return true;
case DIGIT:
return IsDigit(ch);
case LETTER:
return IsLetter(ch);
case LETTER_DIGIT:
return IsLetter(ch) || IsDigit(ch);
case LETTER_DIGIT_DASH_UNDERSCORE:
return (IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '_');
case LETTER_DIGIT_DASH_DOT_SLASH:
return IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '.' ||
ch == '/';
case LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE:
return (IsLetter(ch) || IsDigit(ch) || ch == '-' || ch == '.' ||
ch == '/' || ch == '_');
case LETTER_DIGIT_DOT:
return IsLetter(ch) || IsDigit(ch) || ch == '.';
case LETTER_DIGIT_DOT_PLUS_MINUS:
return IsLetter(ch) || IsDigit(ch) || ch == '+' || ch == '-' ||
ch == '.';
case LETTER_DIGIT_DOT_UNDERSCORE:
return IsLetter(ch) || IsDigit(ch) || ch == '.' || ch == '_';
case LETTER_DIGIT_UNDERSCORE:
return IsLetter(ch) || IsDigit(ch) || ch == '_';
case LOWERLETTER:
return ch >= 'a' && ch <= 'z';
case LOWERLETTER_DIGIT:
return IsLowerLetter(ch) || IsDigit(ch);
case LOWERLETTER_DIGIT_UNDERSCORE:
return IsLowerLetter(ch) || IsDigit(ch) || ch == '_';
case NON_ZERO_DIGIT:
return IsDigit(ch) && ch != '0';
case SPACE:
return IsSpace(ch);
case UPPERLETTER:
return ch >= 'A' && ch <= 'Z';
case RANGLE:
return ch == '>';
}
return false;
}
StringPiece cur_;
const char* capture_start_ = nullptr;
const char* capture_end_ = nullptr;
bool error_ = false;
friend class ScannerTest;
Scanner(const Scanner&) = delete;
void operator=(const Scanner&) = delete;
};
}
}
#endif
#include "tsl/platform/scanner.h"
namespace tsl {
namespace strings {
void Scanner::ScanUntilImpl(char end_ch, bool escaped) {
for (;;) {
if (cur_.empty()) {
Error();
return;
}
const char ch = cur_[0];
if (ch == end_ch) {
return;
}
cur_.remove_prefix(1);
if (escaped && ch == '\\') {
if (cur_.empty()) {
Error();
return;
}
cur_.remove_prefix(1);
}
}
}
bool Scanner::GetResult(StringPiece* remaining, StringPiece* capture) {
if (error_) {
return false;
}
if (remaining != nullptr) {
*remaining = cur_;
}
if (capture != nullptr) {
const char* end = capture_end_ == nullptr ? cur_.data() : capture_end_;
*capture = StringPiece(capture_start_, end - capture_start_);
}
return true;
}
}
} | #include "tsl/platform/scanner.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace strings {
class ScannerTest : public ::testing::Test {
protected:
string ClassStr(Scanner::CharClass clz) {
string s;
for (int i = 0; i < 256; ++i) {
char ch = i;
if (Scanner::Matches(clz, ch)) {
s += ch;
}
}
return s;
}
};
TEST_F(ScannerTest, Any) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(" horse0123")
.Any(Scanner::SPACE)
.Any(Scanner::DIGIT)
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ(" horse", match);
EXPECT_EQ("0123", remaining);
EXPECT_TRUE(Scanner("")
.Any(Scanner::SPACE)
.Any(Scanner::DIGIT)
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("", match);
EXPECT_TRUE(Scanner("----")
.Any(Scanner::SPACE)
.Any(Scanner::DIGIT)
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("----", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, AnySpace) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(" a b ")
.AnySpace()
.One(Scanner::LETTER)
.AnySpace()
.GetResult(&remaining, &match));
EXPECT_EQ(" a ", match);
EXPECT_EQ("b ", remaining);
}
TEST_F(ScannerTest, AnyEscapedNewline) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("\\\n")
.Any(Scanner::LETTER_DIGIT_UNDERSCORE)
.GetResult(&remaining, &match));
EXPECT_EQ("\\\n", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, AnyEmptyString) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("")
.Any(Scanner::LETTER_DIGIT_UNDERSCORE)
.GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, Eos) {
EXPECT_FALSE(Scanner("a").Eos().GetResult());
EXPECT_TRUE(Scanner("").Eos().GetResult());
EXPECT_FALSE(Scanner("abc").OneLiteral("ab").Eos().GetResult());
EXPECT_TRUE(Scanner("abc").OneLiteral("abc").Eos().GetResult());
}
TEST_F(ScannerTest, Many) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("abc").Many(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("0").Many(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("").Many(Scanner::LETTER).GetResult());
EXPECT_TRUE(
Scanner("abc ").Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ(" ", remaining);
EXPECT_EQ("abc", match);
EXPECT_TRUE(
Scanner("abc").Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("abc", match);
}
TEST_F(ScannerTest, One) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner("abc").One(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("0").One(Scanner::LETTER).GetResult());
EXPECT_FALSE(Scanner("").One(Scanner::LETTER).GetResult());
EXPECT_TRUE(Scanner("abc")
.One(Scanner::LETTER)
.One(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("c", remaining);
EXPECT_EQ("ab", match);
EXPECT_TRUE(Scanner("a").One(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("a", match);
}
TEST_F(ScannerTest, OneLiteral) {
EXPECT_FALSE(Scanner("abc").OneLiteral("abC").GetResult());
EXPECT_TRUE(Scanner("abc").OneLiteral("ab").OneLiteral("c").GetResult());
}
TEST_F(ScannerTest, ScanUntil) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(R"(' \1 \2 \3 \' \\'rest)")
.OneLiteral("'")
.ScanUntil('\'')
.OneLiteral("'")
.GetResult(&remaining, &match));
EXPECT_EQ(R"( \\'rest)", remaining);
EXPECT_EQ(R"(' \1 \2 \3 \')", match);
remaining = match = "unset";
EXPECT_FALSE(Scanner(R"(' \1 \2 \3 \\rest)")
.OneLiteral("'")
.ScanUntil('\'')
.GetResult(&remaining, &match));
EXPECT_EQ("unset", remaining);
EXPECT_EQ("unset", match);
remaining = match = "";
EXPECT_TRUE(
Scanner(R"(123\456)").ScanUntil('\\').GetResult(&remaining, &match));
EXPECT_EQ(R"(\456)", remaining);
EXPECT_EQ("123", match);
}
TEST_F(ScannerTest, ScanEscapedUntil) {
StringPiece remaining, match;
EXPECT_TRUE(Scanner(R"(' \1 \2 \3 \' \\'rest)")
.OneLiteral("'")
.ScanEscapedUntil('\'')
.OneLiteral("'")
.GetResult(&remaining, &match));
EXPECT_EQ("rest", remaining);
EXPECT_EQ(R"(' \1 \2 \3 \' \\')", match);
remaining = match = "unset";
EXPECT_FALSE(Scanner(R"(' \1 \2 \3 \' \\rest)")
.OneLiteral("'")
.ScanEscapedUntil('\'')
.GetResult(&remaining, &match));
EXPECT_EQ("unset", remaining);
EXPECT_EQ("unset", match);
}
TEST_F(ScannerTest, ZeroOrOneLiteral) {
StringPiece remaining, match;
EXPECT_TRUE(
Scanner("abc").ZeroOrOneLiteral("abC").GetResult(&remaining, &match));
EXPECT_EQ("abc", remaining);
EXPECT_EQ("", match);
EXPECT_TRUE(
Scanner("abcd").ZeroOrOneLiteral("ab").ZeroOrOneLiteral("c").GetResult(
&remaining, &match));
EXPECT_EQ("d", remaining);
EXPECT_EQ("abc", match);
EXPECT_TRUE(
Scanner("").ZeroOrOneLiteral("abc").GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("", match);
}
TEST_F(ScannerTest, CaptureAndGetResult) {
StringPiece remaining, match;
Scanner scan(" first second");
EXPECT_TRUE(scan.Any(Scanner::SPACE)
.RestartCapture()
.One(Scanner::LETTER)
.Any(Scanner::LETTER_DIGIT)
.StopCapture()
.Any(Scanner::SPACE)
.GetResult(&remaining, &match));
EXPECT_EQ("second", remaining);
EXPECT_EQ("first", match);
EXPECT_TRUE(scan.GetResult());
remaining = "";
EXPECT_TRUE(scan.GetResult(&remaining));
EXPECT_EQ("second", remaining);
remaining = "";
match = "";
EXPECT_TRUE(scan.GetResult(&remaining, &match));
EXPECT_EQ("second", remaining);
EXPECT_EQ("first", match);
scan.RestartCapture().One(Scanner::LETTER).One(Scanner::LETTER);
remaining = "";
match = "";
EXPECT_TRUE(scan.GetResult(&remaining, &match));
EXPECT_EQ("cond", remaining);
EXPECT_EQ("se", match);
}
TEST_F(ScannerTest, MultipleGetResultExtendsCapture) {
StringPiece remaining, match;
Scanner scan("one2three");
EXPECT_TRUE(scan.Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("2three", remaining);
EXPECT_EQ("one", match);
EXPECT_TRUE(scan.Many(Scanner::DIGIT).GetResult(&remaining, &match));
EXPECT_EQ("three", remaining);
EXPECT_EQ("one2", match);
EXPECT_TRUE(scan.Many(Scanner::LETTER).GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("one2three", match);
}
TEST_F(ScannerTest, FailedMatchDoesntChangeResult) {
Scanner scan("name");
StringPiece remaining = "rem";
StringPiece match = "match";
EXPECT_FALSE(scan.One(Scanner::SPACE).GetResult(&remaining, &match));
EXPECT_EQ("rem", remaining);
EXPECT_EQ("match", match);
}
TEST_F(ScannerTest, DefaultCapturesAll) {
Scanner scan("a b");
StringPiece remaining = "rem";
StringPiece match = "match";
EXPECT_TRUE(scan.Any(Scanner::LETTER)
.AnySpace()
.Any(Scanner::LETTER)
.GetResult(&remaining, &match));
EXPECT_EQ("", remaining);
EXPECT_EQ("a b", match);
}
TEST_F(ScannerTest, AllCharClasses) {
EXPECT_EQ(256, ClassStr(Scanner::ALL).size());
EXPECT_EQ("0123456789", ClassStr(Scanner::DIGIT));
EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER));
EXPECT_EQ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT));
EXPECT_EQ(
"-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_"
"abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DASH_UNDERSCORE));
EXPECT_EQ(
"-./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DASH_DOT_SLASH));
EXPECT_EQ(
"-./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_"
"abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE));
EXPECT_EQ(".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DOT));
EXPECT_EQ("+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DOT_PLUS_MINUS));
EXPECT_EQ(".0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_DOT_UNDERSCORE));
EXPECT_EQ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LETTER_DIGIT_UNDERSCORE));
EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", ClassStr(Scanner::LOWERLETTER));
EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LOWERLETTER_DIGIT));
EXPECT_EQ("0123456789_abcdefghijklmnopqrstuvwxyz",
ClassStr(Scanner::LOWERLETTER_DIGIT_UNDERSCORE));
EXPECT_EQ("123456789", ClassStr(Scanner::NON_ZERO_DIGIT));
EXPECT_EQ("\t\n\v\f\r ", ClassStr(Scanner::SPACE));
EXPECT_EQ("ABCDEFGHIJKLMNOPQRSTUVWXYZ", ClassStr(Scanner::UPPERLETTER));
EXPECT_EQ(">", ClassStr(Scanner::RANGLE));
}
TEST_F(ScannerTest, Peek) {
EXPECT_EQ('a', Scanner("abc").Peek());
EXPECT_EQ('a', Scanner("abc").Peek('b'));
EXPECT_EQ('\0', Scanner("").Peek());
EXPECT_EQ('z', Scanner("").Peek('z'));
EXPECT_EQ('A', Scanner("0123A").Any(Scanner::DIGIT).Peek());
EXPECT_EQ('\0', Scanner("0123A").Any(Scanner::LETTER_DIGIT).Peek());
}
}
} |
2,591 | cpp | google/tsl | stringprintf | tsl/platform/stringprintf.cc | tsl/platform/stringprintf_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_STRINGPRINTF_H_
#define TENSORFLOW_TSL_PLATFORM_STRINGPRINTF_H_
#include <stdarg.h>
#include <string>
#include "tsl/platform/macros.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace strings {
std::string Printf(const char* format, ...)
TF_PRINTF_ATTRIBUTE(1, 2);
void Appendf(std::string* dst, const char* format, ...)
TF_PRINTF_ATTRIBUTE(2, 3);
void Appendv(std::string* dst, const char* format, va_list ap);
}
}
#endif
#include "tsl/platform/stringprintf.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
namespace tsl {
namespace strings {
void Appendv(string* dst, const char* format, va_list ap) {
static const int kSpaceLength = 1024;
char space[kSpaceLength];
va_list backup_ap;
va_copy(backup_ap, ap);
int result = vsnprintf(space, kSpaceLength, format, backup_ap);
va_end(backup_ap);
if (result < kSpaceLength) {
if (result >= 0) {
dst->append(space, result);
return;
}
#ifdef _MSC_VER
va_copy(backup_ap, ap);
result = vsnprintf(nullptr, 0, format, backup_ap);
va_end(backup_ap);
#endif
if (result < 0) {
return;
}
}
int length = result + 1;
char* buf = new char[length];
va_copy(backup_ap, ap);
result = vsnprintf(buf, length, format, backup_ap);
va_end(backup_ap);
if (result >= 0 && result < length) {
dst->append(buf, result);
}
delete[] buf;
}
string Printf(const char* format, ...) {
va_list ap;
va_start(ap, format);
string result;
Appendv(&result, format, ap);
va_end(ap);
return result;
}
void Appendf(string* dst, const char* format, ...) {
va_list ap;
va_start(ap, format);
Appendv(dst, format, ap);
va_end(ap);
}
}
} | #include "tsl/platform/stringprintf.h"
#include <string>
#include "tsl/platform/test.h"
namespace tsl {
namespace strings {
namespace {
TEST(PrintfTest, Empty) {
EXPECT_EQ("", Printf("%s", string().c_str()));
EXPECT_EQ("", Printf("%s", ""));
}
TEST(PrintfTest, Misc) {
#if !defined(_MSC_VER)
EXPECT_EQ("123hello w", Printf("%3$d%2$s %1$c", 'w', "hello", 123));
#endif
}
TEST(AppendfTest, Empty) {
string value("Hello");
const char* empty = "";
Appendf(&value, "%s", empty);
EXPECT_EQ("Hello", value);
}
TEST(AppendfTest, EmptyString) {
string value("Hello");
Appendf(&value, "%s", "");
EXPECT_EQ("Hello", value);
}
TEST(AppendfTest, String) {
string value("Hello");
Appendf(&value, " %s", "World");
EXPECT_EQ("Hello World", value);
}
TEST(AppendfTest, Int) {
string value("Hello");
Appendf(&value, " %d", 123);
EXPECT_EQ("Hello 123", value);
}
TEST(PrintfTest, Multibyte) {
char* old_locale = setlocale(LC_CTYPE, nullptr);
setlocale(LC_CTYPE, "en_US.utf8");
const char kInvalidCodePoint[] = "\375\067s";
string value = Printf("%.*s", 3, kInvalidCodePoint);
EXPECT_TRUE(value.empty() || value == kInvalidCodePoint);
int n = 2048;
char* buf = new char[n + 1];
memset(buf, ' ', n - 3);
memcpy(buf + n - 3, kInvalidCodePoint, 4);
value = Printf("%.*s", n, buf);
EXPECT_TRUE(value.empty() || value == buf);
delete[] buf;
setlocale(LC_CTYPE, old_locale);
}
TEST(PrintfTest, NoMultibyte) {
char* old_locale = setlocale(LC_CTYPE, nullptr);
setlocale(LC_CTYPE, "POSIX");
string value = Printf("%.*s", 3, "\375\067s");
setlocale(LC_CTYPE, old_locale);
EXPECT_EQ("\375\067s", value);
}
TEST(PrintfTest, DontOverwriteErrno) {
errno = ECHILD;
string value = Printf("Hello, %s!", "World");
EXPECT_EQ(ECHILD, errno);
}
TEST(PrintfTest, LargeBuf) {
int n = 2048;
char* buf = new char[n + 1];
memset(buf, ' ', n);
buf[n] = 0;
string value = Printf("%s", buf);
EXPECT_EQ(buf, value);
delete[] buf;
}
}
}
} |
2,592 | cpp | google/tsl | random | tsl/platform/random.cc | tsl/platform/random_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_RANDOM_H_
#define TENSORFLOW_TSL_PLATFORM_RANDOM_H_
#include "tsl/platform/types.h"
namespace tsl {
namespace random {
uint64 New64();
uint64 ThreadLocalNew64();
uint64 New64DefaultSeed();
}
}
#endif
#include "tsl/platform/random.h"
#include <memory>
#include <random>
#include "tsl/platform/mutex.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace random {
namespace {
std::mt19937_64* InitRngWithRandomSeed() {
std::random_device device("/dev/urandom");
return new std::mt19937_64(device());
}
std::mt19937_64 InitRngWithDefaultSeed() { return std::mt19937_64(); }
}
uint64 New64() {
static std::mt19937_64* rng = InitRngWithRandomSeed();
static mutex mu(LINKER_INITIALIZED);
mutex_lock l(mu);
return (*rng)();
}
uint64 ThreadLocalNew64() {
static thread_local std::unique_ptr<std::mt19937_64> rng =
std::unique_ptr<std::mt19937_64>(InitRngWithRandomSeed());
return (*rng)();
}
uint64 New64DefaultSeed() {
static std::mt19937_64 rng = InitRngWithDefaultSeed();
static mutex mu(LINKER_INITIALIZED);
mutex_lock l(mu);
return rng();
}
}
} | #include "tsl/platform/random.h"
#include <set>
#include "tsl/platform/test.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace random {
namespace {
TEST(New64Test, SanityCheck) {
std::set<uint64> values;
for (int i = 0; i < 1000000; i++) {
uint64 x = New64();
EXPECT_TRUE(values.insert(x).second) << "duplicate " << x;
}
}
}
}
} |
2,593 | cpp | google/tsl | abi | tsl/platform/abi.cc | tsl/platform/abi_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_ABI_H_
#define TENSORFLOW_TSL_PLATFORM_ABI_H_
#include <string>
#include "tsl/platform/types.h"
namespace tsl {
namespace port {
std::string MaybeAbiDemangle(const char* name);
}
}
#endif
#include "tsl/platform/abi.h"
#include "tsl/platform/types.h"
#if defined(_MSC_VER)
#include <windows.h>
#include <cstring>
#else
#include <cxxabi.h>
#include <cstdlib>
#endif
#include <memory>
#include <string>
#if defined(_MSC_VER)
extern "C" char* __unDName(char* output_string, const char* name,
int max_string_length, void* (*p_alloc)(std::size_t),
void (*p_free)(void*), unsigned short disable_flags);
#endif
namespace tsl {
namespace port {
string MaybeAbiDemangle(const char* name) {
#if defined(_MSC_VER)
std::unique_ptr<char> demangled{__unDName(nullptr, name, 0, std::malloc,
std::free,
static_cast<unsigned short>(0))};
return string(demangled.get() != nullptr ? demangled.get() : name);
#else
int status = 0;
std::unique_ptr<char, void (*)(void*)> res{
abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free};
return (status == 0) ? res.get() : name;
#endif
}
}
} | #include "tsl/platform/abi.h"
#include <typeinfo>
#include "tsl/platform/test.h"
namespace tsl {
struct MyRandomPODType {};
TEST(AbiTest, AbiDemangleTest) {
EXPECT_EQ(port::MaybeAbiDemangle(typeid(int).name()), "int");
#ifdef PLATFORM_WINDOWS
const char pod_type_name[] = "struct tsl::MyRandomPODType";
#else
const char pod_type_name[] = "tsl::MyRandomPODType";
#endif
EXPECT_EQ(port::MaybeAbiDemangle(typeid(MyRandomPODType).name()),
pod_type_name);
EXPECT_EQ(
port::MaybeAbiDemangle("help! i'm caught in a C++ mangle factoryasdf"),
"help! i'm caught in a C++ mangle factoryasdf");
}
} |
2,594 | cpp | google/tsl | retrying_utils | tsl/platform/retrying_utils.cc | tsl/platform/retrying_utils_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_RETRYING_UTILS_H_
#define TENSORFLOW_TSL_PLATFORM_RETRYING_UTILS_H_
#include <functional>
#include "absl/time/time.h"
#include "tsl/platform/status.h"
namespace tsl {
struct RetryConfig {
RetryConfig(int64_t init_delay_time_us = 100 * 1000,
int64_t max_delay_time_us = 32 * 1000 * 1000,
int max_retries = 10) {
this->init_delay_time_us = init_delay_time_us;
this->max_delay_time_us = max_delay_time_us;
this->max_retries = max_retries;
}
int max_retries;
int64_t init_delay_time_us;
int64_t max_delay_time_us;
};
class RetryingUtils {
public:
static absl::Status CallWithRetries(const std::function<absl::Status()>& f,
const RetryConfig& config);
static absl::Status CallWithRetries(
const std::function<absl::Status()>& f,
const std::function<void(int64_t)>& sleep_usec,
const RetryConfig& config);
static absl::Status DeleteWithRetries(
const std::function<absl::Status()>& delete_func,
const RetryConfig& config);
};
absl::Duration ComputeRetryBackoff(
int current_retry_attempt, absl::Duration min_delay = absl::Milliseconds(1),
absl::Duration max_delay = absl::Seconds(10));
}
#endif
#include "tsl/platform/retrying_utils.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
#include "absl/time/time.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/file_system.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/random.h"
namespace tsl {
namespace {
bool IsRetriable(absl::StatusCode code) {
switch (code) {
case absl::StatusCode::kUnavailable:
case absl::StatusCode::kDeadlineExceeded:
case absl::StatusCode::kUnknown:
return true;
default:
return false;
}
}
double GenerateUniformRandomNumber() {
return random::New64() * (1.0 / std::numeric_limits<uint64_t>::max());
}
double GenerateUniformRandomNumberBetween(double a, double b) {
if (a == b) return a;
DCHECK_LT(a, b);
return a + GenerateUniformRandomNumber() * (b - a);
}
}
absl::Status RetryingUtils::CallWithRetries(
const std::function<absl::Status()>& f, const RetryConfig& config) {
return CallWithRetries(
f,
[](int64_t micros) {
return Env::Default()->SleepForMicroseconds(micros);
},
config);
}
absl::Status RetryingUtils::CallWithRetries(
const std::function<absl::Status()>& f,
const std::function<void(int64_t)>& sleep_usec, const RetryConfig& config) {
int retries = 0;
while (true) {
auto status = f();
if (!IsRetriable(status.code())) {
return status;
}
if (retries >= config.max_retries) {
return absl::Status(
absl::StatusCode::kAborted,
strings::StrCat(
"All ", config.max_retries,
" retry attempts failed. The last failure: ", status.message()));
}
int64_t delay_micros = 0;
if (config.init_delay_time_us > 0) {
const int64_t random_micros = random::New64() % 1000000;
delay_micros = std::min(config.init_delay_time_us << retries,
config.max_delay_time_us) +
random_micros;
}
VLOG(1) << "The operation failed and will be automatically retried in "
<< (delay_micros / 1000000.0) << " seconds (attempt "
<< (retries + 1) << " out of " << config.max_retries
<< "), caused by: " << status.ToString();
sleep_usec(delay_micros);
retries++;
}
}
absl::Status RetryingUtils::DeleteWithRetries(
const std::function<absl::Status()>& delete_func,
const RetryConfig& config) {
bool is_retried = false;
return RetryingUtils::CallWithRetries(
[delete_func, &is_retried]() {
const absl::Status status = delete_func();
if (is_retried && status.code() == error::NOT_FOUND) {
return absl::OkStatus();
}
is_retried = true;
return status;
},
config);
}
absl::Duration ComputeRetryBackoff(int current_retry_attempt,
absl::Duration min_delay,
absl::Duration max_delay) {
DCHECK_GE(current_retry_attempt, 0);
constexpr double kBackoffBase = 1.3;
constexpr double kBackoffRandMult = 0.4;
const absl::Duration first_term = min_delay * kBackoffRandMult;
absl::Duration uncapped_second_term =
min_delay * std::pow(kBackoffBase, current_retry_attempt);
absl::Duration second_term =
std::min(uncapped_second_term, max_delay - first_term);
second_term *=
GenerateUniformRandomNumberBetween(1.0 - kBackoffRandMult, 1.0);
return std::max(first_term + second_term, min_delay);
}
} | #include "tsl/platform/retrying_utils.h"
#include <cmath>
#include <fstream>
#include "absl/time/time.h"
#include "tsl/lib/core/status_test_util.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/test.h"
namespace tsl {
namespace {
TEST(RetryingUtilsTest, CallWithRetries_RetryDelays) {
std::vector<double> requested_delays;
std::function<void(int64_t)> sleep = [&requested_delays](int64_t delay) {
requested_delays.emplace_back(delay / 1000000.0);
};
std::function<absl::Status()> f = []() {
return errors::Unavailable("Failed.");
};
const auto& status = RetryingUtils::CallWithRetries(
f, sleep, RetryConfig(500000 ));
EXPECT_TRUE(errors::IsAborted(status));
EXPECT_TRUE(absl::StrContains(
status.message(),
"All 10 retry attempts failed. The last failure: Failed."))
<< status;
EXPECT_EQ(10, requested_delays.size());
EXPECT_NEAR(0.5, requested_delays[0], 1.0);
EXPECT_NEAR(1.0, requested_delays[1], 1.0);
EXPECT_NEAR(2.0, requested_delays[2], 1.0);
EXPECT_NEAR(4.0, requested_delays[3], 1.0);
EXPECT_NEAR(8.0, requested_delays[4], 1.0);
EXPECT_NEAR(16.0, requested_delays[5], 1.0);
EXPECT_NEAR(32.0, requested_delays[6], 1.0);
EXPECT_NEAR(32.0, requested_delays[7], 1.0);
EXPECT_NEAR(32.0, requested_delays[8], 1.0);
EXPECT_NEAR(32.0, requested_delays[9], 1.0);
}
TEST(RetryingUtilsTest, CallWithRetries_NotFoundIsNotRetried) {
std::vector<absl::Status> results(
{errors::Unavailable("Failed."), errors::NotFound("Not found.")});
std::function<absl::Status()> f = [&results]() {
auto result = results[0];
results.erase(results.begin());
return result;
};
EXPECT_TRUE(errors::IsNotFound(RetryingUtils::CallWithRetries(
f, RetryConfig(0 ))));
}
TEST(RetryingUtilsTest, CallWithRetries_ImmediateSuccess) {
std::vector<absl::Status> results({absl::OkStatus()});
std::function<void(int64_t)> sleep = [](int64_t delay) {
ADD_FAILURE() << "Unexpected call to sleep.";
};
std::function<absl::Status()> f = [&results]() {
auto result = results[0];
results.erase(results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::CallWithRetries(
f, sleep, RetryConfig(1L )));
}
TEST(RetryingUtilsTest, CallWithRetries_EventualSuccess) {
std::vector<absl::Status> results({errors::Unavailable("Failed."),
errors::Unavailable("Failed again."),
absl::OkStatus()});
std::function<absl::Status()> f = [&results]() {
auto result = results[0];
results.erase(results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::CallWithRetries(
f, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_ImmediateSuccess) {
std::vector<absl::Status> delete_results({absl::OkStatus()});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_EventualSuccess) {
std::vector<absl::Status> delete_results(
{errors::Unavailable(""), absl::OkStatus()});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_PermissionDeniedNotRetried) {
std::vector<absl::Status> delete_results(
{errors::Unavailable(""), errors::PermissionDenied("")});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
EXPECT_TRUE(errors::IsPermissionDenied(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 ))));
}
TEST(RetryingUtilsTest, DeleteWithRetries_SuccessThroughFileNotFound) {
std::vector<absl::Status> delete_results(
{errors::Unavailable(""), errors::NotFound("")});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
TF_EXPECT_OK(RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 )));
}
TEST(RetryingUtilsTest, DeleteWithRetries_FirstNotFoundReturnedAsIs) {
std::vector<absl::Status> delete_results({errors::NotFound("")});
const auto delete_func = [&delete_results]() {
auto result = delete_results[0];
delete_results.erase(delete_results.begin());
return result;
};
EXPECT_EQ(error::NOT_FOUND,
RetryingUtils::DeleteWithRetries(
delete_func, RetryConfig(0 ))
.code());
}
TEST(RetryingUtilsTest, ComputeRetryBackoff) {
for (int i = 0; i < 30; ++i) {
EXPECT_LE(0.4 * absl::Milliseconds(1) +
0.6 * absl::Milliseconds(1) * std::pow(1.3, i),
ComputeRetryBackoff(i));
EXPECT_LE(
ComputeRetryBackoff(i),
0.4 * absl::Milliseconds(1) + absl::Milliseconds(1) * std::pow(1.3, i));
}
}
TEST(RetryingUtilsTest, ComputeRetryBackoff_MinMaxDelays) {
for (int i = 0; i < 30; ++i) {
EXPECT_EQ(ComputeRetryBackoff(i,
absl::Seconds(10)),
absl::Seconds(10));
EXPECT_EQ(ComputeRetryBackoff(i,
absl::Microseconds(1),
absl::Microseconds(1)),
absl::Microseconds(1));
}
}
}
} |
2,595 | cpp | google/tsl | status_matchers | tsl/platform/status_matchers.cc | tsl/platform/status_matchers_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_STATUS_MATCHERS_H_
#define TENSORFLOW_TSL_PLATFORM_STATUS_MATCHERS_H_
#include <ostream>
#include <string>
#include <utility>
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace tsl {
inline void PrintTo(const tsl::error::Code code, std::ostream* os) {
*os << Code_Name(code);
}
template <typename T>
void PrintTo(const StatusOr<T>& status_or, std::ostream* os) {
*os << ::testing::PrintToString(status_or.status());
if (status_or.ok()) {
*os << ": " << ::testing::PrintToString(status_or.value());
}
}
namespace testing {
namespace internal_status {
inline const absl::Status& GetStatus(const absl::Status& status) {
return status;
}
template <typename T>
inline const absl::Status& GetStatus(const StatusOr<T>& status) {
return status.status();
}
template <typename StatusOrType>
class IsOkAndHoldsMatcherImpl
: public ::testing::MatcherInterface<StatusOrType> {
public:
typedef
typename std::remove_reference<StatusOrType>::type::value_type value_type;
template <typename InnerMatcher>
explicit IsOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher)
: inner_matcher_(::testing::SafeMatcherCast<const value_type&>(
std::forward<InnerMatcher>(inner_matcher))) {}
void DescribeTo(std::ostream* os) const override {
*os << "is OK and has a value that ";
inner_matcher_.DescribeTo(os);
}
void DescribeNegationTo(std::ostream* os) const override {
*os << "isn't OK or has a value that ";
inner_matcher_.DescribeNegationTo(os);
}
bool MatchAndExplain(
StatusOrType actual_value,
::testing::MatchResultListener* result_listener) const override {
if (!actual_value.ok()) {
*result_listener << "which has status " << actual_value.status();
return false;
}
::testing::StringMatchResultListener inner_listener;
const bool matches =
inner_matcher_.MatchAndExplain(*actual_value, &inner_listener);
const std::string inner_explanation = inner_listener.str();
if (!inner_explanation.empty()) {
*result_listener << "which contains value "
<< ::testing::PrintToString(*actual_value) << ", "
<< inner_explanation;
}
return matches;
}
private:
const ::testing::Matcher<const value_type&> inner_matcher_;
};
template <typename InnerMatcher>
class IsOkAndHoldsMatcher {
public:
explicit IsOkAndHoldsMatcher(InnerMatcher inner_matcher)
: inner_matcher_(std::move(inner_matcher)) {}
template <typename StatusOrType>
operator ::testing::Matcher<StatusOrType>() const {
return ::testing::Matcher<StatusOrType>(
new IsOkAndHoldsMatcherImpl<const StatusOrType&>(inner_matcher_));
}
private:
const InnerMatcher inner_matcher_;
};
class StatusIsMatcherCommonImpl {
public:
StatusIsMatcherCommonImpl(
::testing::Matcher<const absl::StatusCode> code_matcher,
::testing::Matcher<const std::string&> message_matcher)
: code_matcher_(std::move(code_matcher)),
message_matcher_(std::move(message_matcher)) {}
void DescribeTo(std::ostream* os) const;
void DescribeNegationTo(std::ostream* os) const;
bool MatchAndExplain(const absl::Status& status,
::testing::MatchResultListener* result_listener) const;
private:
const ::testing::Matcher<const absl::StatusCode> code_matcher_;
const ::testing::Matcher<const std::string&> message_matcher_;
};
template <typename T>
class MonoStatusIsMatcherImpl : public ::testing::MatcherInterface<T> {
public:
explicit MonoStatusIsMatcherImpl(StatusIsMatcherCommonImpl common_impl)
: common_impl_(std::move(common_impl)) {}
void DescribeTo(std::ostream* os) const override {
common_impl_.DescribeTo(os);
}
void DescribeNegationTo(std::ostream* os) const override {
common_impl_.DescribeNegationTo(os);
}
bool MatchAndExplain(
T actual_value,
::testing::MatchResultListener* result_listener) const override {
return common_impl_.MatchAndExplain(GetStatus(actual_value),
result_listener);
}
private:
StatusIsMatcherCommonImpl common_impl_;
};
class StatusIsMatcher {
public:
StatusIsMatcher(::testing::Matcher<const absl::StatusCode> code_matcher,
::testing::Matcher<const std::string&> message_matcher)
: common_impl_(
::testing::MatcherCast<const absl::StatusCode>(code_matcher),
::testing::MatcherCast<const std::string&>(message_matcher)) {}
template <typename T>
operator ::testing::Matcher<T>() const {
return ::testing::MakeMatcher(new MonoStatusIsMatcherImpl<T>(common_impl_));
}
private:
const StatusIsMatcherCommonImpl common_impl_;
};
template <typename T>
class MonoIsOkMatcherImpl : public ::testing::MatcherInterface<T> {
public:
void DescribeTo(std::ostream* os) const override { *os << "is OK"; }
void DescribeNegationTo(std::ostream* os) const override {
*os << "is not OK";
}
bool MatchAndExplain(T actual_value,
::testing::MatchResultListener*) const override {
return GetStatus(actual_value).ok();
}
};
class IsOkMatcher {
public:
template <typename T>
operator ::testing::Matcher<T>() const {
return ::testing::Matcher<T>(new MonoIsOkMatcherImpl<const T&>());
}
};
}
template <typename InnerMatcher>
internal_status::IsOkAndHoldsMatcher<typename std::decay<InnerMatcher>::type>
IsOkAndHolds(InnerMatcher&& inner_matcher) {
return internal_status::IsOkAndHoldsMatcher<
typename std::decay<InnerMatcher>::type>(
std::forward<InnerMatcher>(inner_matcher));
}
template <typename CodeMatcher, typename MessageMatcher>
internal_status::StatusIsMatcher StatusIs(CodeMatcher code_matcher,
MessageMatcher message_matcher) {
return internal_status::StatusIsMatcher(std::move(code_matcher),
std::move(message_matcher));
}
template <typename MessageMatcher>
internal_status::StatusIsMatcher StatusIs(tensorflow::error::Code code_matcher,
MessageMatcher message_matcher) {
return internal_status::StatusIsMatcher(
static_cast<absl::StatusCode>(code_matcher), std::move(message_matcher));
}
template <typename CodeMatcher>
internal_status::StatusIsMatcher StatusIs(CodeMatcher code_matcher) {
return StatusIs(std::move(code_matcher), ::testing::_);
}
template <>
inline internal_status::StatusIsMatcher StatusIs(
tensorflow::error::Code code_matcher) {
return StatusIs(static_cast<absl::StatusCode>(code_matcher), ::testing::_);
}
inline internal_status::IsOkMatcher IsOk() {
return internal_status::IsOkMatcher();
}
}
}
#endif
#include "tsl/platform/status_matchers.h"
#include <ostream>
#include <string>
#include "tsl/platform/status.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace tsl {
namespace testing {
namespace internal_status {
void StatusIsMatcherCommonImpl::DescribeTo(std::ostream* os) const {
*os << "has a status code that ";
code_matcher_.DescribeTo(os);
*os << ", and has an error message that ";
message_matcher_.DescribeTo(os);
}
void StatusIsMatcherCommonImpl::DescribeNegationTo(std::ostream* os) const {
*os << "has a status code that ";
code_matcher_.DescribeNegationTo(os);
*os << ", or has an error message that ";
message_matcher_.DescribeNegationTo(os);
}
bool StatusIsMatcherCommonImpl::MatchAndExplain(
const absl::Status& status,
::testing::MatchResultListener* result_listener) const {
::testing::StringMatchResultListener inner_listener;
inner_listener.Clear();
if (!code_matcher_.MatchAndExplain(
static_cast<absl::StatusCode>(status.code()), &inner_listener)) {
*result_listener << (inner_listener.str().empty()
? "whose status code is wrong"
: "which has a status code " +
inner_listener.str());
return false;
}
if (!message_matcher_.Matches(std::string(status.message()))) {
*result_listener << "whose error message is wrong";
return false;
}
return true;
}
}
}
} | #include "tsl/platform/status_matchers.h"
#include <sstream>
#include <string>
#include <vector>
#include "tsl/platform/errors.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/test.h"
#include "tsl/protobuf/error_codes.pb.h"
namespace tsl {
namespace testing {
namespace {
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::HasSubstr;
using ::testing::Matcher;
using ::testing::MatchesRegex;
using ::testing::Ne;
using ::testing::Not;
using ::testing::PrintToString;
MATCHER_P(LessThan, upper, "") {
if (arg < upper) {
*result_listener << "which is " << (upper - arg) << " less than " << upper;
return true;
}
*result_listener << "which is " << (arg - upper) << " more than " << upper;
return false;
}
template <typename T>
std::string Describe(const Matcher<T>& matcher) {
std::stringstream ss;
matcher.DescribeTo(&ss);
return ss.str();
}
template <typename T>
std::string DescribeNegation(const Matcher<T>& matcher) {
std::stringstream ss;
matcher.DescribeNegationTo(&ss);
return ss.str();
}
template <typename T, typename V>
std::string ExplainMatch(const Matcher<T>& matcher, const V& value) {
::testing::StringMatchResultListener listener;
matcher.MatchAndExplain(value, &listener);
return listener.str();
}
TEST(IsOkAndHoldsTest, MatchesValue) {
absl::StatusOr<std::string> status_or_message("Hello, world");
EXPECT_THAT(status_or_message, IsOkAndHolds("Hello, world"));
EXPECT_THAT(status_or_message, IsOkAndHolds(HasSubstr("Hello,")));
}
TEST(IsOkAndHoldsTest, MatchesContainer) {
absl::StatusOr<std::vector<std::string>> status_or_messages =
std::vector<std::string>{"Hello, world", "Hello, tf"};
EXPECT_THAT(status_or_messages,
IsOkAndHolds(ElementsAre("Hello, world", "Hello, tf")));
EXPECT_THAT(status_or_messages,
IsOkAndHolds(ElementsAre(HasSubstr("world"), HasSubstr("tf"))));
}
TEST(IsOkAndHoldsTest, DoesNotMatchStatus) {
absl::StatusOr<std::string> status_or_message =
errors::InvalidArgument("Invalid argument");
EXPECT_THAT(status_or_message, Not(IsOkAndHolds("Hello, world")));
}
TEST(IsOkAndHoldsTest, DoesNotMatchValue) {
absl::StatusOr<std::string> status_or_message("Hello, tf");
EXPECT_THAT(status_or_message, Not(IsOkAndHolds("Hello, world")));
}
TEST(IsOkAndHoldsTest, DoesNotMatchContainer) {
absl::StatusOr<std::vector<int>> status_or_container({1, 2, 3});
EXPECT_THAT(status_or_container, Not(IsOkAndHolds(ElementsAre(4, 5, 6))));
}
TEST(IsOkAndHoldsTest, DescribeExpectedValue) {
Matcher<absl::StatusOr<std::string>> is_ok_and_has_substr =
IsOkAndHolds(HasSubstr("Hello"));
EXPECT_EQ(Describe(is_ok_and_has_substr),
"is OK and has a value that has substring \"Hello\"");
EXPECT_EQ(DescribeNegation(is_ok_and_has_substr),
"isn't OK or has a value that has no substring \"Hello\"");
}
TEST(IsOkAndHoldsTest, ExplainNotMatchingStatus) {
Matcher<absl::StatusOr<int>> is_ok_and_less_than =
IsOkAndHolds(LessThan(100));
absl::StatusOr<int> status = errors::Unknown("Unknown");
EXPECT_THAT(ExplainMatch(is_ok_and_less_than, status),
HasSubstr("which has status UNKNOWN: Unknown"));
}
TEST(IsOkAndHoldsTest, ExplainNotMatchingValue) {
Matcher<absl::StatusOr<int>> is_ok_and_less_than =
IsOkAndHolds(LessThan(100));
EXPECT_EQ(ExplainMatch(is_ok_and_less_than, 120),
"which contains value 120, which is 20 more than 100");
}
TEST(IsOkAndHoldsTest, ExplainNotMatchingContainer) {
Matcher<absl::StatusOr<std::vector<int>>> is_ok_and_less_than =
IsOkAndHolds(ElementsAre(1, 2, 3));
std::vector<int> actual{4, 5, 6};
EXPECT_THAT(ExplainMatch(is_ok_and_less_than, actual),
HasSubstr("which contains value " + PrintToString(actual)));
}
TEST(StatusIsTest, MatchesOK) {
EXPECT_THAT(absl::OkStatus(), StatusIs(error::OK));
absl::StatusOr<std::string> message("Hello, world");
EXPECT_THAT(message, StatusIs(error::OK));
}
TEST(StatusIsTest, DoesNotMatchOk) {
EXPECT_THAT(errors::DeadlineExceeded("Deadline exceeded"),
Not(StatusIs(error::OK)));
absl::StatusOr<std::string> status = errors::NotFound("Not found");
EXPECT_THAT(status, Not(StatusIs(error::OK)));
}
TEST(StatusIsTest, MatchesStatus) {
absl::Status s = errors::Cancelled("Cancelled");
EXPECT_THAT(s, StatusIs(error::CANCELLED));
EXPECT_THAT(s, StatusIs(error::CANCELLED, "Cancelled"));
EXPECT_THAT(s, StatusIs(_, "Cancelled"));
EXPECT_THAT(s, StatusIs(error::CANCELLED, _));
EXPECT_THAT(s, StatusIs(Ne(error::INVALID_ARGUMENT), _));
EXPECT_THAT(s, StatusIs(error::CANCELLED, HasSubstr("Can")));
EXPECT_THAT(s, StatusIs(error::CANCELLED, MatchesRegex("Can.*")));
}
TEST(StatusIsTest, StatusOrMatchesStatus) {
absl::StatusOr<int> s = errors::InvalidArgument("Invalid Argument");
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, "Invalid Argument"));
EXPECT_THAT(s, StatusIs(_, "Invalid Argument"));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, _));
EXPECT_THAT(s, StatusIs(Ne(error::CANCELLED), _));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, HasSubstr("Argument")));
EXPECT_THAT(s, StatusIs(error::INVALID_ARGUMENT, MatchesRegex(".*Argument")));
}
TEST(StatusIsTest, DoesNotMatchStatus) {
absl::Status s = errors::Internal("Internal");
EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION)));
EXPECT_THAT(s, Not(StatusIs(error::INTERNAL, "Failed Precondition")));
EXPECT_THAT(s, Not(StatusIs(_, "Failed Precondition")));
EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION, _)));
}
TEST(StatusIsTest, StatusOrDoesNotMatchStatus) {
absl::StatusOr<int> s = errors::FailedPrecondition("Failed Precondition");
EXPECT_THAT(s, Not(StatusIs(error::INTERNAL)));
EXPECT_THAT(s, Not(StatusIs(error::FAILED_PRECONDITION, "Internal")));
EXPECT_THAT(s, Not(StatusIs(_, "Internal")));
EXPECT_THAT(s, Not(StatusIs(error::INTERNAL, _)));
}
TEST(StatusIsTest, DescribeExpectedValue) {
Matcher<absl::Status> status_is =
StatusIs(error::UNAVAILABLE, std::string("Unavailable"));
EXPECT_EQ(Describe(status_is),
"has a status code that is equal to UNAVAILABLE, "
"and has an error message that is equal to \"Unavailable\"");
}
TEST(StatusIsTest, DescribeNegatedExpectedValue) {
Matcher<absl::StatusOr<std::string>> status_is =
StatusIs(error::ABORTED, std::string("Aborted"));
EXPECT_EQ(DescribeNegation(status_is),
"has a status code that isn't equal to ABORTED, "
"or has an error message that isn't equal to \"Aborted\"");
}
TEST(StatusIsTest, ExplainNotMatchingErrorCode) {
Matcher<absl::Status> status_is = StatusIs(error::NOT_FOUND, _);
const absl::Status status = errors::AlreadyExists("Already exists");
EXPECT_EQ(ExplainMatch(status_is, status), "whose status code is wrong");
}
TEST(StatusIsTest, ExplainNotMatchingErrorMessage) {
Matcher<absl::Status> status_is = StatusIs(error::NOT_FOUND, "Not found");
const absl::Status status = errors::NotFound("Already exists");
EXPECT_EQ(ExplainMatch(status_is, status), "whose error message is wrong");
}
TEST(StatusIsTest, ExplainStatusOrNotMatchingErrorCode) {
Matcher<absl::StatusOr<int>> status_is = StatusIs(error::ALREADY_EXISTS, _);
const absl::StatusOr<int> status_or = errors::NotFound("Not found");
EXPECT_EQ(ExplainMatch(status_is, status_or), "whose status code is wrong");
}
TEST(StatusIsTest, ExplainStatusOrNotMatchingErrorMessage) {
Matcher<absl::StatusOr<int>> status_is =
StatusIs(error::ALREADY_EXISTS, "Already exists");
const absl::StatusOr<int> status_or = errors::AlreadyExists("Not found");
EXPECT_EQ(ExplainMatch(status_is, status_or), "whose error message is wrong");
}
TEST(StatusIsTest, ExplainStatusOrHasValue) {
Matcher<absl::StatusOr<int>> status_is =
StatusIs(error::RESOURCE_EXHAUSTED, "Resource exhausted");
const absl::StatusOr<int> value = -1;
EXPECT_EQ(ExplainMatch(status_is, value), "whose status code is wrong");
}
TEST(IsOkTest, MatchesOK) {
EXPECT_THAT(absl::OkStatus(), IsOk());
absl::StatusOr<std::string> message = std::string("Hello, world");
EXPECT_THAT(message, IsOk());
}
TEST(IsOkTest, DoesNotMatchOK) {
EXPECT_THAT(errors::PermissionDenied("Permission denied"), Not(IsOk()));
absl::StatusOr<std::string> status =
errors::Unauthenticated("Unauthenticated");
EXPECT_THAT(status, Not(IsOk()));
}
TEST(IsOkTest, DescribeExpectedValue) {
Matcher<absl::Status> status_is_ok = IsOk();
EXPECT_EQ(Describe(status_is_ok), "is OK");
Matcher<absl::StatusOr<std::string>> status_or_is_ok = IsOk();
EXPECT_EQ(Describe(status_or_is_ok), "is OK");
}
TEST(IsOkTest, DescribeNegatedExpectedValue) {
Matcher<absl::Status> status_is_ok = IsOk();
EXPECT_EQ(DescribeNegation(status_is_ok), "is not OK");
Matcher<absl::StatusOr<std::string>> status_or_is_ok = IsOk();
EXPECT_EQ(DescribeNegation(status_or_is_ok), "is not OK");
}
}
}
} |
2,596 | cpp | google/tsl | denormal | tsl/platform/denormal.cc | tsl/platform/denormal_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_DENORMAL_H_
#define TENSORFLOW_TSL_PLATFORM_DENORMAL_H_
#include "tsl/platform/macros.h"
namespace tsl {
namespace port {
class DenormalState {
public:
DenormalState(bool flush_to_zero, bool denormals_are_zero)
: flush_to_zero_(flush_to_zero),
denormals_are_zero_(denormals_are_zero) {}
inline bool flush_to_zero() const { return flush_to_zero_; }
inline bool denormals_are_zero() const { return denormals_are_zero_; }
bool operator==(const DenormalState& other) const;
bool operator!=(const DenormalState& other) const;
private:
bool flush_to_zero_;
bool denormals_are_zero_;
};
DenormalState GetDenormalState();
bool SetDenormalState(const DenormalState& state);
class ScopedRestoreFlushDenormalState {
public:
ScopedRestoreFlushDenormalState();
~ScopedRestoreFlushDenormalState();
private:
DenormalState denormal_state_;
ScopedRestoreFlushDenormalState(const ScopedRestoreFlushDenormalState&) =
delete;
void operator=(const ScopedRestoreFlushDenormalState&) = delete;
};
class ScopedFlushDenormal {
public:
ScopedFlushDenormal();
private:
ScopedRestoreFlushDenormalState restore_;
ScopedFlushDenormal(const ScopedFlushDenormal&) = delete;
void operator=(const ScopedFlushDenormal&) = delete;
};
class ScopedDontFlushDenormal {
public:
ScopedDontFlushDenormal();
private:
ScopedRestoreFlushDenormalState restore_;
ScopedDontFlushDenormal(const ScopedDontFlushDenormal&) = delete;
void operator=(const ScopedDontFlushDenormal&) = delete;
};
}
}
#endif
#include "tsl/platform/denormal.h"
#include <cstdint>
#include "tsl/platform/cpu_info.h"
#include "tsl/platform/platform.h"
#if !defined(__SSE3__) && !defined(__clang__) && \
(defined(__GNUC__) && (__GNUC__ < 4) || \
((__GNUC__ == 4) && (__GNUC_MINOR__ < 9)))
#define GCC_WITHOUT_INTRINSICS
#endif
#if defined(PLATFORM_IS_X86) && !defined(IS_MOBILE_PLATFORM) && \
!defined(GCC_WITHOUT_INTRINSICS)
#define X86_DENORM_USE_INTRINSICS
#endif
#ifdef X86_DENORM_USE_INTRINSICS
#include <pmmintrin.h>
#endif
#if defined(PLATFORM_IS_ARM) && defined(__ARM_FP) && (__ARM_FP > 0)
#define ARM_DENORM_AVAILABLE
#define ARM_FPCR_FZ (1 << 24)
#endif
namespace tsl {
namespace port {
bool DenormalState::operator==(const DenormalState& other) const {
return flush_to_zero() == other.flush_to_zero() &&
denormals_are_zero() == other.denormals_are_zero();
}
bool DenormalState::operator!=(const DenormalState& other) const {
return !(this->operator==(other));
}
#ifdef ARM_DENORM_AVAILABLE
static inline void ArmSetFloatingPointControlRegister(uint32_t fpcr) {
#ifdef PLATFORM_IS_ARM64
__asm__ __volatile__("msr fpcr, %[fpcr]"
:
: [fpcr] "r"(static_cast<uint64_t>(fpcr)));
#else
__asm__ __volatile__("vmsr fpscr, %[fpcr]" : : [fpcr] "r"(fpcr));
#endif
}
static inline uint32_t ArmGetFloatingPointControlRegister() {
uint32_t fpcr;
#ifdef PLATFORM_IS_ARM64
uint64_t fpcr64;
__asm__ __volatile__("mrs %[fpcr], fpcr" : [fpcr] "=r"(fpcr64));
fpcr = static_cast<uint32_t>(fpcr64);
#else
__asm__ __volatile__("vmrs %[fpcr], fpscr" : [fpcr] "=r"(fpcr));
#endif
return fpcr;
}
#endif
bool SetDenormalState(const DenormalState& state) {
#ifdef X86_DENORM_USE_INTRINSICS
if (TestCPUFeature(SSE3)) {
_MM_SET_FLUSH_ZERO_MODE(state.flush_to_zero() ? _MM_FLUSH_ZERO_ON
: _MM_FLUSH_ZERO_OFF);
_MM_SET_DENORMALS_ZERO_MODE(state.denormals_are_zero()
? _MM_DENORMALS_ZERO_ON
: _MM_DENORMALS_ZERO_OFF);
return true;
}
#endif
#ifdef ARM_DENORM_AVAILABLE
if (state.flush_to_zero() == state.denormals_are_zero()) {
uint32_t fpcr = ArmGetFloatingPointControlRegister();
if (state.flush_to_zero()) {
fpcr |= ARM_FPCR_FZ;
} else {
fpcr &= ~ARM_FPCR_FZ;
}
ArmSetFloatingPointControlRegister(fpcr);
return true;
}
#endif
return false;
}
DenormalState GetDenormalState() {
#ifdef X86_DENORM_USE_INTRINSICS
if (TestCPUFeature(SSE3)) {
bool flush_zero_mode = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON;
bool denormals_zero_mode =
_MM_GET_DENORMALS_ZERO_MODE() == _MM_DENORMALS_ZERO_ON;
return DenormalState(flush_zero_mode, denormals_zero_mode);
}
#endif
#ifdef ARM_DENORM_AVAILABLE
uint32_t fpcr = ArmGetFloatingPointControlRegister();
if ((fpcr & ARM_FPCR_FZ) != 0) {
return DenormalState(true, true);
}
#endif
return DenormalState(false, false);
}
ScopedRestoreFlushDenormalState::ScopedRestoreFlushDenormalState()
: denormal_state_(GetDenormalState()) {}
ScopedRestoreFlushDenormalState::~ScopedRestoreFlushDenormalState() {
SetDenormalState(denormal_state_);
}
ScopedFlushDenormal::ScopedFlushDenormal() {
SetDenormalState(
DenormalState(true, true));
}
ScopedDontFlushDenormal::ScopedDontFlushDenormal() {
SetDenormalState(
DenormalState(false, false));
}
}
} | #include "tsl/platform/denormal.h"
#include <cstring>
#include <limits>
#include "tsl/platform/test.h"
namespace tsl {
namespace port {
TEST(DenormalStateTest, ConstructorAndAccessorsWork) {
const bool flush_to_zero[] = {true, true, false, false};
const bool denormals_are_zero[] = {true, false, true, false};
for (int i = 0; i < 4; ++i) {
const DenormalState state =
DenormalState(flush_to_zero[i], denormals_are_zero[i]);
EXPECT_EQ(state.flush_to_zero(), flush_to_zero[i]);
EXPECT_EQ(state.denormals_are_zero(), denormals_are_zero[i]);
}
}
uint32_t bits(float x) {
uint32_t out;
memcpy(&out, &x, sizeof(float));
return out;
}
void CheckDenormalHandling(const DenormalState& state) {
volatile float denormal_output = std::numeric_limits<float>::min();
denormal_output *= 0.25f;
if (state.flush_to_zero()) {
EXPECT_EQ(bits(denormal_output), 0x0);
} else {
EXPECT_NE(bits(denormal_output), 0x0);
}
volatile float normal_output = std::numeric_limits<float>::denorm_min();
normal_output *= std::numeric_limits<float>::max();
if (state.denormals_are_zero()) {
EXPECT_EQ(bits(normal_output), 0x0);
} else {
EXPECT_NE(bits(normal_output), 0x0);
}
}
TEST(DenormalTest, GetAndSetStateWorkWithCorrectFlushing) {
const DenormalState states[] = {
DenormalState(true, true),
DenormalState(true, false),
DenormalState(false, true),
DenormalState(false, false)};
for (const DenormalState& state : states) {
if (SetDenormalState(state)) {
EXPECT_EQ(GetDenormalState(), state);
CheckDenormalHandling(state);
}
}
}
TEST(ScopedRestoreFlushDenormalStateTest, RestoresState) {
const DenormalState flush_denormals(true,
true);
const DenormalState dont_flush_denormals(false,
false);
const bool can_set_denormal_state = SetDenormalState(flush_denormals) &&
SetDenormalState(dont_flush_denormals);
if (can_set_denormal_state) {
SetDenormalState(flush_denormals);
{
ScopedRestoreFlushDenormalState restore_state;
SetDenormalState(dont_flush_denormals);
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
EXPECT_EQ(GetDenormalState(), flush_denormals);
SetDenormalState(dont_flush_denormals);
{
ScopedRestoreFlushDenormalState restore_state;
SetDenormalState(flush_denormals);
EXPECT_EQ(GetDenormalState(), flush_denormals);
}
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
}
TEST(ScopedFlushDenormalTest, SetsFlushingAndRestoresState) {
const DenormalState flush_denormals(true,
true);
const DenormalState dont_flush_denormals(false,
false);
const bool can_set_denormal_state = SetDenormalState(flush_denormals) &&
SetDenormalState(dont_flush_denormals);
if (can_set_denormal_state) {
SetDenormalState(dont_flush_denormals);
{
ScopedFlushDenormal scoped_flush_denormal;
EXPECT_EQ(GetDenormalState(), flush_denormals);
}
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
}
TEST(ScopedDontFlushDenormalTest, SetsNoFlushingAndRestoresState) {
const DenormalState flush_denormals(true,
true);
const DenormalState dont_flush_denormals(false,
false);
const bool can_set_denormal_state = SetDenormalState(flush_denormals) &&
SetDenormalState(dont_flush_denormals);
if (can_set_denormal_state) {
SetDenormalState(flush_denormals);
{
ScopedDontFlushDenormal scoped_dont_flush_denormal;
EXPECT_EQ(GetDenormalState(), dont_flush_denormals);
}
EXPECT_EQ(GetDenormalState(), flush_denormals);
}
}
}
} |
2,597 | cpp | google/tsl | errors | tsl/platform/errors.cc | tsl/platform/errors_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_ERRORS_H_
#define TENSORFLOW_TSL_PLATFORM_ERRORS_H_
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/str_join.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/status.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/strcat.h"
namespace tsl {
namespace error {
using tensorflow::error::ABORTED;
using tensorflow::error::ALREADY_EXISTS;
using tensorflow::error::CANCELLED;
using tensorflow::error::Code;
using tensorflow::error::DATA_LOSS;
using tensorflow::error::DEADLINE_EXCEEDED;
using tensorflow::error::FAILED_PRECONDITION;
using tensorflow::error::INTERNAL;
using tensorflow::error::INVALID_ARGUMENT;
using tensorflow::error::NOT_FOUND;
using tensorflow::error::OK;
using tensorflow::error::OUT_OF_RANGE;
using tensorflow::error::PERMISSION_DENIED;
using tensorflow::error::RESOURCE_EXHAUSTED;
using tensorflow::error::UNAUTHENTICATED;
using tensorflow::error::UNAVAILABLE;
using tensorflow::error::UNIMPLEMENTED;
using tensorflow::error::UNKNOWN;
}
namespace errors {
namespace internal {
template <typename T>
typename std::enable_if<!std::is_convertible<T, strings::AlphaNum>::value,
std::string>::type
PrepareForStrCat(const T& t) {
std::stringstream ss;
ss << t;
return ss.str();
}
inline const strings::AlphaNum& PrepareForStrCat(const strings::AlphaNum& a) {
return a;
}
}
absl::Status IOError(const string& context, int err_number);
inline std::unordered_map<std::string, std::string> GetPayloads(
const absl::Status& status) {
std::unordered_map<std::string, std::string> payloads;
status.ForEachPayload(
[&payloads](::tsl::StringPiece key, const absl::Cord& value) {
payloads[std::string(key)] = std::string(value);
});
return payloads;
}
inline void InsertPayloads(
absl::Status& status,
const std::unordered_map<std::string, std::string>& payloads) {
for (const auto& payload : payloads) {
status.SetPayload(payload.first, absl::Cord(payload.second));
}
}
inline void CopyPayloads(const absl::Status& from, absl::Status& to) {
from.ForEachPayload([&to](::tsl::StringPiece key, const absl::Cord& value) {
to.SetPayload(key, value);
});
}
#if defined(PLATFORM_GOOGLE)
inline absl::Status Create(
absl::StatusCode code, ::tsl::StringPiece message,
const std::unordered_map<std::string, std::string>& payloads,
absl::SourceLocation loc = absl::SourceLocation::current()) {
absl::Status status(code, message, loc);
InsertPayloads(status, payloads);
return status;
}
inline absl::Status CreateWithUpdatedMessage(const absl::Status& status,
::tsl::StringPiece message) {
auto locations = status.GetSourceLocations();
auto initial_loc =
locations.empty() ? absl::SourceLocation::current() : locations[0];
absl::Status new_status = Create(static_cast<absl::StatusCode>(status.code()),
message, GetPayloads(status), initial_loc);
if (locations.size() > 1) {
for (auto loc : locations.subspan(1)) {
new_status.AddSourceLocation(loc);
}
}
return new_status;
}
#else
inline ::absl::Status Create(
absl::StatusCode code, ::tsl::StringPiece message,
const std::unordered_map<std::string, std::string>& payloads) {
Status status(code, message);
InsertPayloads(status, payloads);
return status;
}
inline ::tsl::Status CreateWithUpdatedMessage(const ::tsl::Status& status,
::tsl::StringPiece message) {
return Create(static_cast<absl::StatusCode>(status.code()), message,
GetPayloads(status));
}
#endif
template <typename... Args>
void AppendToMessage(absl::Status* status, Args... args) {
auto new_status = CreateWithUpdatedMessage(
*status, ::tsl::strings::StrCat(status->message(), "\n\t", args...));
CopyPayloads(*status, new_status);
*status = std::move(new_status);
}
#define TF_RETURN_IF_ERROR(...) \
do { \
::absl::Status _status = (__VA_ARGS__); \
if (TF_PREDICT_FALSE(!_status.ok())) { \
MAYBE_ADD_SOURCE_LOCATION(_status) \
return _status; \
} \
} while (0)
#define TF_RETURN_WITH_CONTEXT_IF_ERROR(expr, ...) \
do { \
::tsl::Status _status = (expr); \
if (TF_PREDICT_FALSE(!_status.ok())) { \
::tsl::errors::AppendToMessage(&_status, __VA_ARGS__); \
return _status; \
} \
} while (0)
template <typename... Args>
absl::Status Cancelled(Args... args) {
return absl::Status(absl::StatusCode::kCancelled,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status CancelledWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kCancelled, message, payloads);
}
template <typename... Args>
absl::Status InvalidArgument(Args... args) {
return absl::Status(absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
#if defined(PLATFORM_GOOGLE)
template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
::absl::Status InvalidArgument(
Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3),
::tsl::errors::internal::PrepareForStrCat(arg4)),
loc);
}
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status InvalidArgument(
Arg1 arg1, Arg2 arg2, Arg3 arg3,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)),
loc);
}
template <typename Arg1, typename Arg2>
::absl::Status InvalidArgument(
Arg1 arg1, Arg2 arg2,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)),
loc);
}
template <typename Arg1>
::absl::Status InvalidArgument(
Arg1 arg1, absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)),
loc);
}
template <typename... Args>
::absl::Status InvalidArgumentWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return errors::Create(absl::StatusCode::kInvalidArgument, message, payloads,
loc);
}
#else
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status InvalidArgument(Arg1 arg1, Arg2 arg2, Arg3 arg3) {
return ::absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)));
}
template <typename Arg1, typename Arg2>
::absl::Status InvalidArgument(Arg1 arg1, Arg2 arg2) {
return ::absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)));
}
template <typename Arg1>
::absl::Status InvalidArgument(Arg1 arg1) {
return ::absl::Status(
absl::StatusCode::kInvalidArgument,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)));
}
template <typename... Args>
::absl::Status InvalidArgumentWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kInvalidArgument, message, payloads);
}
#endif
template <typename... Args>
absl::Status NotFound(Args... args) {
return absl::Status(absl::StatusCode::kNotFound,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
#if defined(PLATFORM_GOOGLE)
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status NotFound(
Arg1 arg1, Arg2 arg2, Arg3 arg3,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)),
loc);
}
template <typename Arg1, typename Arg2>
::absl::Status NotFound(
Arg1 arg1, Arg2 arg2,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)),
loc);
}
template <typename Arg1>
::absl::Status NotFound(
Arg1 arg1, absl::SourceLocation loc = absl::SourceLocation::current()) {
return absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)),
loc);
}
template <typename... Args>
::absl::Status NotFoundWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads,
absl::SourceLocation loc = absl::SourceLocation::current()) {
return errors::Create(absl::StatusCode::kNotFound, message, payloads, loc);
}
#else
template <typename Arg1, typename Arg2, typename Arg3>
::absl::Status NotFound(Arg1 arg1, Arg2 arg2, Arg3 arg3) {
return ::absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2),
::tsl::errors::internal::PrepareForStrCat(arg3)));
}
template <typename Arg1, typename Arg2>
::absl::Status NotFound(Arg1 arg1, Arg2 arg2) {
return ::absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1),
::tsl::errors::internal::PrepareForStrCat(arg2)));
}
template <typename Arg1>
::absl::Status NotFound(Arg1 arg1) {
return ::absl::Status(
absl::StatusCode::kNotFound,
::tsl::strings::StrCat(::tsl::errors::internal::PrepareForStrCat(arg1)));
}
template <typename... Args>
::absl::Status NotFoundWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kNotFound, message, payloads);
}
#endif
template <typename... Args>
absl::Status AlreadyExists(Args... args) {
return absl::Status(absl::StatusCode::kAlreadyExists,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status AlreadyExistsWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kAlreadyExists, message, payloads);
}
template <typename... Args>
absl::Status ResourceExhausted(Args... args) {
return absl::Status(absl::StatusCode::kResourceExhausted,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status ResourceExhaustedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kResourceExhausted, message,
payloads);
}
template <typename... Args>
absl::Status Unavailable(Args... args) {
return absl::Status(absl::StatusCode::kUnavailable,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnavailableWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnavailable, message, payloads);
}
template <typename... Args>
absl::Status FailedPrecondition(Args... args) {
return absl::Status(absl::StatusCode::kFailedPrecondition,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status FailedPreconditionWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kFailedPrecondition, message,
payloads);
}
template <typename... Args>
absl::Status OutOfRange(Args... args) {
return absl::Status(absl::StatusCode::kOutOfRange,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status OutOfRangeWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kOutOfRange, message, payloads);
}
template <typename... Args>
absl::Status Unimplemented(Args... args) {
return absl::Status(absl::StatusCode::kUnimplemented,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnimplementedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnimplemented, message, payloads);
}
template <typename... Args>
absl::Status Internal(Args... args) {
return absl::Status(absl::StatusCode::kInternal,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status InternalWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kInternal, message, payloads);
}
template <typename... Args>
absl::Status Aborted(Args... args) {
return absl::Status(absl::StatusCode::kAborted,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status AbortedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kAborted, message, payloads);
}
template <typename... Args>
absl::Status DeadlineExceeded(Args... args) {
return absl::Status(absl::StatusCode::kDeadlineExceeded,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status DeadlineExceededWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kDeadlineExceeded, message, payloads);
}
template <typename... Args>
absl::Status DataLoss(Args... args) {
return absl::Status(absl::StatusCode::kDataLoss,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status DataLossWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kDataLoss, message, payloads);
}
template <typename... Args>
absl::Status Unknown(Args... args) {
return absl::Status(absl::StatusCode::kUnknown,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnknownPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnknown, message, payloads);
}
template <typename... Args>
absl::Status PermissionDenied(Args... args) {
return absl::Status(absl::StatusCode::kPermissionDenied,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status PermissionDeniedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kPermissionDenied, message, payloads);
}
template <typename... Args>
absl::Status Unauthenticated(Args... args) {
return absl::Status(absl::StatusCode::kUnauthenticated,
::tsl::strings::StrCat(
::tsl::errors::internal::PrepareForStrCat(args)...));
}
template <typename... Args>
absl::Status UnauthenticatedWithPayloads(
const ::tsl::StringPiece& message,
const std::unordered_map<std::string, std::string>& payloads) {
return errors::Create(absl::StatusCode::kUnauthenticated, message, payloads);
}
bool IsAborted(const absl::Status& status);
bool IsAlreadyExists(const absl::Status& status);
bool IsCancelled(const absl::Status& status);
bool IsDataLoss(const absl::Status& status);
bool IsDeadlineExceeded(const absl::Status& status);
bool IsFailedPrecondition(const absl::Status& status);
bool IsInternal(const absl::Status& status);
bool IsInvalidArgument(const absl::Status& status);
bool IsNotFound(const absl::Status& status);
bool IsOutOfRange(const absl::Status& status);
bool IsPermissionDenied(const absl::Status& status);
bool IsResourceExhausted(const absl::Status& status);
bool IsUnauthenticated(const absl::Status& status);
bool IsUnavailable(const absl::Status& status);
bool IsUnimplemented(const absl::Status& status);
bool IsUnknown(const absl::Status& status);
inline std::string FormatNodeNameForError(absl::string_view name) {
return strings::StrCat("{{node ", name, "}}");
}
template <typename T>
std::string FormatNodeNamesForError(const T& names) {
return absl::StrJoin(
names, ", ", [](std::string* output, absl::string_view s) {
::tsl::strings::StrAppend(output, FormatNodeNameForError(s));
});
}
inline std::string FormatColocationNodeForError(absl::string_view name) {
return strings::StrCat("{{colocation_node ", name, "}}");
}
template <typename T, typename = std::enable_if_t<
!std::is_convertible_v<T, absl::string_view>>>
std::string FormatColocationNodeForError(const T& names) {
return absl::StrJoin(
names, ", ", [](std::string* output, absl::string_view s) {
::tsl::strings::StrAppend(output, FormatColocationNodeForError(s));
});
}
inline std::string FormatFunctionForError(absl::string_view name) {
return strings::StrCat("{{function_node ", name, "}}");
}
inline absl::Status ReplaceErrorFromNonCommunicationOps(
const absl::Status s, absl::string_view op_name) {
assert(::tsl::errors::IsUnavailable(s));
return absl::Status(
absl::StatusCode::kInternal,
strings::StrCat(
s.message(), "\nExecuting non-communication op <", op_name,
"> originally returned UnavailableError, and was replaced by "
"InternalError to avoid invoking TF network error handling logic."));
}
template <typename T>
std::string FormatOriginalNodeLocationForError(const T& node_names,
const T& func_names) {
std::vector<std::string> error_message;
for (int i = 0; i != node_names.size(); ++i) {
if (i != 0) {
error_message.push_back(", ");
}
if (i < func_names.size()) {
error_message.push_back(FormatFunctionForError(func_names[i]));
}
error_message.push_back(FormatNodeNameForError(node_names[i]));
}
return absl::StrJoin(error_message, "");
}
using ::tsl::error::OK;
}
}
#endif
#include "tsl/platform/errors.h"
#include <errno.h>
#include <string.h>
#include "tsl/platform/status.h"
#include "tsl/platform/strcat.h"
namespace tsl {
namespace errors {
namespace {
absl::StatusCode ErrnoToCode(int err_number) {
absl::StatusCode code;
switch (err_number) {
case 0:
code = absl::StatusCode::kOk;
break;
case EINVAL:
case ENAMETOOLONG:
case E2BIG:
case EDESTADDRREQ:
case EDOM:
case EFAULT:
case EILSEQ:
case ENOPROTOOPT:
case ENOSTR:
case ENOTSOCK:
case ENOTTY:
case EPROTOTYPE:
case ESPIPE:
code = absl::StatusCode::kInvalidArgument;
break;
case ETIMEDOUT:
case ETIME:
code = absl::StatusCode::kDeadlineExceeded;
break;
case ENODEV:
case ENOENT:
case ENXIO:
case ESRCH:
code = absl::StatusCode::kNotFound;
break;
case EEXIST:
case EADDRNOTAVAIL:
case EALREADY:
code = absl::StatusCode::kAlreadyExists;
break;
case EPERM:
case EACCES:
case EROFS:
code = absl::StatusCode::kPermissionDenied;
break;
case ENOTEMPTY:
case EISDIR:
case ENOTDIR:
case EADDRINUSE:
case EBADF:
case EBUSY:
case ECHILD:
case EISCONN:
#if !defined(_WIN32) && !defined(__HAIKU__)
case ENOTBLK:
#endif
case ENOTCONN:
case EPIPE:
#if !defined(_WIN32)
case ESHUTDOWN:
#endif
case ETXTBSY:
code = absl::StatusCode::kFailedPrecondition;
break;
case ENOSPC:
#if !defined(_WIN32)
case EDQUOT:
#endif
case EMFILE:
case EMLINK:
case ENFILE:
case ENOBUFS:
case ENODATA:
case ENOMEM:
case ENOSR:
#if !defined(_WIN32) && !defined(__HAIKU__)
case EUSERS:
#endif
code = absl::StatusCode::kResourceExhausted;
break;
case EFBIG:
case EOVERFLOW:
case ERANGE:
code = absl::StatusCode::kOutOfRange;
break;
case ENOSYS:
case ENOTSUP:
case EAFNOSUPPORT:
#if !defined(_WIN32)
case EPFNOSUPPORT:
#endif
case EPROTONOSUPPORT:
#if !defined(_WIN32) && !defined(__HAIKU__)
case ESOCKTNOSUPPORT:
#endif
case EXDEV:
code = absl::StatusCode::kUnimplemented;
break;
case EAGAIN:
case ECONNREFUSED:
case ECONNABORTED:
case ECONNRESET:
case EINTR:
#if !defined(_WIN32)
case EHOSTDOWN:
#endif
case EHOSTUNREACH:
case ENETDOWN:
case ENETRESET:
case ENETUNREACH:
case ENOLCK:
case ENOLINK:
#if !(defined(__APPLE__) || defined(__FreeBSD__) || defined(_WIN32) || \
defined(__HAIKU__))
case ENONET:
#endif
code = absl::StatusCode::kUnavailable;
break;
case EDEADLK:
#if !defined(_WIN32)
case ESTALE:
#endif
code = absl::StatusCode::kAborted;
break;
case ECANCELED:
code = absl::StatusCode::kCancelled;
break;
case EBADMSG:
case EIDRM:
case EINPROGRESS:
case EIO:
case ELOOP:
case ENOEXEC:
case ENOMSG:
case EPROTO:
#if !defined(_WIN32) && !defined(__HAIKU__)
case EREMOTE:
#endif
code = absl::StatusCode::kUnknown;
break;
default: {
code = absl::StatusCode::kUnknown;
break;
}
}
return code;
}
}
absl::Status IOError(const string& context, int err_number) {
auto code = ErrnoToCode(err_number);
return absl::Status(code,
strings::StrCat(context, "; ", strerror(err_number)));
}
bool IsAborted(const absl::Status& status) {
return status.code() == tsl::error::Code::ABORTED;
}
bool IsAlreadyExists(const absl::Status& status) {
return status.code() == tsl::error::Code::ALREADY_EXISTS;
}
bool IsCancelled(const absl::Status& status) {
return status.code() == tsl::error::Code::CANCELLED;
}
bool IsDataLoss(const absl::Status& status) {
return status.code() == tsl::error::Code::DATA_LOSS;
}
bool IsDeadlineExceeded(const absl::Status& status) {
return status.code() == tsl::error::Code::DEADLINE_EXCEEDED;
}
bool IsFailedPrecondition(const absl::Status& status) {
return status.code() == tsl::error::Code::FAILED_PRECONDITION;
}
bool IsInternal(const absl::Status& status) {
return status.code() == tsl::error::Code::INTERNAL;
}
bool IsInvalidArgument(const absl::Status& status) {
return status.code() == tsl::error::Code::INVALID_ARGUMENT;
}
bool IsNotFound(const absl::Status& status) {
return status.code() == tsl::error::Code::NOT_FOUND;
}
bool IsOutOfRange(const absl::Status& status) {
return status.code() == tsl::error::Code::OUT_OF_RANGE;
}
bool IsPermissionDenied(const absl::Status& status) {
r | #include "tsl/platform/errors.h"
#include "absl/status/status.h"
#include "tsl/platform/test.h"
namespace tsl {
TEST(AppendToMessageTest, PayloadsAreCopied) {
absl::Status status = errors::Aborted("Aborted Error Message");
status.SetPayload("payload_key", absl::Cord("payload_value"));
errors::AppendToMessage(&status, "Appended Message");
EXPECT_EQ(status.message(), "Aborted Error Message\n\tAppended Message");
EXPECT_EQ(status.GetPayload("payload_key"), absl::Cord("payload_value"));
}
TEST(Status, GetAllPayloads) {
absl::Status s_error(absl::StatusCode::kInternal, "Error message");
s_error.SetPayload("Error key", absl::Cord("foo"));
auto payloads_error_status = errors::GetPayloads(s_error);
ASSERT_EQ(payloads_error_status.size(), 1);
ASSERT_EQ(payloads_error_status["Error key"], "foo");
absl::Status s_ok = absl::Status();
auto payloads_ok_status = errors::GetPayloads(s_ok);
ASSERT_TRUE(payloads_ok_status.empty());
}
TEST(Status, OKStatusInsertPayloadsFromErrorStatus) {
absl::Status s_error(absl::StatusCode::kInternal, "Error message");
s_error.SetPayload("Error key", absl::Cord("foo"));
absl::Status s_ok = absl::Status();
errors::InsertPayloads(s_ok, errors::GetPayloads(s_error));
auto payloads_ok_status = errors::GetPayloads(s_ok);
ASSERT_TRUE(payloads_ok_status.empty());
}
TEST(Status, ErrorStatusInsertPayloadsFromOKStatus) {
absl::Status s_error(absl::StatusCode::kInternal, "Error message");
s_error.SetPayload("Error key", absl::Cord("foo"));
absl::Status s_ok = absl::Status();
errors::InsertPayloads(s_error, errors::GetPayloads(s_ok));
ASSERT_EQ(s_error.GetPayload("Error key"), "foo");
}
TEST(Status, ErrorStatusInsertPayloadsFromErrorStatus) {
absl::Status s_error1(absl::StatusCode::kInternal, "Error message");
s_error1.SetPayload("Error key 1", absl::Cord("foo"));
s_error1.SetPayload("Error key 2", absl::Cord("bar"));
absl::Status s_error2(absl::StatusCode::kInternal, "Error message");
s_error2.SetPayload("Error key", absl::Cord("bar"));
ASSERT_EQ(s_error2.GetPayload("Error key"), "bar");
errors::InsertPayloads(s_error2, errors::GetPayloads(s_error1));
ASSERT_EQ(s_error2.GetPayload("Error key 1"), "foo");
ASSERT_EQ(s_error2.GetPayload("Error key 2"), "bar");
auto payloads_error_status = errors::GetPayloads(s_error2);
ASSERT_EQ(payloads_error_status.size(), 3);
}
#if defined(PLATFORM_GOOGLE)
absl::Status GetError() {
return absl::InvalidArgumentError("An invalid argument error");
}
absl::Status PropagateError() {
TF_RETURN_IF_ERROR(GetError());
return absl::OkStatus();
}
absl::Status PropagateError2() {
TF_RETURN_IF_ERROR(PropagateError());
return absl::OkStatus();
}
TEST(Status, StackTracePropagation) {
absl::Status s = PropagateError2();
auto sources = s.GetSourceLocations();
ASSERT_EQ(sources.size(), 3);
for (int i = 0; i < 3; ++i) {
ASSERT_EQ(sources[i].file_name(),
"third_party/tensorflow/tsl/platform/errors_test.cc");
}
}
TEST(Status, SourceLocationsPreservedByAppend) {
absl::Status s = PropagateError2();
ASSERT_EQ(s.GetSourceLocations().size(), 3);
errors::AppendToMessage(&s, "A new message.");
ASSERT_EQ(s.GetSourceLocations().size(), 3);
}
TEST(Status, SourceLocationsPreservedByUpdate) {
absl::Status s = PropagateError2();
ASSERT_EQ(s.GetSourceLocations().size(), 3);
absl::Status s2 = errors::CreateWithUpdatedMessage(s, "New message.");
ASSERT_EQ(s2.GetSourceLocations().size(), 3);
}
#endif
} |
2,598 | cpp | google/tsl | numbers | tsl/platform/numbers.cc | tsl/platform/numbers_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_NUMBERS_H_
#define TENSORFLOW_TSL_PLATFORM_NUMBERS_H_
#include <cstdint>
#include <string>
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace strings {
static const int kFastToBufferSize = 32;
size_t FastInt32ToBufferLeft(int32_t i, char* buffer);
size_t FastUInt32ToBufferLeft(uint32_t i, char* buffer);
size_t FastInt64ToBufferLeft(int64_t i, char* buffer);
size_t FastUInt64ToBufferLeft(uint64_t i, char* buffer);
size_t DoubleToBuffer(double value, char* buffer);
size_t FloatToBuffer(float value, char* buffer);
std::string FpToString(Fprint fp);
bool StringToFp(const std::string& s, Fprint* fp);
StringPiece Uint64ToHexString(uint64_t v, char* buf);
bool HexStringToUint64(const StringPiece& s, uint64_t* result);
bool safe_strto32(StringPiece str, int32_t* value);
bool safe_strtou32(StringPiece str, uint32_t* value);
bool safe_strto64(StringPiece str, int64_t* value);
bool safe_strtou64(StringPiece str, uint64_t* value);
bool safe_strtof(StringPiece str, float* value);
bool safe_strtod(StringPiece str, double* value);
inline bool ProtoParseNumeric(StringPiece s, int32_t* value) {
return safe_strto32(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, uint32_t* value) {
return safe_strtou32(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, int64_t* value) {
return safe_strto64(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, uint64_t* value) {
return safe_strtou64(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, float* value) {
return safe_strtof(s, value);
}
inline bool ProtoParseNumeric(StringPiece s, double* value) {
return safe_strtod(s, value);
}
template <typename T>
bool SafeStringToNumeric(StringPiece s, T* value) {
return ProtoParseNumeric(s, value);
}
std::string HumanReadableNum(int64_t value);
std::string HumanReadableNumBytes(int64_t num_bytes);
std::string HumanReadableElapsedTime(double seconds);
}
}
#endif
#include "tsl/platform/numbers.h"
#include <ctype.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <cinttypes>
#include <cmath>
#include <cstdint>
#include <locale>
#include <unordered_map>
#include "double-conversion/double-conversion.h"
#include "tsl/platform/str_util.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/stringprintf.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace {
template <typename T>
const std::unordered_map<std::string, T>* GetSpecialNumsSingleton() {
static const std::unordered_map<std::string, T>* special_nums =
CHECK_NOTNULL((new const std::unordered_map<std::string, T>{
{"inf", std::numeric_limits<T>::infinity()},
{"+inf", std::numeric_limits<T>::infinity()},
{"-inf", -std::numeric_limits<T>::infinity()},
{"infinity", std::numeric_limits<T>::infinity()},
{"+infinity", std::numeric_limits<T>::infinity()},
{"-infinity", -std::numeric_limits<T>::infinity()},
{"nan", std::numeric_limits<T>::quiet_NaN()},
{"+nan", std::numeric_limits<T>::quiet_NaN()},
{"-nan", -std::numeric_limits<T>::quiet_NaN()},
}));
return special_nums;
}
template <typename T>
T locale_independent_strtonum(const char* str, const char** endptr) {
auto special_nums = GetSpecialNumsSingleton<T>();
std::stringstream s(str);
std::string special_num_str;
s >> special_num_str;
for (size_t i = 0; i < special_num_str.length(); ++i) {
special_num_str[i] =
std::tolower(special_num_str[i], std::locale::classic());
}
auto entry = special_nums->find(special_num_str);
if (entry != special_nums->end()) {
*endptr = str + (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str))
: s.tellg());
return entry->second;
} else {
if (special_num_str.compare(0, 2, "0x") == 0 ||
special_num_str.compare(0, 3, "-0x") == 0) {
return strtol(str, const_cast<char**>(endptr), 16);
}
}
s.str(str);
s.clear();
s.imbue(std::locale::classic());
T result;
s >> result;
if (s.fail()) {
if (result == std::numeric_limits<T>::max() ||
result == std::numeric_limits<T>::infinity()) {
result = std::numeric_limits<T>::infinity();
s.clear(s.rdstate() & ~std::ios::failbit);
} else if (result == -std::numeric_limits<T>::max() ||
result == -std::numeric_limits<T>::infinity()) {
result = -std::numeric_limits<T>::infinity();
s.clear(s.rdstate() & ~std::ios::failbit);
}
}
if (endptr) {
*endptr =
str +
(s.fail() ? static_cast<std::iostream::pos_type>(0)
: (s.eof() ? static_cast<std::iostream::pos_type>(strlen(str))
: s.tellg()));
}
return result;
}
static inline const double_conversion::StringToDoubleConverter&
StringToFloatConverter() {
static const double_conversion::StringToDoubleConverter converter(
double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES |
double_conversion::StringToDoubleConverter::ALLOW_HEX |
double_conversion::StringToDoubleConverter::ALLOW_TRAILING_SPACES |
double_conversion::StringToDoubleConverter::ALLOW_CASE_INSENSIBILITY,
0., 0., "inf", "nan");
return converter;
}
}
namespace strings {
size_t FastInt32ToBufferLeft(int32_t i, char* buffer) {
uint32_t u = i;
size_t length = 0;
if (i < 0) {
*buffer++ = '-';
++length;
u = 0 - u;
}
length += FastUInt32ToBufferLeft(u, buffer);
return length;
}
size_t FastUInt32ToBufferLeft(uint32_t i, char* buffer) {
char* start = buffer;
do {
*buffer++ = ((i % 10) + '0');
i /= 10;
} while (i > 0);
*buffer = 0;
std::reverse(start, buffer);
return buffer - start;
}
size_t FastInt64ToBufferLeft(int64_t i, char* buffer) {
uint64_t u = i;
size_t length = 0;
if (i < 0) {
*buffer++ = '-';
++length;
u = 0 - u;
}
length += FastUInt64ToBufferLeft(u, buffer);
return length;
}
size_t FastUInt64ToBufferLeft(uint64_t i, char* buffer) {
char* start = buffer;
do {
*buffer++ = ((i % 10) + '0');
i /= 10;
} while (i > 0);
*buffer = 0;
std::reverse(start, buffer);
return buffer - start;
}
static const double kDoublePrecisionCheckMax = DBL_MAX / 1.000000000000001;
size_t DoubleToBuffer(double value, char* buffer) {
static_assert(DBL_DIG < 20, "DBL_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
if (std::abs(value) <= kDoublePrecisionCheckMax) {
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
if (locale_independent_strtonum<double>(buffer, nullptr) == value) {
return snprintf_result;
}
}
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG + 2, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
namespace {
char SafeFirstChar(StringPiece str) {
if (str.empty()) return '\0';
return str[0];
}
void SkipSpaces(StringPiece* str) {
while (isspace(SafeFirstChar(*str))) str->remove_prefix(1);
}
}
bool safe_strto64(StringPiece str, int64_t* value) {
SkipSpaces(&str);
int64_t vlimit = kint64max;
int sign = 1;
if (absl::ConsumePrefix(&str, "-")) {
sign = -1;
vlimit = kint64min;
}
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
if (sign == 1) {
do {
int digit = SafeFirstChar(str) - '0';
if ((vlimit - digit) / 10 < result) {
return false;
}
result = result * 10 + digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
} else {
do {
int digit = SafeFirstChar(str) - '0';
if ((vlimit + digit) / 10 > result) {
return false;
}
result = result * 10 - digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
}
SkipSpaces(&str);
if (!str.empty()) return false;
*value = result;
return true;
}
bool safe_strtou64(StringPiece str, uint64_t* value) {
SkipSpaces(&str);
if (!isdigit(SafeFirstChar(str))) return false;
uint64_t result = 0;
do {
int digit = SafeFirstChar(str) - '0';
if ((kuint64max - digit) / 10 < result) {
return false;
}
result = result * 10 + digit;
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = result;
return true;
}
bool safe_strto32(StringPiece str, int32_t* value) {
SkipSpaces(&str);
int64_t vmax = kint32max;
int sign = 1;
if (absl::ConsumePrefix(&str, "-")) {
sign = -1;
++vmax;
}
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
do {
result = result * 10 + SafeFirstChar(str) - '0';
if (result > vmax) {
return false;
}
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = static_cast<int32_t>(result * sign);
return true;
}
bool safe_strtou32(StringPiece str, uint32_t* value) {
SkipSpaces(&str);
if (!isdigit(SafeFirstChar(str))) return false;
int64_t result = 0;
do {
result = result * 10 + SafeFirstChar(str) - '0';
if (result > kuint32max) {
return false;
}
str.remove_prefix(1);
} while (isdigit(SafeFirstChar(str)));
SkipSpaces(&str);
if (!str.empty()) return false;
*value = static_cast<uint32_t>(result);
return true;
}
bool safe_strtof(StringPiece str, float* value) {
int processed_characters_count = -1;
auto len = str.size();
if (len >= kFastToBufferSize) return false;
if (len > std::numeric_limits<int>::max()) return false;
*value = StringToFloatConverter().StringToFloat(
str.data(), static_cast<int>(len), &processed_characters_count);
return processed_characters_count > 0;
}
bool safe_strtod(StringPiece str, double* value) {
int processed_characters_count = -1;
auto len = str.size();
if (len >= kFastToBufferSize) return false;
if (len > std::numeric_limits<int>::max()) return false;
*value = StringToFloatConverter().StringToDouble(
str.data(), static_cast<int>(len), &processed_characters_count);
return processed_characters_count > 0;
}
size_t FloatToBuffer(float value, char* buffer) {
static_assert(FLT_DIG < 10, "FLT_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
float parsed_value;
if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) {
snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG + 3, value);
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
}
return snprintf_result;
}
std::string FpToString(Fprint fp) {
char buf[17];
snprintf(buf, sizeof(buf), "%016llx", static_cast<long long>(fp));
return std::string(buf);
}
bool StringToFp(const std::string& s, Fprint* fp) {
char junk;
uint64_t result;
if (sscanf(s.c_str(), "%" SCNx64 "%c", &result, &junk) == 1) {
*fp = result;
return true;
} else {
return false;
}
}
StringPiece Uint64ToHexString(uint64_t v, char* buf) {
static const char* hexdigits = "0123456789abcdef";
const int num_byte = 16;
buf[num_byte] = '\0';
for (int i = num_byte - 1; i >= 0; i--) {
buf[i] = hexdigits[v & 0xf];
v >>= 4;
}
return StringPiece(buf, num_byte);
}
bool HexStringToUint64(const StringPiece& s, uint64_t* result) {
uint64_t v = 0;
if (s.empty()) {
return false;
}
for (size_t i = 0; i < s.size(); i++) {
char c = s[i];
if (c >= '0' && c <= '9') {
v = (v << 4) + (c - '0');
} else if (c >= 'a' && c <= 'f') {
v = (v << 4) + 10 + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
v = (v << 4) + 10 + (c - 'A');
} else {
return false;
}
}
*result = v;
return true;
}
std::string HumanReadableNum(int64_t value) {
std::string s;
if (value < 0) {
s += "-";
value = -value;
}
if (value < 1000) {
Appendf(&s, "%lld", static_cast<long long>(value));
} else if (value >= static_cast<int64_t>(1e15)) {
Appendf(&s, "%0.3G", static_cast<double>(value));
} else {
static const char units[] = "kMBT";
const char* unit = units;
while (value >= static_cast<int64_t>(1000000)) {
value /= static_cast<int64_t>(1000);
++unit;
CHECK(unit < units + TF_ARRAYSIZE(units));
}
Appendf(&s, "%.2f%c", value / 1000.0, *unit);
}
return s;
}
std::string HumanReadableNumBytes(int64_t num_bytes) {
if (num_bytes == kint64min) {
return "-8E";
}
const char* neg_str = (num_bytes < 0) ? "-" : "";
if (num_bytes < 0) {
num_bytes = -num_bytes;
}
if (num_bytes < 1024) {
char buf[8];
snprintf(buf, sizeof(buf), "%s%lldB", neg_str,
static_cast<long long>(num_bytes));
return std::string(buf);
}
static const char units[] = "KMGTPE";
const char* unit = units;
while (num_bytes >= static_cast<int64_t>(1024) * 1024) {
num_bytes /= 1024;
++unit;
CHECK(unit < units + TF_ARRAYSIZE(units));
}
char buf[16];
snprintf(buf, sizeof(buf), ((*unit == 'K') ? "%s%.1f%ciB" : "%s%.2f%ciB"),
neg_str, num_bytes / 1024.0, *unit);
return std::string(buf);
}
std::string HumanReadableElapsedTime(double seconds) {
std::string human_readable;
if (seconds < 0) {
human_readable = "-";
seconds = -seconds;
}
const double microseconds = seconds * 1.0e6;
if (microseconds < 999.5) {
strings::Appendf(&human_readable, "%0.3g us", microseconds);
return human_readable;
}
double milliseconds = seconds * 1e3;
if (milliseconds >= .995 && milliseconds < 1) {
milliseconds = 1.0;
}
if (milliseconds < 999.5) {
strings::Appendf(&human_readable, "%0.3g ms", milliseconds);
return human_readable;
}
if (seconds < 60.0) {
strings::Appendf(&human_readable, "%0.3g s", seconds);
return human_readable;
}
seconds /= 60.0;
if (seconds < 60.0) {
strings::Appendf(&human_readable, "%0.3g min", seconds);
return human_readable;
}
seconds /= 60.0;
if (seconds < 24.0) {
strings::Appendf(&human_readable, "%0.3g h", seconds);
return human_readable;
}
seconds /= 24.0;
if (seconds < 30.0) {
strings::Appendf(&human_readable, "%0.3g days", seconds);
return human_readable;
}
if (seconds < 365.2425) {
strings::Appendf(&human_readable, "%0.3g months", seconds / 30.436875);
return human_readable;
}
seconds /= 365.2425;
strings::Appendf(&human_readable, "%0.3g years", seconds);
return human_readable;
}
}
} | #include "tsl/platform/numbers.h"
#include <cmath>
#include <string>
#include "tsl/platform/test.h"
namespace tsl {
namespace strings {
TEST(FpToString, Ints) {
for (int s = 0; s < 64; s++) {
for (int delta = -1; delta <= 1; delta++) {
uint64 fp = (1ull << s) + delta;
string s = FpToString(fp);
uint64 fp2;
EXPECT_TRUE(StringToFp(s, &fp2));
EXPECT_EQ(fp, fp2);
}
}
Fprint dummy;
EXPECT_FALSE(StringToFp("", &dummy));
EXPECT_FALSE(StringToFp("xyz", &dummy));
EXPECT_FALSE(StringToFp("0000000000000000xyz", &dummy));
}
TEST(Uint64ToHexString, Ints) {
for (int s = 0; s < 64; s++) {
for (int delta = -1; delta <= 1; delta++) {
uint64 fp = (1ull << s) + delta;
char buf[kFastToBufferSize];
StringPiece s = Uint64ToHexString(fp, buf);
uint64 fp2;
EXPECT_TRUE(HexStringToUint64(s, &fp2));
EXPECT_EQ(fp, fp2) << s;
}
}
uint64 dummy;
EXPECT_FALSE(HexStringToUint64("", &dummy));
EXPECT_FALSE(HexStringToUint64("xyz", &dummy));
EXPECT_FALSE(HexStringToUint64("0000000000000000xyz", &dummy));
}
TEST(HumanReadableNum, Basic) {
EXPECT_EQ(HumanReadableNum(823), "823");
EXPECT_EQ(HumanReadableNum(1024), "1.02k");
EXPECT_EQ(HumanReadableNum(4000), "4.00k");
EXPECT_EQ(HumanReadableNum(999499), "999.50k");
EXPECT_EQ(HumanReadableNum(1000000), "1.00M");
EXPECT_EQ(HumanReadableNum(1048575), "1.05M");
EXPECT_EQ(HumanReadableNum(1048576), "1.05M");
EXPECT_EQ(HumanReadableNum(23956812342), "23.96B");
EXPECT_EQ(HumanReadableNum(123456789012345678), "1.23E+17");
}
TEST(HumanReadableNumBytes, Bytes) {
EXPECT_EQ("0B", HumanReadableNumBytes(0));
EXPECT_EQ("4B", HumanReadableNumBytes(4));
EXPECT_EQ("1023B", HumanReadableNumBytes(1023));
EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1024));
EXPECT_EQ("1.0KiB", HumanReadableNumBytes(1025));
EXPECT_EQ("1.5KiB", HumanReadableNumBytes(1500));
EXPECT_EQ("1.9KiB", HumanReadableNumBytes(1927));
EXPECT_EQ("2.0KiB", HumanReadableNumBytes(2048));
EXPECT_EQ("1.00MiB", HumanReadableNumBytes(1 << 20));
EXPECT_EQ("11.77MiB", HumanReadableNumBytes(12345678));
EXPECT_EQ("1.00GiB", HumanReadableNumBytes(1 << 30));
EXPECT_EQ("1.00TiB", HumanReadableNumBytes(1LL << 40));
EXPECT_EQ("1.00PiB", HumanReadableNumBytes(1LL << 50));
EXPECT_EQ("1.00EiB", HumanReadableNumBytes(1LL << 60));
EXPECT_EQ("-1B", HumanReadableNumBytes(-1));
EXPECT_EQ("-4B", HumanReadableNumBytes(-4));
EXPECT_EQ("-1000B", HumanReadableNumBytes(-1000));
EXPECT_EQ("-11.77MiB", HumanReadableNumBytes(-12345678));
EXPECT_EQ("-8E", HumanReadableNumBytes(kint64min));
}
TEST(HumanReadableElapsedTime, Basic) {
EXPECT_EQ(HumanReadableElapsedTime(-10), "-10 s");
EXPECT_EQ(HumanReadableElapsedTime(-0.001), "-1 ms");
EXPECT_EQ(HumanReadableElapsedTime(-60.0), "-1 min");
EXPECT_EQ(HumanReadableElapsedTime(0.00000001), "0.01 us");
EXPECT_EQ(HumanReadableElapsedTime(0.0000012), "1.2 us");
EXPECT_EQ(HumanReadableElapsedTime(0.0012), "1.2 ms");
EXPECT_EQ(HumanReadableElapsedTime(0.12), "120 ms");
EXPECT_EQ(HumanReadableElapsedTime(1.12), "1.12 s");
EXPECT_EQ(HumanReadableElapsedTime(90.0), "1.5 min");
EXPECT_EQ(HumanReadableElapsedTime(600.0), "10 min");
EXPECT_EQ(HumanReadableElapsedTime(9000.0), "2.5 h");
EXPECT_EQ(HumanReadableElapsedTime(87480.0), "1.01 days");
EXPECT_EQ(HumanReadableElapsedTime(7776000.0), "2.96 months");
EXPECT_EQ(HumanReadableElapsedTime(78840000.0), "2.5 years");
EXPECT_EQ(HumanReadableElapsedTime(382386614.40), "12.1 years");
EXPECT_EQ(HumanReadableElapsedTime(DBL_MAX), "5.7e+300 years");
}
TEST(safe_strto32, Int32s) {
int32 result;
EXPECT_EQ(true, safe_strto32("1", &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto32("123", &result));
EXPECT_EQ(123, result);
EXPECT_EQ(true, safe_strto32(" -123 ", &result));
EXPECT_EQ(-123, result);
EXPECT_EQ(true, safe_strto32("2147483647", &result));
EXPECT_EQ(2147483647, result);
EXPECT_EQ(true, safe_strto32("-2147483648", &result));
EXPECT_EQ(-2147483648, result);
EXPECT_EQ(false, safe_strto32(" 132as ", &result));
EXPECT_EQ(false, safe_strto32(" 132.2 ", &result));
EXPECT_EQ(false, safe_strto32(" -", &result));
EXPECT_EQ(false, safe_strto32("", &result));
EXPECT_EQ(false, safe_strto32(" ", &result));
EXPECT_EQ(false, safe_strto32("123 a", &result));
EXPECT_EQ(false, safe_strto32("2147483648", &result));
EXPECT_EQ(false, safe_strto32("-2147483649", &result));
EXPECT_EQ(true, safe_strto32(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto32(StringPiece(" -123", 4), &result));
EXPECT_EQ(-12, result);
EXPECT_EQ(false, safe_strto32(StringPiece(nullptr, 0), &result));
}
TEST(safe_strtou32, UInt32s) {
uint32 result;
EXPECT_TRUE(safe_strtou32("0", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtou32("1", &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou32("123", &result));
EXPECT_EQ(123, result);
EXPECT_TRUE(safe_strtou32("4294967295", &result));
EXPECT_EQ(4294967295, result);
EXPECT_FALSE(safe_strtou32(" 132as ", &result));
EXPECT_FALSE(safe_strtou32(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou32(" -", &result));
EXPECT_FALSE(safe_strtou32("", &result));
EXPECT_FALSE(safe_strtou32(" ", &result));
EXPECT_FALSE(safe_strtou32("123 a", &result));
EXPECT_FALSE(safe_strtou32("123 456", &result));
EXPECT_FALSE(safe_strtou32("4294967296", &result));
EXPECT_FALSE(safe_strtou32("-1", &result));
EXPECT_TRUE(safe_strtou32(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou32(StringPiece(" 123", 3), &result));
EXPECT_EQ(12, result);
EXPECT_FALSE(safe_strtou32(StringPiece(nullptr, 0), &result));
}
TEST(safe_strto64, Int64s) {
int64 result;
EXPECT_EQ(true, safe_strto64("1", &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto64("123", &result));
EXPECT_EQ(123, result);
EXPECT_EQ(true, safe_strto64(" -123 ", &result));
EXPECT_EQ(-123, result);
EXPECT_EQ(true, safe_strto64("9223372036854775807", &result));
EXPECT_EQ(9223372036854775807, result);
EXPECT_EQ(true, safe_strto64("-9223372036854775808", &result));
EXPECT_EQ(kint64min, result);
EXPECT_EQ(false, safe_strto64(" 132as ", &result));
EXPECT_EQ(false, safe_strto64(" 132.2 ", &result));
EXPECT_EQ(false, safe_strto64(" -", &result));
EXPECT_EQ(false, safe_strto64("", &result));
EXPECT_EQ(false, safe_strto64(" ", &result));
EXPECT_EQ(false, safe_strto64("123 a", &result));
EXPECT_EQ(false, safe_strto64("9223372036854775808", &result));
EXPECT_EQ(false, safe_strto64("-9223372036854775809", &result));
EXPECT_EQ(true, safe_strto64(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_EQ(true, safe_strto64(StringPiece(" -123", 4), &result));
EXPECT_EQ(-12, result);
EXPECT_EQ(false, safe_strto64(StringPiece(nullptr, 0), &result));
}
TEST(safe_strtou64, UInt64s) {
uint64 result;
EXPECT_TRUE(safe_strtou64("0", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtou64("1", &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou64("123", &result));
EXPECT_EQ(123, result);
EXPECT_TRUE(safe_strtou64(" 345 ", &result));
EXPECT_EQ(345, result);
EXPECT_TRUE(safe_strtou64("18446744073709551615", &result));
EXPECT_EQ(18446744073709551615UL, result);
EXPECT_FALSE(safe_strtou64(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou64(" 132.2 ", &result));
EXPECT_FALSE(safe_strtou64(" -", &result));
EXPECT_FALSE(safe_strtou64("", &result));
EXPECT_FALSE(safe_strtou64(" ", &result));
EXPECT_FALSE(safe_strtou64("123 a", &result));
EXPECT_FALSE(safe_strtou64("123 456", &result));
EXPECT_FALSE(safe_strtou64("18446744073709551616", &result));
EXPECT_FALSE(safe_strtou64("-1", &result));
EXPECT_TRUE(safe_strtou64(StringPiece("123", 1), &result));
EXPECT_EQ(1, result);
EXPECT_TRUE(safe_strtou64(StringPiece(" 123", 3), &result));
EXPECT_EQ(12, result);
EXPECT_FALSE(safe_strtou64(StringPiece(nullptr, 0), &result));
}
TEST(safe_strtof, Float) {
float result = 0;
EXPECT_TRUE(safe_strtof("0.123456", &result));
EXPECT_EQ(0.123456f, result);
EXPECT_FALSE(safe_strtof("0.12345abc", &result));
EXPECT_TRUE(safe_strtof("1e39", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("-1e39", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("1e-50", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtof("0xF", &result));
EXPECT_EQ(0xF, result);
EXPECT_TRUE(safe_strtof("-0x2A", &result));
EXPECT_EQ(-42.0f, result);
EXPECT_TRUE(safe_strtof(" -0x2", &result));
EXPECT_EQ(-2.0f, result);
EXPECT_TRUE(safe_strtof("8 \t", &result));
EXPECT_EQ(8.0f, result);
EXPECT_TRUE(safe_strtof("\t20.0\t ", &result));
EXPECT_EQ(20.0f, result);
EXPECT_FALSE(safe_strtof("-infinity is awesome", &result));
char test_str[2 * kFastToBufferSize];
for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a';
test_str[kFastToBufferSize + 1] = '\0';
EXPECT_FALSE(safe_strtof(test_str, &result));
EXPECT_TRUE(safe_strtof("-inf", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("+inf", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("InF", &result));
EXPECT_EQ(std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("-INF", &result));
EXPECT_EQ(-std::numeric_limits<float>::infinity(), result);
EXPECT_TRUE(safe_strtof("nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("-nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("-NaN", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtof("+NAN", &result));
EXPECT_TRUE(std::isnan(result));
}
TEST(safe_strtod, Double) {
double result = 0;
EXPECT_TRUE(safe_strtod("0.1234567890123", &result));
EXPECT_EQ(0.1234567890123, result);
EXPECT_FALSE(safe_strtod("0.1234567890123abc", &result));
char test_str[2 * kFastToBufferSize];
for (int i = 0; i < 2 * kFastToBufferSize; ++i) test_str[i] = 'a';
test_str[kFastToBufferSize + 1] = '\0';
EXPECT_FALSE(safe_strtod(test_str, &result));
EXPECT_TRUE(safe_strtod("1e310", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("-1e310", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("1e-325", &result));
EXPECT_EQ(0, result);
EXPECT_TRUE(safe_strtod(" -0x1c", &result));
EXPECT_EQ(-28.0, result);
EXPECT_TRUE(safe_strtod("50 \t", &result));
EXPECT_EQ(50.0, result);
EXPECT_TRUE(safe_strtod("\t82.0\t ", &result));
EXPECT_EQ(82.0, result);
EXPECT_FALSE(safe_strtod("infinity", &result));
EXPECT_TRUE(safe_strtod("-inf", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("+inf", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("InF", &result));
EXPECT_EQ(std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("-INF", &result));
EXPECT_EQ(-std::numeric_limits<double>::infinity(), result);
EXPECT_TRUE(safe_strtod("nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("-nan", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("-NaN", &result));
EXPECT_TRUE(std::isnan(result));
EXPECT_TRUE(safe_strtod("+NAN", &result));
EXPECT_TRUE(std::isnan(result));
}
}
} |
2,599 | cpp | google/tsl | str_util | tsl/platform/str_util.cc | tsl/platform/str_util_test.cc | #ifndef TENSORFLOW_TSL_PLATFORM_STR_UTIL_H_
#define TENSORFLOW_TSL_PLATFORM_STR_UTIL_H_
#include <cstdint>
#include <string>
#include <vector>
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "tsl/platform/macros.h"
#include "tsl/platform/stringpiece.h"
#include "tsl/platform/types.h"
namespace tsl {
namespace str_util {
std::string CEscape(StringPiece src);
bool CUnescape(StringPiece source, std::string* dest, std::string* error);
void StripTrailingWhitespace(std::string* s);
size_t RemoveLeadingWhitespace(StringPiece* text);
size_t RemoveTrailingWhitespace(StringPiece* text);
size_t RemoveWhitespaceContext(StringPiece* text);
bool ConsumeLeadingDigits(StringPiece* s, uint64_t* val);
bool ConsumeNonWhitespace(StringPiece* s, StringPiece* val);
bool ConsumePrefix(StringPiece* s, StringPiece expected);
bool ConsumeSuffix(StringPiece* s, StringPiece expected);
TF_MUST_USE_RESULT StringPiece StripPrefix(StringPiece s, StringPiece expected);
TF_MUST_USE_RESULT StringPiece StripSuffix(StringPiece s, StringPiece expected);
std::string Lowercase(StringPiece s);
std::string Uppercase(StringPiece s);
void TitlecaseString(std::string* s, StringPiece delimiters);
std::string StringReplace(StringPiece s, StringPiece oldsub, StringPiece newsub,
bool replace_all);
template <typename T>
std::string Join(const T& s, const char* sep) {
return absl::StrJoin(s, sep);
}
template <typename T, typename Formatter>
std::string Join(const T& s, const char* sep, Formatter f) {
return absl::StrJoin(s, sep, f);
}
struct AllowEmpty {
bool operator()(StringPiece sp) const { return true; }
};
struct SkipEmpty {
bool operator()(StringPiece sp) const { return !sp.empty(); }
};
struct SkipWhitespace {
bool operator()(StringPiece sp) const {
return !absl::StripTrailingAsciiWhitespace(sp).empty();
}
};
inline std::vector<string> Split(StringPiece text, StringPiece delims) {
return text.empty() ? std::vector<string>()
: absl::StrSplit(text, absl::ByAnyChar(delims));
}
template <typename Predicate>
std::vector<string> Split(StringPiece text, StringPiece delims, Predicate p) {
return text.empty() ? std::vector<string>()
: absl::StrSplit(text, absl::ByAnyChar(delims), p);
}
inline std::vector<string> Split(StringPiece text, char delim) {
return text.empty() ? std::vector<string>() : absl::StrSplit(text, delim);
}
template <typename Predicate>
std::vector<string> Split(StringPiece text, char delim, Predicate p) {
return text.empty() ? std::vector<string>() : absl::StrSplit(text, delim, p);
}
bool StartsWith(StringPiece text, StringPiece prefix);
bool EndsWith(StringPiece text, StringPiece suffix);
bool StrContains(StringPiece haystack, StringPiece needle);
size_t Strnlen(const char* str, const size_t string_max_len);
std::string ArgDefCase(StringPiece s);
}
}
#endif
#include "tsl/platform/str_util.h"
#include <cctype>
#include <cstdint>
#include <string>
#include <vector>
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/strip.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/stringpiece.h"
namespace tsl {
namespace str_util {
string CEscape(StringPiece src) { return absl::CEscape(src); }
bool CUnescape(StringPiece source, string* dest, string* error) {
return absl::CUnescape(source, dest, error);
}
void StripTrailingWhitespace(string* s) {
absl::StripTrailingAsciiWhitespace(s);
}
size_t RemoveLeadingWhitespace(StringPiece* text) {
absl::string_view new_text = absl::StripLeadingAsciiWhitespace(*text);
size_t count = text->size() - new_text.size();
*text = new_text;
return count;
}
size_t RemoveTrailingWhitespace(StringPiece* text) {
absl::string_view new_text = absl::StripTrailingAsciiWhitespace(*text);
size_t count = text->size() - new_text.size();
*text = new_text;
return count;
}
size_t RemoveWhitespaceContext(StringPiece* text) {
absl::string_view new_text = absl::StripAsciiWhitespace(*text);
size_t count = text->size() - new_text.size();
*text = new_text;
return count;
}
bool ConsumeLeadingDigits(StringPiece* s, uint64_t* val) {
const char* p = s->data();
const char* limit = p + s->size();
uint64_t v = 0;
while (p < limit) {
const char c = *p;
if (c < '0' || c > '9') break;
uint64_t new_v = (v * 10) + (c - '0');
if (new_v / 8 < v) {
return false;
}
v = new_v;
p++;
}
if (p > s->data()) {
s->remove_prefix(p - s->data());
*val = v;
return true;
} else {
return false;
}
}
bool ConsumeNonWhitespace(StringPiece* s, StringPiece* val) {
const char* p = s->data();
const char* limit = p + s->size();
while (p < limit) {
const char c = *p;
if (isspace(c)) break;
p++;
}
const size_t n = p - s->data();
if (n > 0) {
*val = StringPiece(s->data(), n);
s->remove_prefix(n);
return true;
} else {
*val = StringPiece();
return false;
}
}
bool ConsumePrefix(StringPiece* s, StringPiece expected) {
return absl::ConsumePrefix(s, expected);
}
bool ConsumeSuffix(StringPiece* s, StringPiece expected) {
return absl::ConsumeSuffix(s, expected);
}
StringPiece StripPrefix(StringPiece s, StringPiece expected) {
return absl::StripPrefix(s, expected);
}
StringPiece StripSuffix(StringPiece s, StringPiece expected) {
return absl::StripSuffix(s, expected);
}
string Lowercase(StringPiece s) { return absl::AsciiStrToLower(s); }
string Uppercase(StringPiece s) { return absl::AsciiStrToUpper(s); }
void TitlecaseString(string* s, StringPiece delimiters) {
bool upper = true;
for (string::iterator ss = s->begin(); ss != s->end(); ++ss) {
if (upper) {
*ss = toupper(*ss);
}
upper = (delimiters.find(*ss) != StringPiece::npos);
}
}
string StringReplace(StringPiece s, StringPiece oldsub, StringPiece newsub,
bool replace_all) {
string res(s);
size_t pos = 0;
while ((pos = res.find(oldsub.data(), pos, oldsub.size())) != string::npos) {
res.replace(pos, oldsub.size(), newsub.data(), newsub.size());
pos += newsub.size();
if (oldsub.empty()) {
pos++;
}
if (!replace_all) {
break;
}
}
return res;
}
bool StartsWith(StringPiece text, StringPiece prefix) {
return absl::StartsWith(text, prefix);
}
bool EndsWith(StringPiece text, StringPiece suffix) {
return absl::EndsWith(text, suffix);
}
bool StrContains(StringPiece haystack, StringPiece needle) {
return absl::StrContains(haystack, needle);
}
size_t Strnlen(const char* str, const size_t string_max_len) {
size_t len = 0;
while (len < string_max_len && str[len] != '\0') {
++len;
}
return len;
}
string ArgDefCase(StringPiece s) {
const size_t n = s.size();
size_t extra_us = 0;
size_t to_skip = 0;
for (size_t i = 0; i < n; ++i) {
if (i == to_skip && !isalpha(s[i])) {
++to_skip;
continue;
}
if (isupper(s[i]) && i != to_skip && i > 0 && isalnum(s[i - 1])) {
++extra_us;
}
}
string result(n + extra_us - to_skip, '_');
for (size_t i = to_skip, j = 0; i < n; ++i, ++j) {
DCHECK_LT(j, result.size());
char c = s[i];
if (isalnum(c)) {
if (isupper(c)) {
if (i != to_skip) {
DCHECK_GT(j, 0);
if (result[j - 1] != '_') ++j;
}
result[j] = tolower(c);
} else {
result[j] = c;
}
}
}
return result;
}
}
} | #include "tsl/platform/str_util.h"
#include <vector>
#include "tsl/platform/test.h"
namespace tsl {
TEST(CEscape, Basic) {
EXPECT_EQ(str_util::CEscape("hello"), "hello");
EXPECT_EQ(str_util::CEscape("hello\n"), "hello\\n");
EXPECT_EQ(str_util::CEscape("hello\r"), "hello\\r");
EXPECT_EQ(str_util::CEscape("\t\r\"'"), "\\t\\r\\\"\\'");
EXPECT_EQ(str_util::CEscape("\320hi\200"), "\\320hi\\200");
}
string ExpectCUnescapeSuccess(StringPiece source) {
string dest;
string error;
EXPECT_TRUE(str_util::CUnescape(source, &dest, &error)) << error;
return dest;
}
TEST(CUnescape, Basic) {
EXPECT_EQ("hello", ExpectCUnescapeSuccess("hello"));
EXPECT_EQ("hello\n", ExpectCUnescapeSuccess("hello\\n"));
EXPECT_EQ("hello\r", ExpectCUnescapeSuccess("hello\\r"));
EXPECT_EQ("\t\r\"'", ExpectCUnescapeSuccess("\\t\\r\\\"\\'"));
EXPECT_EQ("\320hi\200", ExpectCUnescapeSuccess("\\320hi\\200"));
}
TEST(CUnescape, HandlesCopyOnWriteStrings) {
string dest = "hello";
string read = dest;
string error;
StringPiece source = "llohe";
EXPECT_TRUE(str_util::CUnescape(source, &dest, &error));
EXPECT_EQ("hello", read);
}
TEST(StripTrailingWhitespace, Basic) {
string test;
test = "hello";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "hello");
test = "foo ";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "foo");
test = " ";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "");
test = "";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, "");
test = " abc\t";
str_util::StripTrailingWhitespace(&test);
EXPECT_EQ(test, " abc");
}
TEST(RemoveLeadingWhitespace, Basic) {
string text = " \t \n \r Quick\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 11);
EXPECT_EQ(data, StringPiece("Quick\t"));
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece("Quick\t"));
}
TEST(RemoveLeadingWhitespace, TerminationHandling) {
string text = "\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 1);
EXPECT_EQ(data, StringPiece(""));
EXPECT_EQ(str_util::RemoveLeadingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
TEST(RemoveTrailingWhitespace, Basic) {
string text = " \t \n \r Quick \t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 2);
EXPECT_EQ(data, StringPiece(" \t \n \r Quick"));
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(" \t \n \r Quick"));
}
TEST(RemoveTrailingWhitespace, TerminationHandling) {
string text = "\t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 1);
EXPECT_EQ(data, StringPiece(""));
EXPECT_EQ(str_util::RemoveTrailingWhitespace(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
TEST(RemoveWhitespaceContext, Basic) {
string text = " \t \n \r Quick \t";
StringPiece data(text);
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 13);
EXPECT_EQ(data, StringPiece("Quick"));
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 0);
EXPECT_EQ(data, StringPiece("Quick"));
text = "";
data = text;
EXPECT_EQ(str_util::RemoveWhitespaceContext(&data), 0);
EXPECT_EQ(data, StringPiece(""));
}
void TestConsumeLeadingDigits(StringPiece s, int64_t expected,
StringPiece remaining) {
uint64 v;
StringPiece input(s);
if (str_util::ConsumeLeadingDigits(&input, &v)) {
EXPECT_EQ(v, static_cast<uint64>(expected));
EXPECT_EQ(input, remaining);
} else {
EXPECT_LT(expected, 0);
EXPECT_EQ(input, remaining);
}
}
TEST(ConsumeLeadingDigits, Basic) {
using str_util::ConsumeLeadingDigits;
TestConsumeLeadingDigits("123", 123, "");
TestConsumeLeadingDigits("a123", -1, "a123");
TestConsumeLeadingDigits("9_", 9, "_");
TestConsumeLeadingDigits("11111111111xyz", 11111111111ll, "xyz");
TestConsumeLeadingDigits("1111111111111111111111111111111xyz", -1,
"1111111111111111111111111111111xyz");
TestConsumeLeadingDigits("18446744073709551616xyz", -1,
"18446744073709551616xyz");
TestConsumeLeadingDigits("18446744073709551615xyz", 18446744073709551615ull,
"xyz");
TestConsumeLeadingDigits("184467440737095516159yz", -1,
"184467440737095516159yz");
}
void TestConsumeNonWhitespace(StringPiece s, StringPiece expected,
StringPiece remaining) {
StringPiece v;
StringPiece input(s);
if (str_util::ConsumeNonWhitespace(&input, &v)) {
EXPECT_EQ(v, expected);
EXPECT_EQ(input, remaining);
} else {
EXPECT_EQ(expected, "");
EXPECT_EQ(input, remaining);
}
}
TEST(ConsumeNonWhitespace, Basic) {
TestConsumeNonWhitespace("", "", "");
TestConsumeNonWhitespace(" ", "", " ");
TestConsumeNonWhitespace("abc", "abc", "");
TestConsumeNonWhitespace("abc ", "abc", " ");
}
TEST(ConsumePrefix, Basic) {
string s("abcdef");
StringPiece input(s);
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abcdefg"));
EXPECT_EQ(input, "abcdef");
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abce"));
EXPECT_EQ(input, "abcdef");
EXPECT_TRUE(str_util::ConsumePrefix(&input, ""));
EXPECT_EQ(input, "abcdef");
EXPECT_FALSE(str_util::ConsumePrefix(&input, "abcdeg"));
EXPECT_EQ(input, "abcdef");
EXPECT_TRUE(str_util::ConsumePrefix(&input, "abcdef"));
EXPECT_EQ(input, "");
input = s;
EXPECT_TRUE(str_util::ConsumePrefix(&input, "abcde"));
EXPECT_EQ(input, "f");
}
TEST(StripPrefix, Basic) {
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcdefg"), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abce"), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", ""), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcdeg"), "abcdef");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcdef"), "");
EXPECT_EQ(str_util::StripPrefix("abcdef", "abcde"), "f");
}
TEST(JoinStrings, Basic) {
std::vector<string> s;
s = {"hi"};
EXPECT_EQ(str_util::Join(s, " "), "hi");
s = {"hi", "there", "strings"};
EXPECT_EQ(str_util::Join(s, " "), "hi there strings");
std::vector<StringPiece> sp;
sp = {"hi"};
EXPECT_EQ(str_util::Join(sp, ",,"), "hi");
sp = {"hi", "there", "strings"};
EXPECT_EQ(str_util::Join(sp, "--"), "hi--there--strings");
}
TEST(JoinStrings, Join3) {
std::vector<string> s;
s = {"hi"};
auto l1 = [](string* out, string s) { *out += s; };
EXPECT_EQ(str_util::Join(s, " ", l1), "hi");
s = {"hi", "there", "strings"};
auto l2 = [](string* out, string s) { *out += s[0]; };
EXPECT_EQ(str_util::Join(s, " ", l2), "h t s");
}
TEST(Split, Basic) {
EXPECT_TRUE(str_util::Split("", ',').empty());
EXPECT_EQ(str_util::Join(str_util::Split("a", ','), "|"), "a");
EXPECT_EQ(str_util::Join(str_util::Split(",", ','), "|"), "|");
EXPECT_EQ(str_util::Join(str_util::Split("a,b,c", ','), "|"), "a|b|c");
EXPECT_EQ(str_util::Join(str_util::Split("a,,,b,,c,", ','), "|"),
"a|||b||c|");
EXPECT_EQ(str_util::Join(str_util::Split("a!,!b,!c,", ",!"), "|"),
"a|||b||c|");
EXPECT_EQ(str_util::Join(
str_util::Split("a,,,b,,c,", ',', str_util::SkipEmpty()), "|"),
"a|b|c");
EXPECT_EQ(
str_util::Join(
str_util::Split("a, ,b,,c,", ',', str_util::SkipWhitespace()), "|"),
"a|b|c");
EXPECT_EQ(str_util::Join(str_util::Split("a. !b,;c,", ".,;!",
str_util::SkipWhitespace()),
"|"),
"a|b|c");
}
TEST(Lowercase, Basic) {
EXPECT_EQ("", str_util::Lowercase(""));
EXPECT_EQ("hello", str_util::Lowercase("hello"));
EXPECT_EQ("hello world", str_util::Lowercase("Hello World"));
}
TEST(Uppercase, Basic) {
EXPECT_EQ("", str_util::Uppercase(""));
EXPECT_EQ("HELLO", str_util::Uppercase("hello"));
EXPECT_EQ("HELLO WORLD", str_util::Uppercase("Hello World"));
}
TEST(SnakeCase, Basic) {
EXPECT_EQ("", str_util::ArgDefCase(""));
EXPECT_EQ("", str_util::ArgDefCase("!"));
EXPECT_EQ("", str_util::ArgDefCase("5"));
EXPECT_EQ("", str_util::ArgDefCase("!:"));
EXPECT_EQ("", str_util::ArgDefCase("5-5"));
EXPECT_EQ("", str_util::ArgDefCase("_!"));
EXPECT_EQ("", str_util::ArgDefCase("_5"));
EXPECT_EQ("a", str_util::ArgDefCase("_a"));
EXPECT_EQ("a", str_util::ArgDefCase("_A"));
EXPECT_EQ("i", str_util::ArgDefCase("I"));
EXPECT_EQ("i", str_util::ArgDefCase("i"));
EXPECT_EQ("i_", str_util::ArgDefCase("I%"));
EXPECT_EQ("i_", str_util::ArgDefCase("i%"));
EXPECT_EQ("i", str_util::ArgDefCase("%I"));
EXPECT_EQ("i", str_util::ArgDefCase("-i"));
EXPECT_EQ("i", str_util::ArgDefCase("3i"));
EXPECT_EQ("i", str_util::ArgDefCase("32i"));
EXPECT_EQ("i3", str_util::ArgDefCase("i3"));
EXPECT_EQ("i_a3", str_util::ArgDefCase("i_A3"));
EXPECT_EQ("i_i", str_util::ArgDefCase("II"));
EXPECT_EQ("i_i", str_util::ArgDefCase("I_I"));
EXPECT_EQ("i__i", str_util::ArgDefCase("I__I"));
EXPECT_EQ("i_i_32", str_util::ArgDefCase("II-32"));
EXPECT_EQ("ii_32", str_util::ArgDefCase("Ii-32"));
EXPECT_EQ("hi_there", str_util::ArgDefCase("HiThere"));
EXPECT_EQ("hi_hi", str_util::ArgDefCase("Hi!Hi"));
EXPECT_EQ("hi_hi", str_util::ArgDefCase("HiHi"));
EXPECT_EQ("hihi", str_util::ArgDefCase("Hihi"));
EXPECT_EQ("hi_hi", str_util::ArgDefCase("Hi_Hi"));
}
TEST(TitlecaseString, Basic) {
string s = "sparse_lookup";
str_util::TitlecaseString(&s, "_");
ASSERT_EQ(s, "Sparse_Lookup");
s = "sparse_lookup";
str_util::TitlecaseString(&s, " ");
ASSERT_EQ(s, "Sparse_lookup");
s = "dense";
str_util::TitlecaseString(&s, " ");
ASSERT_EQ(s, "Dense");
}
TEST(StringReplace, Basic) {
EXPECT_EQ("XYZ_XYZ_XYZ", str_util::StringReplace("ABC_ABC_ABC", "ABC", "XYZ",
true));
}
TEST(StringReplace, OnlyFirst) {
EXPECT_EQ("XYZ_ABC_ABC", str_util::StringReplace("ABC_ABC_ABC", "ABC", "XYZ",
false));
}
TEST(StringReplace, IncreaseLength) {
EXPECT_EQ("a b c",
str_util::StringReplace("abc", "b", " b ", true));
}
TEST(StringReplace, IncreaseLengthMultipleMatches) {
EXPECT_EQ("a b b c",
str_util::StringReplace("abbc", "b", " b ", true));
}
TEST(StringReplace, NoChange) {
EXPECT_EQ("abc",
str_util::StringReplace("abc", "d", "X", true));
}
TEST(StringReplace, EmptyStringReplaceFirst) {
EXPECT_EQ("", str_util::StringReplace("", "a", "X", false));
}
TEST(StringReplace, EmptyStringReplaceAll) {
EXPECT_EQ("", str_util::StringReplace("", "a", "X", true));
}
TEST(Strnlen, Basic) {
EXPECT_EQ(0, str_util::Strnlen("ab", 0));
EXPECT_EQ(1, str_util::Strnlen("a", 1));
EXPECT_EQ(2, str_util::Strnlen("abcd", 2));
EXPECT_EQ(3, str_util::Strnlen("abc", 10));
EXPECT_EQ(4, str_util::Strnlen("a \t\n", 10));
}
} |