Code
stringlengths
131
28.2k
Unit Test
stringlengths
40
32.1k
__index_level_0__
int64
0
2.63k
#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,587
#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,588
#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,589
#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,590
#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,591
#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,592
#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,593
#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,594
#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,595
#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,596
#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,597
#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,598
#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,599
#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,600
#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_MUTEX_H_ #define TENSORFLOW_TSL_PLATFORM_DEFAULT_MUTEX_H_ namespace tsl { namespace internal { std::cv_status wait_until_system_clock( CVData *cv_data, MuData *mu_data, const std::chrono::system_clock::time_point timeout_time); } template <class Rep, class Period> std::cv_status condition_variable::wait_for( mutex_lock &lock, std::chrono::duration<Rep, Period> dur) { return tsl::internal::wait_until_system_clock( &this->cv_, &lock.mutex()->mu_, std::chrono::system_clock::now() + dur); } } #endif #include "tsl/platform/mutex.h" #include <time.h> #include "nsync_cv.h" #include "nsync_mu.h" #include "nsync_mu_wait.h" #include "nsync_time.h" namespace tsl { static_assert(sizeof(nsync::nsync_mu) <= sizeof(internal::MuData), "tsl::internal::MuData needs to be bigger"); static inline nsync::nsync_mu *mu_cast(internal::MuData *mu) { return reinterpret_cast<nsync::nsync_mu *>(mu); } static inline const nsync::nsync_mu *mu_cast(const internal::MuData *mu) { return reinterpret_cast<const nsync::nsync_mu *>(mu); } mutex::mutex() { nsync::nsync_mu_init(mu_cast(&mu_)); } void mutex::lock() { nsync::nsync_mu_lock(mu_cast(&mu_)); } bool mutex::try_lock() { return nsync::nsync_mu_trylock(mu_cast(&mu_)) != 0; }; void mutex::unlock() { nsync::nsync_mu_unlock(mu_cast(&mu_)); } void mutex::assert_held() const TF_ASSERT_EXCLUSIVE_LOCK() { nsync::nsync_mu_assert_held(mu_cast(&mu_)); } void mutex::lock_shared() { nsync::nsync_mu_rlock(mu_cast(&mu_)); } bool mutex::try_lock_shared() { return nsync::nsync_mu_rtrylock(mu_cast(&mu_)) != 0; }; void mutex::unlock_shared() { nsync::nsync_mu_runlock(mu_cast(&mu_)); } void mutex::assert_held_shared() const TF_ASSERT_SHARED_LOCK() { nsync::nsync_mu_rassert_held(mu_cast(&mu_)); } static int EvaluateCondition(const void *vcond) { return static_cast<int>(static_cast<const Condition *>(vcond)->Eval()); } void mutex::Await(const Condition &cond) { nsync::nsync_mu_wait(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr); } bool mutex::AwaitWithDeadline(const Condition &cond, uint64 abs_deadline_ns) { time_t seconds = abs_deadline_ns / (1000 * 1000 * 1000); nsync::nsync_time abs_time = nsync::nsync_time_s_ns( seconds, abs_deadline_ns - seconds * (1000 * 1000 * 1000)); return nsync::nsync_mu_wait_with_deadline(mu_cast(&mu_), &EvaluateCondition, &cond, nullptr, abs_time, nullptr) == 0; } static_assert(sizeof(nsync::nsync_cv) <= sizeof(internal::CVData), "tsl::internal::CVData needs to be bigger"); static inline nsync::nsync_cv *cv_cast(internal::CVData *cv) { return reinterpret_cast<nsync::nsync_cv *>(cv); } condition_variable::condition_variable() { nsync::nsync_cv_init(cv_cast(&cv_)); } void condition_variable::wait(mutex_lock &lock) { nsync::nsync_cv_wait(cv_cast(&cv_), mu_cast(&lock.mutex()->mu_)); } void condition_variable::notify_one() { nsync::nsync_cv_signal(cv_cast(&cv_)); } void condition_variable::notify_all() { nsync::nsync_cv_broadcast(cv_cast(&cv_)); } namespace internal { std::cv_status wait_until_system_clock( CVData *cv_data, MuData *mu_data, const std::chrono::system_clock::time_point timeout_time) { int r = nsync::nsync_cv_wait_with_deadline(cv_cast(cv_data), mu_cast(mu_data), timeout_time, nullptr); return r ? std::cv_status::timeout : std::cv_status::no_timeout; } } }
#include "tsl/platform/mutex.h" #include "tsl/platform/test.h" #include "tsl/platform/threadpool.h" namespace tsl { namespace { class MutexTest : public ::testing::Test { protected: mutex_lock GetLock() TF_NO_THREAD_SAFETY_ANALYSIS { return mutex_lock{mu_}; } tf_shared_lock GetSharedLock() TF_NO_THREAD_SAFETY_ANALYSIS { return tf_shared_lock{mu_}; } bool test_try_lock() { bool test = mu_.try_lock(); if (test) mu_.unlock(); return test; } bool test_try_lock_shared() { bool test = mu_.try_lock_shared(); if (test) mu_.unlock_shared(); return test; } mutex mu_; }; TEST_F(MutexTest, MovableMutexLockTest) { EXPECT_TRUE(test_try_lock()); { mutex_lock lock = GetLock(); EXPECT_FALSE(test_try_lock()); EXPECT_FALSE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST_F(MutexTest, SharedMutexLockTest) { EXPECT_TRUE(test_try_lock()); { tf_shared_lock lock = GetSharedLock(); EXPECT_FALSE(test_try_lock()); EXPECT_TRUE(test_try_lock_shared()); } EXPECT_TRUE(test_try_lock()); } TEST(ConditionVariableTest, WaitWithPredicate) { constexpr int kNumThreads = 4; mutex mu; condition_variable cv; bool ready = false; int count = 0; tsl::thread::ThreadPool pool(Env::Default(), "condition_variable_test_wait_with_predicate", kNumThreads); for (int i = 0; i < kNumThreads; ++i) { pool.Schedule([&mu, &cv, &ready, &count]() { mutex_lock lock(mu); cv.wait(lock, [&ready] { return ready; }); ++count; cv.notify_one(); }); } { mutex_lock lock(mu); EXPECT_EQ(count, 0); } { mutex_lock lock(mu); ready = true; cv.notify_all(); } { mutex_lock lock(mu); cv.wait(lock, [&count, kNumThreads] { return count == kNumThreads; }); EXPECT_EQ(count, kNumThreads); } } TEST(ConditionVariableTest, WaitWithTruePredicateDoesntBlock) { mutex mu; mutex_lock lock(mu); condition_variable cv; cv.wait(lock, [] { return true; }); EXPECT_TRUE(static_cast<bool>(lock)); } } }
2,633