ID
stringlengths
36
36
Language
stringclasses
1 value
Repository Name
stringclasses
13 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
13
116
Code
stringlengths
0
278k
Unit Test - (Ground Truth)
stringlengths
78
663k
Code Url
stringlengths
91
198
Test Code Url
stringlengths
93
203
Commit Hash
stringclasses
13 values
def39d7c-185b-4df3-ab96-0c863ee2acb0
cpp
abseil/abseil-cpp
hash_policy_traits
absl/container/internal/hash_policy_traits.h
absl/container/internal/hash_policy_traits_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_HASH_POLICY_TRAITS_H_ #define ABSL_CONTAINER_INTERNAL_HASH_POLICY_TRAITS_H_ #include <cstddef> #include <memory> #include <new> #include <type_traits> #include <utility> #include "absl/container/internal/common_policy_traits.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <class Policy, class = void> struct hash_policy_traits : common_policy_traits<Policy> { using key_type = typename Policy::key_type; private: struct ReturnKey { #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606 template <class Key, absl::enable_if_t<std::is_lvalue_reference<Key>::value, int> = 0> static key_type& Impl(Key&& k, int) { return *std::launder( const_cast<key_type*>(std::addressof(std::forward<Key>(k)))); } #endif template <class Key> static Key Impl(Key&& k, char) { return std::forward<Key>(k); } template <class Key, class... Args> auto operator()(Key&& k, const Args&...) const -> decltype(Impl(std::forward<Key>(k), 0)) { return Impl(std::forward<Key>(k), 0); } }; template <class P = Policy, class = void> struct ConstantIteratorsImpl : std::false_type {}; template <class P> struct ConstantIteratorsImpl<P, absl::void_t<typename P::constant_iterators>> : P::constant_iterators {}; public: using slot_type = typename Policy::slot_type; using init_type = typename Policy::init_type; using reference = decltype(Policy::element(std::declval<slot_type*>())); using pointer = typename std::remove_reference<reference>::type*; using value_type = typename std::remove_reference<reference>::type; using constant_iterators = ConstantIteratorsImpl<>; template <class P = Policy> static size_t space_used(const slot_type* slot) { return P::space_used(slot); } template <class F, class... Ts, class P = Policy> static auto apply(F&& f, Ts&&... ts) -> decltype(P::apply(std::forward<F>(f), std::forward<Ts>(ts)...)) { return P::apply(std::forward<F>(f), std::forward<Ts>(ts)...); } template <class P = Policy> static auto mutable_key(slot_type* slot) -> decltype(P::apply(ReturnKey(), hash_policy_traits::element(slot))) { return P::apply(ReturnKey(), hash_policy_traits::element(slot)); } template <class T, class P = Policy> static auto value(T* elem) -> decltype(P::value(elem)) { return P::value(elem); } using HashSlotFn = size_t (*)(const void* hash_fn, void* slot); template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Waddress" #endif return Policy::template get_hash_slot_fn<Hash>() == nullptr ? &hash_slot_fn_non_type_erased<Hash> : Policy::template get_hash_slot_fn<Hash>(); #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif } static constexpr bool soo_enabled() { return soo_enabled_impl(Rank1{}); } private: template <class Hash> struct HashElement { template <class K, class... Args> size_t operator()(const K& key, Args&&...) const { return h(key); } const Hash& h; }; template <class Hash> static size_t hash_slot_fn_non_type_erased(const void* hash_fn, void* slot) { return Policy::apply(HashElement<Hash>{*static_cast<const Hash*>(hash_fn)}, Policy::element(static_cast<slot_type*>(slot))); } struct Rank0 {}; struct Rank1 : Rank0 {}; template <class P = Policy> static constexpr auto soo_enabled_impl(Rank1) -> decltype(P::soo_enabled()) { return P::soo_enabled(); } static constexpr bool soo_enabled_impl(Rank0) { return true; } }; } ABSL_NAMESPACE_END } #endif
#include "absl/container/internal/hash_policy_traits.h" #include <cstddef> #include <functional> #include <memory> #include <new> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/internal/container_memory.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::testing::MockFunction; using ::testing::Return; using ::testing::ReturnRef; using Alloc = std::allocator<int>; using Slot = int; struct PolicyWithoutOptionalOps { using slot_type = Slot; using key_type = Slot; using init_type = Slot; static std::function<Slot&(Slot*)> element; static int apply(int v) { return apply_impl(v); } static std::function<int(int)> apply_impl; static std::function<Slot&(Slot*)> value; template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return nullptr; } }; std::function<int(int)> PolicyWithoutOptionalOps::apply_impl; std::function<Slot&(Slot*)> PolicyWithoutOptionalOps::value; struct Test : ::testing::Test { Test() { PolicyWithoutOptionalOps::apply_impl = [&](int a1) -> int { return apply.Call(a1); }; PolicyWithoutOptionalOps::value = [&](Slot* a1) -> Slot& { return value.Call(a1); }; } std::allocator<int> alloc; int a = 53; MockFunction<int(int)> apply; MockFunction<Slot&(Slot*)> value; }; TEST_F(Test, apply) { EXPECT_CALL(apply, Call(42)).WillOnce(Return(1337)); EXPECT_EQ(1337, (hash_policy_traits<PolicyWithoutOptionalOps>::apply(42))); } TEST_F(Test, value) { int b = 0; EXPECT_CALL(value, Call(&a)).WillOnce(ReturnRef(b)); EXPECT_EQ(&b, &hash_policy_traits<PolicyWithoutOptionalOps>::value(&a)); } struct Hash { size_t operator()(Slot a) const { return static_cast<size_t>(a) * 5; } }; struct PolicyNoHashFn { using slot_type = Slot; using key_type = Slot; using init_type = Slot; static size_t* apply_called_count; static Slot& element(Slot* slot) { return *slot; } template <typename Fn> static size_t apply(const Fn& fn, int v) { ++(*apply_called_count); return fn(v); } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return nullptr; } }; size_t* PolicyNoHashFn::apply_called_count; struct PolicyCustomHashFn : PolicyNoHashFn { template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return &TypeErasedApplyToSlotFn<Hash, int>; } }; TEST(HashTest, PolicyNoHashFn_get_hash_slot_fn) { size_t apply_called_count = 0; PolicyNoHashFn::apply_called_count = &apply_called_count; Hash hasher; Slot value = 7; auto* fn = hash_policy_traits<PolicyNoHashFn>::get_hash_slot_fn<Hash>(); EXPECT_NE(fn, nullptr); EXPECT_EQ(fn(&hasher, &value), hasher(value)); EXPECT_EQ(apply_called_count, 1); } TEST(HashTest, PolicyCustomHashFn_get_hash_slot_fn) { size_t apply_called_count = 0; PolicyNoHashFn::apply_called_count = &apply_called_count; Hash hasher; Slot value = 7; auto* fn = hash_policy_traits<PolicyCustomHashFn>::get_hash_slot_fn<Hash>(); EXPECT_EQ(fn, PolicyCustomHashFn::get_hash_slot_fn<Hash>()); EXPECT_EQ(fn(&hasher, &value), hasher(value)); EXPECT_EQ(apply_called_count, 0); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_policy_traits.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_policy_traits_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
818c848f-fc2a-436f-9cfd-302b0d2cda6a
cpp
abseil/abseil-cpp
hash_policy_testing
absl/container/internal/hash_policy_testing.h
absl/container/internal/hash_policy_testing_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_HASH_POLICY_TESTING_H_ #define ABSL_CONTAINER_INTERNAL_HASH_POLICY_TESTING_H_ #include <cstdlib> #include <limits> #include <memory> #include <ostream> #include <type_traits> #include <utility> #include <vector> #include "absl/hash/hash.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace hash_testing_internal { template <class Derived> struct WithId { WithId() : id_(next_id<Derived>()) {} WithId(const WithId& that) : id_(that.id_) {} WithId(WithId&& that) : id_(that.id_) { that.id_ = 0; } WithId& operator=(const WithId& that) { id_ = that.id_; return *this; } WithId& operator=(WithId&& that) { id_ = that.id_; that.id_ = 0; return *this; } size_t id() const { return id_; } friend bool operator==(const WithId& a, const WithId& b) { return a.id_ == b.id_; } friend bool operator!=(const WithId& a, const WithId& b) { return !(a == b); } protected: explicit WithId(size_t id) : id_(id) {} private: size_t id_; template <class T> static size_t next_id() { static size_t gId = 1; return gId++; } }; } struct NonStandardLayout { NonStandardLayout() {} explicit NonStandardLayout(std::string s) : value(std::move(s)) {} virtual ~NonStandardLayout() {} friend bool operator==(const NonStandardLayout& a, const NonStandardLayout& b) { return a.value == b.value; } friend bool operator!=(const NonStandardLayout& a, const NonStandardLayout& b) { return a.value != b.value; } template <typename H> friend H AbslHashValue(H h, const NonStandardLayout& v) { return H::combine(std::move(h), v.value); } std::string value; }; struct StatefulTestingHash : absl::container_internal::hash_testing_internal::WithId< StatefulTestingHash> { template <class T> size_t operator()(const T& t) const { return absl::Hash<T>{}(t); } }; struct StatefulTestingEqual : absl::container_internal::hash_testing_internal::WithId< StatefulTestingEqual> { template <class T, class U> bool operator()(const T& t, const U& u) const { return t == u; } }; template <class T = int> struct Alloc : std::allocator<T> { using propagate_on_container_swap = std::true_type; explicit Alloc(size_t id = 0) : id_(id) {} Alloc(const Alloc&) = default; Alloc& operator=(const Alloc&) = default; template <class U> Alloc(const Alloc<U>& that) : std::allocator<T>(that), id_(that.id()) {} template <class U> struct rebind { using other = Alloc<U>; }; size_t id() const { return id_; } friend bool operator==(const Alloc& a, const Alloc& b) { return a.id_ == b.id_; } friend bool operator!=(const Alloc& a, const Alloc& b) { return !(a == b); } private: size_t id_ = (std::numeric_limits<size_t>::max)(); }; template <class Map> auto items(const Map& m) -> std::vector< std::pair<typename Map::key_type, typename Map::mapped_type>> { using std::get; std::vector<std::pair<typename Map::key_type, typename Map::mapped_type>> res; res.reserve(m.size()); for (const auto& v : m) res.emplace_back(get<0>(v), get<1>(v)); return res; } template <class Set> auto keys(const Set& s) -> std::vector<typename std::decay<typename Set::key_type>::type> { std::vector<typename std::decay<typename Set::key_type>::type> res; res.reserve(s.size()); for (const auto& v : s) res.emplace_back(v); return res; } } ABSL_NAMESPACE_END } #if defined(__GLIBCXX__) && __GLIBCXX__ <= 20140425 #define ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS 0 #else #define ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS 1 #endif #endif
#include "absl/container/internal/hash_policy_testing.h" #include "gtest/gtest.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { TEST(_, Hash) { StatefulTestingHash h1; EXPECT_EQ(1, h1.id()); StatefulTestingHash h2; EXPECT_EQ(2, h2.id()); StatefulTestingHash h1c(h1); EXPECT_EQ(1, h1c.id()); StatefulTestingHash h2m(std::move(h2)); EXPECT_EQ(2, h2m.id()); EXPECT_EQ(0, h2.id()); StatefulTestingHash h3; EXPECT_EQ(3, h3.id()); h3 = StatefulTestingHash(); EXPECT_EQ(4, h3.id()); h3 = std::move(h1); EXPECT_EQ(1, h3.id()); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_policy_testing.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_policy_testing_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5f713565-a2b4-48a7-aeea-db9993e84384
cpp
abseil/abseil-cpp
common_policy_traits
absl/container/internal/common_policy_traits.h
absl/container/internal/common_policy_traits_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_COMMON_POLICY_TRAITS_H_ #define ABSL_CONTAINER_INTERNAL_COMMON_POLICY_TRAITS_H_ #include <cstddef> #include <cstring> #include <memory> #include <new> #include <type_traits> #include <utility> #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <class Policy, class = void> struct common_policy_traits { using slot_type = typename Policy::slot_type; using reference = decltype(Policy::element(std::declval<slot_type*>())); using value_type = typename std::remove_reference<reference>::type; template <class Alloc, class... Args> static void construct(Alloc* alloc, slot_type* slot, Args&&... args) { Policy::construct(alloc, slot, std::forward<Args>(args)...); } template <class Alloc> static auto destroy(Alloc* alloc, slot_type* slot) { return Policy::destroy(alloc, slot); } template <class Alloc> static void transfer(Alloc* alloc, slot_type* new_slot, slot_type* old_slot) { transfer_impl(alloc, new_slot, old_slot, Rank2{}); } template <class P = Policy> static auto element(absl::remove_const_t<slot_type>* slot) -> decltype(P::element(slot)) { return P::element(slot); } template <class P = Policy> static auto element(const slot_type* slot) -> decltype(P::element(slot)) { return P::element(slot); } static constexpr bool transfer_uses_memcpy() { return std::is_same<decltype(transfer_impl<std::allocator<char>>( nullptr, nullptr, nullptr, Rank2{})), std::true_type>::value; } template <class Alloc> static constexpr bool destroy_is_trivial() { return std::is_same<decltype(destroy<Alloc>(nullptr, nullptr)), std::true_type>::value; } private: struct Rank0 {}; struct Rank1 : Rank0 {}; struct Rank2 : Rank1 {}; template <class Alloc, class P = Policy> static auto transfer_impl(Alloc* alloc, slot_type* new_slot, slot_type* old_slot, Rank2) -> decltype(P::transfer(alloc, new_slot, old_slot)) { return P::transfer(alloc, new_slot, old_slot); } #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606 template <class Alloc, typename = std::enable_if_t<absl::is_trivially_relocatable< std::conditional_t<false, Alloc, value_type>>::value>> static std::true_type transfer_impl(Alloc*, slot_type* new_slot, slot_type* old_slot, Rank1) { std::memcpy( static_cast<void*>(std::launder( const_cast<std::remove_const_t<value_type>*>(&element(new_slot)))), static_cast<const void*>(&element(old_slot)), sizeof(value_type)); return {}; } #endif template <class Alloc> static void transfer_impl(Alloc* alloc, slot_type* new_slot, slot_type* old_slot, Rank0) { construct(alloc, new_slot, std::move(element(old_slot))); destroy(alloc, old_slot); } }; } ABSL_NAMESPACE_END } #endif
#include "absl/container/internal/common_policy_traits.h" #include <functional> #include <memory> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::testing::MockFunction; using ::testing::AnyNumber; using ::testing::ReturnRef; using Slot = int; struct PolicyWithoutOptionalOps { using slot_type = Slot; using key_type = Slot; using init_type = Slot; struct PolicyFunctions { std::function<void(void*, Slot*, Slot)> construct; std::function<void(void*, Slot*)> destroy; std::function<Slot&(Slot*)> element; }; static PolicyFunctions* functions() { static PolicyFunctions* functions = new PolicyFunctions(); return functions; } static void construct(void* a, Slot* b, Slot c) { functions()->construct(a, b, c); } static void destroy(void* a, Slot* b) { functions()->destroy(a, b); } static Slot& element(Slot* b) { return functions()->element(b); } }; struct PolicyWithOptionalOps : PolicyWithoutOptionalOps { struct TransferFunctions { std::function<void(void*, Slot*, Slot*)> transfer; }; static TransferFunctions* transfer_fn() { static TransferFunctions* transfer_fn = new TransferFunctions(); return transfer_fn; } static void transfer(void* a, Slot* b, Slot* c) { transfer_fn()->transfer(a, b, c); } }; struct PolicyWithMemcpyTransferAndTrivialDestroy : PolicyWithoutOptionalOps { static std::true_type transfer(void*, Slot*, Slot*) { return {}; } static std::true_type destroy(void*, Slot*) { return {}; } }; struct Test : ::testing::Test { Test() { PolicyWithoutOptionalOps::functions()->construct = [&](void* a1, Slot* a2, Slot a3) { construct.Call(a1, a2, std::move(a3)); }; PolicyWithoutOptionalOps::functions()->destroy = [&](void* a1, Slot* a2) { destroy.Call(a1, a2); }; PolicyWithoutOptionalOps::functions()->element = [&](Slot* a1) -> Slot& { return element.Call(a1); }; PolicyWithOptionalOps::transfer_fn()->transfer = [&](void* a1, Slot* a2, Slot* a3) { return transfer.Call(a1, a2, a3); }; } std::allocator<Slot> alloc; int a = 53; MockFunction<void(void*, Slot*, Slot)> construct; MockFunction<void(void*, Slot*)> destroy; MockFunction<Slot&(Slot*)> element; MockFunction<void(void*, Slot*, Slot*)> transfer; }; TEST_F(Test, construct) { EXPECT_CALL(construct, Call(&alloc, &a, 53)); common_policy_traits<PolicyWithoutOptionalOps>::construct(&alloc, &a, 53); } TEST_F(Test, destroy) { EXPECT_CALL(destroy, Call(&alloc, &a)); common_policy_traits<PolicyWithoutOptionalOps>::destroy(&alloc, &a); } TEST_F(Test, element) { int b = 0; EXPECT_CALL(element, Call(&a)).WillOnce(ReturnRef(b)); EXPECT_EQ(&b, &common_policy_traits<PolicyWithoutOptionalOps>::element(&a)); } TEST_F(Test, without_transfer) { int b = 42; EXPECT_CALL(element, Call(&a)).Times(AnyNumber()).WillOnce(ReturnRef(a)); EXPECT_CALL(element, Call(&b)).WillOnce(ReturnRef(b)); EXPECT_CALL(construct, Call(&alloc, &a, b)).Times(AnyNumber()); EXPECT_CALL(destroy, Call(&alloc, &b)).Times(AnyNumber()); common_policy_traits<PolicyWithoutOptionalOps>::transfer(&alloc, &a, &b); } TEST_F(Test, with_transfer) { int b = 42; EXPECT_CALL(transfer, Call(&alloc, &a, &b)); common_policy_traits<PolicyWithOptionalOps>::transfer(&alloc, &a, &b); } TEST(TransferUsesMemcpy, Basic) { EXPECT_FALSE( common_policy_traits<PolicyWithOptionalOps>::transfer_uses_memcpy()); EXPECT_TRUE( common_policy_traits< PolicyWithMemcpyTransferAndTrivialDestroy>::transfer_uses_memcpy()); } TEST(DestroyIsTrivial, Basic) { EXPECT_FALSE(common_policy_traits<PolicyWithOptionalOps>::destroy_is_trivial< std::allocator<char>>()); EXPECT_TRUE(common_policy_traits<PolicyWithMemcpyTransferAndTrivialDestroy>:: destroy_is_trivial<std::allocator<char>>()); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/common_policy_traits.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/common_policy_traits_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
724bea7e-edc7-4246-b9c8-b4da79bb7cdb
cpp
abseil/abseil-cpp
bits
absl/numeric/internal/bits.h
absl/numeric/bits_test.cc
#ifndef ABSL_NUMERIC_INTERNAL_BITS_H_ #define ABSL_NUMERIC_INTERNAL_BITS_H_ #include <cstdint> #include <limits> #include <type_traits> #if defined(_MSC_VER) && !defined(__clang__) #include <intrin.h> #endif #include "absl/base/attributes.h" #include "absl/base/config.h" #if defined(__GNUC__) && !defined(__clang__) #define ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(x) 1 #else #define ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(x) ABSL_HAVE_BUILTIN(x) #endif #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_popcountl) && \ ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_popcountll) #define ABSL_INTERNAL_CONSTEXPR_POPCOUNT constexpr #define ABSL_INTERNAL_HAS_CONSTEXPR_POPCOUNT 1 #else #define ABSL_INTERNAL_CONSTEXPR_POPCOUNT #define ABSL_INTERNAL_HAS_CONSTEXPR_POPCOUNT 0 #endif #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_clz) && \ ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_clzll) #define ABSL_INTERNAL_CONSTEXPR_CLZ constexpr #define ABSL_INTERNAL_HAS_CONSTEXPR_CLZ 1 #else #define ABSL_INTERNAL_CONSTEXPR_CLZ #define ABSL_INTERNAL_HAS_CONSTEXPR_CLZ 0 #endif #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_ctz) && \ ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_ctzll) #define ABSL_INTERNAL_CONSTEXPR_CTZ constexpr #define ABSL_INTERNAL_HAS_CONSTEXPR_CTZ 1 #else #define ABSL_INTERNAL_CONSTEXPR_CTZ #define ABSL_INTERNAL_HAS_CONSTEXPR_CTZ 0 #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace numeric_internal { constexpr bool IsPowerOf2(unsigned int x) noexcept { return x != 0 && (x & (x - 1)) == 0; } template <class T> ABSL_MUST_USE_RESULT ABSL_ATTRIBUTE_ALWAYS_INLINE constexpr T RotateRight( T x, int s) noexcept { static_assert(std::is_unsigned<T>::value, "T must be unsigned"); static_assert(IsPowerOf2(std::numeric_limits<T>::digits), "T must have a power-of-2 size"); return static_cast<T>(x >> (s & (std::numeric_limits<T>::digits - 1))) | static_cast<T>(x << ((-s) & (std::numeric_limits<T>::digits - 1))); } template <class T> ABSL_MUST_USE_RESULT ABSL_ATTRIBUTE_ALWAYS_INLINE constexpr T RotateLeft( T x, int s) noexcept { static_assert(std::is_unsigned<T>::value, "T must be unsigned"); static_assert(IsPowerOf2(std::numeric_limits<T>::digits), "T must have a power-of-2 size"); return static_cast<T>(x << (s & (std::numeric_limits<T>::digits - 1))) | static_cast<T>(x >> ((-s) & (std::numeric_limits<T>::digits - 1))); } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_POPCOUNT inline int Popcount32(uint32_t x) noexcept { #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_popcount) static_assert(sizeof(unsigned int) == sizeof(x), "__builtin_popcount does not take 32-bit arg"); return __builtin_popcount(x); #else x -= ((x >> 1) & 0x55555555); x = ((x >> 2) & 0x33333333) + (x & 0x33333333); return static_cast<int>((((x + (x >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24); #endif } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_POPCOUNT inline int Popcount64(uint64_t x) noexcept { #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_popcountll) static_assert(sizeof(unsigned long long) == sizeof(x), "__builtin_popcount does not take 64-bit arg"); return __builtin_popcountll(x); #else x -= (x >> 1) & 0x5555555555555555ULL; x = ((x >> 2) & 0x3333333333333333ULL) + (x & 0x3333333333333333ULL); return static_cast<int>( (((x + (x >> 4)) & 0xF0F0F0F0F0F0F0FULL) * 0x101010101010101ULL) >> 56); #endif } template <class T> ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_POPCOUNT inline int Popcount(T x) noexcept { static_assert(std::is_unsigned<T>::value, "T must be unsigned"); static_assert(IsPowerOf2(std::numeric_limits<T>::digits), "T must have a power-of-2 size"); static_assert(sizeof(x) <= sizeof(uint64_t), "T is too large"); return sizeof(x) <= sizeof(uint32_t) ? Popcount32(x) : Popcount64(x); } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CLZ inline int CountLeadingZeroes32(uint32_t x) { #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_clz) static_assert(sizeof(unsigned int) == sizeof(x), "__builtin_clz does not take 32-bit arg"); return x == 0 ? 32 : __builtin_clz(x); #elif defined(_MSC_VER) && !defined(__clang__) unsigned long result = 0; if (_BitScanReverse(&result, x)) { return 31 - result; } return 32; #else int zeroes = 28; if (x >> 16) { zeroes -= 16; x >>= 16; } if (x >> 8) { zeroes -= 8; x >>= 8; } if (x >> 4) { zeroes -= 4; x >>= 4; } return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; #endif } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CLZ inline int CountLeadingZeroes16(uint16_t x) { #if ABSL_HAVE_BUILTIN(__builtin_clzg) return x == 0 ? 16 : __builtin_clzg(x); #elif ABSL_HAVE_BUILTIN(__builtin_clzs) static_assert(sizeof(unsigned short) == sizeof(x), "__builtin_clzs does not take 16-bit arg"); return x == 0 ? 16 : __builtin_clzs(x); #else return CountLeadingZeroes32(x) - 16; #endif } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CLZ inline int CountLeadingZeroes64(uint64_t x) { #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_clzll) static_assert(sizeof(unsigned long long) == sizeof(x), "__builtin_clzll does not take 64-bit arg"); return x == 0 ? 64 : __builtin_clzll(x); #elif defined(_MSC_VER) && !defined(__clang__) && \ (defined(_M_X64) || defined(_M_ARM64)) unsigned long result = 0; if (_BitScanReverse64(&result, x)) { return 63 - result; } return 64; #elif defined(_MSC_VER) && !defined(__clang__) unsigned long result = 0; if ((x >> 32) && _BitScanReverse(&result, static_cast<unsigned long>(x >> 32))) { return 31 - result; } if (_BitScanReverse(&result, static_cast<unsigned long>(x))) { return 63 - result; } return 64; #else int zeroes = 60; if (x >> 32) { zeroes -= 32; x >>= 32; } if (x >> 16) { zeroes -= 16; x >>= 16; } if (x >> 8) { zeroes -= 8; x >>= 8; } if (x >> 4) { zeroes -= 4; x >>= 4; } return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; #endif } template <typename T> ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CLZ inline int CountLeadingZeroes(T x) { static_assert(std::is_unsigned<T>::value, "T must be unsigned"); static_assert(IsPowerOf2(std::numeric_limits<T>::digits), "T must have a power-of-2 size"); static_assert(sizeof(T) <= sizeof(uint64_t), "T too large"); return sizeof(T) <= sizeof(uint16_t) ? CountLeadingZeroes16(static_cast<uint16_t>(x)) - (std::numeric_limits<uint16_t>::digits - std::numeric_limits<T>::digits) : (sizeof(T) <= sizeof(uint32_t) ? CountLeadingZeroes32(static_cast<uint32_t>(x)) - (std::numeric_limits<uint32_t>::digits - std::numeric_limits<T>::digits) : CountLeadingZeroes64(x)); } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CTZ inline int CountTrailingZeroesNonzero32(uint32_t x) { #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_ctz) static_assert(sizeof(unsigned int) == sizeof(x), "__builtin_ctz does not take 32-bit arg"); return __builtin_ctz(x); #elif defined(_MSC_VER) && !defined(__clang__) unsigned long result = 0; _BitScanForward(&result, x); return result; #else int c = 31; x &= ~x + 1; if (x & 0x0000FFFF) c -= 16; if (x & 0x00FF00FF) c -= 8; if (x & 0x0F0F0F0F) c -= 4; if (x & 0x33333333) c -= 2; if (x & 0x55555555) c -= 1; return c; #endif } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CTZ inline int CountTrailingZeroesNonzero64(uint64_t x) { #if ABSL_NUMERIC_INTERNAL_HAVE_BUILTIN_OR_GCC(__builtin_ctzll) static_assert(sizeof(unsigned long long) == sizeof(x), "__builtin_ctzll does not take 64-bit arg"); return __builtin_ctzll(x); #elif defined(_MSC_VER) && !defined(__clang__) && \ (defined(_M_X64) || defined(_M_ARM64)) unsigned long result = 0; _BitScanForward64(&result, x); return result; #elif defined(_MSC_VER) && !defined(__clang__) unsigned long result = 0; if (static_cast<uint32_t>(x) == 0) { _BitScanForward(&result, static_cast<unsigned long>(x >> 32)); return result + 32; } _BitScanForward(&result, static_cast<unsigned long>(x)); return result; #else int c = 63; x &= ~x + 1; if (x & 0x00000000FFFFFFFF) c -= 32; if (x & 0x0000FFFF0000FFFF) c -= 16; if (x & 0x00FF00FF00FF00FF) c -= 8; if (x & 0x0F0F0F0F0F0F0F0F) c -= 4; if (x & 0x3333333333333333) c -= 2; if (x & 0x5555555555555555) c -= 1; return c; #endif } ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CTZ inline int CountTrailingZeroesNonzero16(uint16_t x) { #if ABSL_HAVE_BUILTIN(__builtin_ctzg) return __builtin_ctzg(x); #elif ABSL_HAVE_BUILTIN(__builtin_ctzs) static_assert(sizeof(unsigned short) == sizeof(x), "__builtin_ctzs does not take 16-bit arg"); return __builtin_ctzs(x); #else return CountTrailingZeroesNonzero32(x); #endif } template <class T> ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CTZ inline int CountTrailingZeroes(T x) noexcept { static_assert(std::is_unsigned<T>::value, "T must be unsigned"); static_assert(IsPowerOf2(std::numeric_limits<T>::digits), "T must have a power-of-2 size"); static_assert(sizeof(T) <= sizeof(uint64_t), "T too large"); return x == 0 ? std::numeric_limits<T>::digits : (sizeof(T) <= sizeof(uint16_t) ? CountTrailingZeroesNonzero16(static_cast<uint16_t>(x)) : (sizeof(T) <= sizeof(uint32_t) ? CountTrailingZeroesNonzero32( static_cast<uint32_t>(x)) : CountTrailingZeroesNonzero64(x))); } template <class T> ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CLZ inline typename std::enable_if<std::is_unsigned<T>::value, T>::type BitCeilPromotionHelper(T x, T promotion) { return (T{1} << (x + promotion)) >> promotion; } template <class T> ABSL_ATTRIBUTE_ALWAYS_INLINE ABSL_INTERNAL_CONSTEXPR_CLZ inline typename std::enable_if<std::is_unsigned<T>::value, T>::type BitCeilNonPowerOf2(T x) { return BitCeilPromotionHelper( static_cast<T>(std::numeric_limits<T>::digits - CountLeadingZeroes(x)), T{sizeof(T) >= sizeof(unsigned) ? 0 : std::numeric_limits<unsigned>::digits - std::numeric_limits<T>::digits}); } } ABSL_NAMESPACE_END } #endif
#include "absl/numeric/bits.h" #include <limits> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/random.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { template <typename IntT> class IntegerTypesTest : public ::testing::Test {}; using OneByteIntegerTypes = ::testing::Types< unsigned char, uint8_t >; TYPED_TEST_SUITE(IntegerTypesTest, OneByteIntegerTypes); TYPED_TEST(IntegerTypesTest, HandlesTypes) { using UIntType = TypeParam; EXPECT_EQ(rotl(UIntType{0x12}, 0), uint8_t{0x12}); EXPECT_EQ(rotr(UIntType{0x12}, -4), uint8_t{0x21}); static_assert(rotl(UIntType{0x12}, 0) == uint8_t{0x12}, ""); static_assert(rotr(UIntType{0x12}, 0) == uint8_t{0x12}, ""); EXPECT_EQ(rotr(UIntType{0x12}, 0), uint8_t{0x12}); #if ABSL_INTERNAL_HAS_CONSTEXPR_CLZ static_assert(countl_zero(UIntType{}) == 8, ""); static_assert(countl_zero(static_cast<UIntType>(-1)) == 0, ""); static_assert(countl_one(UIntType{}) == 0, ""); static_assert(countl_one(static_cast<UIntType>(-1)) == 8, ""); static_assert(countr_zero(UIntType{}) == 8, ""); static_assert(countr_zero(static_cast<UIntType>(-1)) == 0, ""); static_assert(countr_one(UIntType{}) == 0, ""); static_assert(countr_one(static_cast<UIntType>(-1)) == 8, ""); static_assert(popcount(UIntType{}) == 0, ""); static_assert(popcount(UIntType{1}) == 1, ""); static_assert(popcount(static_cast<UIntType>(-1)) == 8, ""); static_assert(bit_width(UIntType{}) == 0, ""); static_assert(bit_width(UIntType{1}) == 1, ""); static_assert(bit_width(UIntType{3}) == 2, ""); static_assert(bit_width(static_cast<UIntType>(-1)) == 8, ""); #endif EXPECT_EQ(countl_zero(UIntType{}), 8); EXPECT_EQ(countl_zero(static_cast<UIntType>(-1)), 0); EXPECT_EQ(countl_one(UIntType{}), 0); EXPECT_EQ(countl_one(static_cast<UIntType>(-1)), 8); EXPECT_EQ(countr_zero(UIntType{}), 8); EXPECT_EQ(countr_zero(static_cast<UIntType>(-1)), 0); EXPECT_EQ(countr_one(UIntType{}), 0); EXPECT_EQ(countr_one(static_cast<UIntType>(-1)), 8); EXPECT_EQ(popcount(UIntType{}), 0); EXPECT_EQ(popcount(UIntType{1}), 1); EXPECT_FALSE(has_single_bit(UIntType{})); EXPECT_FALSE(has_single_bit(static_cast<UIntType>(-1))); EXPECT_EQ(bit_width(UIntType{}), 0); EXPECT_EQ(bit_width(UIntType{1}), 1); EXPECT_EQ(bit_width(UIntType{3}), 2); EXPECT_EQ(bit_width(static_cast<UIntType>(-1)), 8); } TEST(Rotate, Left) { static_assert(rotl(uint8_t{0x12}, 0) == uint8_t{0x12}, ""); static_assert(rotl(uint16_t{0x1234}, 0) == uint16_t{0x1234}, ""); static_assert(rotl(uint32_t{0x12345678UL}, 0) == uint32_t{0x12345678UL}, ""); static_assert(rotl(uint64_t{0x12345678ABCDEF01ULL}, 0) == uint64_t{0x12345678ABCDEF01ULL}, ""); EXPECT_EQ(rotl(uint8_t{0x12}, 0), uint8_t{0x12}); EXPECT_EQ(rotl(uint16_t{0x1234}, 0), uint16_t{0x1234}); EXPECT_EQ(rotl(uint32_t{0x12345678UL}, 0), uint32_t{0x12345678UL}); EXPECT_EQ(rotl(uint64_t{0x12345678ABCDEF01ULL}, 0), uint64_t{0x12345678ABCDEF01ULL}); EXPECT_EQ(rotl(uint8_t{0x12}, 8), uint8_t{0x12}); EXPECT_EQ(rotl(uint16_t{0x1234}, 16), uint16_t{0x1234}); EXPECT_EQ(rotl(uint32_t{0x12345678UL}, 32), uint32_t{0x12345678UL}); EXPECT_EQ(rotl(uint64_t{0x12345678ABCDEF01ULL}, 64), uint64_t{0x12345678ABCDEF01ULL}); EXPECT_EQ(rotl(uint8_t{0x12}, -8), uint8_t{0x12}); EXPECT_EQ(rotl(uint16_t{0x1234}, -16), uint16_t{0x1234}); EXPECT_EQ(rotl(uint32_t{0x12345678UL}, -32), uint32_t{0x12345678UL}); EXPECT_EQ(rotl(uint64_t{0x12345678ABCDEF01ULL}, -64), uint64_t{0x12345678ABCDEF01ULL}); EXPECT_EQ(rotl(uint8_t{0x12}, 4), uint8_t{0x21}); EXPECT_EQ(rotl(uint16_t{0x1234}, 4), uint16_t{0x2341}); EXPECT_EQ(rotl(uint32_t{0x12345678UL}, 4), uint32_t{0x23456781UL}); EXPECT_EQ(rotl(uint64_t{0x12345678ABCDEF01ULL}, 4), uint64_t{0x2345678ABCDEF011ULL}); EXPECT_EQ(rotl(uint8_t{0x12}, -4), uint8_t{0x21}); EXPECT_EQ(rotl(uint16_t{0x1234}, -4), uint16_t{0x4123}); EXPECT_EQ(rotl(uint32_t{0x12345678UL}, -4), uint32_t{0x81234567UL}); EXPECT_EQ(rotl(uint64_t{0x12345678ABCDEF01ULL}, -4), uint64_t{0x112345678ABCDEF0ULL}); } TEST(Rotate, Right) { static_assert(rotr(uint8_t{0x12}, 0) == uint8_t{0x12}, ""); static_assert(rotr(uint16_t{0x1234}, 0) == uint16_t{0x1234}, ""); static_assert(rotr(uint32_t{0x12345678UL}, 0) == uint32_t{0x12345678UL}, ""); static_assert(rotr(uint64_t{0x12345678ABCDEF01ULL}, 0) == uint64_t{0x12345678ABCDEF01ULL}, ""); EXPECT_EQ(rotr(uint8_t{0x12}, 0), uint8_t{0x12}); EXPECT_EQ(rotr(uint16_t{0x1234}, 0), uint16_t{0x1234}); EXPECT_EQ(rotr(uint32_t{0x12345678UL}, 0), uint32_t{0x12345678UL}); EXPECT_EQ(rotr(uint64_t{0x12345678ABCDEF01ULL}, 0), uint64_t{0x12345678ABCDEF01ULL}); EXPECT_EQ(rotr(uint8_t{0x12}, 8), uint8_t{0x12}); EXPECT_EQ(rotr(uint16_t{0x1234}, 16), uint16_t{0x1234}); EXPECT_EQ(rotr(uint32_t{0x12345678UL}, 32), uint32_t{0x12345678UL}); EXPECT_EQ(rotr(uint64_t{0x12345678ABCDEF01ULL}, 64), uint64_t{0x12345678ABCDEF01ULL}); EXPECT_EQ(rotr(uint8_t{0x12}, -8), uint8_t{0x12}); EXPECT_EQ(rotr(uint16_t{0x1234}, -16), uint16_t{0x1234}); EXPECT_EQ(rotr(uint32_t{0x12345678UL}, -32), uint32_t{0x12345678UL}); EXPECT_EQ(rotr(uint64_t{0x12345678ABCDEF01ULL}, -64), uint64_t{0x12345678ABCDEF01ULL}); EXPECT_EQ(rotr(uint8_t{0x12}, 4), uint8_t{0x21}); EXPECT_EQ(rotr(uint16_t{0x1234}, 4), uint16_t{0x4123}); EXPECT_EQ(rotr(uint32_t{0x12345678UL}, 4), uint32_t{0x81234567UL}); EXPECT_EQ(rotr(uint64_t{0x12345678ABCDEF01ULL}, 4), uint64_t{0x112345678ABCDEF0ULL}); EXPECT_EQ(rotr(uint8_t{0x12}, -4), uint8_t{0x21}); EXPECT_EQ(rotr(uint16_t{0x1234}, -4), uint16_t{0x2341}); EXPECT_EQ(rotr(uint32_t{0x12345678UL}, -4), uint32_t{0x23456781UL}); EXPECT_EQ(rotr(uint64_t{0x12345678ABCDEF01ULL}, -4), uint64_t{0x2345678ABCDEF011ULL}); } TEST(Rotate, Symmetry) { absl::BitGen rng; constexpr int kTrials = 100; for (int i = 0; i < kTrials; ++i) { uint8_t value = absl::Uniform(rng, std::numeric_limits<uint8_t>::min(), std::numeric_limits<uint8_t>::max()); int shift = absl::Uniform(rng, -2 * std::numeric_limits<uint8_t>::digits, 2 * std::numeric_limits<uint8_t>::digits); EXPECT_EQ(rotl(value, shift), rotr(value, -shift)); } for (int i = 0; i < kTrials; ++i) { uint16_t value = absl::Uniform(rng, std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max()); int shift = absl::Uniform(rng, -2 * std::numeric_limits<uint16_t>::digits, 2 * std::numeric_limits<uint16_t>::digits); EXPECT_EQ(rotl(value, shift), rotr(value, -shift)); } for (int i = 0; i < kTrials; ++i) { uint32_t value = absl::Uniform(rng, std::numeric_limits<uint32_t>::min(), std::numeric_limits<uint32_t>::max()); int shift = absl::Uniform(rng, -2 * std::numeric_limits<uint32_t>::digits, 2 * std::numeric_limits<uint32_t>::digits); EXPECT_EQ(rotl(value, shift), rotr(value, -shift)); } for (int i = 0; i < kTrials; ++i) { uint64_t value = absl::Uniform(rng, std::numeric_limits<uint64_t>::min(), std::numeric_limits<uint64_t>::max()); int shift = absl::Uniform(rng, -2 * std::numeric_limits<uint64_t>::digits, 2 * std::numeric_limits<uint64_t>::digits); EXPECT_EQ(rotl(value, shift), rotr(value, -shift)); } } TEST(Counting, LeadingZeroes) { #if ABSL_INTERNAL_HAS_CONSTEXPR_CLZ static_assert(countl_zero(uint8_t{}) == 8, ""); static_assert(countl_zero(static_cast<uint8_t>(-1)) == 0, ""); static_assert(countl_zero(uint16_t{}) == 16, ""); static_assert(countl_zero(static_cast<uint16_t>(-1)) == 0, ""); static_assert(countl_zero(uint32_t{}) == 32, ""); static_assert(countl_zero(~uint32_t{}) == 0, ""); static_assert(countl_zero(uint64_t{}) == 64, ""); static_assert(countl_zero(~uint64_t{}) == 0, ""); #endif EXPECT_EQ(countl_zero(uint8_t{}), 8); EXPECT_EQ(countl_zero(static_cast<uint8_t>(-1)), 0); EXPECT_EQ(countl_zero(uint16_t{}), 16); EXPECT_EQ(countl_zero(static_cast<uint16_t>(-1)), 0); EXPECT_EQ(countl_zero(uint32_t{}), 32); EXPECT_EQ(countl_zero(~uint32_t{}), 0); EXPECT_EQ(countl_zero(uint64_t{}), 64); EXPECT_EQ(countl_zero(~uint64_t{}), 0); for (int i = 0; i < 8; i++) { EXPECT_EQ(countl_zero(static_cast<uint8_t>(1u << i)), 7 - i); } for (int i = 0; i < 16; i++) { EXPECT_EQ(countl_zero(static_cast<uint16_t>(1u << i)), 15 - i); } for (int i = 0; i < 32; i++) { EXPECT_EQ(countl_zero(uint32_t{1} << i), 31 - i); } for (int i = 0; i < 64; i++) { EXPECT_EQ(countl_zero(uint64_t{1} << i), 63 - i); } } TEST(Counting, LeadingOnes) { #if ABSL_INTERNAL_HAS_CONSTEXPR_CLZ static_assert(countl_one(uint8_t{}) == 0, ""); static_assert(countl_one(static_cast<uint8_t>(-1)) == 8, ""); static_assert(countl_one(uint16_t{}) == 0, ""); static_assert(countl_one(static_cast<uint16_t>(-1)) == 16, ""); static_assert(countl_one(uint32_t{}) == 0, ""); static_assert(countl_one(~uint32_t{}) == 32, ""); static_assert(countl_one(uint64_t{}) == 0, ""); static_assert(countl_one(~uint64_t{}) == 64, ""); #endif EXPECT_EQ(countl_one(uint8_t{}), 0); EXPECT_EQ(countl_one(static_cast<uint8_t>(-1)), 8); EXPECT_EQ(countl_one(uint16_t{}), 0); EXPECT_EQ(countl_one(static_cast<uint16_t>(-1)), 16); EXPECT_EQ(countl_one(uint32_t{}), 0); EXPECT_EQ(countl_one(~uint32_t{}), 32); EXPECT_EQ(countl_one(uint64_t{}), 0); EXPECT_EQ(countl_one(~uint64_t{}), 64); } TEST(Counting, TrailingZeroes) { #if ABSL_INTERNAL_HAS_CONSTEXPR_CTZ static_assert(countr_zero(uint8_t{}) == 8, ""); static_assert(countr_zero(static_cast<uint8_t>(-1)) == 0, ""); static_assert(countr_zero(uint16_t{}) == 16, ""); static_assert(countr_zero(static_cast<uint16_t>(-1)) == 0, ""); static_assert(countr_zero(uint32_t{}) == 32, ""); static_assert(countr_zero(~uint32_t{}) == 0, ""); static_assert(countr_zero(uint64_t{}) == 64, ""); static_assert(countr_zero(~uint64_t{}) == 0, ""); #endif EXPECT_EQ(countr_zero(uint8_t{}), 8); EXPECT_EQ(countr_zero(static_cast<uint8_t>(-1)), 0); EXPECT_EQ(countr_zero(uint16_t{}), 16); EXPECT_EQ(countr_zero(static_cast<uint16_t>(-1)), 0); EXPECT_EQ(countr_zero(uint32_t{}), 32); EXPECT_EQ(countr_zero(~uint32_t{}), 0); EXPECT_EQ(countr_zero(uint64_t{}), 64); EXPECT_EQ(countr_zero(~uint64_t{}), 0); } TEST(Counting, TrailingOnes) { #if ABSL_INTERNAL_HAS_CONSTEXPR_CTZ static_assert(countr_one(uint8_t{}) == 0, ""); static_assert(countr_one(static_cast<uint8_t>(-1)) == 8, ""); static_assert(countr_one(uint16_t{}) == 0, ""); static_assert(countr_one(static_cast<uint16_t>(-1)) == 16, ""); static_assert(countr_one(uint32_t{}) == 0, ""); static_assert(countr_one(~uint32_t{}) == 32, ""); static_assert(countr_one(uint64_t{}) == 0, ""); static_assert(countr_one(~uint64_t{}) == 64, ""); #endif EXPECT_EQ(countr_one(uint8_t{}), 0); EXPECT_EQ(countr_one(static_cast<uint8_t>(-1)), 8); EXPECT_EQ(countr_one(uint16_t{}), 0); EXPECT_EQ(countr_one(static_cast<uint16_t>(-1)), 16); EXPECT_EQ(countr_one(uint32_t{}), 0); EXPECT_EQ(countr_one(~uint32_t{}), 32); EXPECT_EQ(countr_one(uint64_t{}), 0); EXPECT_EQ(countr_one(~uint64_t{}), 64); } TEST(Counting, Popcount) { #if ABSL_INTERNAL_HAS_CONSTEXPR_POPCOUNT static_assert(popcount(uint8_t{}) == 0, ""); static_assert(popcount(uint8_t{1}) == 1, ""); static_assert(popcount(static_cast<uint8_t>(-1)) == 8, ""); static_assert(popcount(uint16_t{}) == 0, ""); static_assert(popcount(uint16_t{1}) == 1, ""); static_assert(popcount(static_cast<uint16_t>(-1)) == 16, ""); static_assert(popcount(uint32_t{}) == 0, ""); static_assert(popcount(uint32_t{1}) == 1, ""); static_assert(popcount(~uint32_t{}) == 32, ""); static_assert(popcount(uint64_t{}) == 0, ""); static_assert(popcount(uint64_t{1}) == 1, ""); static_assert(popcount(~uint64_t{}) == 64, ""); #endif EXPECT_EQ(popcount(uint8_t{}), 0); EXPECT_EQ(popcount(uint8_t{1}), 1); EXPECT_EQ(popcount(static_cast<uint8_t>(-1)), 8); EXPECT_EQ(popcount(uint16_t{}), 0); EXPECT_EQ(popcount(uint16_t{1}), 1); EXPECT_EQ(popcount(static_cast<uint16_t>(-1)), 16); EXPECT_EQ(popcount(uint32_t{}), 0); EXPECT_EQ(popcount(uint32_t{1}), 1); EXPECT_EQ(popcount(~uint32_t{}), 32); EXPECT_EQ(popcount(uint64_t{}), 0); EXPECT_EQ(popcount(uint64_t{1}), 1); EXPECT_EQ(popcount(~uint64_t{}), 64); for (int i = 0; i < 8; i++) { EXPECT_EQ(popcount(static_cast<uint8_t>(uint8_t{1} << i)), 1); EXPECT_EQ(popcount(static_cast<uint8_t>(static_cast<uint8_t>(-1) ^ (uint8_t{1} << i))), 7); } for (int i = 0; i < 16; i++) { EXPECT_EQ(popcount(static_cast<uint16_t>(uint16_t{1} << i)), 1); EXPECT_EQ(popcount(static_cast<uint16_t>(static_cast<uint16_t>(-1) ^ (uint16_t{1} << i))), 15); } for (int i = 0; i < 32; i++) { EXPECT_EQ(popcount(uint32_t{1} << i), 1); EXPECT_EQ(popcount(static_cast<uint32_t>(-1) ^ (uint32_t{1} << i)), 31); } for (int i = 0; i < 64; i++) { EXPECT_EQ(popcount(uint64_t{1} << i), 1); EXPECT_EQ(popcount(static_cast<uint64_t>(-1) ^ (uint64_t{1} << i)), 63); } } template <typename T> struct PopcountInput { T value = 0; int expected = 0; }; template <typename T> PopcountInput<T> GeneratePopcountInput(absl::BitGen& gen) { PopcountInput<T> ret; for (int i = 0; i < std::numeric_limits<T>::digits; i++) { bool coin = absl::Bernoulli(gen, 0.2); if (coin) { ret.value |= T{1} << i; ret.expected++; } } return ret; } TEST(Counting, PopcountFuzz) { absl::BitGen rng; constexpr int kTrials = 100; for (int i = 0; i < kTrials; ++i) { auto input = GeneratePopcountInput<uint8_t>(rng); EXPECT_EQ(popcount(input.value), input.expected); } for (int i = 0; i < kTrials; ++i) { auto input = GeneratePopcountInput<uint16_t>(rng); EXPECT_EQ(popcount(input.value), input.expected); } for (int i = 0; i < kTrials; ++i) { auto input = GeneratePopcountInput<uint32_t>(rng); EXPECT_EQ(popcount(input.value), input.expected); } for (int i = 0; i < kTrials; ++i) { auto input = GeneratePopcountInput<uint64_t>(rng); EXPECT_EQ(popcount(input.value), input.expected); } } TEST(IntegralPowersOfTwo, SingleBit) { EXPECT_FALSE(has_single_bit(uint8_t{})); EXPECT_FALSE(has_single_bit(static_cast<uint8_t>(-1))); EXPECT_FALSE(has_single_bit(uint16_t{})); EXPECT_FALSE(has_single_bit(static_cast<uint16_t>(-1))); EXPECT_FALSE(has_single_bit(uint32_t{})); EXPECT_FALSE(has_single_bit(~uint32_t{})); EXPECT_FALSE(has_single_bit(uint64_t{})); EXPECT_FALSE(has_single_bit(~uint64_t{})); static_assert(!has_single_bit(0u), ""); static_assert(has_single_bit(1u), ""); static_assert(has_single_bit(2u), ""); static_assert(!has_single_bit(3u), ""); static_assert(has_single_bit(4u), ""); static_assert(!has_single_bit(1337u), ""); static_assert(has_single_bit(65536u), ""); static_assert(has_single_bit(uint32_t{1} << 30), ""); static_assert(has_single_bit(uint64_t{1} << 42), ""); EXPECT_FALSE(has_single_bit(0u)); EXPECT_TRUE(has_single_bit(1u)); EXPECT_TRUE(has_single_bit(2u)); EXPECT_FALSE(has_single_bit(3u)); EXPECT_TRUE(has_single_bit(4u)); EXPECT_FALSE(has_single_bit(1337u)); EXPECT_TRUE(has_single_bit(65536u)); EXPECT_TRUE(has_single_bit(uint32_t{1} << 30)); EXPECT_TRUE(has_single_bit(uint64_t{1} << 42)); EXPECT_TRUE(has_single_bit( static_cast<uint8_t>(std::numeric_limits<uint8_t>::max() / 2 + 1))); EXPECT_TRUE(has_single_bit( static_cast<uint16_t>(std::numeric_limits<uint16_t>::max() / 2 + 1))); EXPECT_TRUE(has_single_bit( static_cast<uint32_t>(std::numeric_limits<uint32_t>::max() / 2 + 1))); EXPECT_TRUE(has_single_bit( static_cast<uint64_t>(std::numeric_limits<uint64_t>::max() / 2 + 1))); } template <typename T, T arg, T = bit_ceil(arg)> bool IsBitCeilConstantExpression(int) { return true; } template <typename T, T arg> bool IsBitCeilConstantExpression(char) { return false; } TEST(IntegralPowersOfTwo, Ceiling) { #if ABSL_INTERNAL_HAS_CONSTEXPR_CLZ static_assert(bit_ceil(0u) == 1, ""); static_assert(bit_ceil(1u) == 1, ""); static_assert(bit_ceil(2u) == 2, ""); static_assert(bit_ceil(3u) == 4, ""); static_assert(bit_ceil(4u) == 4, ""); static_assert(bit_ceil(1337u) == 2048, ""); static_assert(bit_ceil(65536u) == 65536, ""); static_assert(bit_ceil(65536u - 1337u) == 65536, ""); static_assert(bit_ceil(uint32_t{0x80000000}) == uint32_t{0x80000000}, ""); static_assert(bit_ceil(uint64_t{0x40000000000}) == uint64_t{0x40000000000}, ""); static_assert( bit_ceil(uint64_t{0x8000000000000000}) == uint64_t{0x8000000000000000}, ""); EXPECT_TRUE((IsBitCeilConstantExpression<uint8_t, uint8_t{0x0}>(0))); EXPECT_TRUE((IsBitCeilConstantExpression<uint8_t, uint8_t{0x80}>(0))); EXPECT_FALSE((IsBitCeilConstantExpression<uint8_t, uint8_t{0x81}>(0))); EXPECT_FALSE((IsBitCeilConstantExpression<uint8_t, uint8_t{0xff}>(0))); EXPECT_TRUE((IsBitCeilConstantExpression<uint16_t, uint16_t{0x0}>(0))); EXPECT_TRUE((IsBitCeilConstantExpression<uint16_t, uint16_t{0x8000}>(0))); EXPECT_FALSE((IsBitCeilConstantExpression<uint16_t, uint16_t{0x8001}>(0))); EXPECT_FALSE((IsBitCeilConstantExpression<uint16_t, uint16_t{0xffff}>(0))); EXPECT_TRUE((IsBitCeilConstantExpression<uint32_t, uint32_t{0x0}>(0))); EXPECT_TRUE((IsBitCeilConstantExpression<uint32_t, uint32_t{0x80000000}>(0))); EXPECT_FALSE( (IsBitCeilConstantExpression<uint32_t, uint32_t{0x80000001}>(0))); EXPECT_FALSE( (IsBitCeilConstantExpression<uint32_t, uint32_t{0xffffffff}>(0))); EXPECT_TRUE((IsBitCeilConstantExpression<uint64_t, uint64_t{0x0}>(0))); EXPECT_TRUE( (IsBitCeilConstantExpression<uint64_t, uint64_t{0x8000000000000000}>(0))); EXPECT_FALSE( (IsBitCeilConstantExpression<uint64_t, uint64_t{0x8000000000000001}>(0))); EXPECT_FALSE( (IsBitCeilConstantExpression<uint64_t, uint64_t{0xffffffffffffffff}>(0))); #endif EXPECT_EQ(bit_ceil(0u), 1); EXPECT_EQ(bit_ceil(1u), 1); EXPECT_EQ(bit_ceil(2u), 2); EXPECT_EQ(bit_ceil(3u), 4); EXPECT_EQ(bit_ceil(4u), 4); EXPECT_EQ(bit_ceil(1337u), 2048); EXPECT_EQ(bit_ceil(65536u), 65536); EXPECT_EQ(bit_ceil(65536u - 1337u), 65536); EXPECT_EQ(bit_ceil(uint64_t{0x40000000000}), uint64_t{0x40000000000}); } TEST(IntegralPowersOfTwo, Floor) { #if ABSL_INTERNAL_HAS_CONSTEXPR_CLZ static_assert(bit_floor(0u) == 0, ""); static_assert(bit_floor(1u) == 1, ""); static_assert(bit_floor(2u) == 2, ""); static_assert(bit_floor(3u) == 2, ""); static_assert(bit_floor(4u) == 4, ""); static_assert(bit_floor(1337u) == 1024, ""); static_assert(bit_floor(65536u) == 65536, ""); static_assert(bit_floor(65536u - 1337u) == 32768, ""); static_assert(bit_floor(uint64_t{0x40000000000}) == uint64_t{0x40000000000}, ""); #endif EXPECT_EQ(bit_floor(0u), 0); EXPECT_EQ(bit_floor(1u), 1); EXPECT_EQ(bit_floor(2u), 2); EXPECT_EQ(bit_floor(3u), 2); EXPECT_EQ(bit_floor(4u), 4); EXPECT_EQ(bit_floor(1337u), 1024); EXPECT_EQ(bit_floor(65536u), 65536); EXPECT_EQ(bit_floor(65536u - 1337u), 32768); EXPECT_EQ(bit_floor(uint64_t{0x40000000000}), uint64_t{0x40000000000}); for (int i = 0; i < 8; i++) { uint8_t input = uint8_t{1} << i; EXPECT_EQ(bit_floor(input), input); if (i > 0) { EXPECT_EQ(bit_floor(static_cast<uint8_t>(input + 1)), input); } } for (int i = 0; i < 16; i++) { uint16_t input = uint16_t{1} << i; EXPECT_EQ(bit_floor(input), input); if (i > 0) { EXPECT_EQ(bit_floor(static_cast<uint16_t>(input + 1)), input); } } for (int i = 0; i < 32; i++) { uint32_t input = uint32_t{1} << i; EXPECT_EQ(bit_floor(input), input); if (i > 0) { EXPECT_EQ(bit_floor(input + 1), input); } } for (int i = 0; i < 64; i++) { uint64_t input = uint64_t{1} << i; EXPECT_EQ(bit_floor(input), input); if (i > 0) { EXPECT_EQ(bit_floor(input + 1), input); } } } TEST(IntegralPowersOfTwo, Width) { #if ABSL_INTERNAL_HAS_CONSTEXPR_CLZ static_assert(bit_width(uint8_t{}) == 0, ""); static_assert(bit_width(uint8_t{1}) == 1, ""); static_assert(bit_width(uint8_t{3}) == 2, ""); static_assert(bit_width(static_cast<uint8_t>(-1)) == 8, ""); static_assert(bit_width(uint16_t{}) == 0, ""); static_assert(bit_width(uint16_t{1}) == 1, ""); static_assert(bit_width(uint16_t{3}) == 2, ""); static_assert(bit_width(static_cast<uint16_t>(-1)) == 16, ""); static_assert(bit_width(uint32_t{}) == 0, ""); static_assert(bit_width(uint32_t{1}) == 1, ""); static_assert(bit_width(uint32_t{3}) == 2, ""); static_assert(bit_width(~uint32_t{}) == 32, ""); static_assert(bit_width(uint64_t{}) == 0, ""); static_assert(bit_width(uint64_t{1}) == 1, ""); static_assert(bit_width(uint64_t{3}) == 2, ""); static_assert(bit_width(~uint64_t{}) == 64, ""); #endif EXPECT_EQ(bit_width(uint8_t{}), 0); EXPECT_EQ(bit_width(uint8_t{1}), 1); EXPECT_EQ(bit_width(uint8_t{3}), 2); EXPECT_EQ(bit_width(static_cast<uint8_t>(-1)), 8); EXPECT_EQ(bit_width(uint16_t{}), 0); EXPECT_EQ(bit_width(uint16_t{1}), 1); EXPECT_EQ(bit_width(uint16_t{3}), 2); EXPECT_EQ(bit_width(static_cast<uint16_t>(-1)), 16); EXPECT_EQ(bit_width(uint32_t{}), 0); EXPECT_EQ(bit_width(uint32_t{1}), 1); EXPECT_EQ(bit_width(uint32_t{3}), 2); EXPECT_EQ(bit_width(~uint32_t{}), 32); EXPECT_EQ(bit_width(uint64_t{}), 0); EXPECT_EQ(bit_width(uint64_t{1}), 1); EXPECT_EQ(bit_width(uint64_t{3}), 2); EXPECT_EQ(bit_width(~uint64_t{}), 64); for (int i = 0; i < 8; i++) { EXPECT_EQ(bit_width(static_cast<uint8_t>(uint8_t{1} << i)), i + 1); } for (int i = 0; i < 16; i++) { EXPECT_EQ(bit_width(static_cast<uint16_t>(uint16_t{1} << i)), i + 1); } for (int i = 0; i < 32; i++) { EXPECT_EQ(bit_width(uint32_t{1} << i), i + 1); } for (int i = 0; i < 64; i++) { EXPECT_EQ(bit_width(uint64_t{1} << i), i + 1); } } #if defined(__GNUC__) static_assert(ABSL_INTERNAL_HAS_CONSTEXPR_POPCOUNT, "popcount should be constexpr"); static_assert(ABSL_INTERNAL_HAS_CONSTEXPR_CLZ, "clz should be constexpr"); static_assert(ABSL_INTERNAL_HAS_CONSTEXPR_CTZ, "ctz should be constexpr"); #endif } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/numeric/internal/bits.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/numeric/bits_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f3a36820-fd8a-4ade-adf9-85e9fe96b397
cpp
abseil/abseil-cpp
cleanup
absl/cleanup/internal/cleanup.h
absl/cleanup/cleanup_test.cc
#ifndef ABSL_CLEANUP_INTERNAL_CLEANUP_H_ #define ABSL_CLEANUP_INTERNAL_CLEANUP_H_ #include <new> #include <type_traits> #include <utility> #include "absl/base/internal/invoke.h" #include "absl/base/macros.h" #include "absl/base/thread_annotations.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cleanup_internal { struct Tag {}; template <typename Arg, typename... Args> constexpr bool WasDeduced() { return (std::is_same<cleanup_internal::Tag, Arg>::value) && (sizeof...(Args) == 0); } template <typename Callback> constexpr bool ReturnsVoid() { return (std::is_same<base_internal::invoke_result_t<Callback>, void>::value); } template <typename Callback> class Storage { public: Storage() = delete; explicit Storage(Callback callback) { ::new (GetCallbackBuffer()) Callback(std::move(callback)); is_callback_engaged_ = true; } Storage(Storage&& other) { ABSL_HARDENING_ASSERT(other.IsCallbackEngaged()); ::new (GetCallbackBuffer()) Callback(std::move(other.GetCallback())); is_callback_engaged_ = true; other.DestroyCallback(); } Storage(const Storage& other) = delete; Storage& operator=(Storage&& other) = delete; Storage& operator=(const Storage& other) = delete; void* GetCallbackBuffer() { return static_cast<void*>(+callback_buffer_); } Callback& GetCallback() { return *reinterpret_cast<Callback*>(GetCallbackBuffer()); } bool IsCallbackEngaged() const { return is_callback_engaged_; } void DestroyCallback() { is_callback_engaged_ = false; GetCallback().~Callback(); } void InvokeCallback() ABSL_NO_THREAD_SAFETY_ANALYSIS { std::move(GetCallback())(); } private: bool is_callback_engaged_; alignas(Callback) char callback_buffer_[sizeof(Callback)]; }; } ABSL_NAMESPACE_END } #endif
#include "absl/cleanup/cleanup.h" #include <functional> #include <type_traits> #include <utility> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/utility/utility.h" namespace { using Tag = absl::cleanup_internal::Tag; template <typename Type1, typename Type2> constexpr bool IsSame() { return (std::is_same<Type1, Type2>::value); } struct IdentityFactory { template <typename Callback> static Callback AsCallback(Callback callback) { return Callback(std::move(callback)); } }; class FunctorClass { using Callback = std::function<void()>; public: explicit FunctorClass(Callback callback) : callback_(std::move(callback)) {} FunctorClass(FunctorClass&& other) : callback_(std::exchange(other.callback_, Callback())) {} FunctorClass(const FunctorClass&) = delete; FunctorClass& operator=(const FunctorClass&) = delete; FunctorClass& operator=(FunctorClass&&) = delete; void operator()() const& = delete; void operator()() && { ASSERT_TRUE(callback_); callback_(); callback_ = nullptr; } private: Callback callback_; }; struct FunctorClassFactory { template <typename Callback> static FunctorClass AsCallback(Callback callback) { return FunctorClass(std::move(callback)); } }; struct StdFunctionFactory { template <typename Callback> static std::function<void()> AsCallback(Callback callback) { return std::function<void()>(std::move(callback)); } }; using CleanupTestParams = ::testing::Types<IdentityFactory, FunctorClassFactory, StdFunctionFactory>; template <typename> struct CleanupTest : public ::testing::Test {}; TYPED_TEST_SUITE(CleanupTest, CleanupTestParams); bool fn_ptr_called = false; void FnPtrFunction() { fn_ptr_called = true; } TYPED_TEST(CleanupTest, FactoryProducesCorrectType) { { auto callback = TypeParam::AsCallback([] {}); auto cleanup = absl::MakeCleanup(std::move(callback)); static_assert( IsSame<absl::Cleanup<Tag, decltype(callback)>, decltype(cleanup)>(), ""); } { auto cleanup = absl::MakeCleanup(&FnPtrFunction); static_assert(IsSame<absl::Cleanup<Tag, void (*)()>, decltype(cleanup)>(), ""); } { auto cleanup = absl::MakeCleanup(FnPtrFunction); static_assert(IsSame<absl::Cleanup<Tag, void (*)()>, decltype(cleanup)>(), ""); } } #if defined(ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION) TYPED_TEST(CleanupTest, CTADProducesCorrectType) { { auto callback = TypeParam::AsCallback([] {}); absl::Cleanup cleanup = std::move(callback); static_assert( IsSame<absl::Cleanup<Tag, decltype(callback)>, decltype(cleanup)>(), ""); } { absl::Cleanup cleanup = &FnPtrFunction; static_assert(IsSame<absl::Cleanup<Tag, void (*)()>, decltype(cleanup)>(), ""); } { absl::Cleanup cleanup = FnPtrFunction; static_assert(IsSame<absl::Cleanup<Tag, void (*)()>, decltype(cleanup)>(), ""); } } TYPED_TEST(CleanupTest, FactoryAndCTADProduceSameType) { { auto callback = IdentityFactory::AsCallback([] {}); auto factory_cleanup = absl::MakeCleanup(callback); absl::Cleanup deduction_cleanup = callback; static_assert( IsSame<decltype(factory_cleanup), decltype(deduction_cleanup)>(), ""); } { auto factory_cleanup = absl::MakeCleanup(FunctorClassFactory::AsCallback([] {})); absl::Cleanup deduction_cleanup = FunctorClassFactory::AsCallback([] {}); static_assert( IsSame<decltype(factory_cleanup), decltype(deduction_cleanup)>(), ""); } { auto factory_cleanup = absl::MakeCleanup(StdFunctionFactory::AsCallback([] {})); absl::Cleanup deduction_cleanup = StdFunctionFactory::AsCallback([] {}); static_assert( IsSame<decltype(factory_cleanup), decltype(deduction_cleanup)>(), ""); } { auto factory_cleanup = absl::MakeCleanup(&FnPtrFunction); absl::Cleanup deduction_cleanup = &FnPtrFunction; static_assert( IsSame<decltype(factory_cleanup), decltype(deduction_cleanup)>(), ""); } { auto factory_cleanup = absl::MakeCleanup(FnPtrFunction); absl::Cleanup deduction_cleanup = FnPtrFunction; static_assert( IsSame<decltype(factory_cleanup), decltype(deduction_cleanup)>(), ""); } } #endif TYPED_TEST(CleanupTest, BasicUsage) { bool called = false; { auto cleanup = absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; })); EXPECT_FALSE(called); } EXPECT_TRUE(called); } TYPED_TEST(CleanupTest, BasicUsageWithFunctionPointer) { fn_ptr_called = false; { auto cleanup = absl::MakeCleanup(TypeParam::AsCallback(&FnPtrFunction)); EXPECT_FALSE(fn_ptr_called); } EXPECT_TRUE(fn_ptr_called); } TYPED_TEST(CleanupTest, Cancel) { bool called = false; { auto cleanup = absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; })); EXPECT_FALSE(called); std::move(cleanup).Cancel(); EXPECT_FALSE(called); } EXPECT_FALSE(called); } TYPED_TEST(CleanupTest, Invoke) { bool called = false; { auto cleanup = absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; })); EXPECT_FALSE(called); std::move(cleanup).Invoke(); EXPECT_TRUE(called); called = false; } EXPECT_FALSE(called); } TYPED_TEST(CleanupTest, Move) { bool called = false; { auto moved_from_cleanup = absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; })); EXPECT_FALSE(called); { auto moved_to_cleanup = std::move(moved_from_cleanup); EXPECT_FALSE(called); } EXPECT_TRUE(called); called = false; } EXPECT_FALSE(called); } int DestructionCount = 0; struct DestructionCounter { void operator()() {} ~DestructionCounter() { ++DestructionCount; } }; TYPED_TEST(CleanupTest, DestructorDestroys) { { auto cleanup = absl::MakeCleanup(TypeParam::AsCallback(DestructionCounter())); DestructionCount = 0; } EXPECT_EQ(DestructionCount, 1); } TYPED_TEST(CleanupTest, CancelDestroys) { { auto cleanup = absl::MakeCleanup(TypeParam::AsCallback(DestructionCounter())); DestructionCount = 0; std::move(cleanup).Cancel(); EXPECT_EQ(DestructionCount, 1); } EXPECT_EQ(DestructionCount, 1); } TYPED_TEST(CleanupTest, InvokeDestroys) { { auto cleanup = absl::MakeCleanup(TypeParam::AsCallback(DestructionCounter())); DestructionCount = 0; std::move(cleanup).Invoke(); EXPECT_EQ(DestructionCount, 1); } EXPECT_EQ(DestructionCount, 1); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/cleanup/internal/cleanup.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/cleanup/cleanup_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f3e68bf1-a58d-4abf-a35d-59676e9bf3a6
cpp
abseil/abseil-cpp
sample_recorder
absl/profiling/internal/sample_recorder.h
absl/profiling/internal/sample_recorder_test.cc
#ifndef ABSL_PROFILING_INTERNAL_SAMPLE_RECORDER_H_ #define ABSL_PROFILING_INTERNAL_SAMPLE_RECORDER_H_ #include <atomic> #include <cstddef> #include <functional> #include "absl/base/config.h" #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { template <typename T> struct Sample { absl::Mutex init_mu; T* next = nullptr; T* dead ABSL_GUARDED_BY(init_mu) = nullptr; int64_t weight; }; template <typename T> class SampleRecorder { public: SampleRecorder(); ~SampleRecorder(); template <typename... Targs> T* Register(Targs&&... args); void Unregister(T* sample); using DisposeCallback = void (*)(const T&); DisposeCallback SetDisposeCallback(DisposeCallback f); int64_t Iterate(const std::function<void(const T& stack)>& f); size_t GetMaxSamples() const; void SetMaxSamples(size_t max); private: void PushNew(T* sample); void PushDead(T* sample); template <typename... Targs> T* PopDead(Targs... args); std::atomic<size_t> dropped_samples_; std::atomic<size_t> size_estimate_; std::atomic<size_t> max_samples_{1 << 20}; std::atomic<T*> all_; T graveyard_; std::atomic<DisposeCallback> dispose_; }; template <typename T> typename SampleRecorder<T>::DisposeCallback SampleRecorder<T>::SetDisposeCallback(DisposeCallback f) { return dispose_.exchange(f, std::memory_order_relaxed); } template <typename T> SampleRecorder<T>::SampleRecorder() : dropped_samples_(0), size_estimate_(0), all_(nullptr), dispose_(nullptr) { absl::MutexLock l(&graveyard_.init_mu); graveyard_.dead = &graveyard_; } template <typename T> SampleRecorder<T>::~SampleRecorder() { T* s = all_.load(std::memory_order_acquire); while (s != nullptr) { T* next = s->next; delete s; s = next; } } template <typename T> void SampleRecorder<T>::PushNew(T* sample) { sample->next = all_.load(std::memory_order_relaxed); while (!all_.compare_exchange_weak(sample->next, sample, std::memory_order_release, std::memory_order_relaxed)) { } } template <typename T> void SampleRecorder<T>::PushDead(T* sample) { if (auto* dispose = dispose_.load(std::memory_order_relaxed)) { dispose(*sample); } absl::MutexLock graveyard_lock(&graveyard_.init_mu); absl::MutexLock sample_lock(&sample->init_mu); sample->dead = graveyard_.dead; graveyard_.dead = sample; } template <typename T> template <typename... Targs> T* SampleRecorder<T>::PopDead(Targs... args) { absl::MutexLock graveyard_lock(&graveyard_.init_mu); T* sample = graveyard_.dead; if (sample == &graveyard_) return nullptr; absl::MutexLock sample_lock(&sample->init_mu); graveyard_.dead = sample->dead; sample->dead = nullptr; sample->PrepareForSampling(std::forward<Targs>(args)...); return sample; } template <typename T> template <typename... Targs> T* SampleRecorder<T>::Register(Targs&&... args) { size_t size = size_estimate_.fetch_add(1, std::memory_order_relaxed); if (size > max_samples_.load(std::memory_order_relaxed)) { size_estimate_.fetch_sub(1, std::memory_order_relaxed); dropped_samples_.fetch_add(1, std::memory_order_relaxed); return nullptr; } T* sample = PopDead(args...); if (sample == nullptr) { sample = new T(); { absl::MutexLock sample_lock(&sample->init_mu); sample->init_mu.ForgetDeadlockInfo(); sample->PrepareForSampling(std::forward<Targs>(args)...); } PushNew(sample); } return sample; } template <typename T> void SampleRecorder<T>::Unregister(T* sample) { PushDead(sample); size_estimate_.fetch_sub(1, std::memory_order_relaxed); } template <typename T> int64_t SampleRecorder<T>::Iterate( const std::function<void(const T& stack)>& f) { T* s = all_.load(std::memory_order_acquire); while (s != nullptr) { absl::MutexLock l(&s->init_mu); if (s->dead == nullptr) { f(*s); } s = s->next; } return dropped_samples_.load(std::memory_order_relaxed); } template <typename T> void SampleRecorder<T>::SetMaxSamples(size_t max) { max_samples_.store(max, std::memory_order_release); } template <typename T> size_t SampleRecorder<T>::GetMaxSamples() const { return max_samples_.load(std::memory_order_acquire); } } ABSL_NAMESPACE_END } #endif
#include "absl/profiling/internal/sample_recorder.h" #include <atomic> #include <random> #include <vector> #include "gmock/gmock.h" #include "absl/base/thread_annotations.h" #include "absl/synchronization/internal/thread_pool.h" #include "absl/synchronization/mutex.h" #include "absl/synchronization/notification.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { namespace { using ::absl::synchronization_internal::ThreadPool; using ::testing::IsEmpty; using ::testing::UnorderedElementsAre; struct Info : public Sample<Info> { public: void PrepareForSampling(int64_t w) { weight = w; } std::atomic<size_t> size; absl::Time create_time; }; std::vector<size_t> GetSizes(SampleRecorder<Info>* s) { std::vector<size_t> res; s->Iterate([&](const Info& info) { res.push_back(info.size.load(std::memory_order_acquire)); }); return res; } std::vector<int64_t> GetWeights(SampleRecorder<Info>* s) { std::vector<int64_t> res; s->Iterate([&](const Info& info) { res.push_back(info.weight); }); return res; } Info* Register(SampleRecorder<Info>* s, int64_t weight, size_t size) { auto* info = s->Register(weight); assert(info != nullptr); info->size.store(size); return info; } TEST(SampleRecorderTest, Registration) { SampleRecorder<Info> sampler; auto* info1 = Register(&sampler, 31, 1); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1)); EXPECT_THAT(GetWeights(&sampler), UnorderedElementsAre(31)); auto* info2 = Register(&sampler, 32, 2); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1, 2)); info1->size.store(3); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(3, 2)); EXPECT_THAT(GetWeights(&sampler), UnorderedElementsAre(31, 32)); sampler.Unregister(info1); sampler.Unregister(info2); } TEST(SampleRecorderTest, Unregistration) { SampleRecorder<Info> sampler; std::vector<Info*> infos; for (size_t i = 0; i < 3; ++i) { infos.push_back(Register(&sampler, 33 + i, i)); } EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 1, 2)); EXPECT_THAT(GetWeights(&sampler), UnorderedElementsAre(33, 34, 35)); sampler.Unregister(infos[1]); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2)); EXPECT_THAT(GetWeights(&sampler), UnorderedElementsAre(33, 35)); infos.push_back(Register(&sampler, 36, 3)); infos.push_back(Register(&sampler, 37, 4)); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 3, 4)); EXPECT_THAT(GetWeights(&sampler), UnorderedElementsAre(33, 35, 36, 37)); sampler.Unregister(infos[3]); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 4)); EXPECT_THAT(GetWeights(&sampler), UnorderedElementsAre(33, 35, 37)); sampler.Unregister(infos[0]); sampler.Unregister(infos[2]); sampler.Unregister(infos[4]); EXPECT_THAT(GetSizes(&sampler), IsEmpty()); } TEST(SampleRecorderTest, MultiThreaded) { SampleRecorder<Info> sampler; Notification stop; ThreadPool pool(10); for (int i = 0; i < 10; ++i) { pool.Schedule([&sampler, &stop, i]() { std::random_device rd; std::mt19937 gen(rd()); std::vector<Info*> infoz; while (!stop.HasBeenNotified()) { if (infoz.empty()) { infoz.push_back(sampler.Register(i)); } switch (std::uniform_int_distribution<>(0, 2)(gen)) { case 0: { infoz.push_back(sampler.Register(i)); break; } case 1: { size_t p = std::uniform_int_distribution<>(0, infoz.size() - 1)(gen); Info* info = infoz[p]; infoz[p] = infoz.back(); infoz.pop_back(); EXPECT_EQ(info->weight, i); sampler.Unregister(info); break; } case 2: { absl::Duration oldest = absl::ZeroDuration(); sampler.Iterate([&](const Info& info) { oldest = std::max(oldest, absl::Now() - info.create_time); }); ASSERT_GE(oldest, absl::ZeroDuration()); break; } } } }); } absl::SleepFor(absl::Seconds(3)); stop.Notify(); } TEST(SampleRecorderTest, Callback) { SampleRecorder<Info> sampler; auto* info1 = Register(&sampler, 39, 1); auto* info2 = Register(&sampler, 40, 2); static const Info* expected; auto callback = [](const Info& info) { EXPECT_EQ(&info, expected); }; EXPECT_EQ(sampler.SetDisposeCallback(callback), nullptr); expected = info1; sampler.Unregister(info1); EXPECT_EQ(callback, sampler.SetDisposeCallback(nullptr)); expected = nullptr; sampler.Unregister(info2); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/profiling/internal/sample_recorder.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/profiling/internal/sample_recorder_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
cd4d6a35-82ce-47f3-b580-f9949f4f1774
cpp
abseil/abseil-cpp
structured
absl/log/internal/structured.h
absl/log/structured_test.cc
#ifndef ABSL_LOG_INTERNAL_STRUCTURED_H_ #define ABSL_LOG_INTERNAL_STRUCTURED_H_ #include <ostream> #include "absl/base/config.h" #include "absl/log/internal/log_message.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { class ABSL_MUST_USE_RESULT AsLiteralImpl final { public: explicit AsLiteralImpl(absl::string_view str) : str_(str) {} AsLiteralImpl(const AsLiteralImpl&) = default; AsLiteralImpl& operator=(const AsLiteralImpl&) = default; private: absl::string_view str_; friend std::ostream& operator<<(std::ostream& os, AsLiteralImpl as_literal) { return os << as_literal.str_; } void AddToMessage(log_internal::LogMessage& m) { m.CopyToEncodedBuffer<log_internal::LogMessage::StringType::kLiteral>(str_); } friend log_internal::LogMessage& operator<<(log_internal::LogMessage& m, AsLiteralImpl as_literal) { as_literal.AddToMessage(m); return m; } }; } ABSL_NAMESPACE_END } #endif
#include "absl/log/structured.h" #include <ios> #include <sstream> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/log/internal/test_helpers.h" #include "absl/log/internal/test_matchers.h" #include "absl/log/log.h" #include "absl/log/scoped_mock_log.h" namespace { using ::absl::log_internal::MatchesOstream; using ::absl::log_internal::TextMessage; using ::testing::ElementsAre; using ::testing::Eq; auto *test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); std::ios &LoggingDefaults(std::ios &str) { str.setf(std::ios_base::showbase | std::ios_base::boolalpha | std::ios_base::internal); return str; } TEST(StreamingFormatTest, LogAsLiteral) { std::ostringstream stream; const std::string not_a_literal("hello world"); stream << LoggingDefaults << absl::LogAsLiteral(not_a_literal); absl::ScopedMockLog sink; EXPECT_CALL(sink, Send(AllOf(TextMessage(MatchesOstream(stream)), TextMessage(Eq("hello world")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(literal: "hello world")pb"))))))); sink.StartCapturingLogs(); LOG(INFO) << absl::LogAsLiteral(not_a_literal); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/internal/structured.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/structured_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
a08d2fce-61e5-473e-aede-407232bb0d24
cpp
abseil/abseil-cpp
log_streamer
absl/log/log_streamer.h
absl/log/log_streamer_test.cc
#ifndef ABSL_LOG_LOG_STREAMER_H_ #define ABSL_LOG_LOG_STREAMER_H_ #include <ios> #include <memory> #include <ostream> #include <string> #include <utility> #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/log/absl_log.h" #include "absl/strings/internal/ostringstream.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN class LogStreamer final { public: explicit LogStreamer(absl::LogSeverity severity, absl::string_view file, int line) : severity_(severity), line_(line), file_(file), stream_(absl::in_place, &buf_) { stream_->setf(std::ios_base::showbase | std::ios_base::boolalpha); } LogStreamer(LogStreamer&& that) noexcept : severity_(that.severity_), line_(that.line_), file_(std::move(that.file_)), buf_(std::move(that.buf_)), stream_(std::move(that.stream_)) { if (stream_.has_value()) stream_->str(&buf_); that.stream_.reset(); } LogStreamer& operator=(LogStreamer&& that) { ABSL_LOG_IF(LEVEL(severity_), stream_).AtLocation(file_, line_) << buf_; severity_ = that.severity_; file_ = std::move(that.file_); line_ = that.line_; buf_ = std::move(that.buf_); stream_ = std::move(that.stream_); if (stream_.has_value()) stream_->str(&buf_); that.stream_.reset(); return *this; } ~LogStreamer() { ABSL_LOG_IF(LEVEL(severity_), stream_.has_value()).AtLocation(file_, line_) << buf_; } std::ostream& stream() { return *stream_; } private: absl::LogSeverity severity_; int line_; std::string file_; std::string buf_; absl::optional<absl::strings_internal::OStringStream> stream_; }; inline LogStreamer LogInfoStreamer(absl::string_view file, int line) { return absl::LogStreamer(absl::LogSeverity::kInfo, file, line); } inline LogStreamer LogWarningStreamer(absl::string_view file, int line) { return absl::LogStreamer(absl::LogSeverity::kWarning, file, line); } inline LogStreamer LogErrorStreamer(absl::string_view file, int line) { return absl::LogStreamer(absl::LogSeverity::kError, file, line); } inline LogStreamer LogFatalStreamer(absl::string_view file, int line) { return absl::LogStreamer(absl::LogSeverity::kFatal, file, line); } inline LogStreamer LogDebugFatalStreamer(absl::string_view file, int line) { return absl::LogStreamer(absl::kLogDebugFatal, file, line); } ABSL_NAMESPACE_END } #endif
#include "absl/log/log_streamer.h" #include <ios> #include <iostream> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/internal/sysinfo.h" #include "absl/base/log_severity.h" #include "absl/log/internal/test_actions.h" #include "absl/log/internal/test_helpers.h" #include "absl/log/internal/test_matchers.h" #include "absl/log/log.h" #include "absl/log/scoped_mock_log.h" #include "absl/strings/string_view.h" namespace { using ::absl::log_internal::DeathTestExpectedLogging; using ::absl::log_internal::DeathTestUnexpectedLogging; using ::absl::log_internal::DeathTestValidateExpectations; #if GTEST_HAS_DEATH_TEST using ::absl::log_internal::DiedOfFatal; #endif using ::absl::log_internal::InMatchWindow; using ::absl::log_internal::LogSeverity; using ::absl::log_internal::Prefix; using ::absl::log_internal::SourceFilename; using ::absl::log_internal::SourceLine; using ::absl::log_internal::Stacktrace; using ::absl::log_internal::TextMessage; using ::absl::log_internal::ThreadID; using ::absl::log_internal::Timestamp; using ::testing::_; using ::testing::AnyNumber; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::IsEmpty; using ::testing::IsTrue; auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); void WriteToStream(absl::string_view data, std::ostream* os) { *os << "WriteToStream: " << data; } void WriteToStreamRef(absl::string_view data, std::ostream& os) { os << "WriteToStreamRef: " << data; } TEST(LogStreamerTest, LogInfoStreamer) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kInfo)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::INFO), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto(R"pb(str: "WriteToStream: foo")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); WriteToStream("foo", &absl::LogInfoStreamer("path/file.cc", 1234).stream()); } TEST(LogStreamerTest, LogWarningStreamer) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kWarning)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::WARNING), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto(R"pb(str: "WriteToStream: foo")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); WriteToStream("foo", &absl::LogWarningStreamer("path/file.cc", 1234).stream()); } TEST(LogStreamerTest, LogErrorStreamer) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kError)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::ERROR), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto(R"pb(str: "WriteToStream: foo")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); WriteToStream("foo", &absl::LogErrorStreamer("path/file.cc", 1234).stream()); } #if GTEST_HAS_DEATH_TEST TEST(LogStreamerDeathTest, LogFatalStreamer) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; EXPECT_CALL(test_sink, Send) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Send(AllOf(SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kFatal)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::FATAL), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto( R"pb(str: "WriteToStream: foo")pb"))))))) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); WriteToStream("foo", &absl::LogFatalStreamer("path/file.cc", 1234).stream()); }, DiedOfFatal, DeathTestValidateExpectations()); } #endif #ifdef NDEBUG TEST(LogStreamerTest, LogDebugFatalStreamer) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kError)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::ERROR), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto(R"pb(str: "WriteToStream: foo")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); WriteToStream("foo", &absl::LogDebugFatalStreamer("path/file.cc", 1234).stream()); } #elif GTEST_HAS_DEATH_TEST TEST(LogStreamerDeathTest, LogDebugFatalStreamer) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; EXPECT_CALL(test_sink, Send) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Send(AllOf(SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kFatal)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::FATAL), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto( R"pb(str: "WriteToStream: foo")pb"))))))) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); WriteToStream( "foo", &absl::LogDebugFatalStreamer("path/file.cc", 1234).stream()); }, DiedOfFatal, DeathTestValidateExpectations()); } #endif TEST(LogStreamerTest, LogStreamer) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kError)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::ERROR), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto(R"pb(str: "WriteToStream: foo")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); WriteToStream( "foo", &absl::LogStreamer(absl::LogSeverity::kError, "path/file.cc", 1234) .stream()); } #if GTEST_HAS_DEATH_TEST TEST(LogStreamerDeathTest, LogStreamer) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; EXPECT_CALL(test_sink, Send) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Send(AllOf(SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), Prefix(IsTrue()), LogSeverity(Eq(absl::LogSeverity::kFatal)), Timestamp(InMatchWindow()), ThreadID(Eq(absl::base_internal::GetTID())), TextMessage(Eq("WriteToStream: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), InMatchWindow(), Eq(logging::proto::FATAL), Eq(absl::base_internal::GetTID()), ElementsAre(EqualsProto( R"pb(str: "WriteToStream: foo")pb"))))))) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); WriteToStream("foo", &absl::LogStreamer(absl::LogSeverity::kFatal, "path/file.cc", 1234) .stream()); }, DiedOfFatal, DeathTestValidateExpectations()); } #endif TEST(LogStreamerTest, PassedByReference) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), TextMessage(Eq("WriteToStreamRef: foo")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), _, _, _, ElementsAre(EqualsProto(R"pb(str: "WriteToStreamRef: foo")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); WriteToStreamRef("foo", absl::LogInfoStreamer("path/file.cc", 1234).stream()); } TEST(LogStreamerTest, StoredAsLocal) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); auto streamer = absl::LogInfoStreamer("path/file.cc", 1234); WriteToStream("foo", &streamer.stream()); streamer.stream() << " "; WriteToStreamRef("bar", streamer.stream()); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), TextMessage(Eq("WriteToStream: foo WriteToStreamRef: bar")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), _, _, _, ElementsAre(EqualsProto( R"pb(str: "WriteToStream: foo WriteToStreamRef: bar")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); } #if GTEST_HAS_DEATH_TEST TEST(LogStreamerDeathTest, StoredAsLocal) { EXPECT_EXIT( { auto streamer = absl::LogFatalStreamer("path/file.cc", 1234); std::cerr << "I'm still alive" << std::endl; WriteToStream("foo", &streamer.stream()); }, DiedOfFatal, HasSubstr("I'm still alive")); } #endif TEST(LogStreamerTest, LogsEmptyLine) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), TextMessage(Eq("")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), _, _, _, ElementsAre(EqualsProto(R"pb(str: "")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); absl::LogInfoStreamer("path/file.cc", 1234); } #if GTEST_HAS_DEATH_TEST TEST(LogStreamerDeathTest, LogsEmptyLine) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; EXPECT_CALL(test_sink, Log) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL( test_sink, Send(AllOf(SourceFilename(Eq("path/file.cc")), TextMessage(Eq("")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), _, _, _, _, ElementsAre(EqualsProto(R"pb(str: "")pb"))))))) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); auto streamer = absl::LogFatalStreamer("path/file.cc", 1234); }, DiedOfFatal, DeathTestValidateExpectations()); } #endif TEST(LogStreamerTest, MoveConstruction) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), LogSeverity(Eq(absl::LogSeverity::kInfo)), TextMessage(Eq("hello 0x10 world 0x10")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), _, Eq(logging::proto::INFO), _, ElementsAre(EqualsProto(R"pb(str: "hello 0x10 world 0x10")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); auto streamer1 = absl::LogInfoStreamer("path/file.cc", 1234); streamer1.stream() << "hello " << std::hex << 16; absl::LogStreamer streamer2(std::move(streamer1)); streamer2.stream() << " world " << 16; } TEST(LogStreamerTest, MoveAssignment) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); testing::InSequence seq; EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file2.cc")), SourceLine(Eq(5678)), LogSeverity(Eq(absl::LogSeverity::kWarning)), TextMessage(Eq("something else")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file2.cc"), Eq(5678), _, Eq(logging::proto::WARNING), _, ElementsAre(EqualsProto(R"pb(str: "something else")pb")))), Stacktrace(IsEmpty())))); EXPECT_CALL( test_sink, Send(AllOf( SourceFilename(Eq("path/file.cc")), SourceLine(Eq(1234)), LogSeverity(Eq(absl::LogSeverity::kInfo)), TextMessage(Eq("hello 0x10 world 0x10")), ENCODED_MESSAGE(MatchesEvent( Eq("path/file.cc"), Eq(1234), _, Eq(logging::proto::INFO), _, ElementsAre(EqualsProto(R"pb(str: "hello 0x10 world 0x10")pb")))), Stacktrace(IsEmpty())))); test_sink.StartCapturingLogs(); auto streamer1 = absl::LogInfoStreamer("path/file.cc", 1234); streamer1.stream() << "hello " << std::hex << 16; auto streamer2 = absl::LogWarningStreamer("path/file2.cc", 5678); streamer2.stream() << "something else"; streamer2 = std::move(streamer1); streamer2.stream() << " world " << 16; } TEST(LogStreamerTest, CorrectDefaultFlags) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(TextMessage(Eq("false0xdeadbeef"))))) .Times(2); test_sink.StartCapturingLogs(); absl::LogInfoStreamer("path/file.cc", 1234).stream() << false << std::hex << 0xdeadbeef; LOG(INFO) << false << std::hex << 0xdeadbeef; } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/log_streamer.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/log_streamer_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
71b98cd2-6b0d-4e90-8db5-f7c67caeea68
cpp
abseil/abseil-cpp
check
absl/log/check.h
absl/log/check_test.cc
#ifndef ABSL_LOG_CHECK_H_ #define ABSL_LOG_CHECK_H_ #include "absl/log/internal/check_impl.h" #include "absl/log/internal/check_op.h" #include "absl/log/internal/conditions.h" #include "absl/log/internal/log_message.h" #include "absl/log/internal/strip.h" #define CHECK(condition) ABSL_LOG_INTERNAL_CHECK_IMPL((condition), #condition) #define QCHECK(condition) ABSL_LOG_INTERNAL_QCHECK_IMPL((condition), #condition) #define PCHECK(condition) ABSL_LOG_INTERNAL_PCHECK_IMPL((condition), #condition) #define DCHECK(condition) ABSL_LOG_INTERNAL_DCHECK_IMPL((condition), #condition) #define CHECK_EQ(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_EQ_IMPL((val1), #val1, (val2), #val2) #define CHECK_NE(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_NE_IMPL((val1), #val1, (val2), #val2) #define CHECK_LE(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_LE_IMPL((val1), #val1, (val2), #val2) #define CHECK_LT(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_LT_IMPL((val1), #val1, (val2), #val2) #define CHECK_GE(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_GE_IMPL((val1), #val1, (val2), #val2) #define CHECK_GT(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_GT_IMPL((val1), #val1, (val2), #val2) #define QCHECK_EQ(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_EQ_IMPL((val1), #val1, (val2), #val2) #define QCHECK_NE(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_NE_IMPL((val1), #val1, (val2), #val2) #define QCHECK_LE(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_LE_IMPL((val1), #val1, (val2), #val2) #define QCHECK_LT(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_LT_IMPL((val1), #val1, (val2), #val2) #define QCHECK_GE(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_GE_IMPL((val1), #val1, (val2), #val2) #define QCHECK_GT(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_GT_IMPL((val1), #val1, (val2), #val2) #define DCHECK_EQ(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_EQ_IMPL((val1), #val1, (val2), #val2) #define DCHECK_NE(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_NE_IMPL((val1), #val1, (val2), #val2) #define DCHECK_LE(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_LE_IMPL((val1), #val1, (val2), #val2) #define DCHECK_LT(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_LT_IMPL((val1), #val1, (val2), #val2) #define DCHECK_GE(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_GE_IMPL((val1), #val1, (val2), #val2) #define DCHECK_GT(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_GT_IMPL((val1), #val1, (val2), #val2) #define CHECK_OK(status) ABSL_LOG_INTERNAL_CHECK_OK_IMPL((status), #status) #define QCHECK_OK(status) ABSL_LOG_INTERNAL_QCHECK_OK_IMPL((status), #status) #define DCHECK_OK(status) ABSL_LOG_INTERNAL_DCHECK_OK_IMPL((status), #status) #define CHECK_STREQ(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STREQ_IMPL((s1), #s1, (s2), #s2) #define CHECK_STRNE(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STRNE_IMPL((s1), #s1, (s2), #s2) #define CHECK_STRCASEEQ(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STRCASEEQ_IMPL((s1), #s1, (s2), #s2) #define CHECK_STRCASENE(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STRCASENE_IMPL((s1), #s1, (s2), #s2) #define QCHECK_STREQ(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STREQ_IMPL((s1), #s1, (s2), #s2) #define QCHECK_STRNE(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STRNE_IMPL((s1), #s1, (s2), #s2) #define QCHECK_STRCASEEQ(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STRCASEEQ_IMPL((s1), #s1, (s2), #s2) #define QCHECK_STRCASENE(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STRCASENE_IMPL((s1), #s1, (s2), #s2) #define DCHECK_STREQ(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STREQ_IMPL((s1), #s1, (s2), #s2) #define DCHECK_STRNE(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STRNE_IMPL((s1), #s1, (s2), #s2) #define DCHECK_STRCASEEQ(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STRCASEEQ_IMPL((s1), #s1, (s2), #s2) #define DCHECK_STRCASENE(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STRCASENE_IMPL((s1), #s1, (s2), #s2) #endif
#include "absl/log/check.h" #define ABSL_TEST_CHECK CHECK #define ABSL_TEST_CHECK_OK CHECK_OK #define ABSL_TEST_CHECK_EQ CHECK_EQ #define ABSL_TEST_CHECK_NE CHECK_NE #define ABSL_TEST_CHECK_GE CHECK_GE #define ABSL_TEST_CHECK_LE CHECK_LE #define ABSL_TEST_CHECK_GT CHECK_GT #define ABSL_TEST_CHECK_LT CHECK_LT #define ABSL_TEST_CHECK_STREQ CHECK_STREQ #define ABSL_TEST_CHECK_STRNE CHECK_STRNE #define ABSL_TEST_CHECK_STRCASEEQ CHECK_STRCASEEQ #define ABSL_TEST_CHECK_STRCASENE CHECK_STRCASENE #define ABSL_TEST_DCHECK DCHECK #define ABSL_TEST_DCHECK_OK DCHECK_OK #define ABSL_TEST_DCHECK_EQ DCHECK_EQ #define ABSL_TEST_DCHECK_NE DCHECK_NE #define ABSL_TEST_DCHECK_GE DCHECK_GE #define ABSL_TEST_DCHECK_LE DCHECK_LE #define ABSL_TEST_DCHECK_GT DCHECK_GT #define ABSL_TEST_DCHECK_LT DCHECK_LT #define ABSL_TEST_DCHECK_STREQ DCHECK_STREQ #define ABSL_TEST_DCHECK_STRNE DCHECK_STRNE #define ABSL_TEST_DCHECK_STRCASEEQ DCHECK_STRCASEEQ #define ABSL_TEST_DCHECK_STRCASENE DCHECK_STRCASENE #define ABSL_TEST_QCHECK QCHECK #define ABSL_TEST_QCHECK_OK QCHECK_OK #define ABSL_TEST_QCHECK_EQ QCHECK_EQ #define ABSL_TEST_QCHECK_NE QCHECK_NE #define ABSL_TEST_QCHECK_GE QCHECK_GE #define ABSL_TEST_QCHECK_LE QCHECK_LE #define ABSL_TEST_QCHECK_GT QCHECK_GT #define ABSL_TEST_QCHECK_LT QCHECK_LT #define ABSL_TEST_QCHECK_STREQ QCHECK_STREQ #define ABSL_TEST_QCHECK_STRNE QCHECK_STRNE #define ABSL_TEST_QCHECK_STRCASEEQ QCHECK_STRCASEEQ #define ABSL_TEST_QCHECK_STRCASENE QCHECK_STRCASENE #include "gtest/gtest.h" #include "absl/log/check_test_impl.inc"
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/check.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/check_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
a51f6477-59f1-4381-9f29-e283489b4514
cpp
abseil/abseil-cpp
vlog_is_on
absl/log/vlog_is_on.h
absl/log/vlog_is_on_test.cc
#ifndef ABSL_LOG_VLOG_IS_ON_H_ #define ABSL_LOG_VLOG_IS_ON_H_ #include "absl/log/absl_vlog_is_on.h" #define VLOG_IS_ON(verbose_level) ABSL_VLOG_IS_ON(verbose_level) #endif
#include "absl/log/vlog_is_on.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/log_severity.h" #include "absl/flags/flag.h" #include "absl/log/flags.h" #include "absl/log/globals.h" #include "absl/log/log.h" #include "absl/log/scoped_mock_log.h" #include "absl/types/optional.h" namespace { using ::testing::_; absl::optional<int> MaxLogVerbosity() { #ifdef ABSL_MAX_VLOG_VERBOSITY return ABSL_MAX_VLOG_VERBOSITY; #else return absl::nullopt; #endif } absl::optional<int> MinLogLevel() { #ifdef ABSL_MIN_LOG_LEVEL return static_cast<int>(ABSL_MIN_LOG_LEVEL); #else return absl::nullopt; #endif } class VLogIsOnTest : public ::testing::Test { protected: void SetUp() override { ResetVLogLevels(); } private: static void ResetVLogLevels() { absl::log_internal::UpdateVModule(""); absl::SetGlobalVLogLevel(0); } }; TEST_F(VLogIsOnTest, GlobalWorksWithoutMaxVerbosityAndMinLogLevel) { if (MaxLogVerbosity().has_value() || MinLogLevel().has_value()) { GTEST_SKIP(); } absl::SetGlobalVLogLevel(3); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "important")); log.StartCapturingLogs(); VLOG(3) << "important"; VLOG(4) << "spam"; } TEST_F(VLogIsOnTest, FileWorksWithoutMaxVerbosityAndMinLogLevel) { if (MaxLogVerbosity().has_value() || MinLogLevel().has_value()) { GTEST_SKIP(); } absl::SetVLogLevel("vlog_is_on_test", 3); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "important")); log.StartCapturingLogs(); VLOG(3) << "important"; VLOG(4) << "spam"; } TEST_F(VLogIsOnTest, PatternWorksWithoutMaxVerbosityAndMinLogLevel) { if (MaxLogVerbosity().has_value() || MinLogLevel().has_value()) { GTEST_SKIP(); } absl::SetVLogLevel("vlog_is_on*", 3); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "important")); log.StartCapturingLogs(); VLOG(3) << "important"; VLOG(4) << "spam"; } TEST_F(VLogIsOnTest, PatternOverridesLessGenericOneWithoutMaxVerbosityAndMinLogLevel) { if (MaxLogVerbosity().has_value() || MinLogLevel().has_value()) { GTEST_SKIP(); } absl::SetVLogLevel("vlog_is_on*", -1); absl::SetVLogLevel("vlog*", 3); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "important")); log.StartCapturingLogs(); VLOG(3) << "important"; VLOG(4) << "spam"; } TEST_F(VLogIsOnTest, PatternDoesNotOverridesMoreGenericOneWithoutMaxVerbosityAndMinLogLevel) { if (MaxLogVerbosity().has_value() || MinLogLevel().has_value()) { GTEST_SKIP(); } absl::SetVLogLevel("vlog*", 3); absl::SetVLogLevel("vlog_is_on_some_other_test*", -1); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "important")); log.StartCapturingLogs(); VLOG(3) << "important"; VLOG(5) << "spam"; } TEST_F(VLogIsOnTest, GlobalDoesNotFilterBelowMaxVerbosity) { if (!MaxLogVerbosity().has_value() || *MaxLogVerbosity() < 2) { GTEST_SKIP(); } absl::SetGlobalVLogLevel(1000); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "asdf")); log.StartCapturingLogs(); VLOG(2) << "asdf"; } TEST_F(VLogIsOnTest, FileDoesNotFilterBelowMaxVerbosity) { if (!MaxLogVerbosity().has_value() || *MaxLogVerbosity() < 2) { GTEST_SKIP(); } absl::SetVLogLevel("vlog_is_on_test", 1000); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "asdf")); log.StartCapturingLogs(); VLOG(2) << "asdf"; } TEST_F(VLogIsOnTest, PatternDoesNotFilterBelowMaxVerbosity) { if (!MaxLogVerbosity().has_value() || *MaxLogVerbosity() < 2) { GTEST_SKIP(); } absl::SetVLogLevel("vlog_is_on*", 1000); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "asdf")); log.StartCapturingLogs(); VLOG(2) << "asdf"; } TEST_F(VLogIsOnTest, GlobalFiltersAboveMaxVerbosity) { if (!MaxLogVerbosity().has_value() || *MaxLogVerbosity() >= 4) { GTEST_SKIP(); } absl::SetGlobalVLogLevel(1000); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); log.StartCapturingLogs(); VLOG(4) << "dfgh"; } TEST_F(VLogIsOnTest, FileFiltersAboveMaxVerbosity) { if (!MaxLogVerbosity().has_value() || *MaxLogVerbosity() >= 4) { GTEST_SKIP(); } absl::SetVLogLevel("vlog_is_on_test", 1000); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); log.StartCapturingLogs(); VLOG(4) << "dfgh"; } TEST_F(VLogIsOnTest, PatternFiltersAboveMaxVerbosity) { if (!MaxLogVerbosity().has_value() || *MaxLogVerbosity() >= 4) { GTEST_SKIP(); } absl::SetVLogLevel("vlog_is_on*", 1000); absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); log.StartCapturingLogs(); VLOG(4) << "dfgh"; } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/vlog_is_on.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/vlog_is_on_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
93c98b2f-f94c-4951-b330-76c929dd1705
cpp
abseil/abseil-cpp
absl_check
absl/log/absl_check.h
absl/log/absl_check_test.cc
#ifndef ABSL_LOG_ABSL_CHECK_H_ #define ABSL_LOG_ABSL_CHECK_H_ #include "absl/log/internal/check_impl.h" #define ABSL_CHECK(condition) \ ABSL_LOG_INTERNAL_CHECK_IMPL((condition), #condition) #define ABSL_QCHECK(condition) \ ABSL_LOG_INTERNAL_QCHECK_IMPL((condition), #condition) #define ABSL_PCHECK(condition) \ ABSL_LOG_INTERNAL_PCHECK_IMPL((condition), #condition) #define ABSL_DCHECK(condition) \ ABSL_LOG_INTERNAL_DCHECK_IMPL((condition), #condition) #define ABSL_CHECK_EQ(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_EQ_IMPL((val1), #val1, (val2), #val2) #define ABSL_CHECK_NE(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_NE_IMPL((val1), #val1, (val2), #val2) #define ABSL_CHECK_LE(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_LE_IMPL((val1), #val1, (val2), #val2) #define ABSL_CHECK_LT(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_LT_IMPL((val1), #val1, (val2), #val2) #define ABSL_CHECK_GE(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_GE_IMPL((val1), #val1, (val2), #val2) #define ABSL_CHECK_GT(val1, val2) \ ABSL_LOG_INTERNAL_CHECK_GT_IMPL((val1), #val1, (val2), #val2) #define ABSL_QCHECK_EQ(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_EQ_IMPL((val1), #val1, (val2), #val2) #define ABSL_QCHECK_NE(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_NE_IMPL((val1), #val1, (val2), #val2) #define ABSL_QCHECK_LE(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_LE_IMPL((val1), #val1, (val2), #val2) #define ABSL_QCHECK_LT(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_LT_IMPL((val1), #val1, (val2), #val2) #define ABSL_QCHECK_GE(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_GE_IMPL((val1), #val1, (val2), #val2) #define ABSL_QCHECK_GT(val1, val2) \ ABSL_LOG_INTERNAL_QCHECK_GT_IMPL((val1), #val1, (val2), #val2) #define ABSL_DCHECK_EQ(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_EQ_IMPL((val1), #val1, (val2), #val2) #define ABSL_DCHECK_NE(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_NE_IMPL((val1), #val1, (val2), #val2) #define ABSL_DCHECK_LE(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_LE_IMPL((val1), #val1, (val2), #val2) #define ABSL_DCHECK_LT(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_LT_IMPL((val1), #val1, (val2), #val2) #define ABSL_DCHECK_GE(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_GE_IMPL((val1), #val1, (val2), #val2) #define ABSL_DCHECK_GT(val1, val2) \ ABSL_LOG_INTERNAL_DCHECK_GT_IMPL((val1), #val1, (val2), #val2) #define ABSL_CHECK_OK(status) ABSL_LOG_INTERNAL_CHECK_OK_IMPL((status), #status) #define ABSL_QCHECK_OK(status) \ ABSL_LOG_INTERNAL_QCHECK_OK_IMPL((status), #status) #define ABSL_DCHECK_OK(status) \ ABSL_LOG_INTERNAL_DCHECK_OK_IMPL((status), #status) #define ABSL_CHECK_STREQ(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STREQ_IMPL((s1), #s1, (s2), #s2) #define ABSL_CHECK_STRNE(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STRNE_IMPL((s1), #s1, (s2), #s2) #define ABSL_CHECK_STRCASEEQ(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STRCASEEQ_IMPL((s1), #s1, (s2), #s2) #define ABSL_CHECK_STRCASENE(s1, s2) \ ABSL_LOG_INTERNAL_CHECK_STRCASENE_IMPL((s1), #s1, (s2), #s2) #define ABSL_QCHECK_STREQ(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STREQ_IMPL((s1), #s1, (s2), #s2) #define ABSL_QCHECK_STRNE(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STRNE_IMPL((s1), #s1, (s2), #s2) #define ABSL_QCHECK_STRCASEEQ(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STRCASEEQ_IMPL((s1), #s1, (s2), #s2) #define ABSL_QCHECK_STRCASENE(s1, s2) \ ABSL_LOG_INTERNAL_QCHECK_STRCASENE_IMPL((s1), #s1, (s2), #s2) #define ABSL_DCHECK_STREQ(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STREQ_IMPL((s1), #s1, (s2), #s2) #define ABSL_DCHECK_STRNE(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STRNE_IMPL((s1), #s1, (s2), #s2) #define ABSL_DCHECK_STRCASEEQ(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STRCASEEQ_IMPL((s1), #s1, (s2), #s2) #define ABSL_DCHECK_STRCASENE(s1, s2) \ ABSL_LOG_INTERNAL_DCHECK_STRCASENE_IMPL((s1), #s1, (s2), #s2) #endif
#include "absl/log/absl_check.h" #define ABSL_TEST_CHECK ABSL_CHECK #define ABSL_TEST_CHECK_OK ABSL_CHECK_OK #define ABSL_TEST_CHECK_EQ ABSL_CHECK_EQ #define ABSL_TEST_CHECK_NE ABSL_CHECK_NE #define ABSL_TEST_CHECK_GE ABSL_CHECK_GE #define ABSL_TEST_CHECK_LE ABSL_CHECK_LE #define ABSL_TEST_CHECK_GT ABSL_CHECK_GT #define ABSL_TEST_CHECK_LT ABSL_CHECK_LT #define ABSL_TEST_CHECK_STREQ ABSL_CHECK_STREQ #define ABSL_TEST_CHECK_STRNE ABSL_CHECK_STRNE #define ABSL_TEST_CHECK_STRCASEEQ ABSL_CHECK_STRCASEEQ #define ABSL_TEST_CHECK_STRCASENE ABSL_CHECK_STRCASENE #define ABSL_TEST_DCHECK ABSL_DCHECK #define ABSL_TEST_DCHECK_OK ABSL_DCHECK_OK #define ABSL_TEST_DCHECK_EQ ABSL_DCHECK_EQ #define ABSL_TEST_DCHECK_NE ABSL_DCHECK_NE #define ABSL_TEST_DCHECK_GE ABSL_DCHECK_GE #define ABSL_TEST_DCHECK_LE ABSL_DCHECK_LE #define ABSL_TEST_DCHECK_GT ABSL_DCHECK_GT #define ABSL_TEST_DCHECK_LT ABSL_DCHECK_LT #define ABSL_TEST_DCHECK_STREQ ABSL_DCHECK_STREQ #define ABSL_TEST_DCHECK_STRNE ABSL_DCHECK_STRNE #define ABSL_TEST_DCHECK_STRCASEEQ ABSL_DCHECK_STRCASEEQ #define ABSL_TEST_DCHECK_STRCASENE ABSL_DCHECK_STRCASENE #define ABSL_TEST_QCHECK ABSL_QCHECK #define ABSL_TEST_QCHECK_OK ABSL_QCHECK_OK #define ABSL_TEST_QCHECK_EQ ABSL_QCHECK_EQ #define ABSL_TEST_QCHECK_NE ABSL_QCHECK_NE #define ABSL_TEST_QCHECK_GE ABSL_QCHECK_GE #define ABSL_TEST_QCHECK_LE ABSL_QCHECK_LE #define ABSL_TEST_QCHECK_GT ABSL_QCHECK_GT #define ABSL_TEST_QCHECK_LT ABSL_QCHECK_LT #define ABSL_TEST_QCHECK_STREQ ABSL_QCHECK_STREQ #define ABSL_TEST_QCHECK_STRNE ABSL_QCHECK_STRNE #define ABSL_TEST_QCHECK_STRCASEEQ ABSL_QCHECK_STRCASEEQ #define ABSL_TEST_QCHECK_STRCASENE ABSL_QCHECK_STRCASENE #include "gtest/gtest.h" #include "absl/log/check_test_impl.inc"
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/absl_check.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/absl_check_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
4e2fd81d-47ea-45e7-a4dd-dcd3075df80d
cpp
abseil/abseil-cpp
poisson_distribution
absl/random/poisson_distribution.h
absl/random/poisson_distribution_test.cc
#ifndef ABSL_RANDOM_POISSON_DISTRIBUTION_H_ #define ABSL_RANDOM_POISSON_DISTRIBUTION_H_ #include <cassert> #include <cmath> #include <istream> #include <limits> #include <ostream> #include <type_traits> #include "absl/random/internal/fast_uniform_bits.h" #include "absl/random/internal/fastmath.h" #include "absl/random/internal/generate_real.h" #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename IntType = int> class poisson_distribution { public: using result_type = IntType; class param_type { public: using distribution_type = poisson_distribution; explicit param_type(double mean = 1.0); double mean() const { return mean_; } friend bool operator==(const param_type& a, const param_type& b) { return a.mean_ == b.mean_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class poisson_distribution; double mean_; double emu_; double lmu_; double s_; double log_k_; int split_; static_assert(random_internal::IsIntegral<IntType>::value, "Class-template absl::poisson_distribution<> must be " "parameterized using an integral type."); }; poisson_distribution() : poisson_distribution(1.0) {} explicit poisson_distribution(double mean) : param_(mean) {} explicit poisson_distribution(const param_type& p) : param_(p) {} void reset() {} template <typename URBG> result_type operator()(URBG& g) { return (*this)(g, param_); } template <typename URBG> result_type operator()(URBG& g, const param_type& p); param_type param() const { return param_; } void param(const param_type& p) { param_ = p; } result_type(min)() const { return 0; } result_type(max)() const { return (std::numeric_limits<result_type>::max)(); } double mean() const { return param_.mean(); } friend bool operator==(const poisson_distribution& a, const poisson_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const poisson_distribution& a, const poisson_distribution& b) { return a.param_ != b.param_; } private: param_type param_; random_internal::FastUniformBits<uint64_t> fast_u64_; }; template <typename IntType> poisson_distribution<IntType>::param_type::param_type(double mean) : mean_(mean), split_(0) { assert(mean >= 0); assert(mean <= static_cast<double>((std::numeric_limits<result_type>::max)())); assert(mean <= 1e10); if (mean_ < 10) { split_ = 1; emu_ = std::exp(-mean_); } else if (mean_ <= 50) { split_ = 1 + static_cast<int>(mean_ / 10.0); emu_ = std::exp(-mean_ / static_cast<double>(split_)); } else { constexpr double k2E = 0.7357588823428846; constexpr double kSA = 0.4494580810294493; lmu_ = std::log(mean_); double a = mean_ + 0.5; s_ = kSA + std::sqrt(k2E * a); const double mode = std::ceil(mean_) - 1; log_k_ = lmu_ * mode - absl::random_internal::StirlingLogFactorial(mode); } } template <typename IntType> template <typename URBG> typename poisson_distribution<IntType>::result_type poisson_distribution<IntType>::operator()( URBG& g, const param_type& p) { using random_internal::GeneratePositiveTag; using random_internal::GenerateRealFromBits; using random_internal::GenerateSignedTag; if (p.split_ != 0) { result_type n = 0; for (int split = p.split_; split > 0; --split) { double r = 1.0; do { r *= GenerateRealFromBits<double, GeneratePositiveTag, true>( fast_u64_(g)); ++n; } while (r > p.emu_); --n; } return n; } const double a = p.mean_ + 0.5; for (;;) { const double u = GenerateRealFromBits<double, GeneratePositiveTag, false>( fast_u64_(g)); const double v = GenerateRealFromBits<double, GenerateSignedTag, false>( fast_u64_(g)); const double x = std::floor(p.s_ * v / u + a); if (x < 0) continue; const double rhs = x * p.lmu_; double s = (x <= 1.0) ? 0.0 : (x == 2.0) ? 0.693147180559945 : absl::random_internal::StirlingLogFactorial(x); const double lhs = 2.0 * std::log(u) + p.log_k_ + s; if (lhs < rhs) { return x > static_cast<double>((max)()) ? (max)() : static_cast<result_type>(x); } } } template <typename CharT, typename Traits, typename IntType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const poisson_distribution<IntType>& x) { auto saver = random_internal::make_ostream_state_saver(os); os.precision(random_internal::stream_precision_helper<double>::kPrecision); os << x.mean(); return os; } template <typename CharT, typename Traits, typename IntType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, poisson_distribution<IntType>& x) { using param_type = typename poisson_distribution<IntType>::param_type; auto saver = random_internal::make_istream_state_saver(is); double mean = random_internal::read_floating_point<double>(is); if (!is.fail()) { x.param(param_type(mean)); } return is; } ABSL_NAMESPACE_END } #endif
#include "absl/random/poisson_distribution.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <iterator> #include <random> #include <sstream> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/container/flat_hash_map.h" #include "absl/log/log.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/strip.h" namespace { using absl::random_internal::kChiSquared; template <typename IntType> class PoissonDistributionInterfaceTest : public ::testing::Test {}; using IntTypes = ::testing::Types<int, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t>; TYPED_TEST_SUITE(PoissonDistributionInterfaceTest, IntTypes); TYPED_TEST(PoissonDistributionInterfaceTest, SerializeTest) { using param_type = typename absl::poisson_distribution<TypeParam>::param_type; const double kMax = std::min(1e10 , static_cast<double>(std::numeric_limits<TypeParam>::max())); const double kParams[] = { 1, std::nextafter(1.0, 0.0), std::nextafter(1.0, 2.0), 1e-8, 1e-4, 0.0000005, 0.2, 0.5, 2, 20, 100, 1e4, 1e8, 1.5e9, 1e20, std::numeric_limits<double>::max(), std::numeric_limits<double>::epsilon(), std::nextafter(std::numeric_limits<double>::min(), 1.0), std::numeric_limits<double>::min(), std::numeric_limits<double>::denorm_min(), std::numeric_limits<double>::min() / 2, std::nextafter(std::numeric_limits<double>::min(), 0.0), }; constexpr int kCount = 1000; absl::InsecureBitGen gen; for (const double m : kParams) { const double mean = std::min(kMax, m); const param_type param(mean); absl::poisson_distribution<TypeParam> before(mean); EXPECT_EQ(before.mean(), param.mean()); { absl::poisson_distribution<TypeParam> via_param(param); EXPECT_EQ(via_param, before); EXPECT_EQ(via_param.param(), before.param()); } auto sample_min = before.max(); auto sample_max = before.min(); for (int i = 0; i < kCount; i++) { auto sample = before(gen); EXPECT_GE(sample, before.min()); EXPECT_LE(sample, before.max()); if (sample > sample_max) sample_max = sample; if (sample < sample_min) sample_min = sample; } LOG(INFO) << "Range {" << param.mean() << "}: " << sample_min << ", " << sample_max; std::stringstream ss; ss << before; absl::poisson_distribution<TypeParam> after(3.8); EXPECT_NE(before.mean(), after.mean()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.mean(), after.mean()) << ss.str() << " " << (ss.good() ? "good " : "") << (ss.bad() ? "bad " : "") << (ss.eof() ? "eof " : "") << (ss.fail() ? "fail " : ""); } } class PoissonModel { public: explicit PoissonModel(double mean) : mean_(mean) {} double mean() const { return mean_; } double variance() const { return mean_; } double stddev() const { return std::sqrt(variance()); } double skew() const { return 1.0 / mean_; } double kurtosis() const { return 3.0 + 1.0 / mean_; } void InitCDF(); struct CDF { size_t index; double pmf; double cdf; }; CDF InverseCDF(double p) { CDF target{0, 0, p}; auto it = std::upper_bound( std::begin(cdf_), std::end(cdf_), target, [](const CDF& a, const CDF& b) { return a.cdf < b.cdf; }); return *it; } void LogCDF() { LOG(INFO) << "CDF (mean = " << mean_ << ")"; for (const auto c : cdf_) { LOG(INFO) << c.index << ": pmf=" << c.pmf << " cdf=" << c.cdf; } } private: const double mean_; std::vector<CDF> cdf_; }; void PoissonModel::InitCDF() { if (!cdf_.empty()) { return; } ABSL_ASSERT(mean_ < 201.0); const size_t max_i = 50 * stddev() + mean(); const double e_neg_mean = std::exp(-mean()); ABSL_ASSERT(e_neg_mean > 0); double d = 1; double last_result = e_neg_mean; double cumulative = e_neg_mean; if (e_neg_mean > 1e-10) { cdf_.push_back({0, e_neg_mean, cumulative}); } for (size_t i = 1; i < max_i; i++) { d *= (mean() / i); double result = e_neg_mean * d; cumulative += result; if (result < 1e-10 && result < last_result && cumulative > 0.999999) { break; } if (result > 1e-7) { cdf_.push_back({i, result, cumulative}); } last_result = result; } ABSL_ASSERT(!cdf_.empty()); } struct ZParam { double mean; double p_fail; int trials; size_t samples; }; class PoissonDistributionZTest : public testing::TestWithParam<ZParam>, public PoissonModel { public: PoissonDistributionZTest() : PoissonModel(GetParam().mean) {} template <typename D> bool SingleZTest(const double p, const size_t samples); absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6}; }; template <typename D> bool PoissonDistributionZTest::SingleZTest(const double p, const size_t samples) { D dis(mean()); absl::flat_hash_map<int32_t, int> buckets; std::vector<double> data; data.reserve(samples); for (int j = 0; j < samples; j++) { const auto x = dis(rng_); buckets[x]++; data.push_back(x); } const auto m = absl::random_internal::ComputeDistributionMoments(data); const double max_err = absl::random_internal::MaxErrorTolerance(p); const double z = absl::random_internal::ZScore(mean(), m); const bool pass = absl::random_internal::Near("z", z, 0.0, max_err); if (!pass) { LOG(INFO) << "p=" << p << " max_err=" << max_err << "\n" " mean=" << m.mean << " vs. " << mean() << "\n" " stddev=" << std::sqrt(m.variance) << " vs. " << stddev() << "\n" " skewness=" << m.skewness << " vs. " << skew() << "\n" " kurtosis=" << m.kurtosis << " vs. " << kurtosis() << "\n" " z=" << z; } return pass; } TEST_P(PoissonDistributionZTest, AbslPoissonDistribution) { const auto& param = GetParam(); const int expected_failures = std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail))); const double p = absl::random_internal::RequiredSuccessProbability( param.p_fail, param.trials); int failures = 0; for (int i = 0; i < param.trials; i++) { failures += SingleZTest<absl::poisson_distribution<int32_t>>(p, param.samples) ? 0 : 1; } EXPECT_LE(failures, expected_failures); } std::vector<ZParam> GetZParams() { return std::vector<ZParam>({ ZParam{0.5, 0.01, 100, 1000}, ZParam{1.0, 0.01, 100, 1000}, ZParam{10.0, 0.01, 100, 5000}, ZParam{20.0, 0.01, 100, 10000}, ZParam{50.0, 0.01, 100, 10000}, ZParam{51.0, 0.01, 100, 10000}, ZParam{200.0, 0.05, 10, 100000}, ZParam{100000.0, 0.05, 10, 1000000}, }); } std::string ZParamName(const ::testing::TestParamInfo<ZParam>& info) { const auto& p = info.param; std::string name = absl::StrCat("mean_", absl::SixDigits(p.mean)); return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}}); } INSTANTIATE_TEST_SUITE_P(All, PoissonDistributionZTest, ::testing::ValuesIn(GetZParams()), ZParamName); class PoissonDistributionChiSquaredTest : public testing::TestWithParam<double>, public PoissonModel { public: PoissonDistributionChiSquaredTest() : PoissonModel(GetParam()) {} template <typename D> double ChiSquaredTestImpl(); private: void InitChiSquaredTest(const double buckets); std::vector<size_t> cutoffs_; std::vector<double> expected_; absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6}; }; void PoissonDistributionChiSquaredTest::InitChiSquaredTest( const double buckets) { if (!cutoffs_.empty() && !expected_.empty()) { return; } InitCDF(); double last_cdf = 0; const double inc = 1.0 / buckets; for (double p = inc; p <= 1.0; p += inc) { auto result = InverseCDF(p); if (!cutoffs_.empty() && cutoffs_.back() == result.index) { continue; } double d = result.cdf - last_cdf; cutoffs_.push_back(result.index); expected_.push_back(d); last_cdf = result.cdf; } cutoffs_.push_back(std::numeric_limits<size_t>::max()); expected_.push_back(std::max(0.0, 1.0 - last_cdf)); } template <typename D> double PoissonDistributionChiSquaredTest::ChiSquaredTestImpl() { const int kSamples = 2000; const int kBuckets = 50; ABSL_ASSERT(mean() <= 200); InitChiSquaredTest(kBuckets); D dis(mean()); std::vector<int32_t> counts(cutoffs_.size(), 0); for (int j = 0; j < kSamples; j++) { const size_t x = dis(rng_); auto it = std::lower_bound(std::begin(cutoffs_), std::end(cutoffs_), x); counts[std::distance(cutoffs_.begin(), it)]++; } std::vector<int32_t> e(expected_.size(), 0); for (int i = 0; i < e.size(); i++) { e[i] = kSamples * expected_[i]; } const int dof = static_cast<int>(counts.size()) - 1; const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98); const double chi_square = absl::random_internal::ChiSquare( std::begin(counts), std::end(counts), std::begin(e), std::end(e)); const double p = absl::random_internal::ChiSquarePValue(chi_square, dof); if (chi_square > threshold) { LogCDF(); LOG(INFO) << "VALUES buckets=" << counts.size() << " samples=" << kSamples; for (size_t i = 0; i < counts.size(); i++) { LOG(INFO) << cutoffs_[i] << ": " << counts[i] << " vs. E=" << e[i]; } LOG(INFO) << kChiSquared << "(data, dof=" << dof << ") = " << chi_square << " (" << p << ")\n" << " vs.\n" << kChiSquared << " @ 0.98 = " << threshold; } return p; } TEST_P(PoissonDistributionChiSquaredTest, AbslPoissonDistribution) { const int kTrials = 20; ASSERT_LE(mean(), 200.0); if (mean() > 200.0) { return; } int failures = 0; for (int i = 0; i < kTrials; i++) { double p_value = ChiSquaredTestImpl<absl::poisson_distribution<int32_t>>(); if (p_value < 0.005) { failures++; } } EXPECT_LE(failures, 4); } INSTANTIATE_TEST_SUITE_P(All, PoissonDistributionChiSquaredTest, ::testing::Values(0.5, 1.0, 2.0, 10.0, 50.0, 51.0, 200.0)); TEST(PoissonDistributionTest, StabilityTest) { using testing::ElementsAre; absl::random_internal::sequence_urbg urbg({ 0x035b0dc7e0a18acfull, 0x06cebe0d2653682eull, 0x0061e9b23861596bull, 0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull, 0x4864f22c059bf29eull, 0x247856d8b862665cull, 0xe46e86e9a1337e10ull, 0xd8c8541f3519b133ull, 0xe75b5162c567b9e4ull, 0xf732e5ded7009c5bull, 0xb170b98353121eacull, 0x1ec2e8986d2362caull, 0x814c8e35fe9a961aull, 0x0c3cd59c9b638a02ull, 0xcb3bb6478a07715cull, 0x1224e62c978bbc7full, 0x671ef2cb04e81f6eull, 0x3c1cbd811eaf1808ull, 0x1bbc23cfa8fac721ull, 0xa4c2cda65e596a51ull, 0xb77216fad37adf91ull, 0x836d794457c08849ull, 0xe083df03475f49d7ull, 0xbc9feb512e6b0d6cull, 0xb12d74fdd718c8c5ull, 0x12ff09653bfbe4caull, 0x8dd03a105bc4ee7eull, 0x5738341045ba0d85ull, 0xf3fd722dc65ad09eull, 0xfa14fd21ea2a5705ull, 0xffe6ea4d6edb0c73ull, 0xD07E9EFE2BF11FB4ull, 0x95DBDA4DAE909198ull, 0xEAAD8E716B93D5A0ull, 0xD08ED1D0AFC725E0ull, 0x8E3C5B2F8E7594B7ull, 0x8FF6E2FBF2122B64ull, 0x8888B812900DF01Cull, 0x4FAD5EA0688FC31Cull, 0xD1CFF191B3A8C1ADull, 0x2F2F2218BE0E1777ull, 0xEA752DFE8B021FA1ull, 0xE5A0CC0FB56F74E8ull, 0x18ACF3D6CE89E299ull, 0xB4A84FE0FD13E0B7ull, 0x7CC43B81D2ADA8D9ull, 0x165FA26680957705ull, 0x93CC7314211A1477ull, 0xE6AD206577B5FA86ull, 0xC75442F5FB9D35CFull, 0xEBCDAF0C7B3E89A0ull, 0xD6411BD3AE1E7E49ull, 0x00250E2D2071B35Eull, 0x226800BB57B8E0AFull, 0x2464369BF009B91Eull, 0x5563911D59DFA6AAull, 0x78C14389D95A537Full, 0x207D5BA202E5B9C5ull, 0x832603766295CFA9ull, 0x11C819684E734A41ull, 0xB3472DCA7B14A94Aull, }); std::vector<int> output(10); { absl::poisson_distribution<int> dist(5); std::generate(std::begin(output), std::end(output), [&] { return dist(urbg); }); } EXPECT_THAT(output, ElementsAre(1, 0, 0, 4, 2, 10, 3, 3, 7, 12)); { urbg.reset(); absl::poisson_distribution<int> dist(25); std::generate(std::begin(output), std::end(output), [&] { return dist(urbg); }); } EXPECT_THAT(output, ElementsAre(9, 35, 18, 10, 35, 18, 10, 35, 18, 10)); { urbg.reset(); absl::poisson_distribution<int> dist(121); std::generate(std::begin(output), std::end(output), [&] { return dist(urbg); }); } EXPECT_THAT(output, ElementsAre(161, 122, 129, 124, 112, 112, 117, 120, 130, 114)); } TEST(PoissonDistributionTest, AlgorithmExpectedValue_1) { absl::random_internal::sequence_urbg urbg({0x8000000000000001ull}); absl::poisson_distribution<int> dist(5); EXPECT_EQ(7, dist(urbg)); } TEST(PoissonDistributionTest, AlgorithmExpectedValue_2) { absl::random_internal::sequence_urbg urbg({0x8000000000000001ull}); absl::poisson_distribution<int> dist(25); EXPECT_EQ(36, dist(urbg)); } TEST(PoissonDistributionTest, AlgorithmExpectedValue_3) { absl::random_internal::sequence_urbg urbg( {0x7fffffffffffffffull, 0x8000000000000000ull}); absl::poisson_distribution<int> dist(121); EXPECT_EQ(121, dist(urbg)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/poisson_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/poisson_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
7e858b4c-c1de-484e-a11b-a26d73efd5ce
cpp
abseil/abseil-cpp
bit_gen_ref
absl/random/bit_gen_ref.h
absl/random/bit_gen_ref_test.cc
#ifndef ABSL_RANDOM_BIT_GEN_REF_H_ #define ABSL_RANDOM_BIT_GEN_REF_H_ #include <limits> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/internal/fast_type_id.h" #include "absl/base/macros.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/distribution_caller.h" #include "absl/random/internal/fast_uniform_bits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename URBG, typename = void, typename = void, typename = void> struct is_urbg : std::false_type {}; template <typename URBG> struct is_urbg< URBG, absl::enable_if_t<std::is_same< typename URBG::result_type, typename std::decay<decltype((URBG::min)())>::type>::value>, absl::enable_if_t<std::is_same< typename URBG::result_type, typename std::decay<decltype((URBG::max)())>::type>::value>, absl::enable_if_t<std::is_same< typename URBG::result_type, typename std::decay<decltype(std::declval<URBG>()())>::type>::value>> : std::true_type {}; template <typename> struct DistributionCaller; class MockHelpers; } class BitGenRef { template <template <class...> class Trait, class AlwaysVoid, class... Args> struct detector : std::false_type {}; template <template <class...> class Trait, class... Args> struct detector<Trait, absl::void_t<Trait<Args...>>, Args...> : std::true_type {}; template <class T> using invoke_mock_t = decltype(std::declval<T*>()->InvokeMock( std::declval<base_internal::FastTypeIdType>(), std::declval<void*>(), std::declval<void*>())); template <typename T> using HasInvokeMock = typename detector<invoke_mock_t, void, T>::type; public: BitGenRef(const BitGenRef&) = default; BitGenRef(BitGenRef&&) = default; BitGenRef& operator=(const BitGenRef&) = default; BitGenRef& operator=(BitGenRef&&) = default; template < typename URBGRef, typename URBG = absl::remove_cvref_t<URBGRef>, typename absl::enable_if_t<(!std::is_same<URBG, BitGenRef>::value && random_internal::is_urbg<URBG>::value && !HasInvokeMock<URBG>::value)>* = nullptr> BitGenRef(URBGRef&& gen ABSL_ATTRIBUTE_LIFETIME_BOUND) : t_erased_gen_ptr_(reinterpret_cast<uintptr_t>(&gen)), mock_call_(NotAMock), generate_impl_fn_(ImplFn<URBG>) {} template <typename URBGRef, typename URBG = absl::remove_cvref_t<URBGRef>, typename absl::enable_if_t<(!std::is_same<URBG, BitGenRef>::value && random_internal::is_urbg<URBG>::value && HasInvokeMock<URBG>::value)>* = nullptr> BitGenRef(URBGRef&& gen ABSL_ATTRIBUTE_LIFETIME_BOUND) : t_erased_gen_ptr_(reinterpret_cast<uintptr_t>(&gen)), mock_call_(&MockCall<URBG>), generate_impl_fn_(ImplFn<URBG>) {} using result_type = uint64_t; static constexpr result_type(min)() { return (std::numeric_limits<result_type>::min)(); } static constexpr result_type(max)() { return (std::numeric_limits<result_type>::max)(); } result_type operator()() { return generate_impl_fn_(t_erased_gen_ptr_); } private: using impl_fn = result_type (*)(uintptr_t); using mock_call_fn = bool (*)(uintptr_t, base_internal::FastTypeIdType, void*, void*); template <typename URBG> static result_type ImplFn(uintptr_t ptr) { absl::random_internal::FastUniformBits<result_type> fast_uniform_bits; return fast_uniform_bits(*reinterpret_cast<URBG*>(ptr)); } template <typename URBG> static bool MockCall(uintptr_t gen_ptr, base_internal::FastTypeIdType type, void* result, void* arg_tuple) { return reinterpret_cast<URBG*>(gen_ptr)->InvokeMock(type, result, arg_tuple); } static bool NotAMock(uintptr_t, base_internal::FastTypeIdType, void*, void*) { return false; } inline bool InvokeMock(base_internal::FastTypeIdType type, void* args_tuple, void* result) { if (mock_call_ == NotAMock) return false; return mock_call_(t_erased_gen_ptr_, type, args_tuple, result); } uintptr_t t_erased_gen_ptr_; mock_call_fn mock_call_; impl_fn generate_impl_fn_; template <typename> friend struct ::absl::random_internal::DistributionCaller; friend class ::absl::random_internal::MockHelpers; }; ABSL_NAMESPACE_END } #endif
#include "absl/random/bit_gen_ref.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/internal/fast_type_id.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" namespace absl { ABSL_NAMESPACE_BEGIN class ConstBitGen { public: using result_type = absl::BitGen::result_type; static constexpr result_type(min)() { return (absl::BitGen::min)(); } static constexpr result_type(max)() { return (absl::BitGen::max)(); } result_type operator()() { return 1; } bool InvokeMock(base_internal::FastTypeIdType index, void*, void* result) { *static_cast<int*>(result) = 42; return true; } }; namespace { int FnTest(absl::BitGenRef gen_ref) { return absl::Uniform(gen_ref, 1, 7); } template <typename T> class BitGenRefTest : public testing::Test {}; using BitGenTypes = ::testing::Types<absl::BitGen, absl::InsecureBitGen, std::mt19937, std::mt19937_64, std::minstd_rand>; TYPED_TEST_SUITE(BitGenRefTest, BitGenTypes); TYPED_TEST(BitGenRefTest, BasicTest) { TypeParam gen; auto x = FnTest(gen); EXPECT_NEAR(x, 4, 3); } TYPED_TEST(BitGenRefTest, Copyable) { TypeParam gen; absl::BitGenRef gen_ref(gen); FnTest(gen_ref); } TEST(BitGenRefTest, PassThroughEquivalence) { absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<uint64_t> output(12); { absl::BitGenRef view(urbg); for (auto& v : output) { v = view(); } } std::vector<uint64_t> expected( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); EXPECT_THAT(output, testing::Eq(expected)); } TEST(BitGenRefTest, MockingBitGenBaseOverrides) { ConstBitGen const_gen; EXPECT_EQ(FnTest(const_gen), 42); absl::BitGenRef gen_ref(const_gen); EXPECT_EQ(FnTest(gen_ref), 42); } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/bit_gen_ref.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/bit_gen_ref_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e0f8c4ea-4899-4862-84f8-9544cc6734b4
cpp
abseil/abseil-cpp
uniform_int_distribution
absl/random/uniform_int_distribution.h
absl/random/uniform_int_distribution_test.cc
#ifndef ABSL_RANDOM_UNIFORM_INT_DISTRIBUTION_H_ #define ABSL_RANDOM_UNIFORM_INT_DISTRIBUTION_H_ #include <cassert> #include <istream> #include <limits> #include <type_traits> #include "absl/base/optimization.h" #include "absl/random/internal/fast_uniform_bits.h" #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/internal/traits.h" #include "absl/random/internal/wide_multiply.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename IntType = int> class uniform_int_distribution { private: using unsigned_type = typename random_internal::make_unsigned_bits<IntType>::type; public: using result_type = IntType; class param_type { public: using distribution_type = uniform_int_distribution; explicit param_type( result_type lo = 0, result_type hi = (std::numeric_limits<result_type>::max)()) : lo_(lo), range_(static_cast<unsigned_type>(hi) - static_cast<unsigned_type>(lo)) { assert(lo <= hi); } result_type a() const { return lo_; } result_type b() const { return static_cast<result_type>(static_cast<unsigned_type>(lo_) + range_); } friend bool operator==(const param_type& a, const param_type& b) { return a.lo_ == b.lo_ && a.range_ == b.range_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class uniform_int_distribution; unsigned_type range() const { return range_; } result_type lo_; unsigned_type range_; static_assert(random_internal::IsIntegral<result_type>::value, "Class-template absl::uniform_int_distribution<> must be " "parameterized using an integral type."); }; uniform_int_distribution() : uniform_int_distribution(0) {} explicit uniform_int_distribution( result_type lo, result_type hi = (std::numeric_limits<result_type>::max)()) : param_(lo, hi) {} explicit uniform_int_distribution(const param_type& param) : param_(param) {} void reset() {} template <typename URBG> result_type operator()(URBG& gen) { return (*this)(gen, param()); } template <typename URBG> result_type operator()( URBG& gen, const param_type& param) { return static_cast<result_type>(param.a() + Generate(gen, param.range())); } result_type a() const { return param_.a(); } result_type b() const { return param_.b(); } param_type param() const { return param_; } void param(const param_type& params) { param_ = params; } result_type(min)() const { return a(); } result_type(max)() const { return b(); } friend bool operator==(const uniform_int_distribution& a, const uniform_int_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const uniform_int_distribution& a, const uniform_int_distribution& b) { return !(a == b); } private: template <typename URBG> unsigned_type Generate(URBG& g, unsigned_type R); param_type param_; }; template <typename CharT, typename Traits, typename IntType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const uniform_int_distribution<IntType>& x) { using stream_type = typename random_internal::stream_format_type<IntType>::type; auto saver = random_internal::make_ostream_state_saver(os); os << static_cast<stream_type>(x.a()) << os.fill() << static_cast<stream_type>(x.b()); return os; } template <typename CharT, typename Traits, typename IntType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, uniform_int_distribution<IntType>& x) { using param_type = typename uniform_int_distribution<IntType>::param_type; using result_type = typename uniform_int_distribution<IntType>::result_type; using stream_type = typename random_internal::stream_format_type<IntType>::type; stream_type a; stream_type b; auto saver = random_internal::make_istream_state_saver(is); is >> a >> b; if (!is.fail()) { x.param( param_type(static_cast<result_type>(a), static_cast<result_type>(b))); } return is; } template <typename IntType> template <typename URBG> typename random_internal::make_unsigned_bits<IntType>::type uniform_int_distribution<IntType>::Generate( URBG& g, typename random_internal::make_unsigned_bits<IntType>::type R) { random_internal::FastUniformBits<unsigned_type> fast_bits; unsigned_type bits = fast_bits(g); const unsigned_type Lim = R + 1; if ((R & Lim) == 0) { return bits & R; } using helper = random_internal::wide_multiply<unsigned_type>; auto product = helper::multiply(bits, Lim); if (ABSL_PREDICT_FALSE(helper::lo(product) < Lim)) { const unsigned_type threshold = ((std::numeric_limits<unsigned_type>::max)() - Lim + 1) % Lim; while (helper::lo(product) < threshold) { bits = fast_bits(g); product = helper::multiply(bits, Lim); } } return helper::hi(product); } ABSL_NAMESPACE_END } #endif
#include "absl/random/uniform_int_distribution.h" #include <cmath> #include <cstdint> #include <iterator> #include <random> #include <sstream> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" namespace { template <typename IntType> class UniformIntDistributionTest : public ::testing::Test {}; using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t>; TYPED_TEST_SUITE(UniformIntDistributionTest, IntTypes); TYPED_TEST(UniformIntDistributionTest, ParamSerializeTest) { using Limits = std::numeric_limits<TypeParam>; using param_type = typename absl::uniform_int_distribution<TypeParam>::param_type; const TypeParam kMin = std::is_unsigned<TypeParam>::value ? 37 : -105; const TypeParam kNegOneOrZero = std::is_unsigned<TypeParam>::value ? 0 : -1; constexpr int kCount = 1000; absl::InsecureBitGen gen; for (const auto& param : { param_type(), param_type(2, 2), param_type(9, 32), param_type(kMin, 115), param_type(kNegOneOrZero, Limits::max()), param_type(Limits::min(), Limits::max()), param_type(Limits::lowest(), Limits::max()), param_type(Limits::min() + 1, Limits::max() - 1), }) { const auto a = param.a(); const auto b = param.b(); absl::uniform_int_distribution<TypeParam> before(a, b); EXPECT_EQ(before.a(), param.a()); EXPECT_EQ(before.b(), param.b()); { absl::uniform_int_distribution<TypeParam> via_param(param); EXPECT_EQ(via_param, before); } std::stringstream ss; ss << before; absl::uniform_int_distribution<TypeParam> after(Limits::min() + 3, Limits::max() - 5); EXPECT_NE(before.a(), after.a()); EXPECT_NE(before.b(), after.b()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.a(), after.a()); EXPECT_EQ(before.b(), after.b()); EXPECT_EQ(before.param(), after.param()); EXPECT_EQ(before, after); auto sample_min = after.max(); auto sample_max = after.min(); for (int i = 0; i < kCount; i++) { auto sample = after(gen); EXPECT_GE(sample, after.min()); EXPECT_LE(sample, after.max()); if (sample > sample_max) { sample_max = sample; } if (sample < sample_min) { sample_min = sample; } } LOG(INFO) << "Range: " << sample_min << ", " << sample_max; } } TYPED_TEST(UniformIntDistributionTest, ViolatesPreconditionsDeathTest) { #if GTEST_HAS_DEATH_TEST EXPECT_DEBUG_DEATH({ absl::uniform_int_distribution<TypeParam> dist(10, 1); }, ""); #endif #if defined(NDEBUG) absl::InsecureBitGen gen; absl::uniform_int_distribution<TypeParam> dist(10, 1); auto x = dist(gen); EXPECT_FALSE(absl::StrCat(+x).empty()) << x; #endif } TYPED_TEST(UniformIntDistributionTest, TestMoments) { constexpr int kSize = 100000; using Limits = std::numeric_limits<TypeParam>; using param_type = typename absl::uniform_int_distribution<TypeParam>::param_type; absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6}; std::vector<double> values(kSize); for (const auto& param : {param_type(0, Limits::max()), param_type(13, 127)}) { absl::uniform_int_distribution<TypeParam> dist(param); for (int i = 0; i < kSize; i++) { const auto sample = dist(rng); ASSERT_LE(dist.param().a(), sample); ASSERT_GE(dist.param().b(), sample); values[i] = sample; } auto moments = absl::random_internal::ComputeDistributionMoments(values); const double a = dist.param().a(); const double b = dist.param().b(); const double n = (b - a + 1); const double mean = (a + b) / 2; const double var = ((b - a + 1) * (b - a + 1) - 1) / 12; const double kurtosis = 3 - 6 * (n * n + 1) / (5 * (n * n - 1)); EXPECT_NEAR(mean, moments.mean, 0.01 * var); EXPECT_NEAR(var, moments.variance, 0.015 * var); EXPECT_NEAR(0.0, moments.skewness, 0.025); EXPECT_NEAR(kurtosis, moments.kurtosis, 0.02 * kurtosis); } } TYPED_TEST(UniformIntDistributionTest, ChiSquaredTest50) { using absl::random_internal::kChiSquared; constexpr size_t kTrials = 1000; constexpr int kBuckets = 50; constexpr double kExpected = static_cast<double>(kTrials) / static_cast<double>(kBuckets); const int kThreshold = absl::random_internal::ChiSquareValue(kBuckets, 0.999999); const TypeParam min = std::is_unsigned<TypeParam>::value ? 37 : -37; const TypeParam max = min + kBuckets; absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6}; absl::uniform_int_distribution<TypeParam> dist(min, max); std::vector<int32_t> counts(kBuckets + 1, 0); for (size_t i = 0; i < kTrials; i++) { auto x = dist(rng); counts[x - min]++; } double chi_square = absl::random_internal::ChiSquareWithExpected( std::begin(counts), std::end(counts), kExpected); if (chi_square > kThreshold) { double p_value = absl::random_internal::ChiSquarePValue(chi_square, kBuckets); std::string msg; for (const auto& a : counts) { absl::StrAppend(&msg, a, "\n"); } absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n"); absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ", kThreshold); LOG(INFO) << msg; FAIL() << msg; } } TEST(UniformIntDistributionTest, StabilityTest) { absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<int> output(12); { absl::uniform_int_distribution<int32_t> dist(0, 4); for (auto& v : output) { v = dist(urbg); } } EXPECT_EQ(12, urbg.invocations()); EXPECT_THAT(output, testing::ElementsAre(4, 4, 3, 2, 1, 0, 1, 4, 3, 1, 3, 1)); { urbg.reset(); absl::uniform_int_distribution<int32_t> dist(0, 100); for (auto& v : output) { v = dist(urbg); } } EXPECT_EQ(12, urbg.invocations()); EXPECT_THAT(output, testing::ElementsAre(97, 86, 75, 41, 36, 16, 38, 92, 67, 30, 80, 38)); { urbg.reset(); absl::uniform_int_distribution<int32_t> dist(0, 10000); for (auto& v : output) { v = dist(urbg); } } EXPECT_EQ(12, urbg.invocations()); EXPECT_THAT(output, testing::ElementsAre(9648, 8562, 7439, 4089, 3571, 1602, 3813, 9195, 6641, 2986, 7956, 3765)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/uniform_int_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/uniform_int_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
27394261-aac9-4dc4-be63-5a2f30536a7e
cpp
abseil/abseil-cpp
distributions
absl/random/distributions.h
absl/random/distributions_test.cc
#ifndef ABSL_RANDOM_DISTRIBUTIONS_H_ #define ABSL_RANDOM_DISTRIBUTIONS_H_ #include <limits> #include <type_traits> #include "absl/base/config.h" #include "absl/base/internal/inline_variable.h" #include "absl/meta/type_traits.h" #include "absl/random/bernoulli_distribution.h" #include "absl/random/beta_distribution.h" #include "absl/random/exponential_distribution.h" #include "absl/random/gaussian_distribution.h" #include "absl/random/internal/distribution_caller.h" #include "absl/random/internal/traits.h" #include "absl/random/internal/uniform_helper.h" #include "absl/random/log_uniform_int_distribution.h" #include "absl/random/poisson_distribution.h" #include "absl/random/uniform_int_distribution.h" #include "absl/random/uniform_real_distribution.h" #include "absl/random/zipf_distribution.h" namespace absl { ABSL_NAMESPACE_BEGIN ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalClosedClosedTag, IntervalClosedClosed, {}); ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalClosedClosedTag, IntervalClosed, {}); ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalClosedOpenTag, IntervalClosedOpen, {}); ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalOpenOpenTag, IntervalOpenOpen, {}); ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalOpenOpenTag, IntervalOpen, {}); ABSL_INTERNAL_INLINE_CONSTEXPR(IntervalOpenClosedTag, IntervalOpenClosed, {}); template <typename R = void, typename TagType, typename URBG> typename absl::enable_if_t<!std::is_same<R, void>::value, R> Uniform(TagType tag, URBG&& urbg, R lo, R hi) { using gen_t = absl::decay_t<URBG>; using distribution_t = random_internal::UniformDistributionWrapper<R>; auto a = random_internal::uniform_lower_bound(tag, lo, hi); auto b = random_internal::uniform_upper_bound(tag, lo, hi); if (!random_internal::is_uniform_range_valid(a, b)) return lo; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, tag, lo, hi); } template <typename R = void, typename URBG> typename absl::enable_if_t<!std::is_same<R, void>::value, R> Uniform(URBG&& urbg, R lo, R hi) { using gen_t = absl::decay_t<URBG>; using distribution_t = random_internal::UniformDistributionWrapper<R>; constexpr auto tag = absl::IntervalClosedOpen; auto a = random_internal::uniform_lower_bound(tag, lo, hi); auto b = random_internal::uniform_upper_bound(tag, lo, hi); if (!random_internal::is_uniform_range_valid(a, b)) return lo; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, lo, hi); } template <typename R = void, typename TagType, typename URBG, typename A, typename B> typename absl::enable_if_t<std::is_same<R, void>::value, random_internal::uniform_inferred_return_t<A, B>> Uniform(TagType tag, URBG&& urbg, A lo, B hi) { using gen_t = absl::decay_t<URBG>; using return_t = typename random_internal::uniform_inferred_return_t<A, B>; using distribution_t = random_internal::UniformDistributionWrapper<return_t>; auto a = random_internal::uniform_lower_bound<return_t>(tag, lo, hi); auto b = random_internal::uniform_upper_bound<return_t>(tag, lo, hi); if (!random_internal::is_uniform_range_valid(a, b)) return lo; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, tag, static_cast<return_t>(lo), static_cast<return_t>(hi)); } template <typename R = void, typename URBG, typename A, typename B> typename absl::enable_if_t<std::is_same<R, void>::value, random_internal::uniform_inferred_return_t<A, B>> Uniform(URBG&& urbg, A lo, B hi) { using gen_t = absl::decay_t<URBG>; using return_t = typename random_internal::uniform_inferred_return_t<A, B>; using distribution_t = random_internal::UniformDistributionWrapper<return_t>; constexpr auto tag = absl::IntervalClosedOpen; auto a = random_internal::uniform_lower_bound<return_t>(tag, lo, hi); auto b = random_internal::uniform_upper_bound<return_t>(tag, lo, hi); if (!random_internal::is_uniform_range_valid(a, b)) return lo; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, static_cast<return_t>(lo), static_cast<return_t>(hi)); } template <typename R, typename URBG> typename absl::enable_if_t<!std::numeric_limits<R>::is_signed, R> Uniform(URBG&& urbg) { using gen_t = absl::decay_t<URBG>; using distribution_t = random_internal::UniformDistributionWrapper<R>; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg); } template <typename URBG> bool Bernoulli(URBG&& urbg, double p) { using gen_t = absl::decay_t<URBG>; using distribution_t = absl::bernoulli_distribution; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, p); } template <typename RealType, typename URBG> RealType Beta(URBG&& urbg, RealType alpha, RealType beta) { static_assert( std::is_floating_point<RealType>::value, "Template-argument 'RealType' must be a floating-point type, in " "absl::Beta<RealType, URBG>(...)"); using gen_t = absl::decay_t<URBG>; using distribution_t = typename absl::beta_distribution<RealType>; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, alpha, beta); } template <typename RealType, typename URBG> RealType Exponential(URBG&& urbg, RealType lambda = 1) { static_assert( std::is_floating_point<RealType>::value, "Template-argument 'RealType' must be a floating-point type, in " "absl::Exponential<RealType, URBG>(...)"); using gen_t = absl::decay_t<URBG>; using distribution_t = typename absl::exponential_distribution<RealType>; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, lambda); } template <typename RealType, typename URBG> RealType Gaussian(URBG&& urbg, RealType mean = 0, RealType stddev = 1) { static_assert( std::is_floating_point<RealType>::value, "Template-argument 'RealType' must be a floating-point type, in " "absl::Gaussian<RealType, URBG>(...)"); using gen_t = absl::decay_t<URBG>; using distribution_t = typename absl::gaussian_distribution<RealType>; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, mean, stddev); } template <typename IntType, typename URBG> IntType LogUniform(URBG&& urbg, IntType lo, IntType hi, IntType base = 2) { static_assert(random_internal::IsIntegral<IntType>::value, "Template-argument 'IntType' must be an integral type, in " "absl::LogUniform<IntType, URBG>(...)"); using gen_t = absl::decay_t<URBG>; using distribution_t = typename absl::log_uniform_int_distribution<IntType>; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, lo, hi, base); } template <typename IntType, typename URBG> IntType Poisson(URBG&& urbg, double mean = 1.0) { static_assert(random_internal::IsIntegral<IntType>::value, "Template-argument 'IntType' must be an integral type, in " "absl::Poisson<IntType, URBG>(...)"); using gen_t = absl::decay_t<URBG>; using distribution_t = typename absl::poisson_distribution<IntType>; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, mean); } template <typename IntType, typename URBG> IntType Zipf(URBG&& urbg, IntType hi = (std::numeric_limits<IntType>::max)(), double q = 2.0, double v = 1.0) { static_assert(random_internal::IsIntegral<IntType>::value, "Template-argument 'IntType' must be an integral type, in " "absl::Zipf<IntType, URBG>(...)"); using gen_t = absl::decay_t<URBG>; using distribution_t = typename absl::zipf_distribution<IntType>; return random_internal::DistributionCaller<gen_t>::template Call< distribution_t>(&urbg, hi, q, v); } ABSL_NAMESPACE_END } #endif
#include "absl/random/distributions.h" #include <cfloat> #include <cmath> #include <cstdint> #include <limits> #include <type_traits> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/meta/type_traits.h" #include "absl/numeric/int128.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/random.h" namespace { constexpr int kSize = 400000; class RandomDistributionsTest : public testing::Test {}; struct Invalid {}; template <typename A, typename B> auto InferredUniformReturnT(int) -> decltype(absl::Uniform(std::declval<absl::InsecureBitGen&>(), std::declval<A>(), std::declval<B>())); template <typename, typename> Invalid InferredUniformReturnT(...); template <typename TagType, typename A, typename B> auto InferredTaggedUniformReturnT(int) -> decltype(absl::Uniform(std::declval<TagType>(), std::declval<absl::InsecureBitGen&>(), std::declval<A>(), std::declval<B>())); template <typename, typename, typename> Invalid InferredTaggedUniformReturnT(...); template <typename A, typename B, typename Expect> void CheckArgsInferType() { static_assert( absl::conjunction< std::is_same<Expect, decltype(InferredUniformReturnT<A, B>(0))>, std::is_same<Expect, decltype(InferredUniformReturnT<B, A>(0))>>::value, ""); static_assert( absl::conjunction< std::is_same<Expect, decltype(InferredTaggedUniformReturnT< absl::IntervalOpenOpenTag, A, B>(0))>, std::is_same<Expect, decltype(InferredTaggedUniformReturnT< absl::IntervalOpenOpenTag, B, A>(0))>>::value, ""); } template <typename A, typename B, typename ExplicitRet> auto ExplicitUniformReturnT(int) -> decltype(absl::Uniform<ExplicitRet>( std::declval<absl::InsecureBitGen&>(), std::declval<A>(), std::declval<B>())); template <typename, typename, typename ExplicitRet> Invalid ExplicitUniformReturnT(...); template <typename TagType, typename A, typename B, typename ExplicitRet> auto ExplicitTaggedUniformReturnT(int) -> decltype(absl::Uniform<ExplicitRet>( std::declval<TagType>(), std::declval<absl::InsecureBitGen&>(), std::declval<A>(), std::declval<B>())); template <typename, typename, typename, typename ExplicitRet> Invalid ExplicitTaggedUniformReturnT(...); template <typename A, typename B, typename Expect> void CheckArgsReturnExpectedType() { static_assert( absl::conjunction< std::is_same<Expect, decltype(ExplicitUniformReturnT<A, B, Expect>(0))>, std::is_same<Expect, decltype(ExplicitUniformReturnT<B, A, Expect>( 0))>>::value, ""); static_assert( absl::conjunction< std::is_same<Expect, decltype(ExplicitTaggedUniformReturnT< absl::IntervalOpenOpenTag, A, B, Expect>(0))>, std::is_same<Expect, decltype(ExplicitTaggedUniformReturnT< absl::IntervalOpenOpenTag, B, A, Expect>(0))>>::value, ""); } template <typename R> auto UniformNoBoundsReturnT(int) -> decltype(absl::Uniform<R>(std::declval<absl::InsecureBitGen&>())); template <typename> Invalid UniformNoBoundsReturnT(...); TEST_F(RandomDistributionsTest, UniformTypeInference) { CheckArgsInferType<uint16_t, uint16_t, uint16_t>(); CheckArgsInferType<uint32_t, uint32_t, uint32_t>(); CheckArgsInferType<uint64_t, uint64_t, uint64_t>(); CheckArgsInferType<int16_t, int16_t, int16_t>(); CheckArgsInferType<int32_t, int32_t, int32_t>(); CheckArgsInferType<int64_t, int64_t, int64_t>(); CheckArgsInferType<float, float, float>(); CheckArgsInferType<double, double, double>(); CheckArgsReturnExpectedType<int16_t, int16_t, int32_t>(); CheckArgsReturnExpectedType<uint16_t, uint16_t, int32_t>(); CheckArgsReturnExpectedType<int16_t, int16_t, int64_t>(); CheckArgsReturnExpectedType<int16_t, int32_t, int64_t>(); CheckArgsReturnExpectedType<int16_t, int32_t, double>(); CheckArgsReturnExpectedType<float, float, double>(); CheckArgsReturnExpectedType<int, int, int16_t>(); CheckArgsInferType<uint16_t, uint32_t, uint32_t>(); CheckArgsInferType<uint16_t, uint64_t, uint64_t>(); CheckArgsInferType<uint16_t, int32_t, int32_t>(); CheckArgsInferType<uint16_t, int64_t, int64_t>(); CheckArgsInferType<uint16_t, float, float>(); CheckArgsInferType<uint16_t, double, double>(); CheckArgsInferType<int16_t, int32_t, int32_t>(); CheckArgsInferType<int16_t, int64_t, int64_t>(); CheckArgsInferType<int16_t, float, float>(); CheckArgsInferType<int16_t, double, double>(); CheckArgsInferType<uint16_t, int16_t, Invalid>(); CheckArgsInferType<int16_t, uint32_t, Invalid>(); CheckArgsInferType<int16_t, uint64_t, Invalid>(); CheckArgsInferType<uint32_t, uint64_t, uint64_t>(); CheckArgsInferType<uint32_t, int64_t, int64_t>(); CheckArgsInferType<uint32_t, double, double>(); CheckArgsInferType<int32_t, int64_t, int64_t>(); CheckArgsInferType<int32_t, double, double>(); CheckArgsInferType<uint32_t, int32_t, Invalid>(); CheckArgsInferType<int32_t, uint64_t, Invalid>(); CheckArgsInferType<int32_t, float, Invalid>(); CheckArgsInferType<uint32_t, float, Invalid>(); CheckArgsInferType<uint64_t, int64_t, Invalid>(); CheckArgsInferType<int64_t, float, Invalid>(); CheckArgsInferType<int64_t, double, Invalid>(); CheckArgsInferType<float, double, double>(); } TEST_F(RandomDistributionsTest, UniformExamples) { absl::InsecureBitGen gen; EXPECT_NE(1, absl::Uniform(gen, static_cast<uint16_t>(0), 1.0f)); EXPECT_NE(1, absl::Uniform(gen, 0, 1.0)); EXPECT_NE(1, absl::Uniform(absl::IntervalOpenOpen, gen, static_cast<uint16_t>(0), 1.0f)); EXPECT_NE(1, absl::Uniform(absl::IntervalOpenOpen, gen, 0, 1.0)); EXPECT_NE(1, absl::Uniform(absl::IntervalOpenOpen, gen, -1, 1.0)); EXPECT_NE(1, absl::Uniform<double>(absl::IntervalOpenOpen, gen, -1, 1)); EXPECT_NE(1, absl::Uniform<float>(absl::IntervalOpenOpen, gen, 0, 1)); EXPECT_NE(1, absl::Uniform<float>(gen, 0, 1)); } TEST_F(RandomDistributionsTest, UniformNoBounds) { absl::InsecureBitGen gen; absl::Uniform<uint8_t>(gen); absl::Uniform<uint16_t>(gen); absl::Uniform<uint32_t>(gen); absl::Uniform<uint64_t>(gen); absl::Uniform<absl::uint128>(gen); testing::StaticAssertTypeEq<uint8_t, decltype(UniformNoBoundsReturnT<uint8_t>(0))>(); testing::StaticAssertTypeEq<uint16_t, decltype(UniformNoBoundsReturnT<uint16_t>(0))>(); testing::StaticAssertTypeEq<uint32_t, decltype(UniformNoBoundsReturnT<uint32_t>(0))>(); testing::StaticAssertTypeEq<uint64_t, decltype(UniformNoBoundsReturnT<uint64_t>(0))>(); testing::StaticAssertTypeEq< absl::uint128, decltype(UniformNoBoundsReturnT<absl::uint128>(0))>(); testing::StaticAssertTypeEq<Invalid, decltype(UniformNoBoundsReturnT<int8_t>(0))>(); testing::StaticAssertTypeEq<Invalid, decltype(UniformNoBoundsReturnT<int16_t>(0))>(); testing::StaticAssertTypeEq<Invalid, decltype(UniformNoBoundsReturnT<int32_t>(0))>(); testing::StaticAssertTypeEq<Invalid, decltype(UniformNoBoundsReturnT<int64_t>(0))>(); testing::StaticAssertTypeEq< Invalid, decltype(UniformNoBoundsReturnT<absl::int128>(0))>(); testing::StaticAssertTypeEq<Invalid, decltype(UniformNoBoundsReturnT<float>(0))>(); testing::StaticAssertTypeEq<Invalid, decltype(UniformNoBoundsReturnT<double>(0))>(); } TEST_F(RandomDistributionsTest, UniformNonsenseRanges) { #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0 GTEST_SKIP() << "Skipping the test because we detected x87 floating-point semantics"; #endif absl::InsecureBitGen gen; EXPECT_EQ(0, absl::Uniform<uint64_t>(gen, 0, 0)); EXPECT_EQ(1, absl::Uniform<uint64_t>(gen, 1, 0)); EXPECT_EQ(0, absl::Uniform<uint64_t>(absl::IntervalOpenOpen, gen, 0, 0)); EXPECT_EQ(1, absl::Uniform<uint64_t>(absl::IntervalOpenOpen, gen, 1, 0)); constexpr auto m = (std::numeric_limits<uint64_t>::max)(); EXPECT_EQ(m, absl::Uniform(gen, m, m)); EXPECT_EQ(m, absl::Uniform(gen, m, m - 1)); EXPECT_EQ(m - 1, absl::Uniform(gen, m - 1, m)); EXPECT_EQ(m, absl::Uniform(absl::IntervalOpenOpen, gen, m, m)); EXPECT_EQ(m, absl::Uniform(absl::IntervalOpenOpen, gen, m, m - 1)); EXPECT_EQ(m - 1, absl::Uniform(absl::IntervalOpenOpen, gen, m - 1, m)); EXPECT_EQ(0, absl::Uniform<int64_t>(gen, 0, 0)); EXPECT_EQ(1, absl::Uniform<int64_t>(gen, 1, 0)); EXPECT_EQ(0, absl::Uniform<int64_t>(absl::IntervalOpenOpen, gen, 0, 0)); EXPECT_EQ(1, absl::Uniform<int64_t>(absl::IntervalOpenOpen, gen, 1, 0)); constexpr auto l = (std::numeric_limits<int64_t>::min)(); constexpr auto r = (std::numeric_limits<int64_t>::max)(); EXPECT_EQ(l, absl::Uniform(gen, l, l)); EXPECT_EQ(r, absl::Uniform(gen, r, r)); EXPECT_EQ(r, absl::Uniform(gen, r, r - 1)); EXPECT_EQ(r - 1, absl::Uniform(gen, r - 1, r)); EXPECT_EQ(l, absl::Uniform(absl::IntervalOpenOpen, gen, l, l)); EXPECT_EQ(r, absl::Uniform(absl::IntervalOpenOpen, gen, r, r)); EXPECT_EQ(r, absl::Uniform(absl::IntervalOpenOpen, gen, r, r - 1)); EXPECT_EQ(r - 1, absl::Uniform(absl::IntervalOpenOpen, gen, r - 1, r)); const double e = std::nextafter(1.0, 2.0); const double f = std::nextafter(1.0, 0.0); const double g = std::numeric_limits<double>::denorm_min(); EXPECT_EQ(1.0, absl::Uniform(gen, 1.0, e)); EXPECT_EQ(1.0, absl::Uniform(gen, 1.0, f)); EXPECT_EQ(0.0, absl::Uniform(gen, 0.0, g)); EXPECT_EQ(e, absl::Uniform(absl::IntervalOpenOpen, gen, 1.0, e)); EXPECT_EQ(f, absl::Uniform(absl::IntervalOpenOpen, gen, 1.0, f)); EXPECT_EQ(g, absl::Uniform(absl::IntervalOpenOpen, gen, 0.0, g)); } TEST_F(RandomDistributionsTest, UniformReal) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Uniform(gen, 0, 1.0); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.5, moments.mean, 0.02); EXPECT_NEAR(1 / 12.0, moments.variance, 0.02); EXPECT_NEAR(0.0, moments.skewness, 0.02); EXPECT_NEAR(9 / 5.0, moments.kurtosis, 0.02); } TEST_F(RandomDistributionsTest, UniformInt) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { const int64_t kMax = 1000000000000ll; int64_t j = absl::Uniform(absl::IntervalClosedClosed, gen, 0, kMax); values[i] = static_cast<double>(j) / static_cast<double>(kMax); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.5, moments.mean, 0.02); EXPECT_NEAR(1 / 12.0, moments.variance, 0.02); EXPECT_NEAR(0.0, moments.skewness, 0.02); EXPECT_NEAR(9 / 5.0, moments.kurtosis, 0.02); } TEST_F(RandomDistributionsTest, Exponential) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Exponential<double>(gen); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(1.0, moments.mean, 0.02); EXPECT_NEAR(1.0, moments.variance, 0.025); EXPECT_NEAR(2.0, moments.skewness, 0.1); EXPECT_LT(5.0, moments.kurtosis); } TEST_F(RandomDistributionsTest, PoissonDefault) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Poisson<int64_t>(gen); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(1.0, moments.mean, 0.02); EXPECT_NEAR(1.0, moments.variance, 0.02); EXPECT_NEAR(1.0, moments.skewness, 0.025); EXPECT_LT(2.0, moments.kurtosis); } TEST_F(RandomDistributionsTest, PoissonLarge) { constexpr double kMean = 100000000.0; std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Poisson<int64_t>(gen, kMean); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(kMean, moments.mean, kMean * 0.015); EXPECT_NEAR(kMean, moments.variance, kMean * 0.015); EXPECT_NEAR(std::sqrt(kMean), moments.skewness, kMean * 0.02); EXPECT_LT(2.0, moments.kurtosis); } TEST_F(RandomDistributionsTest, Bernoulli) { constexpr double kP = 0.5151515151; std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Bernoulli(gen, kP); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(kP, moments.mean, 0.01); } TEST_F(RandomDistributionsTest, Beta) { constexpr double kAlpha = 2.0; constexpr double kBeta = 3.0; std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Beta(gen, kAlpha, kBeta); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.4, moments.mean, 0.01); } TEST_F(RandomDistributionsTest, Zipf) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Zipf<int64_t>(gen, 100); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(6.5944, moments.mean, 2000) << moments; } TEST_F(RandomDistributionsTest, Gaussian) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::Gaussian<double>(gen); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.0, moments.mean, 0.02); EXPECT_NEAR(1.0, moments.variance, 0.04); EXPECT_NEAR(0, moments.skewness, 0.2); EXPECT_NEAR(3.0, moments.kurtosis, 0.5); } TEST_F(RandomDistributionsTest, LogUniform) { std::vector<double> values(kSize); absl::InsecureBitGen gen; for (int i = 0; i < kSize; i++) { values[i] = absl::LogUniform<int64_t>(gen, 0, (1 << 10) - 1); } const double mean = (0 + 1 + 1 + 2 + 3 + 4 + 7 + 8 + 15 + 16 + 31 + 32 + 63 + 64 + 127 + 128 + 255 + 256 + 511 + 512 + 1023) / (2.0 * 11.0); const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(mean, moments.mean, 2) << moments; } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/distributions.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/distributions_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
6d4b58ec-0bbb-4003-9e37-3c759e3179f7
cpp
abseil/abseil-cpp
uniform_real_distribution
absl/random/uniform_real_distribution.h
absl/random/uniform_real_distribution_test.cc
#ifndef ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_ #define ABSL_RANDOM_UNIFORM_REAL_DISTRIBUTION_H_ #include <cassert> #include <cmath> #include <cstdint> #include <istream> #include <limits> #include <type_traits> #include "absl/meta/type_traits.h" #include "absl/random/internal/fast_uniform_bits.h" #include "absl/random/internal/generate_real.h" #include "absl/random/internal/iostream_state_saver.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename RealType = double> class uniform_real_distribution { public: using result_type = RealType; class param_type { public: using distribution_type = uniform_real_distribution; explicit param_type(result_type lo = 0, result_type hi = 1) : lo_(lo), hi_(hi), range_(hi - lo) { assert(lo <= hi); assert(range_ <= (std::numeric_limits<result_type>::max)()); } result_type a() const { return lo_; } result_type b() const { return hi_; } friend bool operator==(const param_type& a, const param_type& b) { return a.lo_ == b.lo_ && a.hi_ == b.hi_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class uniform_real_distribution; result_type lo_, hi_, range_; static_assert(std::is_floating_point<RealType>::value, "Class-template absl::uniform_real_distribution<> must be " "parameterized using a floating-point type."); }; uniform_real_distribution() : uniform_real_distribution(0) {} explicit uniform_real_distribution(result_type lo, result_type hi = 1) : param_(lo, hi) {} explicit uniform_real_distribution(const param_type& param) : param_(param) {} void reset() {} template <typename URBG> result_type operator()(URBG& gen) { return operator()(gen, param_); } template <typename URBG> result_type operator()(URBG& gen, const param_type& p); result_type a() const { return param_.a(); } result_type b() const { return param_.b(); } param_type param() const { return param_; } void param(const param_type& params) { param_ = params; } result_type(min)() const { return a(); } result_type(max)() const { return b(); } friend bool operator==(const uniform_real_distribution& a, const uniform_real_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const uniform_real_distribution& a, const uniform_real_distribution& b) { return a.param_ != b.param_; } private: param_type param_; random_internal::FastUniformBits<uint64_t> fast_u64_; }; template <typename RealType> template <typename URBG> typename uniform_real_distribution<RealType>::result_type uniform_real_distribution<RealType>::operator()( URBG& gen, const param_type& p) { using random_internal::GeneratePositiveTag; using random_internal::GenerateRealFromBits; using real_type = absl::conditional_t<std::is_same<RealType, float>::value, float, double>; while (true) { const result_type sample = GenerateRealFromBits<real_type, GeneratePositiveTag, true>( fast_u64_(gen)); const result_type res = p.a() + (sample * p.range_); if (res < p.b() || p.range_ <= 0 || !std::isfinite(p.range_)) { return res; } } } template <typename CharT, typename Traits, typename RealType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const uniform_real_distribution<RealType>& x) { auto saver = random_internal::make_ostream_state_saver(os); os.precision(random_internal::stream_precision_helper<RealType>::kPrecision); os << x.a() << os.fill() << x.b(); return os; } template <typename CharT, typename Traits, typename RealType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, uniform_real_distribution<RealType>& x) { using param_type = typename uniform_real_distribution<RealType>::param_type; using result_type = typename uniform_real_distribution<RealType>::result_type; auto saver = random_internal::make_istream_state_saver(is); auto a = random_internal::read_floating_point<result_type>(is); if (is.fail()) return is; auto b = random_internal::read_floating_point<result_type>(is); if (!is.fail()) { x.param(param_type(a, b)); } return is; } ABSL_NAMESPACE_END } #endif
#include "absl/random/uniform_real_distribution.h" #include <cfloat> #include <cmath> #include <cstdint> #include <iterator> #include <random> #include <sstream> #include <string> #include <type_traits> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/numeric/internal/representation.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" namespace { template <typename RealType> class UniformRealDistributionTest : public ::testing::Test {}; using RealTypes = std::conditional<absl::numeric_internal::IsDoubleDouble(), ::testing::Types<float, double>, ::testing::Types<float, double, long double>>::type; TYPED_TEST_SUITE(UniformRealDistributionTest, RealTypes); TYPED_TEST(UniformRealDistributionTest, ParamSerializeTest) { #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0 GTEST_SKIP() << "Skipping the test because we detected x87 floating-point semantics"; #endif using DistributionType = absl::uniform_real_distribution<TypeParam>; using real_type = TypeParam; using param_type = typename DistributionType::param_type; constexpr const real_type kMax = std::numeric_limits<real_type>::max(); constexpr const real_type kMin = std::numeric_limits<real_type>::min(); constexpr const real_type kEpsilon = std::numeric_limits<real_type>::epsilon(); constexpr const real_type kLowest = std::numeric_limits<real_type>::lowest(); const real_type kDenormMax = std::nextafter(kMin, real_type{0}); const real_type kOneMinusE = std::nextafter(real_type{1}, real_type{0}); constexpr const real_type kTwo60{1152921504606846976}; constexpr int kCount = 1000; absl::InsecureBitGen gen; for (const auto& param : { param_type(), param_type(real_type{0}, real_type{1}), param_type(real_type(-0.1), real_type(0.1)), param_type(real_type(0.05), real_type(0.12)), param_type(real_type(-0.05), real_type(0.13)), param_type(real_type(-0.05), real_type(-0.02)), param_type(real_type(2.0), real_type(2.0)), param_type(kTwo60, real_type(1152921504606847040)), param_type(kTwo60, real_type(1152921504606847104)), param_type(kTwo60, real_type(1152921504606847232)), param_type(kTwo60, real_type(1152921573326323712)), param_type(kTwo60, real_type(1152921642045800448)), param_type(kTwo60, real_type(1152921779484753920)), param_type(0, kMax), param_type(kLowest, 0), param_type(0, kMin), param_type(0, kEpsilon), param_type(-kEpsilon, kEpsilon), param_type(0, kOneMinusE), param_type(0, kDenormMax), }) { const auto a = param.a(); const auto b = param.b(); DistributionType before(a, b); EXPECT_EQ(before.a(), param.a()); EXPECT_EQ(before.b(), param.b()); { DistributionType via_param(param); EXPECT_EQ(via_param, before); } std::stringstream ss; ss << before; DistributionType after(real_type(1.0), real_type(3.1)); EXPECT_NE(before.a(), after.a()); EXPECT_NE(before.b(), after.b()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.a(), after.a()); EXPECT_EQ(before.b(), after.b()); EXPECT_EQ(before.param(), after.param()); EXPECT_EQ(before, after); auto sample_min = after.max(); auto sample_max = after.min(); for (int i = 0; i < kCount; i++) { auto sample = after(gen); if (after.min() == after.max()) { EXPECT_EQ(sample, after.min()); } else { EXPECT_GE(sample, after.min()); EXPECT_LT(sample, after.max()); } if (sample > sample_max) { sample_max = sample; } if (sample < sample_min) { sample_min = sample; } } if (!std::is_same<real_type, long double>::value) { LOG(INFO) << "Range: " << static_cast<double>(sample_min) << ", " << static_cast<double>(sample_max); } } } #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4756) #endif TYPED_TEST(UniformRealDistributionTest, ViolatesPreconditionsDeathTest) { using DistributionType = absl::uniform_real_distribution<TypeParam>; using real_type = TypeParam; #if GTEST_HAS_DEATH_TEST EXPECT_DEBUG_DEATH({ DistributionType dist(10.0, 1.0); }, ""); EXPECT_DEBUG_DEATH( { DistributionType dist(std::numeric_limits<real_type>::lowest(), std::numeric_limits<real_type>::max()); }, ""); const auto kEpsilon = std::nexttoward( (std::numeric_limits<real_type>::max() - std::nexttoward(std::numeric_limits<real_type>::max(), 0.0)) / 2, std::numeric_limits<real_type>::max()); EXPECT_DEBUG_DEATH( { DistributionType dist(-kEpsilon, std::numeric_limits<real_type>::max()); }, ""); EXPECT_DEBUG_DEATH( { DistributionType dist(std::numeric_limits<real_type>::lowest(), kEpsilon); }, ""); #endif #if defined(NDEBUG) absl::InsecureBitGen gen; { DistributionType dist(10.0, 1.0); auto x = dist(gen); EXPECT_FALSE(std::isnan(x)) << x; } { DistributionType dist(std::numeric_limits<real_type>::lowest(), std::numeric_limits<real_type>::max()); auto x = dist(gen); EXPECT_FALSE(std::isfinite(x)) << x; } #endif } #ifdef _MSC_VER #pragma warning(pop) #endif TYPED_TEST(UniformRealDistributionTest, TestMoments) { using DistributionType = absl::uniform_real_distribution<TypeParam>; constexpr int kSize = 1000000; std::vector<double> values(kSize); absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6}; DistributionType dist; for (int i = 0; i < kSize; i++) { values[i] = dist(rng); } const auto moments = absl::random_internal::ComputeDistributionMoments(values); EXPECT_NEAR(0.5, moments.mean, 0.01); EXPECT_NEAR(1 / 12.0, moments.variance, 0.015); EXPECT_NEAR(0.0, moments.skewness, 0.02); EXPECT_NEAR(9 / 5.0, moments.kurtosis, 0.015); } TYPED_TEST(UniformRealDistributionTest, ChiSquaredTest50) { using DistributionType = absl::uniform_real_distribution<TypeParam>; using param_type = typename DistributionType::param_type; using absl::random_internal::kChiSquared; constexpr size_t kTrials = 100000; constexpr int kBuckets = 50; constexpr double kExpected = static_cast<double>(kTrials) / static_cast<double>(kBuckets); const int kThreshold = absl::random_internal::ChiSquareValue(kBuckets - 1, 0.999999); absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6}; for (const auto& param : {param_type(0, 1), param_type(5, 12), param_type(-5, 13), param_type(-5, -2)}) { const double min_val = param.a(); const double max_val = param.b(); const double factor = kBuckets / (max_val - min_val); std::vector<int32_t> counts(kBuckets, 0); DistributionType dist(param); for (size_t i = 0; i < kTrials; i++) { auto x = dist(rng); auto bucket = static_cast<size_t>((x - min_val) * factor); counts[bucket]++; } double chi_square = absl::random_internal::ChiSquareWithExpected( std::begin(counts), std::end(counts), kExpected); if (chi_square > kThreshold) { double p_value = absl::random_internal::ChiSquarePValue(chi_square, kBuckets); std::string msg; for (const auto& a : counts) { absl::StrAppend(&msg, a, "\n"); } absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n"); absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ", kThreshold); LOG(INFO) << msg; FAIL() << msg; } } } TYPED_TEST(UniformRealDistributionTest, StabilityTest) { using DistributionType = absl::uniform_real_distribution<TypeParam>; using real_type = TypeParam; absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<int> output(12); DistributionType dist; std::generate(std::begin(output), std::end(output), [&] { return static_cast<int>(real_type(1000000) * dist(urbg)); }); EXPECT_THAT( output, testing::ElementsAre(59, 999246, 762494, 395876, 167716, 82545, 925251, 77341, 12527, 708791, 834451, 932808)); } TEST(UniformRealDistributionTest, AlgorithmBounds) { absl::uniform_real_distribution<double> dist; { absl::random_internal::sequence_urbg urbg({0x0000000000000001ull}); double a = dist(urbg); EXPECT_EQ(a, 5.42101086242752217004e-20); } { absl::random_internal::sequence_urbg urbg({0x7fffffffffffffefull}); double a = dist(urbg); EXPECT_EQ(a, 0.499999999999999944489); } { absl::random_internal::sequence_urbg urbg({0x8000000000000000ull}); double a = dist(urbg); EXPECT_EQ(a, 0.5); } { absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFEFull}); double a = dist(urbg); EXPECT_EQ(a, 0.999999999999999888978); } { absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFFFull}); double a = dist(urbg); EXPECT_EQ(a, 0.999999999999999888978); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/uniform_real_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/uniform_real_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
7e1f6c5e-90d3-42ee-80fe-610b0813dc09
cpp
abseil/abseil-cpp
mocking_bit_gen
absl/random/mocking_bit_gen.h
absl/random/mocking_bit_gen_test.cc
#ifndef ABSL_RANDOM_MOCKING_BIT_GEN_H_ #define ABSL_RANDOM_MOCKING_BIT_GEN_H_ #include <memory> #include <tuple> #include <type_traits> #include <utility> #include "gmock/gmock.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/fast_type_id.h" #include "absl/container/flat_hash_map.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/mock_helpers.h" #include "absl/random/random.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN class BitGenRef; namespace random_internal { template <typename> struct DistributionCaller; class MockHelpers; template <bool EnableValidation> class MockingBitGenImpl { public: MockingBitGenImpl() = default; ~MockingBitGenImpl() = default; using result_type = absl::BitGen::result_type; static constexpr result_type(min)() { return (absl::BitGen::min)(); } static constexpr result_type(max)() { return (absl::BitGen::max)(); } result_type operator()() { return gen_(); } private: template <typename ResultT, typename... Args> static auto GetMockFnType(ResultT, std::tuple<Args...>) -> ::testing::MockFunction<ResultT(Args...)>; template <typename MockFnType, typename ValidatorT, typename ResultT, typename Tuple> struct MockFnCaller; template <typename MockFnType, typename ValidatorT, typename ResultT, typename... Args> struct MockFnCaller<MockFnType, ValidatorT, ResultT, std::tuple<Args...>> { MockFnType* fn; inline ResultT operator()(Args... args) { ResultT result = fn->Call(args...); ValidatorT::Validate(result, args...); return result; } }; class FunctionHolder { public: virtual ~FunctionHolder() = default; virtual void Apply( void* args_tuple, void* result) = 0; }; template <typename MockFnType, typename ValidatorT, typename ResultT, typename ArgTupleT> class FunctionHolderImpl final : public FunctionHolder { public: void Apply(void* args_tuple, void* result) final { *static_cast<ResultT*>(result) = absl::apply( MockFnCaller<MockFnType, ValidatorT, ResultT, ArgTupleT>{&mock_fn_}, *static_cast<ArgTupleT*>(args_tuple)); } MockFnType mock_fn_; }; template <typename ResultT, typename ArgTupleT, typename SelfT, typename ValidatorT> auto RegisterMock(SelfT&, base_internal::FastTypeIdType type, ValidatorT) -> decltype(GetMockFnType(std::declval<ResultT>(), std::declval<ArgTupleT>()))& { using ActualValidatorT = std::conditional_t<EnableValidation, ValidatorT, NoOpValidator>; using MockFnType = decltype(GetMockFnType(std::declval<ResultT>(), std::declval<ArgTupleT>())); using WrappedFnType = absl::conditional_t< std::is_same<SelfT, ::testing::NiceMock<MockingBitGenImpl>>::value, ::testing::NiceMock<MockFnType>, absl::conditional_t< std::is_same<SelfT, ::testing::NaggyMock<MockingBitGenImpl>>::value, ::testing::NaggyMock<MockFnType>, absl::conditional_t< std::is_same<SelfT, ::testing::StrictMock<MockingBitGenImpl>>::value, ::testing::StrictMock<MockFnType>, MockFnType>>>; using ImplT = FunctionHolderImpl<WrappedFnType, ActualValidatorT, ResultT, ArgTupleT>; auto& mock = mocks_[type]; if (!mock) { mock = absl::make_unique<ImplT>(); } return static_cast<ImplT*>(mock.get())->mock_fn_; } inline bool InvokeMock(base_internal::FastTypeIdType type, void* args_tuple, void* result) { auto it = mocks_.find(type); if (it == mocks_.end()) return false; it->second->Apply(args_tuple, result); return true; } absl::flat_hash_map<base_internal::FastTypeIdType, std::unique_ptr<FunctionHolder>> mocks_; absl::BitGen gen_; template <typename> friend struct ::absl::random_internal::DistributionCaller; friend class ::absl::BitGenRef; friend class ::absl::random_internal::MockHelpers; }; } using MockingBitGen = random_internal::MockingBitGenImpl<true>; using UnvalidatedMockingBitGen ABSL_DEPRECATED("Use MockingBitGen instead") = random_internal::MockingBitGenImpl<false>; ABSL_NAMESPACE_END } #endif
#include "absl/random/mocking_bit_gen.h" #include <cmath> #include <cstddef> #include <cstdint> #include <iterator> #include <numeric> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "absl/random/bit_gen_ref.h" #include "absl/random/mock_distributions.h" #include "absl/random/random.h" namespace { using ::testing::_; using ::testing::Ne; using ::testing::Return; TEST(BasicMocking, AllDistributionsAreOverridable) { absl::MockingBitGen gen; EXPECT_NE(absl::Uniform<int>(gen, 1, 1000000), 20); EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 1000000)) .WillOnce(Return(20)); EXPECT_EQ(absl::Uniform<int>(gen, 1, 1000000), 20); EXPECT_NE(absl::Uniform<double>(gen, 0.0, 100.0), 5.0); EXPECT_CALL(absl::MockUniform<double>(), Call(gen, 0.0, 100.0)) .WillOnce(Return(5.0)); EXPECT_EQ(absl::Uniform<double>(gen, 0.0, 100.0), 5.0); EXPECT_NE(absl::Exponential<double>(gen, 1.0), 42); EXPECT_CALL(absl::MockExponential<double>(), Call(gen, 1.0)) .WillOnce(Return(42)); EXPECT_EQ(absl::Exponential<double>(gen, 1.0), 42); EXPECT_NE(absl::Poisson<int>(gen, 1.0), 500); EXPECT_CALL(absl::MockPoisson<int>(), Call(gen, 1.0)).WillOnce(Return(500)); EXPECT_EQ(absl::Poisson<int>(gen, 1.0), 500); EXPECT_NE(absl::Bernoulli(gen, 0.000001), true); EXPECT_CALL(absl::MockBernoulli(), Call(gen, 0.000001)) .WillOnce(Return(true)); EXPECT_EQ(absl::Bernoulli(gen, 0.000001), true); EXPECT_NE(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); EXPECT_CALL(absl::MockZipf<int>(), Call(gen, 1000000, 2.0, 1.0)) .WillOnce(Return(1221)); EXPECT_EQ(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); EXPECT_NE(absl::Gaussian<double>(gen, 0.0, 1.0), 0.001); EXPECT_CALL(absl::MockGaussian<double>(), Call(gen, 0.0, 1.0)) .WillOnce(Return(0.001)); EXPECT_EQ(absl::Gaussian<double>(gen, 0.0, 1.0), 0.001); EXPECT_NE(absl::LogUniform<int>(gen, 0, 1000000, 2), 500000); EXPECT_CALL(absl::MockLogUniform<int>(), Call(gen, 0, 1000000, 2)) .WillOnce(Return(500000)); EXPECT_EQ(absl::LogUniform<int>(gen, 0, 1000000, 2), 500000); } TEST(BasicMocking, OnDistribution) { absl::MockingBitGen gen; EXPECT_NE(absl::Uniform<int>(gen, 1, 1000000), 20); ON_CALL(absl::MockUniform<int>(), Call(gen, 1, 1000000)) .WillByDefault(Return(20)); EXPECT_EQ(absl::Uniform<int>(gen, 1, 1000000), 20); EXPECT_NE(absl::Uniform<double>(gen, 0.0, 100.0), 5.0); ON_CALL(absl::MockUniform<double>(), Call(gen, 0.0, 100.0)) .WillByDefault(Return(5.0)); EXPECT_EQ(absl::Uniform<double>(gen, 0.0, 100.0), 5.0); EXPECT_NE(absl::Exponential<double>(gen, 1.0), 42); ON_CALL(absl::MockExponential<double>(), Call(gen, 1.0)) .WillByDefault(Return(42)); EXPECT_EQ(absl::Exponential<double>(gen, 1.0), 42); EXPECT_NE(absl::Poisson<int>(gen, 1.0), 500); ON_CALL(absl::MockPoisson<int>(), Call(gen, 1.0)).WillByDefault(Return(500)); EXPECT_EQ(absl::Poisson<int>(gen, 1.0), 500); EXPECT_NE(absl::Bernoulli(gen, 0.000001), true); ON_CALL(absl::MockBernoulli(), Call(gen, 0.000001)) .WillByDefault(Return(true)); EXPECT_EQ(absl::Bernoulli(gen, 0.000001), true); EXPECT_NE(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); ON_CALL(absl::MockZipf<int>(), Call(gen, 1000000, 2.0, 1.0)) .WillByDefault(Return(1221)); EXPECT_EQ(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); EXPECT_NE(absl::Gaussian<double>(gen, 0.0, 1.0), 0.001); ON_CALL(absl::MockGaussian<double>(), Call(gen, 0.0, 1.0)) .WillByDefault(Return(0.001)); EXPECT_EQ(absl::Gaussian<double>(gen, 0.0, 1.0), 0.001); EXPECT_NE(absl::LogUniform<int>(gen, 0, 1000000, 2), 2040); ON_CALL(absl::MockLogUniform<int>(), Call(gen, 0, 1000000, 2)) .WillByDefault(Return(2040)); EXPECT_EQ(absl::LogUniform<int>(gen, 0, 1000000, 2), 2040); } TEST(BasicMocking, GMockMatchers) { absl::MockingBitGen gen; EXPECT_NE(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); ON_CALL(absl::MockZipf<int>(), Call(gen, 1000000, 2.0, 1.0)) .WillByDefault(Return(1221)); EXPECT_EQ(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); } TEST(BasicMocking, OverridesWithMultipleGMockExpectations) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 10000)) .WillOnce(Return(20)) .WillOnce(Return(40)) .WillOnce(Return(60)); EXPECT_EQ(absl::Uniform(gen, 1, 10000), 20); EXPECT_EQ(absl::Uniform(gen, 1, 10000), 40); EXPECT_EQ(absl::Uniform(gen, 1, 10000), 60); } TEST(BasicMocking, DefaultArgument) { absl::MockingBitGen gen; ON_CALL(absl::MockExponential<double>(), Call(gen, 1.0)) .WillByDefault(Return(200)); EXPECT_EQ(absl::Exponential<double>(gen), 200); EXPECT_EQ(absl::Exponential<double>(gen, 1.0), 200); } TEST(BasicMocking, MultipleGenerators) { auto get_value = [](absl::BitGenRef gen_ref) { return absl::Uniform(gen_ref, 1, 1000000); }; absl::MockingBitGen unmocked_generator; absl::MockingBitGen mocked_with_3; absl::MockingBitGen mocked_with_11; EXPECT_CALL(absl::MockUniform<int>(), Call(mocked_with_3, 1, 1000000)) .WillOnce(Return(3)) .WillRepeatedly(Return(17)); EXPECT_CALL(absl::MockUniform<int>(), Call(mocked_with_11, 1, 1000000)) .WillOnce(Return(11)) .WillRepeatedly(Return(17)); int unmocked_value = get_value(unmocked_generator); EXPECT_NE(unmocked_value, 3); EXPECT_NE(unmocked_value, 11); EXPECT_EQ(get_value(mocked_with_3), 3); EXPECT_EQ(get_value(mocked_with_11), 11); EXPECT_NE(get_value(mocked_with_3), 3); EXPECT_NE(get_value(mocked_with_11), 11); } TEST(BasicMocking, MocksNotTriggeredForIncorrectTypes) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<uint32_t>(), Call(gen)) .WillRepeatedly(Return(42)); bool uint16_always42 = true; for (int i = 0; i < 10000; i++) { EXPECT_EQ(absl::Uniform<uint32_t>(gen), 42); uint16_always42 = uint16_always42 && absl::Uniform<uint16_t>(gen) == 42; } EXPECT_FALSE(uint16_always42); } TEST(BasicMocking, FailsOnUnsatisfiedMocks) { EXPECT_NONFATAL_FAILURE( []() { absl::MockingBitGen gen; EXPECT_CALL(absl::MockExponential<double>(), Call(gen, 1.0)) .WillOnce(Return(3.0)); }(), "unsatisfied and active"); } TEST(OnUniform, RespectsUniformIntervalSemantics) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalClosed, gen, 1, 1000000)) .WillOnce(Return(301)); EXPECT_NE(absl::Uniform(gen, 1, 1000000), 301); EXPECT_EQ(absl::Uniform(absl::IntervalClosed, gen, 1, 1000000), 301); } TEST(OnUniform, RespectsNoArgUnsignedShorthand) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<uint32_t>(), Call(gen)).WillOnce(Return(42)); EXPECT_EQ(absl::Uniform<uint32_t>(gen), 42); } TEST(RepeatedlyModifier, ForceSnakeEyesForManyDice) { auto roll_some_dice = [](absl::BitGenRef gen_ref) { std::vector<int> results(16); for (auto& r : results) { r = absl::Uniform(absl::IntervalClosed, gen_ref, 1, 6); } return results; }; std::vector<int> results; absl::MockingBitGen gen; results = roll_some_dice(gen); EXPECT_LT(std::accumulate(std::begin(results), std::end(results), 0), results.size() * 6); ON_CALL(absl::MockUniform<int>(), Call(absl::IntervalClosed, gen, 1, 6)) .WillByDefault(Return(6)); results = roll_some_dice(gen); EXPECT_EQ(std::accumulate(std::begin(results), std::end(results), 0), results.size() * 6); } TEST(WillOnce, DistinctCounters) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 1000000)) .Times(3) .WillRepeatedly(Return(1)); EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1000001, 2000000)) .Times(3) .WillRepeatedly(Return(1000001)); EXPECT_EQ(absl::Uniform(gen, 1000001, 2000000), 1000001); EXPECT_EQ(absl::Uniform(gen, 1, 1000000), 1); EXPECT_EQ(absl::Uniform(gen, 1000001, 2000000), 1000001); EXPECT_EQ(absl::Uniform(gen, 1, 1000000), 1); EXPECT_EQ(absl::Uniform(gen, 1000001, 2000000), 1000001); EXPECT_EQ(absl::Uniform(gen, 1, 1000000), 1); } TEST(TimesModifier, ModifierSaturatesAndExpires) { EXPECT_NONFATAL_FAILURE( []() { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 0, 1000000)) .Times(3) .WillRepeatedly(Return(15)) .RetiresOnSaturation(); EXPECT_EQ(absl::Uniform(gen, 0, 1000000), 15); EXPECT_EQ(absl::Uniform(gen, 0, 1000000), 15); EXPECT_EQ(absl::Uniform(gen, 0, 1000000), 15); EXPECT_NE(absl::Uniform(gen, 0, 1000000), 15); }(), ""); } TEST(TimesModifier, Times0) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockBernoulli(), Call(gen, 0.0)).Times(0); EXPECT_CALL(absl::MockPoisson<int>(), Call(gen, 1.0)).Times(0); } TEST(AnythingMatcher, MatchesAnyArgument) { using testing::_; { absl::MockingBitGen gen; ON_CALL(absl::MockUniform<int>(), Call(absl::IntervalClosed, gen, _, 1000)) .WillByDefault(Return(11)); ON_CALL(absl::MockUniform<int>(), Call(absl::IntervalClosed, gen, _, Ne(1000))) .WillByDefault(Return(99)); EXPECT_EQ(absl::Uniform(absl::IntervalClosed, gen, 10, 1000000), 99); EXPECT_EQ(absl::Uniform(absl::IntervalClosed, gen, 10, 1000), 11); } { absl::MockingBitGen gen; ON_CALL(absl::MockUniform<int>(), Call(gen, 1, _)) .WillByDefault(Return(25)); ON_CALL(absl::MockUniform<int>(), Call(gen, Ne(1), _)) .WillByDefault(Return(99)); EXPECT_EQ(absl::Uniform(gen, 3, 1000000), 99); EXPECT_EQ(absl::Uniform(gen, 1, 1000000), 25); } { absl::MockingBitGen gen; ON_CALL(absl::MockUniform<int>(), Call(gen, _, _)) .WillByDefault(Return(145)); EXPECT_EQ(absl::Uniform(gen, 1, 1000), 145); EXPECT_EQ(absl::Uniform(gen, 10, 1000), 145); EXPECT_EQ(absl::Uniform(gen, 100, 1000), 145); } } TEST(AnythingMatcher, WithWillByDefault) { using testing::_; absl::MockingBitGen gen; std::vector<int> values = {11, 22, 33, 44, 55, 66, 77, 88, 99, 1010}; ON_CALL(absl::MockUniform<size_t>(), Call(gen, 0, _)) .WillByDefault(Return(0)); for (int i = 0; i < 100; i++) { auto& elem = values[absl::Uniform(gen, 0u, values.size())]; EXPECT_EQ(elem, 11); } } TEST(BasicMocking, WillByDefaultWithArgs) { using testing::_; absl::MockingBitGen gen; ON_CALL(absl::MockPoisson<int>(), Call(gen, _)) .WillByDefault([](double lambda) { return static_cast<int>(std::rint(lambda * 10)); }); EXPECT_EQ(absl::Poisson<int>(gen, 1.7), 17); EXPECT_EQ(absl::Poisson<int>(gen, 0.03), 0); } TEST(MockingBitGen, InSequenceSucceedsInOrder) { absl::MockingBitGen gen; testing::InSequence seq; EXPECT_CALL(absl::MockPoisson<int>(), Call(gen, 1.0)).WillOnce(Return(3)); EXPECT_CALL(absl::MockPoisson<int>(), Call(gen, 2.0)).WillOnce(Return(4)); EXPECT_EQ(absl::Poisson<int>(gen, 1.0), 3); EXPECT_EQ(absl::Poisson<int>(gen, 2.0), 4); } TEST(MockingBitGen, NiceMock) { ::testing::NiceMock<absl::MockingBitGen> gen; ON_CALL(absl::MockUniform<int>(), Call(gen, _, _)).WillByDefault(Return(145)); ON_CALL(absl::MockPoisson<int>(), Call(gen, _)).WillByDefault(Return(3)); EXPECT_EQ(absl::Uniform(gen, 1, 1000), 145); EXPECT_EQ(absl::Uniform(gen, 10, 1000), 145); EXPECT_EQ(absl::Uniform(gen, 100, 1000), 145); } TEST(MockingBitGen, NaggyMock) { ::testing::NaggyMock<absl::MockingBitGen> gen; ON_CALL(absl::MockUniform<int>(), Call(gen, _, _)).WillByDefault(Return(145)); ON_CALL(absl::MockPoisson<int>(), Call(gen, _)).WillByDefault(Return(3)); EXPECT_EQ(absl::Uniform(gen, 1, 1000), 145); } TEST(MockingBitGen, StrictMock_NotEnough) { EXPECT_NONFATAL_FAILURE( []() { ::testing::StrictMock<absl::MockingBitGen> gen; EXPECT_CALL(absl::MockUniform<int>(), Call(gen, _, _)) .WillOnce(Return(145)); }(), "unsatisfied and active"); } TEST(MockingBitGen, StrictMock_TooMany) { ::testing::StrictMock<absl::MockingBitGen> gen; EXPECT_CALL(absl::MockUniform<int>(), Call(gen, _, _)).WillOnce(Return(145)); EXPECT_EQ(absl::Uniform(gen, 1, 1000), 145); EXPECT_NONFATAL_FAILURE( [&]() { EXPECT_EQ(absl::Uniform(gen, 0, 1000), 0); }(), "over-saturated and active"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/mocking_bit_gen.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/mocking_bit_gen_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f924b834-016b-4653-93b1-644440671e27
cpp
abseil/abseil-cpp
bernoulli_distribution
absl/random/bernoulli_distribution.h
absl/random/bernoulli_distribution_test.cc
#ifndef ABSL_RANDOM_BERNOULLI_DISTRIBUTION_H_ #define ABSL_RANDOM_BERNOULLI_DISTRIBUTION_H_ #include <cstdint> #include <istream> #include <limits> #include "absl/base/optimization.h" #include "absl/random/internal/fast_uniform_bits.h" #include "absl/random/internal/iostream_state_saver.h" namespace absl { ABSL_NAMESPACE_BEGIN class bernoulli_distribution { public: using result_type = bool; class param_type { public: using distribution_type = bernoulli_distribution; explicit param_type(double p = 0.5) : prob_(p) { assert(p >= 0.0 && p <= 1.0); } double p() const { return prob_; } friend bool operator==(const param_type& p1, const param_type& p2) { return p1.p() == p2.p(); } friend bool operator!=(const param_type& p1, const param_type& p2) { return p1.p() != p2.p(); } private: double prob_; }; bernoulli_distribution() : bernoulli_distribution(0.5) {} explicit bernoulli_distribution(double p) : param_(p) {} explicit bernoulli_distribution(param_type p) : param_(p) {} void reset() {} template <typename URBG> bool operator()(URBG& g) { return Generate(param_.p(), g); } template <typename URBG> bool operator()(URBG& g, const param_type& param) { return Generate(param.p(), g); } param_type param() const { return param_; } void param(const param_type& param) { param_ = param; } double p() const { return param_.p(); } result_type(min)() const { return false; } result_type(max)() const { return true; } friend bool operator==(const bernoulli_distribution& d1, const bernoulli_distribution& d2) { return d1.param_ == d2.param_; } friend bool operator!=(const bernoulli_distribution& d1, const bernoulli_distribution& d2) { return d1.param_ != d2.param_; } private: static constexpr uint64_t kP32 = static_cast<uint64_t>(1) << 32; template <typename URBG> static bool Generate(double p, URBG& g); param_type param_; }; template <typename CharT, typename Traits> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const bernoulli_distribution& x) { auto saver = random_internal::make_ostream_state_saver(os); os.precision(random_internal::stream_precision_helper<double>::kPrecision); os << x.p(); return os; } template <typename CharT, typename Traits> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, bernoulli_distribution& x) { auto saver = random_internal::make_istream_state_saver(is); auto p = random_internal::read_floating_point<double>(is); if (!is.fail()) { x.param(bernoulli_distribution::param_type(p)); } return is; } template <typename URBG> bool bernoulli_distribution::Generate(double p, URBG& g) { random_internal::FastUniformBits<uint32_t> fast_u32; while (true) { const uint64_t c = static_cast<uint64_t>(static_cast<int64_t>(p * kP32)); const uint32_t v = fast_u32(g); if (ABSL_PREDICT_TRUE(v != c)) return v < c; const double q = static_cast<double>(c) / kP32; const double left = p - q; const double here = left * kP32; if (here == 0) return false; p = here; } } ABSL_NAMESPACE_END } #endif
#include "absl/random/bernoulli_distribution.h" #include <cmath> #include <cstddef> #include <random> #include <sstream> #include <utility> #include "gtest/gtest.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" namespace { class BernoulliTest : public testing::TestWithParam<std::pair<double, size_t>> { }; TEST_P(BernoulliTest, Serialize) { const double d = GetParam().first; absl::bernoulli_distribution before(d); { absl::bernoulli_distribution via_param{ absl::bernoulli_distribution::param_type(d)}; EXPECT_EQ(via_param, before); } std::stringstream ss; ss << before; absl::bernoulli_distribution after(0.6789); EXPECT_NE(before.p(), after.p()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.p(), after.p()); EXPECT_EQ(before.param(), after.param()); EXPECT_EQ(before, after); } TEST_P(BernoulliTest, Accuracy) { const std::pair<double, size_t> para = GetParam(); size_t trials = para.second; double p = para.first; absl::random_internal::pcg64_2018_engine rng(0x2B7E151628AED2A6); size_t yes = 0; absl::bernoulli_distribution dist(p); for (size_t i = 0; i < trials; ++i) { if (dist(rng)) yes++; } const double stddev_p = std::sqrt((p * (1.0 - p)) / trials); const double expected = trials * p; const double stddev = trials * stddev_p; EXPECT_NEAR(yes, expected, 5 * stddev) << "@" << p << ", " << std::abs(static_cast<double>(yes) - expected) / stddev << " stddev"; } INSTANTIATE_TEST_SUITE_P( All, BernoulliTest, ::testing::Values( std::make_pair(0, 30000), std::make_pair(1e-3, 30000000), std::make_pair(0.1, 3000000), std::make_pair(0.5, 3000000), std::make_pair(0.9, 30000000), std::make_pair(0.999, 30000000), std::make_pair(1, 30000), std::make_pair(std::nextafter(1.0, 0.0), 1), std::make_pair(std::numeric_limits<double>::epsilon(), 1), std::make_pair(std::nextafter(std::numeric_limits<double>::min(), 1.0), 1), std::make_pair(std::numeric_limits<double>::min(), 1), std::make_pair( std::numeric_limits<double>::denorm_min(), 1), std::make_pair(std::numeric_limits<double>::min() / 2, 1), std::make_pair(std::nextafter(std::numeric_limits<double>::min(), 0.0), 1))); TEST(BernoulliTest, StabilityTest) { absl::random_internal::sequence_urbg urbg({ 0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull, 0x4864f22c059bf29eull, 0x247856d8b862665cull, 0xe46e86e9a1337e10ull, 0xd8c8541f3519b133ull, 0xe75b5162c567b9e4ull, 0xf732e5ded7009c5bull, 0xb170b98353121eacull, 0x1ec2e8986d2362caull, 0x814c8e35fe9a961aull, 0x0c3cd59c9b638a02ull, 0xcb3bb6478a07715cull, 0x1224e62c978bbc7full, 0x671ef2cb04e81f6eull, 0x3c1cbd811eaf1808ull, 0x1bbc23cfa8fac721ull, 0xa4c2cda65e596a51ull, 0xb77216fad37adf91ull, 0x836d794457c08849ull, 0xe083df03475f49d7ull, 0xbc9feb512e6b0d6cull, 0xb12d74fdd718c8c5ull, 0x12ff09653bfbe4caull, 0x8dd03a105bc4ee7eull, 0x5738341045ba0d85ull, 0xe3fd722dc65ad09eull, 0x5a14fd21ea2a5705ull, 0x14e6ea4d6edb0c73ull, 0x275b0dc7e0a18acfull, 0x36cebe0d2653682eull, 0x0361e9b23861596bull, }); auto generate = [&urbg](absl::bernoulli_distribution& dist) { std::string output; output.reserve(36); urbg.reset(); for (int i = 0; i < 35; i++) { output.append(dist(urbg) ? "1" : "0"); } return output; }; const double kP = 0.0331289862362; { absl::bernoulli_distribution dist(kP); auto v = generate(dist); EXPECT_EQ(35, urbg.invocations()); EXPECT_EQ(v, "00000000000010000000000010000000000") << dist; } { absl::bernoulli_distribution dist(kP * 10.0); auto v = generate(dist); EXPECT_EQ(35, urbg.invocations()); EXPECT_EQ(v, "00000100010010010010000011000011010") << dist; } { absl::bernoulli_distribution dist(kP * 20.0); auto v = generate(dist); EXPECT_EQ(35, urbg.invocations()); EXPECT_EQ(v, "00011110010110110011011111110111011") << dist; } { absl::bernoulli_distribution dist(1.0 - kP); auto v = generate(dist); EXPECT_EQ(35, urbg.invocations()); EXPECT_EQ(v, "11111111111111111111011111111111111") << dist; } } TEST(BernoulliTest, StabilityTest2) { absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); auto generate = [&urbg](absl::bernoulli_distribution& dist) { std::string output; output.reserve(13); urbg.reset(); for (int i = 0; i < 12; i++) { output.append(dist(urbg) ? "1" : "0"); } return output; }; constexpr double b0 = 1.0 / 13.0 / 0.2; constexpr double b1 = 2.0 / 13.0 / 0.2; constexpr double b3 = (5.0 / 13.0 / 0.2) - ((1 - b0) + (1 - b1) + (1 - b1)); { absl::bernoulli_distribution dist(b0); auto v = generate(dist); EXPECT_EQ(12, urbg.invocations()); EXPECT_EQ(v, "000011100101") << dist; } { absl::bernoulli_distribution dist(b1); auto v = generate(dist); EXPECT_EQ(12, urbg.invocations()); EXPECT_EQ(v, "001111101101") << dist; } { absl::bernoulli_distribution dist(b3); auto v = generate(dist); EXPECT_EQ(12, urbg.invocations()); EXPECT_EQ(v, "001111101111") << dist; } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/bernoulli_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/bernoulli_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ad4e9a72-a8db-425a-9ae6-e50292248763
cpp
abseil/abseil-cpp
log_uniform_int_distribution
absl/random/log_uniform_int_distribution.h
absl/random/log_uniform_int_distribution_test.cc
#ifndef ABSL_RANDOM_LOG_UNIFORM_INT_DISTRIBUTION_H_ #define ABSL_RANDOM_LOG_UNIFORM_INT_DISTRIBUTION_H_ #include <algorithm> #include <cassert> #include <cmath> #include <istream> #include <limits> #include <ostream> #include <type_traits> #include "absl/numeric/bits.h" #include "absl/random/internal/fastmath.h" #include "absl/random/internal/generate_real.h" #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/internal/traits.h" #include "absl/random/uniform_int_distribution.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename IntType = int> class log_uniform_int_distribution { private: using unsigned_type = typename random_internal::make_unsigned_bits<IntType>::type; public: using result_type = IntType; class param_type { public: using distribution_type = log_uniform_int_distribution; explicit param_type( result_type min = 0, result_type max = (std::numeric_limits<result_type>::max)(), result_type base = 2) : min_(min), max_(max), base_(base), range_(static_cast<unsigned_type>(max_) - static_cast<unsigned_type>(min_)), log_range_(0) { assert(max_ >= min_); assert(base_ > 1); if (base_ == 2) { log_range_ = (std::min)(random_internal::BitWidth(range()), std::numeric_limits<unsigned_type>::digits); } else { const double inv_log_base = 1.0 / std::log(static_cast<double>(base_)); const double log_range = std::log(static_cast<double>(range()) + 0.5); log_range_ = static_cast<int>(std::ceil(inv_log_base * log_range)); } } result_type(min)() const { return min_; } result_type(max)() const { return max_; } result_type base() const { return base_; } friend bool operator==(const param_type& a, const param_type& b) { return a.min_ == b.min_ && a.max_ == b.max_ && a.base_ == b.base_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class log_uniform_int_distribution; int log_range() const { return log_range_; } unsigned_type range() const { return range_; } result_type min_; result_type max_; result_type base_; unsigned_type range_; int log_range_; static_assert(random_internal::IsIntegral<IntType>::value, "Class-template absl::log_uniform_int_distribution<> must be " "parameterized using an integral type."); }; log_uniform_int_distribution() : log_uniform_int_distribution(0) {} explicit log_uniform_int_distribution( result_type min, result_type max = (std::numeric_limits<result_type>::max)(), result_type base = 2) : param_(min, max, base) {} explicit log_uniform_int_distribution(const param_type& p) : param_(p) {} void reset() {} template <typename URBG> result_type operator()(URBG& g) { return (*this)(g, param_); } template <typename URBG> result_type operator()(URBG& g, const param_type& p) { return static_cast<result_type>((p.min)() + Generate(g, p)); } result_type(min)() const { return (param_.min)(); } result_type(max)() const { return (param_.max)(); } result_type base() const { return param_.base(); } param_type param() const { return param_; } void param(const param_type& p) { param_ = p; } friend bool operator==(const log_uniform_int_distribution& a, const log_uniform_int_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const log_uniform_int_distribution& a, const log_uniform_int_distribution& b) { return a.param_ != b.param_; } private: template <typename URNG> unsigned_type Generate(URNG& g, const param_type& p); param_type param_; }; template <typename IntType> template <typename URBG> typename log_uniform_int_distribution<IntType>::unsigned_type log_uniform_int_distribution<IntType>::Generate( URBG& g, const param_type& p) { const int e = absl::uniform_int_distribution<int>(0, p.log_range())(g); if (e == 0) { return 0; } const int d = e - 1; unsigned_type base_e, top_e; if (p.base() == 2) { base_e = static_cast<unsigned_type>(1) << d; top_e = (e >= std::numeric_limits<unsigned_type>::digits) ? (std::numeric_limits<unsigned_type>::max)() : (static_cast<unsigned_type>(1) << e) - 1; } else { const double r = std::pow(static_cast<double>(p.base()), d); const double s = (r * static_cast<double>(p.base())) - 1.0; base_e = (r > static_cast<double>((std::numeric_limits<unsigned_type>::max)())) ? (std::numeric_limits<unsigned_type>::max)() : static_cast<unsigned_type>(r); top_e = (s > static_cast<double>((std::numeric_limits<unsigned_type>::max)())) ? (std::numeric_limits<unsigned_type>::max)() : static_cast<unsigned_type>(s); } const unsigned_type lo = (base_e >= p.range()) ? p.range() : base_e; const unsigned_type hi = (top_e >= p.range()) ? p.range() : top_e; return absl::uniform_int_distribution<result_type>( static_cast<result_type>(lo), static_cast<result_type>(hi))(g); } template <typename CharT, typename Traits, typename IntType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const log_uniform_int_distribution<IntType>& x) { using stream_type = typename random_internal::stream_format_type<IntType>::type; auto saver = random_internal::make_ostream_state_saver(os); os << static_cast<stream_type>((x.min)()) << os.fill() << static_cast<stream_type>((x.max)()) << os.fill() << static_cast<stream_type>(x.base()); return os; } template <typename CharT, typename Traits, typename IntType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, log_uniform_int_distribution<IntType>& x) { using param_type = typename log_uniform_int_distribution<IntType>::param_type; using result_type = typename log_uniform_int_distribution<IntType>::result_type; using stream_type = typename random_internal::stream_format_type<IntType>::type; stream_type min; stream_type max; stream_type base; auto saver = random_internal::make_istream_state_saver(is); is >> min >> max >> base; if (!is.fail()) { x.param(param_type(static_cast<result_type>(min), static_cast<result_type>(max), static_cast<result_type>(base))); } return is; } ABSL_NAMESPACE_END } #endif
#include "absl/random/log_uniform_int_distribution.h" #include <cstddef> #include <cstdint> #include <iterator> #include <random> #include <sstream> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/strip.h" namespace { template <typename IntType> class LogUniformIntDistributionTypeTest : public ::testing::Test {}; using IntTypes = ::testing::Types<int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t>; TYPED_TEST_SUITE(LogUniformIntDistributionTypeTest, IntTypes); TYPED_TEST(LogUniformIntDistributionTypeTest, SerializeTest) { using param_type = typename absl::log_uniform_int_distribution<TypeParam>::param_type; using Limits = std::numeric_limits<TypeParam>; constexpr int kCount = 1000; absl::InsecureBitGen gen; for (const auto& param : { param_type(0, 1), param_type(0, 2), param_type(0, 2, 10), param_type(9, 32, 4), param_type(1, 101, 10), param_type(1, Limits::max() / 2), param_type(0, Limits::max() - 1), param_type(0, Limits::max(), 2), param_type(0, Limits::max(), 10), param_type(Limits::min(), 0), param_type(Limits::lowest(), Limits::max()), param_type(Limits::min(), Limits::max()), }) { const auto min = param.min(); const auto max = param.max(); const auto base = param.base(); absl::log_uniform_int_distribution<TypeParam> before(min, max, base); EXPECT_EQ(before.min(), param.min()); EXPECT_EQ(before.max(), param.max()); EXPECT_EQ(before.base(), param.base()); { absl::log_uniform_int_distribution<TypeParam> via_param(param); EXPECT_EQ(via_param, before); } std::stringstream ss; ss << before; absl::log_uniform_int_distribution<TypeParam> after(3, 6, 17); EXPECT_NE(before.max(), after.max()); EXPECT_NE(before.base(), after.base()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.min(), after.min()); EXPECT_EQ(before.max(), after.max()); EXPECT_EQ(before.base(), after.base()); EXPECT_EQ(before.param(), after.param()); EXPECT_EQ(before, after); auto sample_min = after.max(); auto sample_max = after.min(); for (int i = 0; i < kCount; i++) { auto sample = after(gen); EXPECT_GE(sample, after.min()); EXPECT_LE(sample, after.max()); if (sample > sample_max) sample_max = sample; if (sample < sample_min) sample_min = sample; } LOG(INFO) << "Range: " << sample_min << ", " << sample_max; } } using log_uniform_i32 = absl::log_uniform_int_distribution<int32_t>; class LogUniformIntChiSquaredTest : public testing::TestWithParam<log_uniform_i32::param_type> { public: double ChiSquaredTestImpl(); absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6}; }; double LogUniformIntChiSquaredTest::ChiSquaredTestImpl() { using absl::random_internal::kChiSquared; const auto& param = GetParam(); const bool is_2 = (param.base() == 2); const double base_log = 1.0 / std::log(param.base()); const auto bucket_index = [base_log, is_2, &param](int32_t x) { uint64_t y = static_cast<uint64_t>(x) - param.min(); return (y == 0) ? 0 : is_2 ? static_cast<int>(1 + std::log2(y)) : static_cast<int>(1 + std::log(y) * base_log); }; const int max_bucket = bucket_index(param.max()); const size_t trials = 15 + (max_bucket + 1) * 10; log_uniform_i32 dist(param); std::vector<int64_t> buckets(max_bucket + 1); for (size_t i = 0; i < trials; ++i) { const auto sample = dist(rng_); ABSL_ASSERT(sample <= dist.max()); ABSL_ASSERT(sample >= dist.min()); int bucket = bucket_index(sample); ABSL_ASSERT(bucket <= max_bucket); ++buckets[bucket]; } const int dof = buckets.size() - 1; const double expected = trials / static_cast<double>(buckets.size()); const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98); double chi_square = absl::random_internal::ChiSquareWithExpected( std::begin(buckets), std::end(buckets), expected); const double p = absl::random_internal::ChiSquarePValue(chi_square, dof); if (chi_square > threshold) { LOG(INFO) << "values"; for (size_t i = 0; i < buckets.size(); i++) { LOG(INFO) << i << ": " << buckets[i]; } LOG(INFO) << "trials=" << trials << "\n" << kChiSquared << "(data, " << dof << ") = " << chi_square << " (" << p << ")\n" << kChiSquared << " @ 0.98 = " << threshold; } return p; } TEST_P(LogUniformIntChiSquaredTest, MultiTest) { const int kTrials = 5; int failures = 0; for (int i = 0; i < kTrials; i++) { double p_value = ChiSquaredTestImpl(); if (p_value < 0.005) { failures++; } } EXPECT_LE(failures, 4); } std::vector<log_uniform_i32::param_type> GenParams() { using Param = log_uniform_i32::param_type; using Limits = std::numeric_limits<int32_t>; return std::vector<Param>{ Param{0, 1, 2}, Param{1, 1, 2}, Param{0, 2, 2}, Param{0, 3, 2}, Param{0, 4, 2}, Param{0, 9, 10}, Param{0, 10, 10}, Param{0, 11, 10}, Param{1, 10, 10}, Param{0, (1 << 8) - 1, 2}, Param{0, (1 << 8), 2}, Param{0, (1 << 30) - 1, 2}, Param{-1000, 1000, 10}, Param{0, Limits::max(), 2}, Param{0, Limits::max(), 3}, Param{0, Limits::max(), 10}, Param{Limits::min(), 0}, Param{Limits::min(), Limits::max(), 2}, }; } std::string ParamName( const ::testing::TestParamInfo<log_uniform_i32::param_type>& info) { const auto& p = info.param; std::string name = absl::StrCat("min_", p.min(), "__max_", p.max(), "__base_", p.base()); return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}}); } INSTANTIATE_TEST_SUITE_P(All, LogUniformIntChiSquaredTest, ::testing::ValuesIn(GenParams()), ParamName); TEST(LogUniformIntDistributionTest, StabilityTest) { using testing::ElementsAre; absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<int> output(6); { absl::log_uniform_int_distribution<int32_t> dist(0, 256); std::generate(std::begin(output), std::end(output), [&] { return dist(urbg); }); EXPECT_THAT(output, ElementsAre(256, 66, 4, 6, 57, 103)); } urbg.reset(); { absl::log_uniform_int_distribution<int32_t> dist(0, 256, 10); std::generate(std::begin(output), std::end(output), [&] { return dist(urbg); }); EXPECT_THAT(output, ElementsAre(8, 4, 0, 0, 0, 69)); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/log_uniform_int_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/log_uniform_int_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
22374c95-74ad-4522-a47e-9eb6cff3e0a9
cpp
abseil/abseil-cpp
mock_distributions
absl/random/mock_distributions.h
absl/random/mock_distributions_test.cc
#ifndef ABSL_RANDOM_MOCK_DISTRIBUTIONS_H_ #define ABSL_RANDOM_MOCK_DISTRIBUTIONS_H_ #include "absl/base/config.h" #include "absl/random/bernoulli_distribution.h" #include "absl/random/beta_distribution.h" #include "absl/random/distributions.h" #include "absl/random/exponential_distribution.h" #include "absl/random/gaussian_distribution.h" #include "absl/random/internal/mock_overload_set.h" #include "absl/random/internal/mock_validators.h" #include "absl/random/log_uniform_int_distribution.h" #include "absl/random/mocking_bit_gen.h" #include "absl/random/poisson_distribution.h" #include "absl/random/zipf_distribution.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename R> using MockUniform = random_internal::MockOverloadSetWithValidator< random_internal::UniformDistributionWrapper<R>, random_internal::UniformDistributionValidator<R>, R(IntervalClosedOpenTag, MockingBitGen&, R, R), R(IntervalClosedClosedTag, MockingBitGen&, R, R), R(IntervalOpenOpenTag, MockingBitGen&, R, R), R(IntervalOpenClosedTag, MockingBitGen&, R, R), R(MockingBitGen&, R, R), R(MockingBitGen&)>; using MockBernoulli = random_internal::MockOverloadSet<absl::bernoulli_distribution, bool(MockingBitGen&, double)>; template <typename RealType> using MockBeta = random_internal::MockOverloadSet<absl::beta_distribution<RealType>, RealType(MockingBitGen&, RealType, RealType)>; template <typename RealType> using MockExponential = random_internal::MockOverloadSet<absl::exponential_distribution<RealType>, RealType(MockingBitGen&, RealType)>; template <typename RealType> using MockGaussian = random_internal::MockOverloadSet<absl::gaussian_distribution<RealType>, RealType(MockingBitGen&, RealType, RealType)>; template <typename IntType> using MockLogUniform = random_internal::MockOverloadSet< absl::log_uniform_int_distribution<IntType>, IntType(MockingBitGen&, IntType, IntType, IntType)>; template <typename IntType> using MockPoisson = random_internal::MockOverloadSet<absl::poisson_distribution<IntType>, IntType(MockingBitGen&, double)>; template <typename IntType> using MockZipf = random_internal::MockOverloadSet<absl::zipf_distribution<IntType>, IntType(MockingBitGen&, IntType, double, double)>; ABSL_NAMESPACE_END } #endif
#include "absl/random/mock_distributions.h" #include <cmath> #include <limits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/numeric/int128.h" #include "absl/random/distributions.h" #include "absl/random/mocking_bit_gen.h" #include "absl/random/random.h" namespace { using ::testing::Return; TEST(MockDistributions, Examples) { absl::MockingBitGen gen; EXPECT_NE(absl::Uniform<int>(gen, 1, 1000000), 20); EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 1000000)) .WillOnce(Return(20)); EXPECT_EQ(absl::Uniform<int>(gen, 1, 1000000), 20); EXPECT_NE(absl::Uniform<double>(gen, 0.0, 100.0), 5.0); EXPECT_CALL(absl::MockUniform<double>(), Call(gen, 0.0, 100.0)) .WillOnce(Return(5.0)); EXPECT_EQ(absl::Uniform<double>(gen, 0.0, 100.0), 5.0); EXPECT_NE(absl::Exponential<double>(gen, 1.0), 42); EXPECT_CALL(absl::MockExponential<double>(), Call(gen, 1.0)) .WillOnce(Return(42)); EXPECT_EQ(absl::Exponential<double>(gen, 1.0), 42); EXPECT_NE(absl::Poisson<int>(gen, 1.0), 500); EXPECT_CALL(absl::MockPoisson<int>(), Call(gen, 1.0)).WillOnce(Return(500)); EXPECT_EQ(absl::Poisson<int>(gen, 1.0), 500); EXPECT_NE(absl::Bernoulli(gen, 0.000001), true); EXPECT_CALL(absl::MockBernoulli(), Call(gen, 0.000001)) .WillOnce(Return(true)); EXPECT_EQ(absl::Bernoulli(gen, 0.000001), true); EXPECT_NE(absl::Beta<double>(gen, 3.0, 2.0), 0.567); EXPECT_CALL(absl::MockBeta<double>(), Call(gen, 3.0, 2.0)) .WillOnce(Return(0.567)); EXPECT_EQ(absl::Beta<double>(gen, 3.0, 2.0), 0.567); EXPECT_NE(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); EXPECT_CALL(absl::MockZipf<int>(), Call(gen, 1000000, 2.0, 1.0)) .WillOnce(Return(1221)); EXPECT_EQ(absl::Zipf<int>(gen, 1000000, 2.0, 1.0), 1221); EXPECT_NE(absl::Gaussian<double>(gen, 0.0, 1.0), 0.001); EXPECT_CALL(absl::MockGaussian<double>(), Call(gen, 0.0, 1.0)) .WillOnce(Return(0.001)); EXPECT_EQ(absl::Gaussian<double>(gen, 0.0, 1.0), 0.001); EXPECT_NE(absl::LogUniform<int>(gen, 0, 1000000, 2), 2040); EXPECT_CALL(absl::MockLogUniform<int>(), Call(gen, 0, 1000000, 2)) .WillOnce(Return(2040)); EXPECT_EQ(absl::LogUniform<int>(gen, 0, 1000000, 2), 2040); } TEST(MockUniform, OutOfBoundsIsAllowed) { absl::UnvalidatedMockingBitGen gen; EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 100)).WillOnce(Return(0)); EXPECT_EQ(absl::Uniform<int>(gen, 1, 100), 0); } TEST(ValidatedMockDistributions, UniformUInt128Works) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<absl::uint128>(), Call(gen)) .WillOnce(Return(absl::Uint128Max())); EXPECT_EQ(absl::Uniform<absl::uint128>(gen), absl::Uint128Max()); } TEST(ValidatedMockDistributions, UniformDoubleBoundaryCases) { absl::MockingBitGen gen; EXPECT_CALL(absl::MockUniform<double>(), Call(gen, 1.0, 10.0)) .WillOnce(Return( std::nextafter(10.0, -std::numeric_limits<double>::infinity()))); EXPECT_EQ(absl::Uniform<double>(gen, 1.0, 10.0), std::nextafter(10.0, -std::numeric_limits<double>::infinity())); EXPECT_CALL(absl::MockUniform<double>(), Call(absl::IntervalOpen, gen, 1.0, 10.0)) .WillOnce(Return( std::nextafter(10.0, -std::numeric_limits<double>::infinity()))); EXPECT_EQ(absl::Uniform<double>(absl::IntervalOpen, gen, 1.0, 10.0), std::nextafter(10.0, -std::numeric_limits<double>::infinity())); EXPECT_CALL(absl::MockUniform<double>(), Call(absl::IntervalOpen, gen, 1.0, 10.0)) .WillOnce( Return(std::nextafter(1.0, std::numeric_limits<double>::infinity()))); EXPECT_EQ(absl::Uniform<double>(absl::IntervalOpen, gen, 1.0, 10.0), std::nextafter(1.0, std::numeric_limits<double>::infinity())); } TEST(ValidatedMockDistributions, UniformDoubleEmptyRangeCases) { absl::MockingBitGen gen; ON_CALL(absl::MockUniform<double>(), Call(absl::IntervalOpen, gen, 1.0, 1.0)) .WillByDefault(Return(1.0)); EXPECT_EQ(absl::Uniform<double>(absl::IntervalOpen, gen, 1.0, 1.0), 1.0); ON_CALL(absl::MockUniform<double>(), Call(absl::IntervalOpenClosed, gen, 1.0, 1.0)) .WillByDefault(Return(1.0)); EXPECT_EQ(absl::Uniform<double>(absl::IntervalOpenClosed, gen, 1.0, 1.0), 1.0); ON_CALL(absl::MockUniform<double>(), Call(absl::IntervalClosedOpen, gen, 1.0, 1.0)) .WillByDefault(Return(1.0)); EXPECT_EQ(absl::Uniform<double>(absl::IntervalClosedOpen, gen, 1.0, 1.0), 1.0); } TEST(ValidatedMockDistributions, UniformIntEmptyRangeCases) { absl::MockingBitGen gen; ON_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpen, gen, 1, 1)) .WillByDefault(Return(1)); EXPECT_EQ(absl::Uniform<int>(absl::IntervalOpen, gen, 1, 1), 1); ON_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpenClosed, gen, 1, 1)) .WillByDefault(Return(1)); EXPECT_EQ(absl::Uniform<int>(absl::IntervalOpenClosed, gen, 1, 1), 1); ON_CALL(absl::MockUniform<int>(), Call(absl::IntervalClosedOpen, gen, 1, 1)) .WillByDefault(Return(1)); EXPECT_EQ(absl::Uniform<int>(absl::IntervalClosedOpen, gen, 1, 1), 1); } TEST(ValidatedMockUniformDeathTest, Examples) { absl::MockingBitGen gen; EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 100)) .WillOnce(Return(0)); absl::Uniform<int>(gen, 1, 100); }, " 0 is not in \\[1, 100\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 100)) .WillOnce(Return(101)); absl::Uniform<int>(gen, 1, 100); }, " 101 is not in \\[1, 100\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(gen, 1, 100)) .WillOnce(Return(100)); absl::Uniform<int>(gen, 1, 100); }, " 100 is not in \\[1, 100\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpen, gen, 1, 100)) .WillOnce(Return(1)); absl::Uniform<int>(absl::IntervalOpen, gen, 1, 100); }, " 1 is not in \\(1, 100\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpen, gen, 1, 100)) .WillOnce(Return(101)); absl::Uniform<int>(absl::IntervalOpen, gen, 1, 100); }, " 101 is not in \\(1, 100\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpen, gen, 1, 100)) .WillOnce(Return(100)); absl::Uniform<int>(absl::IntervalOpen, gen, 1, 100); }, " 100 is not in \\(1, 100\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpenClosed, gen, 1, 100)) .WillOnce(Return(1)); absl::Uniform<int>(absl::IntervalOpenClosed, gen, 1, 100); }, " 1 is not in \\(1, 100\\]"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpenClosed, gen, 1, 100)) .WillOnce(Return(101)); absl::Uniform<int>(absl::IntervalOpenClosed, gen, 1, 100); }, " 101 is not in \\(1, 100\\]"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpenClosed, gen, 1, 100)) .WillOnce(Return(0)); absl::Uniform<int>(absl::IntervalOpenClosed, gen, 1, 100); }, " 0 is not in \\(1, 100\\]"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalOpenClosed, gen, 1, 100)) .WillOnce(Return(101)); absl::Uniform<int>(absl::IntervalOpenClosed, gen, 1, 100); }, " 101 is not in \\(1, 100\\]"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalClosed, gen, 1, 100)) .WillOnce(Return(0)); absl::Uniform<int>(absl::IntervalClosed, gen, 1, 100); }, " 0 is not in \\[1, 100\\]"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<int>(), Call(absl::IntervalClosed, gen, 1, 100)) .WillOnce(Return(101)); absl::Uniform<int>(absl::IntervalClosed, gen, 1, 100); }, " 101 is not in \\[1, 100\\]"); } TEST(ValidatedMockUniformDeathTest, DoubleBoundaryCases) { absl::MockingBitGen gen; EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<double>(), Call(gen, 1.0, 10.0)) .WillOnce(Return(10.0)); EXPECT_EQ(absl::Uniform<double>(gen, 1.0, 10.0), 10.0); }, " 10 is not in \\[1, 10\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<double>(), Call(absl::IntervalOpen, gen, 1.0, 10.0)) .WillOnce(Return(10.0)); EXPECT_EQ(absl::Uniform<double>(absl::IntervalOpen, gen, 1.0, 10.0), 10.0); }, " 10 is not in \\(1, 10\\)"); EXPECT_DEATH_IF_SUPPORTED( { EXPECT_CALL(absl::MockUniform<double>(), Call(absl::IntervalOpen, gen, 1.0, 10.0)) .WillOnce(Return(1.0)); EXPECT_EQ(absl::Uniform<double>(absl::IntervalOpen, gen, 1.0, 10.0), 1.0); }, " 1 is not in \\(1, 10\\)"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/mock_distributions.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/mock_distributions_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
26eccd9e-9633-4d68-9b75-cb9b02e992db
cpp
abseil/abseil-cpp
beta_distribution
absl/random/beta_distribution.h
absl/random/beta_distribution_test.cc
#ifndef ABSL_RANDOM_BETA_DISTRIBUTION_H_ #define ABSL_RANDOM_BETA_DISTRIBUTION_H_ #include <cassert> #include <cmath> #include <istream> #include <limits> #include <ostream> #include <type_traits> #include "absl/meta/type_traits.h" #include "absl/random/internal/fast_uniform_bits.h" #include "absl/random/internal/fastmath.h" #include "absl/random/internal/generate_real.h" #include "absl/random/internal/iostream_state_saver.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename RealType = double> class beta_distribution { public: using result_type = RealType; class param_type { public: using distribution_type = beta_distribution; explicit param_type(result_type alpha, result_type beta) : alpha_(alpha), beta_(beta) { assert(alpha >= 0); assert(beta >= 0); assert(alpha <= (std::numeric_limits<result_type>::max)()); assert(beta <= (std::numeric_limits<result_type>::max)()); if (alpha == 0 || beta == 0) { method_ = DEGENERATE_SMALL; x_ = (alpha >= beta) ? 1 : 0; return; } if (beta < alpha) { inverted_ = true; a_ = beta; b_ = alpha; } else { inverted_ = false; a_ = alpha; b_ = beta; } if (a_ <= 1 && b_ >= ThresholdForLargeA()) { method_ = DEGENERATE_SMALL; x_ = inverted_ ? result_type(1) : result_type(0); return; } if ((b_ < 1.0 && a_ + b_ <= 1.2) || a_ <= ThresholdForSmallA()) { method_ = JOEHNK; a_ = result_type(1) / alpha_; b_ = result_type(1) / beta_; if (std::isinf(a_) || std::isinf(b_)) { method_ = DEGENERATE_SMALL; x_ = inverted_ ? result_type(1) : result_type(0); } return; } if (a_ >= ThresholdForLargeA()) { method_ = DEGENERATE_LARGE; result_type r = a_ / b_; x_ = (inverted_ ? result_type(1) : r) / (1 + r); return; } x_ = a_ + b_; log_x_ = std::log(x_); if (a_ <= 1) { method_ = CHENG_BA; y_ = result_type(1) / a_; gamma_ = a_ + a_; return; } method_ = CHENG_BB; result_type r = (a_ - 1) / (b_ - 1); y_ = std::sqrt((1 + r) / (b_ * r * 2 - r + 1)); gamma_ = a_ + result_type(1) / y_; } result_type alpha() const { return alpha_; } result_type beta() const { return beta_; } friend bool operator==(const param_type& a, const param_type& b) { return a.alpha_ == b.alpha_ && a.beta_ == b.beta_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class beta_distribution; #ifdef _MSC_VER #define ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR #else #define ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR constexpr #endif static ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR result_type ThresholdForSmallA() { return result_type(1) / std::log((std::numeric_limits<result_type>::max)()); } static ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR result_type ThresholdForLargeA() { return std::exp( std::log((std::numeric_limits<result_type>::max)()) - std::log(std::log((std::numeric_limits<result_type>::max)())) - ThresholdPadding()); } #undef ABSL_RANDOM_INTERNAL_LOG_EXP_CONSTEXPR static constexpr result_type ThresholdPadding() { return 0; } enum Method { JOEHNK, CHENG_BA, CHENG_BB, DEGENERATE_SMALL, DEGENERATE_LARGE, }; result_type alpha_; result_type beta_; result_type a_{}; result_type b_{}; result_type x_{}; result_type log_x_{}; result_type y_{}; result_type gamma_{}; Method method_{}; bool inverted_{}; static_assert(std::is_floating_point<RealType>::value, "Class-template absl::beta_distribution<> must be " "parameterized using a floating-point type."); }; beta_distribution() : beta_distribution(1) {} explicit beta_distribution(result_type alpha, result_type beta = 1) : param_(alpha, beta) {} explicit beta_distribution(const param_type& p) : param_(p) {} void reset() {} template <typename URBG> result_type operator()(URBG& g) { return (*this)(g, param_); } template <typename URBG> result_type operator()(URBG& g, const param_type& p); param_type param() const { return param_; } void param(const param_type& p) { param_ = p; } result_type(min)() const { return 0; } result_type(max)() const { return 1; } result_type alpha() const { return param_.alpha(); } result_type beta() const { return param_.beta(); } friend bool operator==(const beta_distribution& a, const beta_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const beta_distribution& a, const beta_distribution& b) { return a.param_ != b.param_; } private: template <typename URBG> result_type AlgorithmJoehnk(URBG& g, const param_type& p); template <typename URBG> result_type AlgorithmCheng(URBG& g, const param_type& p); template <typename URBG> result_type DegenerateCase(URBG& g, const param_type& p) { if (p.method_ == param_type::DEGENERATE_SMALL && p.alpha_ == p.beta_) { random_internal::FastUniformBits<uint8_t> fast_u8; return static_cast<result_type>((fast_u8(g) & 0x10) != 0); } return p.x_; } param_type param_; random_internal::FastUniformBits<uint64_t> fast_u64_; }; #if defined(__powerpc64__) || defined(__PPC64__) || defined(__powerpc__) || \ defined(__ppc__) || defined(__PPC__) template <> constexpr long double beta_distribution<long double>::param_type::ThresholdPadding() { return 10; } #endif template <typename RealType> template <typename URBG> typename beta_distribution<RealType>::result_type beta_distribution<RealType>::AlgorithmJoehnk( URBG& g, const param_type& p) { using random_internal::GeneratePositiveTag; using random_internal::GenerateRealFromBits; using real_type = absl::conditional_t<std::is_same<RealType, float>::value, float, double>; result_type u, v, x, y, z; for (;;) { u = GenerateRealFromBits<real_type, GeneratePositiveTag, false>( fast_u64_(g)); v = GenerateRealFromBits<real_type, GeneratePositiveTag, false>( fast_u64_(g)); if (!std::is_same<float, result_type>::value) { x = std::pow(u, p.a_); y = std::pow(v, p.b_); z = x + y; if (z > 1) { continue; } if (z > 0) { return x / z; } } x = std::log(u) * p.a_; y = std::log(v) * p.b_; if (!std::isfinite(x) || !std::isfinite(y)) { continue; } z = x > y ? (x + std::log(1 + std::exp(y - x))) : (y + std::log(1 + std::exp(x - y))); if (z > 0) { continue; } return std::exp(x - z); } } template <typename RealType> template <typename URBG> typename beta_distribution<RealType>::result_type beta_distribution<RealType>::AlgorithmCheng( URBG& g, const param_type& p) { using random_internal::GeneratePositiveTag; using random_internal::GenerateRealFromBits; using real_type = absl::conditional_t<std::is_same<RealType, float>::value, float, double>; static constexpr result_type kLogFour = result_type(1.3862943611198906188344642429163531361); static constexpr result_type kS = result_type(2.6094379124341003746007593332261876); const bool use_algorithm_ba = (p.method_ == param_type::CHENG_BA); result_type u1, u2, v, w, z, r, s, t, bw_inv, lhs; for (;;) { u1 = GenerateRealFromBits<real_type, GeneratePositiveTag, false>( fast_u64_(g)); u2 = GenerateRealFromBits<real_type, GeneratePositiveTag, false>( fast_u64_(g)); v = p.y_ * std::log(u1 / (1 - u1)); w = p.a_ * std::exp(v); bw_inv = result_type(1) / (p.b_ + w); r = p.gamma_ * v - kLogFour; s = p.a_ + r - w; z = u1 * u1 * u2; if (!use_algorithm_ba && s + kS >= 5 * z) { break; } t = std::log(z); if (!use_algorithm_ba && s >= t) { break; } lhs = p.x_ * (p.log_x_ + std::log(bw_inv)) + r; if (lhs >= t) { break; } } return p.inverted_ ? (1 - w * bw_inv) : w * bw_inv; } template <typename RealType> template <typename URBG> typename beta_distribution<RealType>::result_type beta_distribution<RealType>::operator()(URBG& g, const param_type& p) { switch (p.method_) { case param_type::JOEHNK: return AlgorithmJoehnk(g, p); case param_type::CHENG_BA: ABSL_FALLTHROUGH_INTENDED; case param_type::CHENG_BB: return AlgorithmCheng(g, p); default: return DegenerateCase(g, p); } } template <typename CharT, typename Traits, typename RealType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const beta_distribution<RealType>& x) { auto saver = random_internal::make_ostream_state_saver(os); os.precision(random_internal::stream_precision_helper<RealType>::kPrecision); os << x.alpha() << os.fill() << x.beta(); return os; } template <typename CharT, typename Traits, typename RealType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, beta_distribution<RealType>& x) { using result_type = typename beta_distribution<RealType>::result_type; using param_type = typename beta_distribution<RealType>::param_type; result_type alpha, beta; auto saver = random_internal::make_istream_state_saver(is); alpha = random_internal::read_floating_point<result_type>(is); if (is.fail()) return is; beta = random_internal::read_floating_point<result_type>(is); if (!is.fail()) { x.param(param_type(alpha, beta)); } return is; } ABSL_NAMESPACE_END } #endif
#include "absl/random/beta_distribution.h" #include <algorithm> #include <cfloat> #include <cstddef> #include <cstdint> #include <iterator> #include <random> #include <sstream> #include <string> #include <type_traits> #include <unordered_map> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/numeric/internal/representation.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/strip.h" namespace { template <typename IntType> class BetaDistributionInterfaceTest : public ::testing::Test {}; constexpr bool ShouldExerciseLongDoubleTests() { #if defined(__i686__) && defined(__x86_64__) return !absl::numeric_internal::IsDoubleDouble(); #else return false; #endif } using RealTypes = std::conditional<ShouldExerciseLongDoubleTests(), ::testing::Types<float, double, long double>, ::testing::Types<float, double>>::type; TYPED_TEST_SUITE(BetaDistributionInterfaceTest, RealTypes); TYPED_TEST(BetaDistributionInterfaceTest, SerializeTest) { const TypeParam kSmallA = 1.0f / std::log((std::numeric_limits<TypeParam>::max)()); const TypeParam kLargeA = std::exp(std::log((std::numeric_limits<TypeParam>::max)()) - std::log(std::log((std::numeric_limits<TypeParam>::max)()))); using param_type = typename absl::beta_distribution<TypeParam>::param_type; constexpr int kCount = 1000; absl::InsecureBitGen gen; const TypeParam kValues[] = { TypeParam(1e-20), TypeParam(1e-12), TypeParam(1e-8), TypeParam(1e-4), TypeParam(1e-3), TypeParam(0.1), TypeParam(0.25), std::nextafter(TypeParam(0.5), TypeParam(0)), std::nextafter(TypeParam(0.5), TypeParam(1)), TypeParam(0.5), TypeParam(1.0), std::nextafter(TypeParam(1), TypeParam(0)), std::nextafter(TypeParam(1), TypeParam(2)), TypeParam(12.5), TypeParam(1e2), TypeParam(1e8), TypeParam(1e12), TypeParam(1e20), kSmallA, std::nextafter(kSmallA, TypeParam(0)), std::nextafter(kSmallA, TypeParam(1)), kLargeA, std::nextafter(kLargeA, TypeParam(0)), std::nextafter(kLargeA, std::numeric_limits<TypeParam>::max()), std::numeric_limits<TypeParam>::max(), std::numeric_limits<TypeParam>::epsilon(), std::nextafter(std::numeric_limits<TypeParam>::min(), TypeParam(1)), std::numeric_limits<TypeParam>::min(), std::numeric_limits<TypeParam>::denorm_min(), std::numeric_limits<TypeParam>::min() / 2, std::nextafter(std::numeric_limits<TypeParam>::min(), TypeParam(0)), }; for (TypeParam alpha : kValues) { for (TypeParam beta : kValues) { LOG(INFO) << absl::StreamFormat("Smoke test for Beta(%a, %a)", alpha, beta); param_type param(alpha, beta); absl::beta_distribution<TypeParam> before(alpha, beta); EXPECT_EQ(before.alpha(), param.alpha()); EXPECT_EQ(before.beta(), param.beta()); { absl::beta_distribution<TypeParam> via_param(param); EXPECT_EQ(via_param, before); EXPECT_EQ(via_param.param(), before.param()); } for (int i = 0; i < kCount; ++i) { auto sample = before(gen); EXPECT_TRUE(std::isfinite(sample)); EXPECT_GE(sample, before.min()); EXPECT_LE(sample, before.max()); } std::stringstream ss; ss << before; absl::beta_distribution<TypeParam> after(3.8f, 1.43f); EXPECT_NE(before.alpha(), after.alpha()); EXPECT_NE(before.beta(), after.beta()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.alpha(), after.alpha()); EXPECT_EQ(before.beta(), after.beta()); EXPECT_EQ(before, after) << ss.str() << " " << (ss.good() ? "good " : "") << (ss.bad() ? "bad " : "") << (ss.eof() ? "eof " : "") << (ss.fail() ? "fail " : ""); } } } TYPED_TEST(BetaDistributionInterfaceTest, DegenerateCases) { absl::random_internal::pcg64_2018_engine rng(0x2B7E151628AED2A6); constexpr int kCount = 1000; const TypeParam kSmallValues[] = { std::numeric_limits<TypeParam>::min(), std::numeric_limits<TypeParam>::denorm_min(), std::nextafter(std::numeric_limits<TypeParam>::min(), TypeParam(0)), std::numeric_limits<TypeParam>::epsilon(), }; const TypeParam kLargeValues[] = { std::numeric_limits<TypeParam>::max() * static_cast<TypeParam>(0.9999), std::numeric_limits<TypeParam>::max() - 1, std::numeric_limits<TypeParam>::max(), }; { for (TypeParam alpha : kSmallValues) { for (TypeParam beta : kSmallValues) { int zeros = 0; int ones = 0; absl::beta_distribution<TypeParam> d(alpha, beta); for (int i = 0; i < kCount; ++i) { TypeParam x = d(rng); if (x == 0.0) { zeros++; } else if (x == 1.0) { ones++; } } EXPECT_EQ(ones + zeros, kCount); if (alpha == beta) { EXPECT_NE(ones, 0); EXPECT_NE(zeros, 0); } } } } { for (TypeParam alpha : kSmallValues) { for (TypeParam beta : kLargeValues) { absl::beta_distribution<TypeParam> d(alpha, beta); for (int i = 0; i < kCount; ++i) { EXPECT_EQ(d(rng), 0.0); } } } } { for (TypeParam alpha : kLargeValues) { for (TypeParam beta : kSmallValues) { absl::beta_distribution<TypeParam> d(alpha, beta); for (int i = 0; i < kCount; ++i) { EXPECT_EQ(d(rng), 1.0); } } } } { absl::beta_distribution<TypeParam> d(std::numeric_limits<TypeParam>::max(), std::numeric_limits<TypeParam>::max()); for (int i = 0; i < kCount; ++i) { EXPECT_EQ(d(rng), 0.5); } } { absl::beta_distribution<TypeParam> d( std::numeric_limits<TypeParam>::max(), std::numeric_limits<TypeParam>::max() * 0.9999); for (int i = 0; i < kCount; ++i) { TypeParam x = d(rng); EXPECT_NE(x, 0.5f); EXPECT_FLOAT_EQ(x, 0.500025f); } } } class BetaDistributionModel { public: explicit BetaDistributionModel(::testing::tuple<double, double> p) : alpha_(::testing::get<0>(p)), beta_(::testing::get<1>(p)) {} double Mean() const { return alpha_ / (alpha_ + beta_); } double Variance() const { return alpha_ * beta_ / (alpha_ + beta_ + 1) / (alpha_ + beta_) / (alpha_ + beta_); } double Kurtosis() const { return 3 + 6 * ((alpha_ - beta_) * (alpha_ - beta_) * (alpha_ + beta_ + 1) - alpha_ * beta_ * (2 + alpha_ + beta_)) / alpha_ / beta_ / (alpha_ + beta_ + 2) / (alpha_ + beta_ + 3); } protected: const double alpha_; const double beta_; }; class BetaDistributionTest : public ::testing::TestWithParam<::testing::tuple<double, double>>, public BetaDistributionModel { public: BetaDistributionTest() : BetaDistributionModel(GetParam()) {} protected: template <class D> bool SingleZTestOnMeanAndVariance(double p, size_t samples); template <class D> bool SingleChiSquaredTest(double p, size_t samples, size_t buckets); absl::InsecureBitGen rng_; }; template <class D> bool BetaDistributionTest::SingleZTestOnMeanAndVariance(double p, size_t samples) { D dis(alpha_, beta_); std::vector<double> data; data.reserve(samples); for (size_t i = 0; i < samples; i++) { const double variate = dis(rng_); EXPECT_FALSE(std::isnan(variate)); EXPECT_GE(variate, 0.0); EXPECT_LE(variate, 1.0); data.push_back(variate); } const auto m = absl::random_internal::ComputeDistributionMoments(data); const double mean_stddev = std::sqrt(Variance() / static_cast<double>(m.n)); const double variance_stddev = std::sqrt( (Kurtosis() - 1) * Variance() * Variance() / static_cast<double>(m.n)); const double z_variance = (m.variance - Variance()) / variance_stddev; const double max_err = absl::random_internal::MaxErrorTolerance(p); const double z_mean = absl::random_internal::ZScore(Mean(), m); const bool pass = absl::random_internal::Near("z", z_mean, 0.0, max_err) && absl::random_internal::Near("z_variance", z_variance, 0.0, max_err); if (!pass) { LOG(INFO) << "Beta(" << alpha_ << ", " << beta_ << "), mean: sample " << m.mean << ", expect " << Mean() << ", which is " << std::abs(m.mean - Mean()) / mean_stddev << " stddevs away, variance: sample " << m.variance << ", expect " << Variance() << ", which is " << std::abs(m.variance - Variance()) / variance_stddev << " stddevs away."; } return pass; } template <class D> bool BetaDistributionTest::SingleChiSquaredTest(double p, size_t samples, size_t buckets) { constexpr double kErr = 1e-7; std::vector<double> cutoffs, expected; const double bucket_width = 1.0 / static_cast<double>(buckets); int i = 1; int unmerged_buckets = 0; for (; i < buckets; ++i) { const double p = bucket_width * static_cast<double>(i); const double boundary = absl::random_internal::BetaIncompleteInv(alpha_, beta_, p); if ((cutoffs.empty() && boundary < kErr) || (!cutoffs.empty() && boundary <= cutoffs.back())) { unmerged_buckets++; continue; } if (boundary >= 1.0 - 1e-10) { break; } cutoffs.push_back(boundary); expected.push_back(static_cast<double>(1 + unmerged_buckets) * bucket_width * static_cast<double>(samples)); unmerged_buckets = 0; } cutoffs.push_back(std::numeric_limits<double>::infinity()); expected.push_back(static_cast<double>(buckets - i + 1) * bucket_width * static_cast<double>(samples)); EXPECT_GE(cutoffs.size(), 3) << alpha_ << ", " << beta_; D dis(alpha_, beta_); std::vector<int32_t> counts(cutoffs.size(), 0); for (int i = 0; i < samples; i++) { const double x = dis(rng_); auto it = std::upper_bound(cutoffs.begin(), cutoffs.end(), x); counts[std::distance(cutoffs.begin(), it)]++; } const int dof = cutoffs.size() - 1; const double chi_square = absl::random_internal::ChiSquare( counts.begin(), counts.end(), expected.begin(), expected.end()); const bool pass = (absl::random_internal::ChiSquarePValue(chi_square, dof) >= p); if (!pass) { for (size_t i = 0; i < cutoffs.size(); i++) { LOG(INFO) << "cutoff[" << i << "] = " << cutoffs[i] << ", actual count " << counts[i] << ", expected " << static_cast<int>(expected[i]); } LOG(INFO) << "Beta(" << alpha_ << ", " << beta_ << ") " << absl::random_internal::kChiSquared << " " << chi_square << ", p = " << absl::random_internal::ChiSquarePValue(chi_square, dof); } return pass; } TEST_P(BetaDistributionTest, TestSampleStatistics) { static constexpr int kRuns = 20; static constexpr double kPFail = 0.02; const double p = absl::random_internal::RequiredSuccessProbability(kPFail, kRuns); static constexpr int kSampleCount = 10000; static constexpr int kBucketCount = 100; int failed = 0; for (int i = 0; i < kRuns; ++i) { if (!SingleZTestOnMeanAndVariance<absl::beta_distribution<double>>( p, kSampleCount)) { failed++; } if (!SingleChiSquaredTest<absl::beta_distribution<double>>( 0.005, kSampleCount, kBucketCount)) { failed++; } } EXPECT_LE(failed, 5); } std::string ParamName( const ::testing::TestParamInfo<::testing::tuple<double, double>>& info) { std::string name = absl::StrCat("alpha_", ::testing::get<0>(info.param), "__beta_", ::testing::get<1>(info.param)); return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}}); } INSTANTIATE_TEST_SUITE_P( TestSampleStatisticsCombinations, BetaDistributionTest, ::testing::Combine(::testing::Values(0.1, 0.2, 0.9, 1.1, 2.5, 10.0, 123.4), ::testing::Values(0.1, 0.2, 0.9, 1.1, 2.5, 10.0, 123.4)), ParamName); INSTANTIATE_TEST_SUITE_P( TestSampleStatistics_SelectedPairs, BetaDistributionTest, ::testing::Values(std::make_pair(0.5, 1000), std::make_pair(1000, 0.5), std::make_pair(900, 1000), std::make_pair(10000, 20000), std::make_pair(4e5, 2e7), std::make_pair(1e7, 1e5)), ParamName); TEST(BetaDistributionTest, StabilityTest) { using testing::ElementsAre; absl::random_internal::sequence_urbg urbg({ 0xffff00000000e6c8ull, 0xffff0000000006c8ull, 0x800003766295CFA9ull, 0x11C819684E734A41ull, 0x832603766295CFA9ull, 0x7fbe76c8b4395800ull, 0xB3472DCA7B14A94Aull, 0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0x00035C904C70A239ull, 0x00009E0BCBAADE14ull, 0x0000000000622CA7ull, 0x4864f22c059bf29eull, 0x247856d8b862665cull, 0xe46e86e9a1337e10ull, 0xd8c8541f3519b133ull, 0xffe75b52c567b9e4ull, 0xfffff732e5709c5bull, 0xff1f7f0b983532acull, 0x1ec2e8986d2362caull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x814c8e35fe9a961aull, 0x0c3cd59c9b638a02ull, 0xcb3bb6478a07715cull, 0x1224e62c978bbc7full, 0x671ef2cb04e81f6eull, 0x3c1cbd811eaf1808ull, 0x1bbc23cfa8fac721ull, 0xa4c2cda65e596a51ull, 0xb77216fad37adf91ull, 0x836d794457c08849ull, 0xe083df03475f49d7ull, 0xbc9feb512e6b0d6cull, 0xb12d74fdd718c8c5ull, 0x12ff09653bfbe4caull, 0x8dd03a105bc4ee7eull, 0x5738341045ba0d85ull, 0xf3fd722dc65ad09eull, 0xfa14fd21ea2a5705ull, 0xffe6ea4d6edb0c73ull, 0xD07E9EFE2BF11FB4ull, 0x95DBDA4DAE909198ull, 0xEAAD8E716B93D5A0ull, 0xD08ED1D0AFC725E0ull, 0x8E3C5B2F8E7594B7ull, 0x8FF6E2FBF2122B64ull, 0x8888B812900DF01Cull, 0x4FAD5EA0688FC31Cull, 0xD1CFF191B3A8C1ADull, 0x2F2F2218BE0E1777ull, 0xEA752DFE8B021FA1ull, }); auto float_to_u64 = [](float d) { int exp = 0; auto f = std::frexp(d, &exp); return (static_cast<uint64_t>(1e5 * f) * 10000) + std::abs(exp); }; auto double_to_u64 = [](double d) { int exp = 0; auto f = std::frexp(d, &exp); return (static_cast<uint64_t>(1e10 * f) * 10000) + std::abs(exp); }; std::vector<uint64_t> output(20); { absl::beta_distribution<float> dist(0.1f, 0.2f); std::generate(std::begin(output), std::end(output), [&] { return float_to_u64(dist(urbg)); }); EXPECT_EQ(44, urbg.invocations()); EXPECT_THAT(output, testing::ElementsAre( 998340000, 619030004, 500000001, 999990000, 996280000, 500000001, 844740004, 847210001, 999970000, 872320000, 585480007, 933280000, 869080042, 647670031, 528240004, 969980004, 626050008, 915930002, 833440033, 878040015)); } urbg.reset(); { absl::beta_distribution<double> dist(0.1, 0.2); std::generate(std::begin(output), std::end(output), [&] { return double_to_u64(dist(urbg)); }); EXPECT_EQ(44, urbg.invocations()); EXPECT_THAT( output, testing::ElementsAre( 99834713000000, 61903356870004, 50000000000001, 99999721170000, 99628374770000, 99999999990000, 84474397860004, 84721276240001, 99997407490000, 87232528120000, 58548364780007, 93328932910000, 86908237770042, 64767917930031, 52824581970004, 96998544140004, 62605946270008, 91593604380002, 83345031740033, 87804397230015)); } urbg.reset(); { absl::beta_distribution<double> dist(0.9, 2.0); std::generate(std::begin(output), std::end(output), [&] { return double_to_u64(dist(urbg)); }); EXPECT_EQ(62, urbg.invocations()); EXPECT_THAT( output, testing::ElementsAre( 62069004780001, 64433204450001, 53607416560000, 89644295430008, 61434586310019, 55172615890002, 62187161490000, 56433684810003, 80454622050005, 86418558710003, 92920514700001, 64645184680001, 58549183380000, 84881283650005, 71078728590002, 69949694970000, 73157461710001, 68592191300001, 70747623900000, 78584696930005)); } urbg.reset(); { absl::beta_distribution<double> dist(1.5, 2.5); std::generate(std::begin(output), std::end(output), [&] { return double_to_u64(dist(urbg)); }); EXPECT_EQ(54, urbg.invocations()); EXPECT_THAT( output, testing::ElementsAre( 75000029250001, 76751482860001, 53264575220000, 69193133650005, 78028324470013, 91573587560002, 59167523770000, 60658618560002, 80075870540000, 94141320460004, 63196592770003, 78883906300002, 96797992590001, 76907587800001, 56645167560000, 65408302280003, 53401156320001, 64731238570000, 83065573750001, 79788333820001)); } } TEST(BetaDistributionTest, AlgorithmBounds) { #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0 GTEST_SKIP() << "Skipping the test because we detected x87 floating-point semantics"; #endif { absl::random_internal::sequence_urbg urbg( {0x7fbe76c8b4395800ull, 0x8000000000000000ull}); absl::beta_distribution<double> dist(1e-4, 1e-4); double a = dist(urbg); EXPECT_EQ(a, 2.0202860861567108529e-09); EXPECT_EQ(2, urbg.invocations()); } { absl::beta_distribution<float> dist(0.5, 0.5); absl::random_internal::sequence_urbg urbg( {0xffff00000006e6c8ull, 0xffff00000007c7c8ull, 0x800003766295CFA9ull, 0x11C819684E734A41ull}); { double y = absl::beta_distribution<double>(0.5, 0.5)(urbg); EXPECT_EQ(4, urbg.invocations()); EXPECT_EQ(y, 0.9810668952633862) << y; } urbg.reset(); { float x = absl::beta_distribution<float>(0.5, 0.5)(urbg); EXPECT_EQ(4, urbg.invocations()); EXPECT_NEAR(0.98106688261032104, x, 0.0000005) << x << "f"; } } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/beta_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/beta_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
49de6d11-ef16-4650-b8b9-f2614c7904de
cpp
abseil/abseil-cpp
zipf_distribution
absl/random/zipf_distribution.h
absl/random/zipf_distribution_test.cc
#ifndef ABSL_RANDOM_ZIPF_DISTRIBUTION_H_ #define ABSL_RANDOM_ZIPF_DISTRIBUTION_H_ #include <cassert> #include <cmath> #include <istream> #include <limits> #include <ostream> #include <type_traits> #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/internal/traits.h" #include "absl/random/uniform_real_distribution.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename IntType = int> class zipf_distribution { public: using result_type = IntType; class param_type { public: using distribution_type = zipf_distribution; explicit param_type(result_type k = (std::numeric_limits<IntType>::max)(), double q = 2.0, double v = 1.0); result_type k() const { return k_; } double q() const { return q_; } double v() const { return v_; } friend bool operator==(const param_type& a, const param_type& b) { return a.k_ == b.k_ && a.q_ == b.q_ && a.v_ == b.v_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class zipf_distribution; inline double h(double x) const; inline double hinv(double x) const; inline double compute_s() const; inline double pow_negative_q(double x) const; IntType k_; double q_; double v_; double one_minus_q_; double s_; double one_minus_q_inv_; double hxm_; double hx0_minus_hxm_; static_assert(random_internal::IsIntegral<IntType>::value, "Class-template absl::zipf_distribution<> must be " "parameterized using an integral type."); }; zipf_distribution() : zipf_distribution((std::numeric_limits<IntType>::max)()) {} explicit zipf_distribution(result_type k, double q = 2.0, double v = 1.0) : param_(k, q, v) {} explicit zipf_distribution(const param_type& p) : param_(p) {} void reset() {} template <typename URBG> result_type operator()(URBG& g) { return (*this)(g, param_); } template <typename URBG> result_type operator()(URBG& g, const param_type& p); result_type k() const { return param_.k(); } double q() const { return param_.q(); } double v() const { return param_.v(); } param_type param() const { return param_; } void param(const param_type& p) { param_ = p; } result_type(min)() const { return 0; } result_type(max)() const { return k(); } friend bool operator==(const zipf_distribution& a, const zipf_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const zipf_distribution& a, const zipf_distribution& b) { return a.param_ != b.param_; } private: param_type param_; }; template <typename IntType> zipf_distribution<IntType>::param_type::param_type( typename zipf_distribution<IntType>::result_type k, double q, double v) : k_(k), q_(q), v_(v), one_minus_q_(1 - q) { assert(q > 1); assert(v > 0); assert(k > 0); one_minus_q_inv_ = 1 / one_minus_q_; constexpr double kMax = 18446744073709549568.0; double kd = static_cast<double>(k); if (kd > kMax) { kd = kMax; } hxm_ = h(kd + 0.5); const bool use_precomputed = (v == 1.0 && q == 2.0); const double h0x5 = use_precomputed ? (-1.0 / 1.5) : h(0.5); const double elogv_q = (v_ == 1.0) ? 1 : pow_negative_q(v_); hx0_minus_hxm_ = (h0x5 - elogv_q) - hxm_; s_ = use_precomputed ? 0.46153846153846123 : compute_s(); } template <typename IntType> double zipf_distribution<IntType>::param_type::h(double x) const { x += v_; return (one_minus_q_ == -1.0) ? (-1.0 / x) : (std::exp(std::log(x) * one_minus_q_) * one_minus_q_inv_); } template <typename IntType> double zipf_distribution<IntType>::param_type::hinv(double x) const { return -v_ + ((one_minus_q_ == -1.0) ? (-1.0 / x) : std::exp(one_minus_q_inv_ * std::log(one_minus_q_ * x))); } template <typename IntType> double zipf_distribution<IntType>::param_type::compute_s() const { return 1.0 - hinv(h(1.5) - pow_negative_q(v_ + 1.0)); } template <typename IntType> double zipf_distribution<IntType>::param_type::pow_negative_q(double x) const { return q_ == 2.0 ? (1.0 / (x * x)) : std::exp(std::log(x) * -q_); } template <typename IntType> template <typename URBG> typename zipf_distribution<IntType>::result_type zipf_distribution<IntType>::operator()( URBG& g, const param_type& p) { absl::uniform_real_distribution<double> uniform_double; double k; for (;;) { const double v = uniform_double(g); const double u = p.hxm_ + v * p.hx0_minus_hxm_; const double x = p.hinv(u); k = rint(x); if (k > static_cast<double>(p.k())) continue; if (k - x <= p.s_) break; const double h = p.h(k + 0.5); const double r = p.pow_negative_q(p.v_ + k); if (u >= h - r) break; } IntType ki = static_cast<IntType>(k); assert(ki <= p.k_); return ki; } template <typename CharT, typename Traits, typename IntType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const zipf_distribution<IntType>& x) { using stream_type = typename random_internal::stream_format_type<IntType>::type; auto saver = random_internal::make_ostream_state_saver(os); os.precision(random_internal::stream_precision_helper<double>::kPrecision); os << static_cast<stream_type>(x.k()) << os.fill() << x.q() << os.fill() << x.v(); return os; } template <typename CharT, typename Traits, typename IntType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, zipf_distribution<IntType>& x) { using result_type = typename zipf_distribution<IntType>::result_type; using param_type = typename zipf_distribution<IntType>::param_type; using stream_type = typename random_internal::stream_format_type<IntType>::type; stream_type k; double q; double v; auto saver = random_internal::make_istream_state_saver(is); is >> k >> q >> v; if (!is.fail()) { x.param(param_type(static_cast<result_type>(k), q, v)); } return is; } ABSL_NAMESPACE_END } #endif
#include "absl/random/zipf_distribution.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <iterator> #include <random> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/strip.h" namespace { using ::absl::random_internal::kChiSquared; using ::testing::ElementsAre; template <typename IntType> class ZipfDistributionTypedTest : public ::testing::Test {}; using IntTypes = ::testing::Types<int, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t>; TYPED_TEST_SUITE(ZipfDistributionTypedTest, IntTypes); TYPED_TEST(ZipfDistributionTypedTest, SerializeTest) { using param_type = typename absl::zipf_distribution<TypeParam>::param_type; constexpr int kCount = 1000; absl::InsecureBitGen gen; for (const auto& param : { param_type(), param_type(32), param_type(100, 3, 2), param_type(std::numeric_limits<TypeParam>::max(), 4, 3), param_type(std::numeric_limits<TypeParam>::max() / 2), }) { const auto k = param.k(); const auto q = param.q(); const auto v = param.v(); absl::zipf_distribution<TypeParam> before(k, q, v); EXPECT_EQ(before.k(), param.k()); EXPECT_EQ(before.q(), param.q()); EXPECT_EQ(before.v(), param.v()); { absl::zipf_distribution<TypeParam> via_param(param); EXPECT_EQ(via_param, before); } std::stringstream ss; ss << before; absl::zipf_distribution<TypeParam> after(4, 5.5, 4.4); EXPECT_NE(before.k(), after.k()); EXPECT_NE(before.q(), after.q()); EXPECT_NE(before.v(), after.v()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.k(), after.k()); EXPECT_EQ(before.q(), after.q()); EXPECT_EQ(before.v(), after.v()); EXPECT_EQ(before.param(), after.param()); EXPECT_EQ(before, after); auto sample_min = after.max(); auto sample_max = after.min(); for (int i = 0; i < kCount; i++) { auto sample = after(gen); EXPECT_GE(sample, after.min()); EXPECT_LE(sample, after.max()); if (sample > sample_max) sample_max = sample; if (sample < sample_min) sample_min = sample; } LOG(INFO) << "Range: " << sample_min << ", " << sample_max; } } class ZipfModel { public: ZipfModel(size_t k, double q, double v) : k_(k), q_(q), v_(v) {} double mean() const { return mean_; } double PMF(size_t i) { return i >= hnq_.size() ? 0.0 : hnq_[i] / sum_hnq_; } double CDF(size_t i) { if (i >= hnq_.size()) { return 1.0; } auto it = std::begin(hnq_); double h = 0.0; for (const auto end = it; it != end; it++) { h += *it; } return h / sum_hnq_; } std::pair<size_t, size_t> InverseCDF(double p) { size_t min = 0; size_t max = hnq_.size(); while (max > min + 1) { size_t target = (max + min) >> 1; double x = CDF(target); if (x > p) { max = target; } else { min = target; } } return {min, max}; } void Init() { if (!hnq_.empty()) { return; } hnq_.clear(); hnq_.reserve(std::min(k_, size_t{1000})); sum_hnq_ = 0; double qm1 = q_ - 1.0; double sum_hnq_m1 = 0; for (size_t i = 0; i < k_; i++) { const double x = v_ + i; const double hnqm1 = (q_ == 2.0) ? (1.0 / x) : (q_ == 3.0) ? (1.0 / (x * x)) : std::pow(x, -qm1); sum_hnq_m1 += hnqm1; const double hnq = (q_ == 2.0) ? (1.0 / (x * x)) : (q_ == 3.0) ? (1.0 / (x * x * x)) : std::pow(x, -q_); sum_hnq_ += hnq; hnq_.push_back(hnq); if (i > 1000 && hnq <= 1e-10) { break; } } assert(sum_hnq_ > 0); mean_ = sum_hnq_m1 / sum_hnq_; } private: const size_t k_; const double q_; const double v_; double mean_; std::vector<double> hnq_; double sum_hnq_; }; using zipf_u64 = absl::zipf_distribution<uint64_t>; class ZipfTest : public testing::TestWithParam<zipf_u64::param_type>, public ZipfModel { public: ZipfTest() : ZipfModel(GetParam().k(), GetParam().q(), GetParam().v()) {} absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6}; }; TEST_P(ZipfTest, ChiSquaredTest) { const auto& param = GetParam(); Init(); size_t trials = 10000; std::vector<size_t> points; std::vector<double> expected; { double last_cdf = 0.0; double min_p = 1.0; for (double p = 0.01; p < 1.0; p += 0.01) { auto x = InverseCDF(p); if (points.empty() || points.back() < x.second) { const double p = CDF(x.second); points.push_back(x.second); double q = p - last_cdf; expected.push_back(q); last_cdf = p; if (q < min_p) { min_p = q; } } } if (last_cdf < 0.999) { points.push_back(std::numeric_limits<size_t>::max()); double q = 1.0 - last_cdf; expected.push_back(q); if (q < min_p) { min_p = q; } } else { points.back() = std::numeric_limits<size_t>::max(); expected.back() += (1.0 - last_cdf); } trials = static_cast<size_t>(8.0 / min_p); } ASSERT_GT(points.size(), 0); std::vector<int64_t> buckets(points.size(), 0); double avg = 0; { zipf_u64 dis(param); for (size_t i = 0; i < trials; i++) { uint64_t x = dis(rng_); ASSERT_LE(x, dis.max()); ASSERT_GE(x, dis.min()); avg += static_cast<double>(x); auto it = std::upper_bound(std::begin(points), std::end(points), static_cast<size_t>(x)); buckets[std::distance(std::begin(points), it)]++; } avg = avg / static_cast<double>(trials); } for (auto& e : expected) { e *= trials; } const int dof = static_cast<int>(expected.size()) - 1; const double threshold = absl::random_internal::ChiSquareValue(dof, 0.9999); const double chi_square = absl::random_internal::ChiSquare( std::begin(buckets), std::end(buckets), std::begin(expected), std::end(expected)); const double p_actual = absl::random_internal::ChiSquarePValue(chi_square, dof); if (chi_square > threshold) { LOG(INFO) << "values"; for (size_t i = 0; i < expected.size(); i++) { LOG(INFO) << points[i] << ": " << buckets[i] << " vs. E=" << expected[i]; } LOG(INFO) << "trials " << trials; LOG(INFO) << "mean " << avg << " vs. expected " << mean(); LOG(INFO) << kChiSquared << "(data, " << dof << ") = " << chi_square << " (" << p_actual << ")"; LOG(INFO) << kChiSquared << " @ 0.9995 = " << threshold; FAIL() << kChiSquared << " value of " << chi_square << " is above the threshold."; } } std::vector<zipf_u64::param_type> GenParams() { using param = zipf_u64::param_type; const auto k = param().k(); const auto q = param().q(); const auto v = param().v(); const uint64_t k2 = 1 << 10; return std::vector<zipf_u64::param_type>{ param(k, q, v), param(4, q, v), param(1 << 4, q, v), param(k2, q, v), param(k2, q, 0.5), param(k2, q, 1.5), param(k2, q, 2.5), param(k2, q, 10), param(k2, 1.5, v), param(k2, 3, v), param(k2, 5, v), param(k2, 10, v), param(k2, 1.5, 0.5), param(k2, 3, 1.5), param(k, 10, 10)}; } std::string ParamName( const ::testing::TestParamInfo<zipf_u64::param_type>& info) { const auto& p = info.param; std::string name = absl::StrCat("k_", p.k(), "__q_", absl::SixDigits(p.q()), "__v_", absl::SixDigits(p.v())); return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}}); } INSTANTIATE_TEST_SUITE_P(All, ZipfTest, ::testing::ValuesIn(GenParams()), ParamName); TEST(ZipfDistributionTest, StabilityTest) { absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<int> output(10); { absl::zipf_distribution<int32_t> dist; std::generate(std::begin(output), std::end(output), [&] { return dist(urbg); }); EXPECT_THAT(output, ElementsAre(10031, 0, 0, 3, 6, 0, 7, 47, 0, 0)); } urbg.reset(); { absl::zipf_distribution<int32_t> dist(std::numeric_limits<int32_t>::max(), 3.3); std::generate(std::begin(output), std::end(output), [&] { return dist(urbg); }); EXPECT_THAT(output, ElementsAre(44, 0, 0, 0, 0, 1, 0, 1, 3, 0)); } } TEST(ZipfDistributionTest, AlgorithmBounds) { absl::zipf_distribution<int32_t> dist; const std::pair<uint64_t, int32_t> kInputs[] = { {0xffffffffffffffff, 0x0}, {0x7fffffffffffffff, 0x0}, {0x3ffffffffffffffb, 0x1}, {0x1ffffffffffffffd, 0x4}, {0xffffffffffffffe, 0x9}, {0x7ffffffffffffff, 0x12}, {0x3ffffffffffffff, 0x25}, {0x1ffffffffffffff, 0x4c}, {0xffffffffffffff, 0x99}, {0x7fffffffffffff, 0x132}, {0x3fffffffffffff, 0x265}, {0x1fffffffffffff, 0x4cc}, {0xfffffffffffff, 0x999}, {0x7ffffffffffff, 0x1332}, {0x3ffffffffffff, 0x2665}, {0x1ffffffffffff, 0x4ccc}, {0xffffffffffff, 0x9998}, {0x7fffffffffff, 0x1332f}, {0x3fffffffffff, 0x2665a}, {0x1fffffffffff, 0x4cc9e}, {0xfffffffffff, 0x998e0}, {0x7ffffffffff, 0x133051}, {0x3ffffffffff, 0x265ae4}, {0x1ffffffffff, 0x4c9ed3}, {0xffffffffff, 0x98e223}, {0x7fffffffff, 0x13058c4}, {0x3fffffffff, 0x25b178e}, {0x1fffffffff, 0x4a062b2}, {0xfffffffff, 0x8ee23b8}, {0x7ffffffff, 0x10b21642}, {0x3ffffffff, 0x1d89d89d}, {0x1ffffffff, 0x2fffffff}, {0xffffffff, 0x45d1745d}, {0x7fffffff, 0x5a5a5a5a}, {0x3fffffff, 0x69ee5846}, {0x1fffffff, 0x73ecade3}, {0xfffffff, 0x79a9d260}, {0x7ffffff, 0x7cc0532b}, {0x3ffffff, 0x7e5ad146}, {0x1ffffff, 0x7f2c0bec}, {0xffffff, 0x7f95adef}, {0x7fffff, 0x7fcac0da}, {0x3fffff, 0x7fe55ae2}, {0x1fffff, 0x7ff2ac0e}, {0xfffff, 0x7ff955ae}, {0x7ffff, 0x7ffcaac1}, {0x3ffff, 0x7ffe555b}, {0x1ffff, 0x7fff2aac}, {0xffff, 0x7fff9556}, {0x7fff, 0x7fffcaab}, {0x3fff, 0x7fffe555}, {0x1fff, 0x7ffff2ab}, {0xfff, 0x7ffff955}, {0x7ff, 0x7ffffcab}, {0x3ff, 0x7ffffe55}, {0x1ff, 0x7fffff2b}, {0xff, 0x7fffff95}, {0x7f, 0x7fffffcb}, {0x3f, 0x7fffffe5}, {0x1f, 0x7ffffff3}, {0xf, 0x7ffffff9}, {0x7, 0x7ffffffd}, {0x3, 0x7ffffffe}, {0x1, 0x7fffffff}, }; for (const auto& instance : kInputs) { absl::random_internal::sequence_urbg urbg({instance.first}); EXPECT_EQ(instance.second, dist(urbg)); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/zipf_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/zipf_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e0837984-608a-4366-a9d6-6e4cd4a9f979
cpp
abseil/abseil-cpp
exponential_distribution
absl/random/exponential_distribution.h
absl/random/exponential_distribution_test.cc
#ifndef ABSL_RANDOM_EXPONENTIAL_DISTRIBUTION_H_ #define ABSL_RANDOM_EXPONENTIAL_DISTRIBUTION_H_ #include <cassert> #include <cmath> #include <istream> #include <limits> #include <type_traits> #include "absl/meta/type_traits.h" #include "absl/random/internal/fast_uniform_bits.h" #include "absl/random/internal/generate_real.h" #include "absl/random/internal/iostream_state_saver.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename RealType = double> class exponential_distribution { public: using result_type = RealType; class param_type { public: using distribution_type = exponential_distribution; explicit param_type(result_type lambda = 1) : lambda_(lambda) { assert(lambda > 0); neg_inv_lambda_ = -result_type(1) / lambda_; } result_type lambda() const { return lambda_; } friend bool operator==(const param_type& a, const param_type& b) { return a.lambda_ == b.lambda_; } friend bool operator!=(const param_type& a, const param_type& b) { return !(a == b); } private: friend class exponential_distribution; result_type lambda_; result_type neg_inv_lambda_; static_assert( std::is_floating_point<RealType>::value, "Class-template absl::exponential_distribution<> must be parameterized " "using a floating-point type."); }; exponential_distribution() : exponential_distribution(1) {} explicit exponential_distribution(result_type lambda) : param_(lambda) {} explicit exponential_distribution(const param_type& p) : param_(p) {} void reset() {} template <typename URBG> result_type operator()(URBG& g) { return (*this)(g, param_); } template <typename URBG> result_type operator()(URBG& g, const param_type& p); param_type param() const { return param_; } void param(const param_type& p) { param_ = p; } result_type(min)() const { return 0; } result_type(max)() const { return std::numeric_limits<result_type>::infinity(); } result_type lambda() const { return param_.lambda(); } friend bool operator==(const exponential_distribution& a, const exponential_distribution& b) { return a.param_ == b.param_; } friend bool operator!=(const exponential_distribution& a, const exponential_distribution& b) { return a.param_ != b.param_; } private: param_type param_; random_internal::FastUniformBits<uint64_t> fast_u64_; }; template <typename RealType> template <typename URBG> typename exponential_distribution<RealType>::result_type exponential_distribution<RealType>::operator()( URBG& g, const param_type& p) { using random_internal::GenerateNegativeTag; using random_internal::GenerateRealFromBits; using real_type = absl::conditional_t<std::is_same<RealType, float>::value, float, double>; const result_type u = GenerateRealFromBits<real_type, GenerateNegativeTag, false>(fast_u64_(g)); return p.neg_inv_lambda_ * std::log1p(u); } template <typename CharT, typename Traits, typename RealType> std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const exponential_distribution<RealType>& x) { auto saver = random_internal::make_ostream_state_saver(os); os.precision(random_internal::stream_precision_helper<RealType>::kPrecision); os << x.lambda(); return os; } template <typename CharT, typename Traits, typename RealType> std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, exponential_distribution<RealType>& x) { using result_type = typename exponential_distribution<RealType>::result_type; using param_type = typename exponential_distribution<RealType>::param_type; result_type lambda; auto saver = random_internal::make_istream_state_saver(is); lambda = random_internal::read_floating_point<result_type>(is); if (!is.fail()) { x.param(param_type(lambda)); } return is; } ABSL_NAMESPACE_END } #endif
#include "absl/random/exponential_distribution.h" #include <algorithm> #include <cfloat> #include <cmath> #include <cstddef> #include <cstdint> #include <iterator> #include <limits> #include <random> #include <sstream> #include <string> #include <type_traits> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/log/log.h" #include "absl/numeric/internal/representation.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/strip.h" namespace { using absl::random_internal::kChiSquared; template <typename RealType> class ExponentialDistributionTypedTest : public ::testing::Test {}; using RealTypes = std::conditional<absl::numeric_internal::IsDoubleDouble(), ::testing::Types<float, double>, ::testing::Types<float, double, long double>>::type; TYPED_TEST_SUITE(ExponentialDistributionTypedTest, RealTypes); TYPED_TEST(ExponentialDistributionTypedTest, SerializeTest) { using param_type = typename absl::exponential_distribution<TypeParam>::param_type; const TypeParam kParams[] = { 1, std::nextafter(TypeParam(1), TypeParam(0)), std::nextafter(TypeParam(1), TypeParam(2)), TypeParam(1e-8), TypeParam(1e-4), TypeParam(1), TypeParam(2), TypeParam(1e4), TypeParam(1e8), TypeParam(1e20), TypeParam(2.5), std::numeric_limits<TypeParam>::max(), std::numeric_limits<TypeParam>::epsilon(), std::nextafter(std::numeric_limits<TypeParam>::min(), TypeParam(1)), std::numeric_limits<TypeParam>::min(), std::numeric_limits<TypeParam>::denorm_min(), std::numeric_limits<TypeParam>::min() / 2, std::nextafter(std::numeric_limits<TypeParam>::min(), TypeParam(0)), }; constexpr int kCount = 1000; absl::InsecureBitGen gen; for (const TypeParam lambda : kParams) { if (!std::isfinite(lambda)) continue; ABSL_ASSERT(lambda > 0); const param_type param(lambda); absl::exponential_distribution<TypeParam> before(lambda); EXPECT_EQ(before.lambda(), param.lambda()); { absl::exponential_distribution<TypeParam> via_param(param); EXPECT_EQ(via_param, before); EXPECT_EQ(via_param.param(), before.param()); } auto sample_min = before.max(); auto sample_max = before.min(); for (int i = 0; i < kCount; i++) { auto sample = before(gen); EXPECT_GE(sample, before.min()) << before; EXPECT_LE(sample, before.max()) << before; if (sample > sample_max) sample_max = sample; if (sample < sample_min) sample_min = sample; } if (!std::is_same<TypeParam, long double>::value) { LOG(INFO) << "Range {" << lambda << "}: " << sample_min << ", " << sample_max << ", lambda=" << lambda; } std::stringstream ss; ss << before; if (!std::isfinite(lambda)) { continue; } absl::exponential_distribution<TypeParam> after(34.56f); EXPECT_NE(before.lambda(), after.lambda()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.lambda(), after.lambda()) << ss.str() << " " << (ss.good() ? "good " : "") << (ss.bad() ? "bad " : "") << (ss.eof() ? "eof " : "") << (ss.fail() ? "fail " : ""); } } class ExponentialModel { public: explicit ExponentialModel(double lambda) : lambda_(lambda), beta_(1.0 / lambda) {} double lambda() const { return lambda_; } double mean() const { return beta_; } double variance() const { return beta_ * beta_; } double stddev() const { return std::sqrt(variance()); } double skew() const { return 2; } double kurtosis() const { return 6.0; } double CDF(double x) { return 1.0 - std::exp(-lambda_ * x); } double InverseCDF(double p) { ABSL_ASSERT(p >= 0.0); ABSL_ASSERT(p < 1.0); return -beta_ * std::log(1.0 - p); } private: const double lambda_; const double beta_; }; struct Param { double lambda; double p_fail; int trials; }; class ExponentialDistributionTests : public testing::TestWithParam<Param>, public ExponentialModel { public: ExponentialDistributionTests() : ExponentialModel(GetParam().lambda) {} template <typename D> bool SingleZTest(const double p, const size_t samples); template <typename D> double SingleChiSquaredTest(); absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6}; }; template <typename D> bool ExponentialDistributionTests::SingleZTest(const double p, const size_t samples) { D dis(lambda()); std::vector<double> data; data.reserve(samples); for (size_t i = 0; i < samples; i++) { const double x = dis(rng_); data.push_back(x); } const auto m = absl::random_internal::ComputeDistributionMoments(data); const double max_err = absl::random_internal::MaxErrorTolerance(p); const double z = absl::random_internal::ZScore(mean(), m); const bool pass = absl::random_internal::Near("z", z, 0.0, max_err); if (!pass) { LOG(INFO) << "p=" << p << " max_err=" << max_err << "\n" " lambda=" << lambda() << "\n" " mean=" << m.mean << " vs. " << mean() << "\n" " stddev=" << std::sqrt(m.variance) << " vs. " << stddev() << "\n" " skewness=" << m.skewness << " vs. " << skew() << "\n" " kurtosis=" << m.kurtosis << " vs. " << kurtosis() << "\n" " z=" << z << " vs. 0"; } return pass; } template <typename D> double ExponentialDistributionTests::SingleChiSquaredTest() { const size_t kSamples = 10000; const int kBuckets = 50; std::vector<double> cutoffs; const double kInc = 1.0 / static_cast<double>(kBuckets); for (double p = kInc; p < 1.0; p += kInc) { cutoffs.push_back(InverseCDF(p)); } if (cutoffs.back() != std::numeric_limits<double>::infinity()) { cutoffs.push_back(std::numeric_limits<double>::infinity()); } D dis(lambda()); std::vector<int32_t> counts(cutoffs.size(), 0); for (int j = 0; j < kSamples; j++) { const double x = dis(rng_); auto it = std::upper_bound(cutoffs.begin(), cutoffs.end(), x); counts[std::distance(cutoffs.begin(), it)]++; } const int dof = static_cast<int>(counts.size()) - 1; const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98); const double expected = static_cast<double>(kSamples) / static_cast<double>(counts.size()); double chi_square = absl::random_internal::ChiSquareWithExpected( std::begin(counts), std::end(counts), expected); double p = absl::random_internal::ChiSquarePValue(chi_square, dof); if (chi_square > threshold) { for (size_t i = 0; i < cutoffs.size(); i++) { LOG(INFO) << i << " : (" << cutoffs[i] << ") = " << counts[i]; } LOG(INFO) << "lambda " << lambda() << "\n" " expected " << expected << "\n" << kChiSquared << " " << chi_square << " (" << p << ")\n" << kChiSquared << " @ 0.98 = " << threshold; } return p; } TEST_P(ExponentialDistributionTests, ZTest) { const size_t kSamples = 10000; const auto& param = GetParam(); const int expected_failures = std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail))); const double p = absl::random_internal::RequiredSuccessProbability( param.p_fail, param.trials); int failures = 0; for (int i = 0; i < param.trials; i++) { failures += SingleZTest<absl::exponential_distribution<double>>(p, kSamples) ? 0 : 1; } EXPECT_LE(failures, expected_failures); } TEST_P(ExponentialDistributionTests, ChiSquaredTest) { const int kTrials = 20; int failures = 0; for (int i = 0; i < kTrials; i++) { double p_value = SingleChiSquaredTest<absl::exponential_distribution<double>>(); if (p_value < 0.005) { failures++; } } EXPECT_LE(failures, 4); } std::vector<Param> GenParams() { return { Param{1.0, 0.02, 100}, Param{2.5, 0.02, 100}, Param{10, 0.02, 100}, Param{1e4, 0.02, 100}, Param{1e9, 0.02, 100}, Param{0.1, 0.02, 100}, Param{1e-3, 0.02, 100}, Param{1e-5, 0.02, 100}, }; } std::string ParamName(const ::testing::TestParamInfo<Param>& info) { const auto& p = info.param; std::string name = absl::StrCat("lambda_", absl::SixDigits(p.lambda)); return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}}); } INSTANTIATE_TEST_SUITE_P(All, ExponentialDistributionTests, ::testing::ValuesIn(GenParams()), ParamName); TEST(ExponentialDistributionTest, StabilityTest) { absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<int> output(14); { absl::exponential_distribution<double> dist; std::generate(std::begin(output), std::end(output), [&] { return static_cast<int>(10000.0 * dist(urbg)); }); EXPECT_EQ(14, urbg.invocations()); EXPECT_THAT(output, testing::ElementsAre(0, 71913, 14375, 5039, 1835, 861, 25936, 804, 126, 12337, 17984, 27002, 0, 71913)); } urbg.reset(); { absl::exponential_distribution<float> dist; std::generate(std::begin(output), std::end(output), [&] { return static_cast<int>(10000.0f * dist(urbg)); }); EXPECT_EQ(14, urbg.invocations()); EXPECT_THAT(output, testing::ElementsAre(0, 71913, 14375, 5039, 1835, 861, 25936, 804, 126, 12337, 17984, 27002, 0, 71913)); } } TEST(ExponentialDistributionTest, AlgorithmBounds) { #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0 GTEST_SKIP() << "Skipping the test because we detected x87 floating-point semantics"; #endif absl::exponential_distribution<double> dist; { absl::random_internal::sequence_urbg urbg({0x0000000000000001ull}); double a = dist(urbg); EXPECT_EQ(a, 5.42101086242752217004e-20); } { absl::random_internal::sequence_urbg urbg({0x7fffffffffffffefull}); double a = dist(urbg); EXPECT_EQ(a, 0.693147180559945175204); } { absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFeFull}); double a = dist(urbg); EXPECT_EQ(a, 36.7368005696771007251); } { absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFFFull}); double a = dist(urbg); EXPECT_EQ(a, 36.7368005696771007251); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/exponential_distribution.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/exponential_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
3560fe2e-68b3-49ac-ba97-3b1490679161
cpp
abseil/abseil-cpp
explicit_seed_seq
absl/random/internal/explicit_seed_seq.h
absl/random/internal/explicit_seed_seq_test.cc
#ifndef ABSL_RANDOM_INTERNAL_EXPLICIT_SEED_SEQ_H_ #define ABSL_RANDOM_INTERNAL_EXPLICIT_SEED_SEQ_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <initializer_list> #include <iterator> #include <vector> #include "absl/base/config.h" #include "absl/base/internal/endian.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { class ExplicitSeedSeq { public: using result_type = uint32_t; ExplicitSeedSeq() : state_() {} ExplicitSeedSeq(const ExplicitSeedSeq& other) = default; ExplicitSeedSeq& operator=(const ExplicitSeedSeq& other) = default; ExplicitSeedSeq(ExplicitSeedSeq&& other) = default; ExplicitSeedSeq& operator=(ExplicitSeedSeq&& other) = default; template <typename Iterator> ExplicitSeedSeq(Iterator begin, Iterator end) { for (auto it = begin; it != end; it++) { state_.push_back(*it & 0xffffffff); } } template <typename T> ExplicitSeedSeq(std::initializer_list<T> il) : ExplicitSeedSeq(il.begin(), il.end()) {} size_t size() const { return state_.size(); } template <typename OutIterator> void param(OutIterator out) const { std::copy(std::begin(state_), std::end(state_), out); } template <typename OutIterator> void generate(OutIterator begin, OutIterator end) { for (size_t index = 0; begin != end; begin++) { *begin = state_.empty() ? 0 : state_[index++]; if (index >= state_.size()) { index = 0; } } } protected: std::vector<uint32_t> state_; }; } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/explicit_seed_seq.h" #include <iterator> #include <random> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/seed_sequences.h" namespace { using ::absl::random_internal::ExplicitSeedSeq; template <typename Sseq> bool ConformsToInterface() { { Sseq default_constructed_seq; } { uint32_t init_array[] = {1, 3, 5, 7, 9}; Sseq iterator_constructed_seq(init_array, &init_array[5]); } { Sseq list_constructed_seq = {1, 3, 5, 7, 9, 11, 13}; } { uint32_t init_array[] = {1, 2, 3, 4, 5}; Sseq seq(init_array, &init_array[ABSL_ARRAYSIZE(init_array)]); EXPECT_EQ(seq.size(), ABSL_ARRAYSIZE(init_array)); uint32_t state_array[ABSL_ARRAYSIZE(init_array)]; seq.param(state_array); for (int i = 0; i < ABSL_ARRAYSIZE(state_array); i++) { EXPECT_EQ(state_array[i], i + 1); } } { Sseq seq; uint32_t seeds[5]; seq.generate(seeds, &seeds[ABSL_ARRAYSIZE(seeds)]); } return true; } } TEST(SeedSequences, CheckInterfaces) { EXPECT_TRUE(ConformsToInterface<std::seed_seq>()); EXPECT_TRUE(ConformsToInterface<ExplicitSeedSeq>()); } TEST(ExplicitSeedSeq, DefaultConstructorGeneratesZeros) { const size_t kNumBlocks = 128; uint32_t outputs[kNumBlocks]; ExplicitSeedSeq seq; seq.generate(outputs, &outputs[kNumBlocks]); for (uint32_t& seed : outputs) { EXPECT_EQ(seed, 0); } } TEST(ExplicitSeeqSeq, SeedMaterialIsForwardedIdentically) { const size_t kNumBlocks = 128; uint32_t seed_material[kNumBlocks]; std::random_device urandom{"/dev/urandom"}; for (uint32_t& seed : seed_material) { seed = urandom(); } ExplicitSeedSeq seq(seed_material, &seed_material[kNumBlocks]); { const size_t kNumGenerated = kNumBlocks / 2; uint32_t outputs[kNumGenerated]; seq.generate(outputs, &outputs[kNumGenerated]); for (size_t i = 0; i < kNumGenerated; i++) { EXPECT_EQ(outputs[i], seed_material[i]); } } { const size_t kNumGenerated = kNumBlocks; uint32_t outputs[kNumGenerated]; seq.generate(outputs, &outputs[kNumGenerated]); for (size_t i = 0; i < kNumGenerated; i++) { EXPECT_EQ(outputs[i], seed_material[i]); } } { const size_t kNumGenerated = kNumBlocks * 2; uint32_t outputs[kNumGenerated]; seq.generate(outputs, &outputs[kNumGenerated]); for (size_t i = 0; i < kNumGenerated; i++) { EXPECT_EQ(outputs[i], seed_material[i % kNumBlocks]); } } } TEST(ExplicitSeedSeq, CopyAndMoveConstructors) { using testing::Each; using testing::Eq; using testing::Not; using testing::Pointwise; uint32_t entropy[4]; std::random_device urandom("/dev/urandom"); for (uint32_t& entry : entropy) { entry = urandom(); } ExplicitSeedSeq seq_from_entropy(std::begin(entropy), std::end(entropy)); { ExplicitSeedSeq seq_copy(seq_from_entropy); EXPECT_EQ(seq_copy.size(), seq_from_entropy.size()); std::vector<uint32_t> seeds_1(1000, 0); std::vector<uint32_t> seeds_2(1000, 1); seq_from_entropy.generate(seeds_1.begin(), seeds_1.end()); seq_copy.generate(seeds_2.begin(), seeds_2.end()); EXPECT_THAT(seeds_1, Pointwise(Eq(), seeds_2)); } { for (uint32_t& entry : entropy) { entry = urandom(); } ExplicitSeedSeq another_seq(std::begin(entropy), std::end(entropy)); std::vector<uint32_t> seeds_1(1000, 0); std::vector<uint32_t> seeds_2(1000, 0); seq_from_entropy.generate(seeds_1.begin(), seeds_1.end()); another_seq.generate(seeds_2.begin(), seeds_2.end()); EXPECT_THAT(seeds_1, Not(Pointwise(Eq(), seeds_2))); #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstringop-overflow" #endif another_seq = seq_from_entropy; #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic pop #endif seq_from_entropy.generate(seeds_1.begin(), seeds_1.end()); another_seq.generate(seeds_2.begin(), seeds_2.end()); EXPECT_THAT(seeds_1, Pointwise(Eq(), seeds_2)); } { std::vector<uint32_t> seeds_1(1000, 0); seq_from_entropy.generate(seeds_1.begin(), seeds_1.end()); absl::random_internal::ExplicitSeedSeq moved_seq( std::move(seq_from_entropy)); std::vector<uint32_t> seeds_2(1000, 1); moved_seq.generate(seeds_2.begin(), seeds_2.end()); EXPECT_THAT(seeds_1, Pointwise(Eq(), seeds_2)); EXPECT_EQ(seq_from_entropy.size(), 0); seq_from_entropy.generate(seeds_1.begin(), seeds_1.end()); EXPECT_THAT(seeds_1, Each(Eq(0))); } } TEST(ExplicitSeedSeq, StdURBGGoldenTests) { { ExplicitSeedSeq seed_sequence{12, 34, 56}; std::minstd_rand rng(seed_sequence); std::minstd_rand::result_type values[4] = {rng(), rng(), rng(), rng()}; EXPECT_THAT(values, testing::ElementsAre(579252, 43785881, 464353103, 1501811174)); } { ExplicitSeedSeq seed_sequence{12, 34, 56}; std::mt19937 rng(seed_sequence); std::mt19937::result_type values[4] = {rng(), rng(), rng(), rng()}; EXPECT_THAT(values, testing::ElementsAre(138416803, 151130212, 33817739, 138416803)); } { ExplicitSeedSeq seed_sequence{12, 34, 56}; std::mt19937_64 rng(seed_sequence); std::mt19937_64::result_type values[4] = {rng(), rng(), rng(), rng()}; EXPECT_THAT(values, testing::ElementsAre(19738651785169348, 1464811352364190456, 18054685302720800, 19738651785169348)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/explicit_seed_seq.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/explicit_seed_seq_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
13c74551-8b9b-4b0c-9ad5-cb802b4f4b9c
cpp
abseil/abseil-cpp
fast_uniform_bits
absl/random/internal/fast_uniform_bits.h
absl/random/internal/fast_uniform_bits_test.cc
#ifndef ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_ #define ABSL_RANDOM_INTERNAL_FAST_UNIFORM_BITS_H_ #include <cstddef> #include <cstdint> #include <limits> #include <type_traits> #include "absl/base/config.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename UIntType> constexpr bool IsPowerOfTwoOrZero(UIntType n) { return (n == 0) || ((n & (n - 1)) == 0); } template <typename URBG> constexpr typename URBG::result_type RangeSize() { using result_type = typename URBG::result_type; static_assert((URBG::max)() != (URBG::min)(), "URBG range cannot be 0."); return ((URBG::max)() == (std::numeric_limits<result_type>::max)() && (URBG::min)() == std::numeric_limits<result_type>::lowest()) ? result_type{0} : ((URBG::max)() - (URBG::min)() + result_type{1}); } template <typename UIntType> constexpr UIntType IntegerLog2(UIntType n) { return (n <= 1) ? 0 : 1 + IntegerLog2(n >> 1); } template <typename URBG> constexpr size_t NumBits() { return static_cast<size_t>( RangeSize<URBG>() == 0 ? std::numeric_limits<typename URBG::result_type>::digits : IntegerLog2(RangeSize<URBG>())); } template <typename UIntType> constexpr UIntType MaskFromShift(size_t n) { return ((n % std::numeric_limits<UIntType>::digits) == 0) ? ~UIntType{0} : (UIntType{1} << n) - UIntType{1}; } struct SimplifiedLoopTag {}; struct RejectionLoopTag {}; template <typename UIntType = uint64_t> class FastUniformBits { public: using result_type = UIntType; static constexpr result_type(min)() { return 0; } static constexpr result_type(max)() { return (std::numeric_limits<result_type>::max)(); } template <typename URBG> result_type operator()(URBG& g); private: static_assert(IsUnsigned<UIntType>::value, "Class-template FastUniformBits<> must be parameterized using " "an unsigned type."); template <typename URBG> result_type Generate(URBG& g, SimplifiedLoopTag); template <typename URBG> result_type Generate(URBG& g, RejectionLoopTag); }; template <typename UIntType> template <typename URBG> typename FastUniformBits<UIntType>::result_type FastUniformBits<UIntType>::operator()(URBG& g) { static_assert((URBG::max)() > (URBG::min)(), "URBG::max and URBG::min may not be equal."); using tag = absl::conditional_t<IsPowerOfTwoOrZero(RangeSize<URBG>()), SimplifiedLoopTag, RejectionLoopTag>; return Generate(g, tag{}); } template <typename UIntType> template <typename URBG> typename FastUniformBits<UIntType>::result_type FastUniformBits<UIntType>::Generate(URBG& g, SimplifiedLoopTag) { static_assert(IsPowerOfTwoOrZero(RangeSize<URBG>()), "incorrect Generate tag for URBG instance"); static constexpr size_t kResultBits = std::numeric_limits<result_type>::digits; static constexpr size_t kUrbgBits = NumBits<URBG>(); static constexpr size_t kIters = (kResultBits / kUrbgBits) + (kResultBits % kUrbgBits != 0); static constexpr size_t kShift = (kIters == 1) ? 0 : kUrbgBits; static constexpr auto kMin = (URBG::min)(); result_type r = static_cast<result_type>(g() - kMin); for (size_t n = 1; n < kIters; ++n) { r = static_cast<result_type>(r << kShift) + static_cast<result_type>(g() - kMin); } return r; } template <typename UIntType> template <typename URBG> typename FastUniformBits<UIntType>::result_type FastUniformBits<UIntType>::Generate(URBG& g, RejectionLoopTag) { static_assert(!IsPowerOfTwoOrZero(RangeSize<URBG>()), "incorrect Generate tag for URBG instance"); using urbg_result_type = typename URBG::result_type; static constexpr size_t kResultBits = std::numeric_limits<result_type>::digits; static constexpr urbg_result_type kUrbgRange = RangeSize<URBG>(); static constexpr size_t kUrbgBits = NumBits<URBG>(); static constexpr size_t kA = (kResultBits / kUrbgBits) + ((kResultBits % kUrbgBits) != 0); static constexpr size_t kABits = kResultBits / kA; static constexpr urbg_result_type kARejection = ((kUrbgRange >> kABits) << kABits); static constexpr size_t kTotalIters = ((kUrbgRange - kARejection) <= (kARejection / kA)) ? kA : (kA + 1); static constexpr size_t kSmallIters = kTotalIters - (kResultBits % kTotalIters); static constexpr size_t kSmallBits = kResultBits / kTotalIters; static constexpr urbg_result_type kSmallRejection = ((kUrbgRange >> kSmallBits) << kSmallBits); static constexpr size_t kLargeBits = kSmallBits + 1; static constexpr urbg_result_type kLargeRejection = ((kUrbgRange >> kLargeBits) << kLargeBits); static_assert(kResultBits == kSmallIters * kSmallBits + (kTotalIters - kSmallIters) * kLargeBits, "Error in looping constant calculations."); static constexpr size_t kSmallShift = kSmallBits % kResultBits; static constexpr auto kSmallMask = MaskFromShift<urbg_result_type>(kSmallShift); static constexpr size_t kLargeShift = kLargeBits % kResultBits; static constexpr auto kLargeMask = MaskFromShift<urbg_result_type>(kLargeShift); static constexpr auto kMin = (URBG::min)(); result_type s = 0; for (size_t n = 0; n < kSmallIters; ++n) { urbg_result_type v; do { v = g() - kMin; } while (v >= kSmallRejection); s = (s << kSmallShift) + static_cast<result_type>(v & kSmallMask); } for (size_t n = kSmallIters; n < kTotalIters; ++n) { urbg_result_type v; do { v = g() - kMin; } while (v >= kLargeRejection); s = (s << kLargeShift) + static_cast<result_type>(v & kLargeMask); } return s; } } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/fast_uniform_bits.h" #include <random> #include "gtest/gtest.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { namespace { template <typename IntType> class FastUniformBitsTypedTest : public ::testing::Test {}; using IntTypes = ::testing::Types<uint8_t, uint16_t, uint32_t, uint64_t>; TYPED_TEST_SUITE(FastUniformBitsTypedTest, IntTypes); TYPED_TEST(FastUniformBitsTypedTest, BasicTest) { using Limits = std::numeric_limits<TypeParam>; using FastBits = FastUniformBits<TypeParam>; EXPECT_EQ(0, (FastBits::min)()); EXPECT_EQ((Limits::max)(), (FastBits::max)()); constexpr int kIters = 10000; std::random_device rd; std::mt19937 gen(rd()); FastBits fast; for (int i = 0; i < kIters; i++) { const auto v = fast(gen); EXPECT_LE(v, (FastBits::max)()); EXPECT_GE(v, (FastBits::min)()); } } template <typename UIntType, UIntType Lo, UIntType Hi, UIntType Val = Lo> struct FakeUrbg { using result_type = UIntType; FakeUrbg() = default; explicit FakeUrbg(bool r) : reject(r) {} static constexpr result_type(max)() { return Hi; } static constexpr result_type(min)() { return Lo; } result_type operator()() { return ((++calls % 2) == 1 && reject) ? Hi : Val; } bool reject = false; size_t calls = 0; }; TEST(FastUniformBitsTest, IsPowerOfTwoOrZero) { EXPECT_TRUE(IsPowerOfTwoOrZero(uint8_t{0})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint8_t{1})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint8_t{2})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint8_t{3})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint8_t{4})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint8_t{16})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint8_t{17})); EXPECT_FALSE(IsPowerOfTwoOrZero((std::numeric_limits<uint8_t>::max)())); EXPECT_TRUE(IsPowerOfTwoOrZero(uint16_t{0})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint16_t{1})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint16_t{2})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint16_t{3})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint16_t{4})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint16_t{16})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint16_t{17})); EXPECT_FALSE(IsPowerOfTwoOrZero((std::numeric_limits<uint16_t>::max)())); EXPECT_TRUE(IsPowerOfTwoOrZero(uint32_t{0})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint32_t{1})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint32_t{2})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint32_t{3})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint32_t{32})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint32_t{17})); EXPECT_FALSE(IsPowerOfTwoOrZero((std::numeric_limits<uint32_t>::max)())); EXPECT_TRUE(IsPowerOfTwoOrZero(uint64_t{0})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint64_t{1})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint64_t{2})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint64_t{3})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint64_t{4})); EXPECT_TRUE(IsPowerOfTwoOrZero(uint64_t{64})); EXPECT_FALSE(IsPowerOfTwoOrZero(uint64_t{17})); EXPECT_FALSE(IsPowerOfTwoOrZero((std::numeric_limits<uint64_t>::max)())); } TEST(FastUniformBitsTest, IntegerLog2) { EXPECT_EQ(0, IntegerLog2(uint16_t{0})); EXPECT_EQ(0, IntegerLog2(uint16_t{1})); EXPECT_EQ(1, IntegerLog2(uint16_t{2})); EXPECT_EQ(1, IntegerLog2(uint16_t{3})); EXPECT_EQ(2, IntegerLog2(uint16_t{4})); EXPECT_EQ(2, IntegerLog2(uint16_t{5})); EXPECT_EQ(2, IntegerLog2(uint16_t{7})); EXPECT_EQ(3, IntegerLog2(uint16_t{8})); EXPECT_EQ(63, IntegerLog2((std::numeric_limits<uint64_t>::max)())); } TEST(FastUniformBitsTest, RangeSize) { EXPECT_EQ(2, (RangeSize<FakeUrbg<uint8_t, 0, 1>>())); EXPECT_EQ(3, (RangeSize<FakeUrbg<uint8_t, 0, 2>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint8_t, 0, 3>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint8_t, 2, 5>>())); EXPECT_EQ(5, (RangeSize<FakeUrbg<uint8_t, 2, 6>>())); EXPECT_EQ(9, (RangeSize<FakeUrbg<uint8_t, 2, 10>>())); EXPECT_EQ( 0, (RangeSize< FakeUrbg<uint8_t, 0, (std::numeric_limits<uint8_t>::max)()>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint16_t, 0, 3>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint16_t, 2, 5>>())); EXPECT_EQ(5, (RangeSize<FakeUrbg<uint16_t, 2, 6>>())); EXPECT_EQ(18, (RangeSize<FakeUrbg<uint16_t, 1000, 1017>>())); EXPECT_EQ( 0, (RangeSize< FakeUrbg<uint16_t, 0, (std::numeric_limits<uint16_t>::max)()>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint32_t, 0, 3>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint32_t, 2, 5>>())); EXPECT_EQ(5, (RangeSize<FakeUrbg<uint32_t, 2, 6>>())); EXPECT_EQ(18, (RangeSize<FakeUrbg<uint32_t, 1000, 1017>>())); EXPECT_EQ(0, (RangeSize<FakeUrbg<uint32_t, 0, 0xffffffff>>())); EXPECT_EQ(0xffffffff, (RangeSize<FakeUrbg<uint32_t, 1, 0xffffffff>>())); EXPECT_EQ(0xfffffffe, (RangeSize<FakeUrbg<uint32_t, 1, 0xfffffffe>>())); EXPECT_EQ(0xfffffffd, (RangeSize<FakeUrbg<uint32_t, 2, 0xfffffffe>>())); EXPECT_EQ( 0, (RangeSize< FakeUrbg<uint32_t, 0, (std::numeric_limits<uint32_t>::max)()>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint64_t, 0, 3>>())); EXPECT_EQ(4, (RangeSize<FakeUrbg<uint64_t, 2, 5>>())); EXPECT_EQ(5, (RangeSize<FakeUrbg<uint64_t, 2, 6>>())); EXPECT_EQ(18, (RangeSize<FakeUrbg<uint64_t, 1000, 1017>>())); EXPECT_EQ(0x100000000, (RangeSize<FakeUrbg<uint64_t, 0, 0xffffffff>>())); EXPECT_EQ(0xffffffff, (RangeSize<FakeUrbg<uint64_t, 1, 0xffffffff>>())); EXPECT_EQ(0xfffffffe, (RangeSize<FakeUrbg<uint64_t, 1, 0xfffffffe>>())); EXPECT_EQ(0xfffffffd, (RangeSize<FakeUrbg<uint64_t, 2, 0xfffffffe>>())); EXPECT_EQ(0, (RangeSize<FakeUrbg<uint64_t, 0, 0xffffffffffffffff>>())); EXPECT_EQ(0xffffffffffffffff, (RangeSize<FakeUrbg<uint64_t, 1, 0xffffffffffffffff>>())); EXPECT_EQ(0xfffffffffffffffe, (RangeSize<FakeUrbg<uint64_t, 1, 0xfffffffffffffffe>>())); EXPECT_EQ(0xfffffffffffffffd, (RangeSize<FakeUrbg<uint64_t, 2, 0xfffffffffffffffe>>())); EXPECT_EQ( 0, (RangeSize< FakeUrbg<uint64_t, 0, (std::numeric_limits<uint64_t>::max)()>>())); } using Urng1_5bit = FakeUrbg<uint8_t, 0, 2, 0>; using Urng4bits = FakeUrbg<uint8_t, 1, 0x10, 2>; using Urng22bits = FakeUrbg<uint32_t, 0, 0x3fffff, 0x301020>; using Urng31bits = FakeUrbg<uint32_t, 1, 0xfffffffe, 0x60070f03>; using Urng32bits = FakeUrbg<uint32_t, 0, 0xffffffff, 0x74010f01>; using Urng33bits = FakeUrbg<uint64_t, 1, 0x1ffffffff, 0x013301033>; using Urng63bits = FakeUrbg<uint64_t, 1, 0xfffffffffffffffe, 0xfedcba9012345678>; using Urng64bits = FakeUrbg<uint64_t, 0, 0xffffffffffffffff, 0x123456780fedcba9>; TEST(FastUniformBitsTest, OutputsUpTo32Bits) { Urng1_5bit urng1_5; Urng4bits urng4; Urng22bits urng22; Urng31bits urng31; Urng32bits urng32; Urng33bits urng33; Urng63bits urng63; Urng64bits urng64; { FastUniformBits<uint8_t> fast8; EXPECT_EQ(0x0, fast8(urng1_5)); EXPECT_EQ(0x11, fast8(urng4)); EXPECT_EQ(0x20, fast8(urng22)); EXPECT_EQ(0x2, fast8(urng31)); EXPECT_EQ(0x1, fast8(urng32)); EXPECT_EQ(0x32, fast8(urng33)); EXPECT_EQ(0x77, fast8(urng63)); EXPECT_EQ(0xa9, fast8(urng64)); } { FastUniformBits<uint16_t> fast16; EXPECT_EQ(0x0, fast16(urng1_5)); EXPECT_EQ(0x1111, fast16(urng4)); EXPECT_EQ(0x1020, fast16(urng22)); EXPECT_EQ(0x0f02, fast16(urng31)); EXPECT_EQ(0x0f01, fast16(urng32)); EXPECT_EQ(0x1032, fast16(urng33)); EXPECT_EQ(0x5677, fast16(urng63)); EXPECT_EQ(0xcba9, fast16(urng64)); } { FastUniformBits<uint32_t> fast32; EXPECT_EQ(0x0, fast32(urng1_5)); EXPECT_EQ(0x11111111, fast32(urng4)); EXPECT_EQ(0x08301020, fast32(urng22)); EXPECT_EQ(0x0f020f02, fast32(urng31)); EXPECT_EQ(0x74010f01, fast32(urng32)); EXPECT_EQ(0x13301032, fast32(urng33)); EXPECT_EQ(0x12345677, fast32(urng63)); EXPECT_EQ(0x0fedcba9, fast32(urng64)); } } TEST(FastUniformBitsTest, Outputs64Bits) { FastUniformBits<uint64_t> fast64; { FakeUrbg<uint8_t, 0, 1, 0> urng0; FakeUrbg<uint8_t, 0, 1, 1> urng1; Urng4bits urng4; Urng22bits urng22; Urng31bits urng31; Urng32bits urng32; Urng33bits urng33; Urng63bits urng63; Urng64bits urng64; EXPECT_EQ(0x0, fast64(urng0)); EXPECT_EQ(64, urng0.calls); EXPECT_EQ(0xffffffffffffffff, fast64(urng1)); EXPECT_EQ(64, urng1.calls); EXPECT_EQ(0x1111111111111111, fast64(urng4)); EXPECT_EQ(16, urng4.calls); EXPECT_EQ(0x01020c0408301020, fast64(urng22)); EXPECT_EQ(3, urng22.calls); EXPECT_EQ(0x387811c3c0870f02, fast64(urng31)); EXPECT_EQ(3, urng31.calls); EXPECT_EQ(0x74010f0174010f01, fast64(urng32)); EXPECT_EQ(2, urng32.calls); EXPECT_EQ(0x808194040cb01032, fast64(urng33)); EXPECT_EQ(3, urng33.calls); EXPECT_EQ(0x1234567712345677, fast64(urng63)); EXPECT_EQ(2, urng63.calls); EXPECT_EQ(0x123456780fedcba9, fast64(urng64)); EXPECT_EQ(1, urng64.calls); } { Urng1_5bit urng1_5; EXPECT_EQ(0x0, fast64(urng1_5)); EXPECT_EQ(65, urng1_5.calls); } { Urng1_5bit urng1_5(true); Urng31bits urng31(true); Urng33bits urng33(true); Urng63bits urng63(true); EXPECT_EQ(0, fast64(urng1_5)); EXPECT_EQ(128, urng1_5.calls); EXPECT_EQ(0x387811c3c0870f02, fast64(urng31)); EXPECT_EQ(6, urng31.calls); EXPECT_EQ(0x808194040cb01032, fast64(urng33)); EXPECT_EQ(6, urng33.calls); EXPECT_EQ(0x1234567712345677, fast64(urng63)); EXPECT_EQ(4, urng63.calls); } } TEST(FastUniformBitsTest, URBG32bitRegression) { EXPECT_EQ(2147483646, RangeSize<std::minstd_rand>()); EXPECT_EQ(30, IntegerLog2(RangeSize<std::minstd_rand>())); std::minstd_rand gen(1); FastUniformBits<uint64_t> fast64; EXPECT_EQ(0x05e47095f8791f45, fast64(gen)); EXPECT_EQ(0x028be17e3c07c122, fast64(gen)); EXPECT_EQ(0x55d2847c1626e8c2, fast64(gen)); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/fast_uniform_bits.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/fast_uniform_bits_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f984bfc5-570a-4e15-a5fa-d3f2a282abf0
cpp
abseil/abseil-cpp
iostream_state_saver
absl/random/internal/iostream_state_saver.h
absl/random/internal/iostream_state_saver_test.cc
#ifndef ABSL_RANDOM_INTERNAL_IOSTREAM_STATE_SAVER_H_ #define ABSL_RANDOM_INTERNAL_IOSTREAM_STATE_SAVER_H_ #include <cmath> #include <iostream> #include <limits> #include <type_traits> #include "absl/meta/type_traits.h" #include "absl/numeric/int128.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename T> class null_state_saver { public: using stream_type = T; using flags_type = std::ios_base::fmtflags; null_state_saver(T&, flags_type) {} ~null_state_saver() {} }; template <typename OStream> class ostream_state_saver { public: using ostream_type = OStream; using flags_type = std::ios_base::fmtflags; using fill_type = typename ostream_type::char_type; using precision_type = std::streamsize; ostream_state_saver(ostream_type& os, flags_type flags, fill_type fill) : os_(os), flags_(os.flags(flags)), fill_(os.fill(fill)), precision_(os.precision()) { } ~ostream_state_saver() { os_.precision(precision_); os_.fill(fill_); os_.flags(flags_); } private: ostream_type& os_; const flags_type flags_; const fill_type fill_; const precision_type precision_; }; #if defined(__NDK_MAJOR__) && __NDK_MAJOR__ < 16 #define ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT 1 #else #define ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT 0 #endif template <typename CharT, typename Traits> ostream_state_saver<std::basic_ostream<CharT, Traits>> make_ostream_state_saver( std::basic_ostream<CharT, Traits>& os, std::ios_base::fmtflags flags = std::ios_base::dec | std::ios_base::left | #if ABSL_RANDOM_INTERNAL_IOSTREAM_HEXFLOAT std::ios_base::fixed | #endif std::ios_base::scientific) { using result_type = ostream_state_saver<std::basic_ostream<CharT, Traits>>; return result_type(os, flags, os.widen(' ')); } template <typename T> typename absl::enable_if_t<!std::is_base_of<std::ios_base, T>::value, null_state_saver<T>> make_ostream_state_saver(T& is, std::ios_base::fmtflags flags = std::ios_base::dec) { std::cerr << "null_state_saver"; using result_type = null_state_saver<T>; return result_type(is, flags); } template <typename T> struct stream_precision_helper { static constexpr int kPrecision = (std::numeric_limits<T>::max_digits10 > std::numeric_limits<T>::digits10) ? std::numeric_limits<T>::max_digits10 : (std::numeric_limits<T>::digits10 + 3); }; template <> struct stream_precision_helper<float> { static constexpr int kPrecision = 9; }; template <> struct stream_precision_helper<double> { static constexpr int kPrecision = 17; }; template <> struct stream_precision_helper<long double> { static constexpr int kPrecision = 36; }; template <typename IStream> class istream_state_saver { public: using istream_type = IStream; using flags_type = std::ios_base::fmtflags; istream_state_saver(istream_type& is, flags_type flags) : is_(is), flags_(is.flags(flags)) {} ~istream_state_saver() { is_.flags(flags_); } private: istream_type& is_; flags_type flags_; }; template <typename CharT, typename Traits> istream_state_saver<std::basic_istream<CharT, Traits>> make_istream_state_saver( std::basic_istream<CharT, Traits>& is, std::ios_base::fmtflags flags = std::ios_base::dec | std::ios_base::scientific | std::ios_base::skipws) { using result_type = istream_state_saver<std::basic_istream<CharT, Traits>>; return result_type(is, flags); } template <typename T> typename absl::enable_if_t<!std::is_base_of<std::ios_base, T>::value, null_state_saver<T>> make_istream_state_saver(T& is, std::ios_base::fmtflags flags = std::ios_base::dec) { using result_type = null_state_saver<T>; return result_type(is, flags); } template <typename T> struct stream_format_type : public std::conditional<(sizeof(T) == sizeof(char)), int, T> {}; template <typename T> struct stream_u128_helper; template <> struct stream_u128_helper<absl::uint128> { template <typename IStream> inline absl::uint128 read(IStream& in) { uint64_t h = 0; uint64_t l = 0; in >> h >> l; return absl::MakeUint128(h, l); } template <typename OStream> inline void write(absl::uint128 val, OStream& out) { uint64_t h = absl::Uint128High64(val); uint64_t l = absl::Uint128Low64(val); out << h << out.fill() << l; } }; #ifdef ABSL_HAVE_INTRINSIC_INT128 template <> struct stream_u128_helper<__uint128_t> { template <typename IStream> inline __uint128_t read(IStream& in) { uint64_t h = 0; uint64_t l = 0; in >> h >> l; return (static_cast<__uint128_t>(h) << 64) | l; } template <typename OStream> inline void write(__uint128_t val, OStream& out) { uint64_t h = static_cast<uint64_t>(val >> 64u); uint64_t l = static_cast<uint64_t>(val); out << h << out.fill() << l; } }; #endif template <typename FloatType, typename IStream> inline FloatType read_floating_point(IStream& is) { static_assert(std::is_floating_point<FloatType>::value, ""); FloatType dest; is >> dest; if (is.fail() && (std::fabs(dest) == (std::numeric_limits<FloatType>::min)() || std::fpclassify(dest) == FP_SUBNORMAL)) { is.clear(is.rdstate() & (~std::ios_base::failbit)); } return dest; } } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/iostream_state_saver.h" #include <errno.h> #include <stdio.h> #include <sstream> #include <string> #include "gtest/gtest.h" namespace { using absl::random_internal::make_istream_state_saver; using absl::random_internal::make_ostream_state_saver; using absl::random_internal::stream_precision_helper; template <typename T> typename absl::enable_if_t<std::is_integral<T>::value, T> StreamRoundTrip(T t) { std::stringstream ss; { auto saver = make_ostream_state_saver(ss); ss.precision(stream_precision_helper<T>::kPrecision); ss << t; } T result = 0; { auto saver = make_istream_state_saver(ss); ss >> result; } EXPECT_FALSE(ss.fail()) << ss.str() << " " << (ss.good() ? "good " : "") << (ss.bad() ? "bad " : "") << (ss.eof() ? "eof " : "") << (ss.fail() ? "fail " : ""); return result; } template <typename T> typename absl::enable_if_t<std::is_floating_point<T>::value, T> StreamRoundTrip(T t) { std::stringstream ss; { auto saver = make_ostream_state_saver(ss); ss.precision(stream_precision_helper<T>::kPrecision); ss << t; } T result = 0; { auto saver = make_istream_state_saver(ss); result = absl::random_internal::read_floating_point<T>(ss); } EXPECT_FALSE(ss.fail()) << ss.str() << " " << (ss.good() ? "good " : "") << (ss.bad() ? "bad " : "") << (ss.eof() ? "eof " : "") << (ss.fail() ? "fail " : ""); return result; } TEST(IOStreamStateSaver, BasicSaverState) { std::stringstream ss; ss.precision(2); ss.fill('x'); ss.flags(std::ios_base::dec | std::ios_base::right); { auto saver = make_ostream_state_saver(ss); ss.precision(10); EXPECT_NE('x', ss.fill()); EXPECT_EQ(10, ss.precision()); EXPECT_NE(std::ios_base::dec | std::ios_base::right, ss.flags()); ss << 1.23; } EXPECT_EQ('x', ss.fill()); EXPECT_EQ(2, ss.precision()); EXPECT_EQ(std::ios_base::dec | std::ios_base::right, ss.flags()); } TEST(IOStreamStateSaver, RoundTripInts) { const uint64_t kUintValues[] = { 0, 1, static_cast<uint64_t>(-1), 2, static_cast<uint64_t>(-2), 1 << 7, 1 << 8, 1 << 16, 1ull << 32, 1ull << 50, 1ull << 62, 1ull << 63, (1 << 7) - 1, (1 << 8) - 1, (1 << 16) - 1, (1ull << 32) - 1, (1ull << 50) - 1, (1ull << 62) - 1, (1ull << 63) - 1, static_cast<uint64_t>(-(1 << 8)), static_cast<uint64_t>(-(1 << 16)), static_cast<uint64_t>(-(1ll << 32)), static_cast<uint64_t>(-(1ll << 50)), static_cast<uint64_t>(-(1ll << 62)), static_cast<uint64_t>(-(1 << 8) - 1), static_cast<uint64_t>(-(1 << 16) - 1), static_cast<uint64_t>(-(1ll << 32) - 1), static_cast<uint64_t>(-(1ll << 50) - 1), static_cast<uint64_t>(-(1ll << 62) - 1), }; for (const uint64_t u : kUintValues) { EXPECT_EQ(u, StreamRoundTrip<uint64_t>(u)); int64_t x = static_cast<int64_t>(u); EXPECT_EQ(x, StreamRoundTrip<int64_t>(x)); double d = static_cast<double>(x); EXPECT_EQ(d, StreamRoundTrip<double>(d)); float f = d; EXPECT_EQ(f, StreamRoundTrip<float>(f)); } } TEST(IOStreamStateSaver, RoundTripFloats) { static_assert( stream_precision_helper<float>::kPrecision >= 9, "stream_precision_helper<float>::kPrecision should be at least 9"); const float kValues[] = { 1, std::nextafter(1.0f, 0.0f), std::nextafter(1.0f, 2.0f), 1.0e+1f, 1.0e-1f, 1.0e+2f, 1.0e-2f, 1.0e+10f, 1.0e-10f, 0.00000051110000111311111111f, -0.00000051110000111211111111f, 1.234678912345678912345e+6f, 1.234678912345678912345e-6f, 1.234678912345678912345e+30f, 1.234678912345678912345e-30f, 1.234678912345678912345e+38f, 1.0234678912345678912345e-38f, std::numeric_limits<float>::max(), std::numeric_limits<float>::lowest(), std::numeric_limits<float>::epsilon(), std::nextafter(std::numeric_limits<float>::min(), 1.0f), std::numeric_limits<float>::min(), std::numeric_limits<float>::denorm_min(), std::numeric_limits<float>::min() / 2, std::nextafter(std::numeric_limits<float>::min(), 0.0f), std::nextafter(std::numeric_limits<float>::denorm_min(), 1.0f), }; for (const float f : kValues) { EXPECT_EQ(f, StreamRoundTrip<float>(f)); EXPECT_EQ(-f, StreamRoundTrip<float>(-f)); double d = f; EXPECT_EQ(d, StreamRoundTrip<double>(d)); EXPECT_EQ(-d, StreamRoundTrip<double>(-d)); if (f <= static_cast<float>(std::numeric_limits<int64_t>::max()) && f >= static_cast<float>(std::numeric_limits<int64_t>::lowest())) { int64_t x = static_cast<int64_t>(f); EXPECT_EQ(x, StreamRoundTrip<int64_t>(x)); } } } TEST(IOStreamStateSaver, RoundTripDoubles) { static_assert( stream_precision_helper<double>::kPrecision >= 17, "stream_precision_helper<double>::kPrecision should be at least 17"); const double kValues[] = { 1, std::nextafter(1.0, 0.0), std::nextafter(1.0, 2.0), 1.0e+1, 1.0e-1, 1.0e+2, 1.0e-2, 1.0e+10, 1.0e-10, 0.00000051110000111311111111, -0.00000051110000111211111111, 1.234678912345678912345e+6, 1.234678912345678912345e-6, 1.234678912345678912345e+30, 1.234678912345678912345e-30, 1.234678912345678912345e+38, 1.0234678912345678912345e-38, 1.0e+100, 1.0e-100, 1.234678912345678912345e+308, 1.0234678912345678912345e-308, 2.22507385850720138e-308, std::numeric_limits<double>::max(), std::numeric_limits<double>::lowest(), std::numeric_limits<double>::epsilon(), std::nextafter(std::numeric_limits<double>::min(), 1.0), std::numeric_limits<double>::min(), std::numeric_limits<double>::denorm_min(), std::numeric_limits<double>::min() / 2, std::nextafter(std::numeric_limits<double>::min(), 0.0), std::nextafter(std::numeric_limits<double>::denorm_min(), 1.0f), }; for (const double d : kValues) { EXPECT_EQ(d, StreamRoundTrip<double>(d)); EXPECT_EQ(-d, StreamRoundTrip<double>(-d)); if (d <= std::numeric_limits<float>::max() && d >= std::numeric_limits<float>::lowest()) { float f = static_cast<float>(d); EXPECT_EQ(f, StreamRoundTrip<float>(f)); } if (d <= static_cast<double>(std::numeric_limits<int64_t>::max()) && d >= static_cast<double>(std::numeric_limits<int64_t>::lowest())) { int64_t x = static_cast<int64_t>(d); EXPECT_EQ(x, StreamRoundTrip<int64_t>(x)); } } } TEST(IOStreamStateSaver, RoundTripLongDoubles) { static_assert( stream_precision_helper<long double>::kPrecision >= 36, "stream_precision_helper<long double>::kPrecision should be at least 36"); using real_type = long double; const real_type kValues[] = { 1, std::nextafter(1.0, 0.0), std::nextafter(1.0, 2.0), 1.0e+1, 1.0e-1, 1.0e+2, 1.0e-2, 1.0e+10, 1.0e-10, 0.00000051110000111311111111, -0.00000051110000111211111111, 1.2346789123456789123456789123456789e+6, 1.2346789123456789123456789123456789e-6, 1.2346789123456789123456789123456789e+30, 1.2346789123456789123456789123456789e-30, 1.2346789123456789123456789123456789e+38, 1.2346789123456789123456789123456789e-38, 1.2346789123456789123456789123456789e+308, 1.2346789123456789123456789123456789e-308, 1.0e+100, 1.0e-100, 1.234678912345678912345e+308, 1.0234678912345678912345e-308, std::numeric_limits<real_type>::max(), std::numeric_limits<real_type>::lowest(), std::numeric_limits<real_type>::epsilon(), std::nextafter(std::numeric_limits<real_type>::min(), real_type(1)), std::numeric_limits<real_type>::min(), std::numeric_limits<real_type>::denorm_min(), std::numeric_limits<real_type>::min() / 2, std::nextafter(std::numeric_limits<real_type>::min(), 0.0), std::nextafter(std::numeric_limits<real_type>::denorm_min(), 1.0f), }; int index = -1; for (const long double dd : kValues) { index++; EXPECT_EQ(dd, StreamRoundTrip<real_type>(dd)) << index; EXPECT_EQ(-dd, StreamRoundTrip<real_type>(-dd)) << index; if (dd <= std::numeric_limits<double>::max() && dd >= std::numeric_limits<double>::lowest()) { double d = static_cast<double>(dd); EXPECT_EQ(d, StreamRoundTrip<double>(d)); } if (dd <= static_cast<long double>(std::numeric_limits<int64_t>::max()) && dd >= static_cast<long double>(std::numeric_limits<int64_t>::lowest())) { int64_t x = static_cast<int64_t>(dd); EXPECT_EQ(x, StreamRoundTrip<int64_t>(x)); } } } TEST(StrToDTest, DoubleMin) { const char kV[] = "2.22507385850720138e-308"; char* end; double x = std::strtod(kV, &end); EXPECT_EQ(std::numeric_limits<double>::min(), x); } TEST(StrToDTest, DoubleDenormMin) { const char kV[] = "4.94065645841246544e-324"; char* end; double x = std::strtod(kV, &end); EXPECT_EQ(std::numeric_limits<double>::denorm_min(), x); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/iostream_state_saver.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/iostream_state_saver_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
847a5dd2-48c1-4e5d-839a-ac7295ef96e3
cpp
abseil/abseil-cpp
traits
absl/random/internal/traits.h
absl/random/internal/traits_test.cc
#ifndef ABSL_RANDOM_INTERNAL_TRAITS_H_ #define ABSL_RANDOM_INTERNAL_TRAITS_H_ #include <cstdint> #include <limits> #include <type_traits> #include "absl/base/config.h" #include "absl/numeric/bits.h" #include "absl/numeric/int128.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename A, typename B> class is_widening_convertible { template <class T> static constexpr int rank() { return !std::numeric_limits<T>::is_integer + std::numeric_limits<T>::is_signed; } public: static constexpr bool value = std::numeric_limits<A>::digits <= std::numeric_limits<B>::digits && rank<A>() <= rank<B>(); }; template <typename T> struct IsIntegral : std::is_integral<T> {}; template <> struct IsIntegral<absl::int128> : std::true_type {}; template <> struct IsIntegral<absl::uint128> : std::true_type {}; template <typename T> struct MakeUnsigned : std::make_unsigned<T> {}; template <> struct MakeUnsigned<absl::int128> { using type = absl::uint128; }; template <> struct MakeUnsigned<absl::uint128> { using type = absl::uint128; }; template <typename T> struct IsUnsigned : std::is_unsigned<T> {}; template <> struct IsUnsigned<absl::int128> : std::false_type {}; template <> struct IsUnsigned<absl::uint128> : std::true_type {}; template <size_t N> struct unsigned_bits; template <> struct unsigned_bits<8> { using type = uint8_t; }; template <> struct unsigned_bits<16> { using type = uint16_t; }; template <> struct unsigned_bits<32> { using type = uint32_t; }; template <> struct unsigned_bits<64> { using type = uint64_t; }; template <> struct unsigned_bits<128> { using type = absl::uint128; }; struct U256 { uint128 hi; uint128 lo; }; template <> struct unsigned_bits<256> { using type = U256; }; template <typename IntType> struct make_unsigned_bits { using type = typename unsigned_bits< std::numeric_limits<typename MakeUnsigned<IntType>::type>::digits>::type; }; template <typename T> int BitWidth(T v) { constexpr int half_bits = sizeof(T) * 8 / 2; if (sizeof(T) == 16 && (v >> half_bits) != 0) { return bit_width(static_cast<uint64_t>(v >> half_bits)) + half_bits; } else { return bit_width(static_cast<uint64_t>(v)); } } } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/traits.h" #include <cstdint> #include <type_traits> #include "gtest/gtest.h" namespace { using absl::random_internal::is_widening_convertible; template <typename T> void CheckWideningConvertsToSelf() { static_assert(is_widening_convertible<T, T>::value, "Type is not convertible to self!"); } template <typename T, typename Next, typename... Args> void CheckWideningConvertsToSelf() { CheckWideningConvertsToSelf<T>(); CheckWideningConvertsToSelf<Next, Args...>(); } template <typename T> void CheckNotWideningConvertibleWithSigned() { using signed_t = typename std::make_signed<T>::type; static_assert(!is_widening_convertible<T, signed_t>::value, "Unsigned type is convertible to same-sized signed-type!"); static_assert(!is_widening_convertible<signed_t, T>::value, "Signed type is convertible to same-sized unsigned-type!"); } template <typename T, typename Next, typename... Args> void CheckNotWideningConvertibleWithSigned() { CheckNotWideningConvertibleWithSigned<T>(); CheckWideningConvertsToSelf<Next, Args...>(); } template <typename T, typename Higher> void CheckWideningConvertsToLargerTypes() { using signed_t = typename std::make_signed<T>::type; using higher_t = Higher; using signed_higher_t = typename std::make_signed<Higher>::type; static_assert(is_widening_convertible<T, higher_t>::value, "Type not embeddable into larger type!"); static_assert(is_widening_convertible<T, signed_higher_t>::value, "Type not embeddable into larger signed type!"); static_assert(!is_widening_convertible<signed_t, higher_t>::value, "Signed type is embeddable into larger unsigned type!"); static_assert(is_widening_convertible<signed_t, signed_higher_t>::value, "Signed type not embeddable into larger signed type!"); } template <typename T, typename Higher, typename Next, typename... Args> void CheckWideningConvertsToLargerTypes() { CheckWideningConvertsToLargerTypes<T, Higher>(); CheckWideningConvertsToLargerTypes<Higher, Next, Args...>(); } template <typename T, typename U, bool expect = true> void CheckWideningConvertsTo() { static_assert(is_widening_convertible<T, U>::value == expect, "Unexpected result for is_widening_convertible<T, U>!"); } TEST(TraitsTest, IsWideningConvertibleTest) { constexpr bool kInvalid = false; CheckWideningConvertsToSelf< uint8_t, uint16_t, uint32_t, uint64_t, int8_t, int16_t, int32_t, int64_t, float, double>(); CheckNotWideningConvertibleWithSigned< uint8_t, uint16_t, uint32_t, uint64_t>(); CheckWideningConvertsToLargerTypes< uint8_t, uint16_t, uint32_t, uint64_t>(); CheckWideningConvertsTo<float, double>(); CheckWideningConvertsTo<uint16_t, float>(); CheckWideningConvertsTo<uint32_t, double>(); CheckWideningConvertsTo<uint64_t, double, kInvalid>(); CheckWideningConvertsTo<double, float, kInvalid>(); CheckWideningConvertsTo<bool, int>(); CheckWideningConvertsTo<bool, float>(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/traits.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/traits_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
31b643bb-7a3b-4dc4-9c36-efa9bd166423
cpp
abseil/abseil-cpp
nonsecure_base
absl/random/internal/nonsecure_base.h
absl/random/internal/nonsecure_base_test.cc
#ifndef ABSL_RANDOM_INTERNAL_NONSECURE_BASE_H_ #define ABSL_RANDOM_INTERNAL_NONSECURE_BASE_H_ #include <algorithm> #include <cstdint> #include <iterator> #include <type_traits> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/container/inlined_vector.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/pool_urbg.h" #include "absl/random/internal/salted_seed_seq.h" #include "absl/random/internal/seed_material.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { class RandenPoolSeedSeq { private: struct ContiguousTag {}; struct BufferTag {}; template <typename Contiguous> void generate_impl(ContiguousTag, Contiguous begin, Contiguous end) { const size_t n = static_cast<size_t>(std::distance(begin, end)); auto* a = &(*begin); RandenPool<uint8_t>::Fill( absl::MakeSpan(reinterpret_cast<uint8_t*>(a), sizeof(*a) * n)); } template <typename RandomAccessIterator> void generate_impl(BufferTag, RandomAccessIterator begin, RandomAccessIterator end) { const size_t n = std::distance(begin, end); absl::InlinedVector<uint32_t, 8> data(n, 0); RandenPool<uint32_t>::Fill(absl::MakeSpan(data.begin(), data.end())); std::copy(std::begin(data), std::end(data), begin); } public: using result_type = uint32_t; size_t size() { return 0; } template <typename OutIterator> void param(OutIterator) const {} template <typename RandomAccessIterator> void generate(RandomAccessIterator begin, RandomAccessIterator end) { if (begin != end) { using U = typename std::iterator_traits<RandomAccessIterator>::value_type; using TagType = absl::conditional_t< (std::is_pointer<RandomAccessIterator>::value || std::is_same<RandomAccessIterator, typename std::vector<U>::iterator>::value), ContiguousTag, BufferTag>; generate_impl(TagType{}, begin, end); } } }; template <typename URBG, typename Seeder = RandenPoolSeedSeq> class NonsecureURBGBase { public: using result_type = typename URBG::result_type; NonsecureURBGBase() : urbg_(ConstructURBG()) {} NonsecureURBGBase(const NonsecureURBGBase&) = delete; NonsecureURBGBase& operator=(const NonsecureURBGBase&) = delete; NonsecureURBGBase(NonsecureURBGBase&&) = default; NonsecureURBGBase& operator=(NonsecureURBGBase&&) = default; template <class SSeq, typename = typename absl::enable_if_t< !std::is_same<SSeq, NonsecureURBGBase>::value>> explicit NonsecureURBGBase(SSeq&& seq) : urbg_(ConstructURBG(std::forward<SSeq>(seq))) {} static constexpr result_type(min)() { return (URBG::min)(); } static constexpr result_type(max)() { return (URBG::max)(); } result_type operator()() { return urbg_(); } void discard(unsigned long long values) { urbg_.discard(values); } bool operator==(const NonsecureURBGBase& other) const { return urbg_ == other.urbg_; } bool operator!=(const NonsecureURBGBase& other) const { return !(urbg_ == other.urbg_); } private: static URBG ConstructURBG() { Seeder seeder; return URBG(seeder); } template <typename SSeq> static URBG ConstructURBG(SSeq&& seq) { auto salted_seq = random_internal::MakeSaltedSeedSeq(std::forward<SSeq>(seq)); return URBG(salted_seq); } URBG urbg_; }; } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/nonsecure_base.h" #include <algorithm> #include <cstdint> #include <iostream> #include <memory> #include <random> #include <sstream> #include "gtest/gtest.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" namespace { using ExampleNonsecureURBG = absl::random_internal::NonsecureURBGBase<std::mt19937>; template <typename T> void Use(const T&) {} } TEST(NonsecureURBGBase, DefaultConstructorIsValid) { ExampleNonsecureURBG urbg; } TEST(RecommendedTemplates, CanBeConstructed) { absl::BitGen default_generator; absl::InsecureBitGen insecure_generator; } TEST(RecommendedTemplates, CanDiscardValues) { absl::BitGen default_generator; absl::InsecureBitGen insecure_generator; default_generator.discard(5); insecure_generator.discard(5); } TEST(NonsecureURBGBase, StandardInterface) { using E = absl::random_internal::NonsecureURBGBase<std::minstd_rand>; using T = typename E::result_type; static_assert(!std::is_copy_constructible<E>::value, "NonsecureURBGBase should not be copy constructible"); static_assert(!absl::is_copy_assignable<E>::value, "NonsecureURBGBase should not be copy assignable"); static_assert(std::is_move_constructible<E>::value, "NonsecureURBGBase should be move constructible"); static_assert(absl::is_move_assignable<E>::value, "NonsecureURBGBase should be move assignable"); static_assert(std::is_same<decltype(std::declval<E>()()), T>::value, "return type of operator() must be result_type"); { const E x, y; Use(x); Use(y); static_assert(std::is_same<decltype(x == y), bool>::value, "return type of operator== must be bool"); static_assert(std::is_same<decltype(x != y), bool>::value, "return type of operator== must be bool"); } E e; std::seed_seq q{1, 2, 3}; E{}; E{q}; { E tmp(q); E m = std::move(tmp); E n(std::move(m)); EXPECT_TRUE(e != n); } { E a(q); E b(q); EXPECT_TRUE(a != e); EXPECT_TRUE(a == b); a(); EXPECT_TRUE(a != b); } unsigned long long z = 1; e.discard(z); } TEST(NonsecureURBGBase, SeedSeqConstructorIsValid) { std::seed_seq seq; ExampleNonsecureURBG rbg(seq); } TEST(NonsecureURBGBase, CompatibleWithDistributionUtils) { ExampleNonsecureURBG rbg; absl::Uniform(rbg, 0, 100); absl::Uniform(rbg, 0.5, 0.7); absl::Poisson<uint32_t>(rbg); absl::Exponential<float>(rbg); } TEST(NonsecureURBGBase, CompatibleWithStdDistributions) { ExampleNonsecureURBG rbg; static_cast<void>(std::uniform_int_distribution<uint32_t>(0, 100)(rbg)); static_cast<void>(std::uniform_real_distribution<float>()(rbg)); static_cast<void>(std::bernoulli_distribution(0.2)(rbg)); } TEST(NonsecureURBGBase, ConsecutiveDefaultInstancesYieldUniqueVariates) { const size_t kNumSamples = 128; ExampleNonsecureURBG rbg1; ExampleNonsecureURBG rbg2; for (size_t i = 0; i < kNumSamples; i++) { EXPECT_NE(rbg1(), rbg2()); } } TEST(NonsecureURBGBase, EqualSeedSequencesYieldEqualVariates) { std::seed_seq seq; ExampleNonsecureURBG rbg1(seq); ExampleNonsecureURBG rbg2(seq); for (uint32_t i = 0; i < 1000; i++) { EXPECT_EQ(rbg1(), rbg2()); } rbg1.discard(100); rbg2.discard(100); for (uint32_t i = 0; i < 1000; i++) { EXPECT_EQ(rbg1(), rbg2()); } } TEST(RandenPoolSeedSeqTest, SeederWorksForU32) { absl::random_internal::RandenPoolSeedSeq seeder; uint32_t state[2] = {0, 0}; seeder.generate(std::begin(state), std::end(state)); EXPECT_FALSE(state[0] == 0 && state[1] == 0); } TEST(RandenPoolSeedSeqTest, SeederWorksForU64) { absl::random_internal::RandenPoolSeedSeq seeder; uint64_t state[2] = {0, 0}; seeder.generate(std::begin(state), std::end(state)); EXPECT_FALSE(state[0] == 0 && state[1] == 0); EXPECT_FALSE((state[0] >> 32) == 0 && (state[1] >> 32) == 0); } TEST(RandenPoolSeedSeqTest, SeederWorksForS32) { absl::random_internal::RandenPoolSeedSeq seeder; int32_t state[2] = {0, 0}; seeder.generate(std::begin(state), std::end(state)); EXPECT_FALSE(state[0] == 0 && state[1] == 0); } TEST(RandenPoolSeedSeqTest, SeederWorksForVector) { absl::random_internal::RandenPoolSeedSeq seeder; std::vector<uint32_t> state(2); seeder.generate(std::begin(state), std::end(state)); EXPECT_FALSE(state[0] == 0 && state[1] == 0); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/nonsecure_base.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/nonsecure_base_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
a89c744e-fd86-4576-97ff-88a73e955d7c
cpp
abseil/abseil-cpp
fastmath
absl/random/internal/fastmath.h
absl/random/internal/fastmath_test.cc
#ifndef ABSL_RANDOM_INTERNAL_FASTMATH_H_ #define ABSL_RANDOM_INTERNAL_FASTMATH_H_ #include <cassert> #include <cmath> #include <cstdint> #include "absl/numeric/bits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { inline int IntLog2Floor(uint64_t n) { return (n <= 1) ? 0 : (63 - countl_zero(n)); } inline int IntLog2Ceil(uint64_t n) { return (n <= 1) ? 0 : (64 - countl_zero(n - 1)); } inline double StirlingLogFactorial(double n) { assert(n >= 1); constexpr double kLog2PI = 1.83787706640934548356; const double logn = std::log(n); const double ninv = 1.0 / static_cast<double>(n); return n * logn - n + 0.5 * (kLog2PI + logn) + (1.0 / 12.0) * ninv - (1.0 / 360.0) * ninv * ninv * ninv; } } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/fastmath.h" #include "gtest/gtest.h" #if defined(__native_client__) || defined(__EMSCRIPTEN__) #define ABSL_RANDOM_INACCURATE_LOG2 #endif namespace { TEST(FastMathTest, IntLog2FloorTest) { using absl::random_internal::IntLog2Floor; constexpr uint64_t kZero = 0; EXPECT_EQ(0, IntLog2Floor(0)); EXPECT_EQ(0, IntLog2Floor(1)); EXPECT_EQ(1, IntLog2Floor(2)); EXPECT_EQ(63, IntLog2Floor(~kZero)); EXPECT_LT(IntLog2Floor(~kZero), static_cast<int>(std::log2(~kZero))); for (int i = 0; i < 64; i++) { const uint64_t i_pow_2 = static_cast<uint64_t>(1) << i; EXPECT_EQ(i, IntLog2Floor(i_pow_2)); EXPECT_EQ(i, static_cast<int>(std::log2(i_pow_2))); uint64_t y = i_pow_2; for (int j = i - 1; j > 0; --j) { y = y | (i_pow_2 >> j); EXPECT_EQ(i, IntLog2Floor(y)); } } } TEST(FastMathTest, IntLog2CeilTest) { using absl::random_internal::IntLog2Ceil; constexpr uint64_t kZero = 0; EXPECT_EQ(0, IntLog2Ceil(0)); EXPECT_EQ(0, IntLog2Ceil(1)); EXPECT_EQ(1, IntLog2Ceil(2)); EXPECT_EQ(64, IntLog2Ceil(~kZero)); EXPECT_LE(IntLog2Ceil(~kZero), static_cast<int>(std::log2(~kZero))); for (int i = 0; i < 64; i++) { const uint64_t i_pow_2 = static_cast<uint64_t>(1) << i; EXPECT_EQ(i, IntLog2Ceil(i_pow_2)); #ifndef ABSL_RANDOM_INACCURATE_LOG2 EXPECT_EQ(i, static_cast<int>(std::ceil(std::log2(i_pow_2)))); #endif uint64_t y = i_pow_2; for (int j = i - 1; j > 0; --j) { y = y | (i_pow_2 >> j); EXPECT_EQ(i + 1, IntLog2Ceil(y)); } } } TEST(FastMathTest, StirlingLogFactorial) { using absl::random_internal::StirlingLogFactorial; EXPECT_NEAR(StirlingLogFactorial(1.0), 0, 1e-3); EXPECT_NEAR(StirlingLogFactorial(1.50), 0.284683, 1e-3); EXPECT_NEAR(StirlingLogFactorial(2.0), 0.69314718056, 1e-4); for (int i = 2; i < 50; i++) { double d = static_cast<double>(i); EXPECT_NEAR(StirlingLogFactorial(d), std::lgamma(d + 1), 3e-5); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/fastmath.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/fastmath_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
1e57cfe2-0c5a-4707-a50b-7bf3a0666fa5
cpp
abseil/abseil-cpp
uniform_helper
absl/random/internal/uniform_helper.h
absl/random/internal/uniform_helper_test.cc
#ifndef ABSL_RANDOM_INTERNAL_UNIFORM_HELPER_H_ #define ABSL_RANDOM_INTERNAL_UNIFORM_HELPER_H_ #include <cmath> #include <limits> #include <type_traits> #include "absl/base/config.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename IntType> class uniform_int_distribution; template <typename RealType> class uniform_real_distribution; namespace random_internal { template <typename T> struct TagTypeCompare {}; template <typename T> constexpr bool operator==(TagTypeCompare<T>, TagTypeCompare<T>) { return true; } template <typename T> constexpr bool operator!=(TagTypeCompare<T>, TagTypeCompare<T>) { return false; } } struct IntervalClosedClosedTag : public random_internal::TagTypeCompare<IntervalClosedClosedTag> {}; struct IntervalClosedOpenTag : public random_internal::TagTypeCompare<IntervalClosedOpenTag> {}; struct IntervalOpenClosedTag : public random_internal::TagTypeCompare<IntervalOpenClosedTag> {}; struct IntervalOpenOpenTag : public random_internal::TagTypeCompare<IntervalOpenOpenTag> {}; namespace random_internal { template <typename A, typename B> using uniform_inferred_return_t = absl::enable_if_t<absl::disjunction<is_widening_convertible<A, B>, is_widening_convertible<B, A>>::value, typename std::conditional< is_widening_convertible<A, B>::value, B, A>::type>; template <typename IntType, typename Tag> typename absl::enable_if_t< absl::conjunction< IsIntegral<IntType>, absl::disjunction<std::is_same<Tag, IntervalOpenClosedTag>, std::is_same<Tag, IntervalOpenOpenTag>>>::value, IntType> uniform_lower_bound(Tag, IntType a, IntType) { return a < (std::numeric_limits<IntType>::max)() ? (a + 1) : a; } template <typename FloatType, typename Tag> typename absl::enable_if_t< absl::conjunction< std::is_floating_point<FloatType>, absl::disjunction<std::is_same<Tag, IntervalOpenClosedTag>, std::is_same<Tag, IntervalOpenOpenTag>>>::value, FloatType> uniform_lower_bound(Tag, FloatType a, FloatType b) { return std::nextafter(a, b); } template <typename NumType, typename Tag> typename absl::enable_if_t< absl::disjunction<std::is_same<Tag, IntervalClosedClosedTag>, std::is_same<Tag, IntervalClosedOpenTag>>::value, NumType> uniform_lower_bound(Tag, NumType a, NumType) { return a; } template <typename IntType, typename Tag> typename absl::enable_if_t< absl::conjunction< IsIntegral<IntType>, absl::disjunction<std::is_same<Tag, IntervalClosedOpenTag>, std::is_same<Tag, IntervalOpenOpenTag>>>::value, IntType> uniform_upper_bound(Tag, IntType, IntType b) { return b > (std::numeric_limits<IntType>::min)() ? (b - 1) : b; } template <typename FloatType, typename Tag> typename absl::enable_if_t< absl::conjunction< std::is_floating_point<FloatType>, absl::disjunction<std::is_same<Tag, IntervalClosedOpenTag>, std::is_same<Tag, IntervalOpenOpenTag>>>::value, FloatType> uniform_upper_bound(Tag, FloatType, FloatType b) { return b; } template <typename IntType, typename Tag> typename absl::enable_if_t< absl::conjunction< IsIntegral<IntType>, absl::disjunction<std::is_same<Tag, IntervalClosedClosedTag>, std::is_same<Tag, IntervalOpenClosedTag>>>::value, IntType> uniform_upper_bound(Tag, IntType, IntType b) { return b; } template <typename FloatType, typename Tag> typename absl::enable_if_t< absl::conjunction< std::is_floating_point<FloatType>, absl::disjunction<std::is_same<Tag, IntervalClosedClosedTag>, std::is_same<Tag, IntervalOpenClosedTag>>>::value, FloatType> uniform_upper_bound(Tag, FloatType, FloatType b) { return std::nextafter(b, (std::numeric_limits<FloatType>::max)()); } template <typename FloatType> absl::enable_if_t<std::is_floating_point<FloatType>::value, bool> is_uniform_range_valid(FloatType a, FloatType b) { return a <= b && std::isfinite(b - a); } template <typename IntType> absl::enable_if_t<IsIntegral<IntType>::value, bool> is_uniform_range_valid(IntType a, IntType b) { return a <= b; } template <typename NumType> using UniformDistribution = typename std::conditional<IsIntegral<NumType>::value, absl::uniform_int_distribution<NumType>, absl::uniform_real_distribution<NumType>>::type; template <typename NumType> struct UniformDistributionWrapper : public UniformDistribution<NumType> { template <typename TagType> explicit UniformDistributionWrapper(TagType, NumType lo, NumType hi) : UniformDistribution<NumType>( uniform_lower_bound<NumType>(TagType{}, lo, hi), uniform_upper_bound<NumType>(TagType{}, lo, hi)) {} explicit UniformDistributionWrapper(NumType lo, NumType hi) : UniformDistribution<NumType>( uniform_lower_bound<NumType>(IntervalClosedOpenTag(), lo, hi), uniform_upper_bound<NumType>(IntervalClosedOpenTag(), lo, hi)) {} explicit UniformDistributionWrapper() : UniformDistribution<NumType>(std::numeric_limits<NumType>::lowest(), (std::numeric_limits<NumType>::max)()) {} }; } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/uniform_helper.h" #include <cmath> #include <cstdint> #include <random> #include "gtest/gtest.h" namespace { using absl::IntervalClosedClosedTag; using absl::IntervalClosedOpenTag; using absl::IntervalOpenClosedTag; using absl::IntervalOpenOpenTag; using absl::random_internal::uniform_inferred_return_t; using absl::random_internal::uniform_lower_bound; using absl::random_internal::uniform_upper_bound; class UniformHelperTest : public testing::Test {}; TEST_F(UniformHelperTest, UniformBoundFunctionsGeneral) { constexpr IntervalClosedClosedTag IntervalClosedClosed; constexpr IntervalClosedOpenTag IntervalClosedOpen; constexpr IntervalOpenClosedTag IntervalOpenClosed; constexpr IntervalOpenOpenTag IntervalOpenOpen; EXPECT_EQ(uniform_lower_bound(IntervalOpenClosed, 0, 100), 1); EXPECT_EQ(uniform_lower_bound(IntervalOpenOpen, 0, 100), 1); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenClosed, 0, 1.0), 0); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenOpen, 0, 1.0), 0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenClosed, 0, 1.0), 0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenOpen, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound(IntervalClosedClosed, 0, 100), 0); EXPECT_EQ(uniform_lower_bound(IntervalClosedOpen, 0, 100), 0); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedClosed, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedOpen, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedClosed, 0, 1.0), 0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedOpen, 0, 1.0), 0); EXPECT_EQ(uniform_upper_bound(IntervalOpenOpen, 0, 100), 99); EXPECT_EQ(uniform_upper_bound(IntervalClosedOpen, 0, 100), 99); EXPECT_EQ(uniform_upper_bound<float>(IntervalOpenOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound<float>(IntervalClosedOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalOpenOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalClosedOpen, 0, 1.0), 1.0); EXPECT_EQ(uniform_upper_bound(IntervalOpenClosed, 0, 100), 100); EXPECT_EQ(uniform_upper_bound(IntervalClosedClosed, 0, 100), 100); EXPECT_GT(uniform_upper_bound<float>(IntervalOpenClosed, 0, 1.0), 1.0); EXPECT_GT(uniform_upper_bound<float>(IntervalClosedClosed, 0, 1.0), 1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalOpenClosed, 0, 1.0), 1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalClosedClosed, 0, 1.0), 1.0); EXPECT_EQ(uniform_lower_bound(IntervalOpenClosed, -100, -1), -99); EXPECT_EQ(uniform_lower_bound(IntervalOpenOpen, -100, -1), -99); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenClosed, -2.0, -1.0), -2.0); EXPECT_GT(uniform_lower_bound<float>(IntervalOpenOpen, -2.0, -1.0), -2.0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenClosed, -2.0, -1.0), -2.0); EXPECT_GT(uniform_lower_bound<double>(IntervalOpenOpen, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound(IntervalClosedClosed, -100, -1), -100); EXPECT_EQ(uniform_lower_bound(IntervalClosedOpen, -100, -1), -100); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedClosed, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound<float>(IntervalClosedOpen, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedClosed, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_lower_bound<double>(IntervalClosedOpen, -2.0, -1.0), -2.0); EXPECT_EQ(uniform_upper_bound(IntervalOpenOpen, -100, -1), -2); EXPECT_EQ(uniform_upper_bound(IntervalClosedOpen, -100, -1), -2); EXPECT_EQ(uniform_upper_bound<float>(IntervalOpenOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound<float>(IntervalClosedOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalOpenOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound<double>(IntervalClosedOpen, -2.0, -1.0), -1.0); EXPECT_EQ(uniform_upper_bound(IntervalOpenClosed, -100, -1), -1); EXPECT_EQ(uniform_upper_bound(IntervalClosedClosed, -100, -1), -1); EXPECT_GT(uniform_upper_bound<float>(IntervalOpenClosed, -2.0, -1.0), -1.0); EXPECT_GT(uniform_upper_bound<float>(IntervalClosedClosed, -2.0, -1.0), -1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalOpenClosed, -2.0, -1.0), -1.0); EXPECT_GT(uniform_upper_bound<double>(IntervalClosedClosed, -2.0, -1.0), -1.0); EXPECT_GT(uniform_lower_bound(IntervalOpenClosed, 1.0, 2.0), 1.0); EXPECT_LT(uniform_lower_bound(IntervalOpenClosed, 1.0, +0.0), 1.0); EXPECT_LT(uniform_lower_bound(IntervalOpenClosed, 1.0, -0.0), 1.0); EXPECT_LT(uniform_lower_bound(IntervalOpenClosed, 1.0, -1.0), 1.0); } TEST_F(UniformHelperTest, UniformBoundFunctionsIntBounds) { constexpr IntervalOpenOpenTag IntervalOpenOpen; constexpr auto m = (std::numeric_limits<uint64_t>::max)(); EXPECT_EQ(1, uniform_lower_bound(IntervalOpenOpen, 0u, 0u)); EXPECT_EQ(m, uniform_lower_bound(IntervalOpenOpen, m, m)); EXPECT_EQ(m, uniform_lower_bound(IntervalOpenOpen, m - 1, m - 1)); EXPECT_EQ(0, uniform_upper_bound(IntervalOpenOpen, 0u, 0u)); EXPECT_EQ(m - 1, uniform_upper_bound(IntervalOpenOpen, m, m)); constexpr auto l = (std::numeric_limits<int64_t>::min)(); constexpr auto r = (std::numeric_limits<int64_t>::max)(); EXPECT_EQ(1, uniform_lower_bound(IntervalOpenOpen, 0, 0)); EXPECT_EQ(l + 1, uniform_lower_bound(IntervalOpenOpen, l, l)); EXPECT_EQ(r, uniform_lower_bound(IntervalOpenOpen, r - 1, r - 1)); EXPECT_EQ(r, uniform_lower_bound(IntervalOpenOpen, r, r)); EXPECT_EQ(-1, uniform_upper_bound(IntervalOpenOpen, 0, 0)); EXPECT_EQ(l, uniform_upper_bound(IntervalOpenOpen, l, l)); EXPECT_EQ(r - 1, uniform_upper_bound(IntervalOpenOpen, r, r)); } TEST_F(UniformHelperTest, UniformBoundFunctionsRealBounds) { constexpr IntervalOpenClosedTag IntervalOpenClosed; EXPECT_EQ(1.0, uniform_lower_bound(IntervalOpenClosed, 1.0, 1.0)); EXPECT_EQ(1.0f, uniform_lower_bound(IntervalOpenClosed, 1.0f, 1.0f)); constexpr auto r = (std::numeric_limits<double>::max)(); const auto re = std::nexttoward(r, 0.0); constexpr auto l = -r; const auto le = std::nexttoward(l, 0.0); EXPECT_EQ(l, uniform_lower_bound(IntervalOpenClosed, l, l)); EXPECT_EQ(r, uniform_lower_bound(IntervalOpenClosed, r, r)); EXPECT_EQ(le, uniform_lower_bound(IntervalOpenClosed, l, r)); EXPECT_EQ(le, uniform_lower_bound(IntervalOpenClosed, l, 0.0)); EXPECT_EQ(le, uniform_lower_bound(IntervalOpenClosed, l, le)); EXPECT_EQ(r, uniform_lower_bound(IntervalOpenClosed, re, r)); EXPECT_EQ(le, uniform_upper_bound(IntervalOpenClosed, l, l)); EXPECT_EQ(r, uniform_upper_bound(IntervalOpenClosed, r, r)); EXPECT_EQ(r, uniform_upper_bound(IntervalOpenClosed, l, r)); EXPECT_EQ(r, uniform_upper_bound(IntervalOpenClosed, l, re)); EXPECT_EQ(r, uniform_upper_bound(IntervalOpenClosed, 0.0, r)); EXPECT_EQ(r, uniform_upper_bound(IntervalOpenClosed, re, r)); EXPECT_EQ(r, uniform_upper_bound(IntervalOpenClosed, le, re)); const double e = std::nextafter(1.0, 2.0); const double f = std::nextafter(1.0, 0.0); EXPECT_EQ(e, uniform_lower_bound(IntervalOpenClosed, 1.0, e)); EXPECT_EQ(std::nextafter(e, 2.0), uniform_upper_bound(IntervalOpenClosed, 1.0, e)); EXPECT_EQ(1.0, uniform_lower_bound(IntervalOpenClosed, f, 1.0)); EXPECT_EQ(e, uniform_upper_bound(IntervalOpenClosed, f, 1.0)); const double g = std::numeric_limits<double>::denorm_min(); const double h = std::nextafter(g, 1.0); EXPECT_EQ(g, uniform_lower_bound(IntervalOpenClosed, 0.0, g)); EXPECT_EQ(h, uniform_upper_bound(IntervalOpenClosed, 0.0, g)); EXPECT_EQ(h, uniform_lower_bound(IntervalOpenClosed, g, 1.0)); EXPECT_EQ(e, uniform_upper_bound(IntervalOpenClosed, g, 1.0)); EXPECT_EQ(f, uniform_lower_bound(IntervalOpenClosed, 1.0, -1.0)); } struct Invalid {}; template <typename A, typename B> auto InferredUniformReturnT(int) -> uniform_inferred_return_t<A, B>; template <typename, typename> Invalid InferredUniformReturnT(...); template <typename A, typename B, typename Expect> void CheckArgsInferType() { static_assert( absl::conjunction< std::is_same<Expect, decltype(InferredUniformReturnT<A, B>(0))>, std::is_same<Expect, decltype(InferredUniformReturnT<B, A>(0))>>::value, ""); } TEST_F(UniformHelperTest, UniformTypeInference) { CheckArgsInferType<uint16_t, uint16_t, uint16_t>(); CheckArgsInferType<uint32_t, uint32_t, uint32_t>(); CheckArgsInferType<uint64_t, uint64_t, uint64_t>(); CheckArgsInferType<int16_t, int16_t, int16_t>(); CheckArgsInferType<int32_t, int32_t, int32_t>(); CheckArgsInferType<int64_t, int64_t, int64_t>(); CheckArgsInferType<float, float, float>(); CheckArgsInferType<double, double, double>(); CheckArgsInferType<uint16_t, uint32_t, uint32_t>(); CheckArgsInferType<uint16_t, uint64_t, uint64_t>(); CheckArgsInferType<uint16_t, int32_t, int32_t>(); CheckArgsInferType<uint16_t, int64_t, int64_t>(); CheckArgsInferType<uint16_t, float, float>(); CheckArgsInferType<uint16_t, double, double>(); CheckArgsInferType<int16_t, int32_t, int32_t>(); CheckArgsInferType<int16_t, int64_t, int64_t>(); CheckArgsInferType<int16_t, float, float>(); CheckArgsInferType<int16_t, double, double>(); CheckArgsInferType<uint16_t, int16_t, Invalid>(); CheckArgsInferType<int16_t, uint32_t, Invalid>(); CheckArgsInferType<int16_t, uint64_t, Invalid>(); CheckArgsInferType<uint32_t, uint64_t, uint64_t>(); CheckArgsInferType<uint32_t, int64_t, int64_t>(); CheckArgsInferType<uint32_t, double, double>(); CheckArgsInferType<int32_t, int64_t, int64_t>(); CheckArgsInferType<int32_t, double, double>(); CheckArgsInferType<uint32_t, int32_t, Invalid>(); CheckArgsInferType<int32_t, uint64_t, Invalid>(); CheckArgsInferType<int32_t, float, Invalid>(); CheckArgsInferType<uint32_t, float, Invalid>(); CheckArgsInferType<uint64_t, int64_t, Invalid>(); CheckArgsInferType<int64_t, float, Invalid>(); CheckArgsInferType<int64_t, double, Invalid>(); CheckArgsInferType<float, double, double>(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/uniform_helper.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/uniform_helper_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
288f78e0-d9c8-4919-8c6f-aad0fdd90c4a
cpp
abseil/abseil-cpp
randen_engine
absl/random/internal/randen_engine.h
absl/random/internal/randen_engine_test.cc
#ifndef ABSL_RANDOM_INTERNAL_RANDEN_ENGINE_H_ #define ABSL_RANDOM_INTERNAL_RANDEN_ENGINE_H_ #include <algorithm> #include <cinttypes> #include <cstdlib> #include <iostream> #include <iterator> #include <limits> #include <type_traits> #include "absl/base/internal/endian.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/internal/randen.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename T> class alignas(8) randen_engine { public: using result_type = T; static_assert(std::is_unsigned<result_type>::value, "randen_engine template argument must be a built-in unsigned " "integer type"); static constexpr result_type(min)() { return (std::numeric_limits<result_type>::min)(); } static constexpr result_type(max)() { return (std::numeric_limits<result_type>::max)(); } randen_engine() : randen_engine(0) {} explicit randen_engine(result_type seed_value) { seed(seed_value); } template <class SeedSequence, typename = typename absl::enable_if_t< !std::is_same<SeedSequence, randen_engine>::value>> explicit randen_engine(SeedSequence&& seq) { seed(seq); } randen_engine(const randen_engine& other) : next_(other.next_), impl_(other.impl_) { std::memcpy(state(), other.state(), kStateSizeT * sizeof(result_type)); } randen_engine& operator=(const randen_engine& other) { next_ = other.next_; impl_ = other.impl_; std::memcpy(state(), other.state(), kStateSizeT * sizeof(result_type)); return *this; } result_type operator()() { auto* begin = state(); if (next_ >= kStateSizeT) { next_ = kCapacityT; impl_.Generate(begin); } return little_endian::ToHost(begin[next_++]); } template <class SeedSequence> typename absl::enable_if_t< !std::is_convertible<SeedSequence, result_type>::value> seed(SeedSequence&& seq) { seed(); reseed(seq); } void seed(result_type seed_value = 0) { next_ = kStateSizeT; auto* begin = state(); std::fill(begin, begin + kCapacityT, 0); std::fill(begin + kCapacityT, begin + kStateSizeT, seed_value); } template <class SeedSequence> void reseed(SeedSequence& seq) { using sequence_result_type = typename SeedSequence::result_type; static_assert(sizeof(sequence_result_type) == 4, "SeedSequence::result_type must be 32-bit"); constexpr size_t kBufferSize = Randen::kSeedBytes / sizeof(sequence_result_type); alignas(16) sequence_result_type buffer[kBufferSize]; const size_t entropy_size = seq.size(); if (entropy_size < kBufferSize) { const size_t requested_entropy = (entropy_size == 0) ? 8u : entropy_size; std::fill(buffer + requested_entropy, buffer + kBufferSize, 0); seq.generate(buffer, buffer + requested_entropy); #ifdef ABSL_IS_BIG_ENDIAN for (sequence_result_type& e : buffer) { e = absl::little_endian::FromHost(e); } #endif size_t dst = kBufferSize; while (dst > 7) { dst -= 4; size_t src = dst >> 1; std::swap(buffer[--dst], buffer[--src]); std::swap(buffer[--dst], buffer[--src]); std::swap(buffer[--dst], buffer[--src]); std::swap(buffer[--dst], buffer[--src]); } } else { seq.generate(buffer, buffer + kBufferSize); } impl_.Absorb(buffer, state()); next_ = kStateSizeT; } void discard(uint64_t count) { uint64_t step = std::min<uint64_t>(kStateSizeT - next_, count); count -= step; constexpr uint64_t kRateT = kStateSizeT - kCapacityT; auto* begin = state(); while (count > 0) { next_ = kCapacityT; impl_.Generate(*reinterpret_cast<result_type(*)[kStateSizeT]>(begin)); step = std::min<uint64_t>(kRateT, count); count -= step; } next_ += step; } bool operator==(const randen_engine& other) const { const auto* begin = state(); return next_ == other.next_ && std::equal(begin, begin + kStateSizeT, other.state()); } bool operator!=(const randen_engine& other) const { return !(*this == other); } template <class CharT, class Traits> friend std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const randen_engine<T>& engine) { using numeric_type = typename random_internal::stream_format_type<result_type>::type; auto saver = random_internal::make_ostream_state_saver(os); auto* it = engine.state(); for (auto* end = it + kStateSizeT; it < end; ++it) { os << static_cast<numeric_type>(little_endian::FromHost(*it)) << os.fill(); } os << engine.next_; return os; } template <class CharT, class Traits> friend std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, randen_engine<T>& engine) { using numeric_type = typename random_internal::stream_format_type<result_type>::type; result_type state[kStateSizeT]; size_t next; for (auto& elem : state) { numeric_type value; is >> value; elem = little_endian::ToHost(static_cast<result_type>(value)); } is >> next; if (is.fail()) { return is; } std::memcpy(engine.state(), state, sizeof(state)); engine.next_ = next; return is; } private: static constexpr size_t kStateSizeT = Randen::kStateBytes / sizeof(result_type); static constexpr size_t kCapacityT = Randen::kCapacityBytes / sizeof(result_type); result_type* state() { return reinterpret_cast<result_type*>( (reinterpret_cast<uintptr_t>(&raw_state_) & 0xf) ? (raw_state_ + 8) : raw_state_); } const result_type* state() const { return const_cast<randen_engine*>(this)->state(); } alignas(8) char raw_state_[Randen::kStateBytes + 8]; size_t next_; Randen impl_; }; } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/randen_engine.h" #include <algorithm> #include <bitset> #include <random> #include <sstream> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/random/internal/explicit_seed_seq.h" #include "absl/strings/str_cat.h" #include "absl/time/clock.h" #define UPDATE_GOLDEN 0 using randen_u64 = absl::random_internal::randen_engine<uint64_t>; using randen_u32 = absl::random_internal::randen_engine<uint32_t>; using absl::random_internal::ExplicitSeedSeq; namespace { template <typename UIntType> class RandenEngineTypedTest : public ::testing::Test {}; using UIntTypes = ::testing::Types<uint8_t, uint16_t, uint32_t, uint64_t>; TYPED_TEST_SUITE(RandenEngineTypedTest, UIntTypes); TYPED_TEST(RandenEngineTypedTest, VerifyReseedChangesAllValues) { using randen = typename absl::random_internal::randen_engine<TypeParam>; using result_type = typename randen::result_type; const size_t kNumOutputs = (sizeof(randen) * 2 / sizeof(TypeParam)) + 1; randen engine; { std::seed_seq seq1{1, 2, 3, 4, 5, 6, 7}; engine.seed(seq1); } result_type a[kNumOutputs]; std::generate(std::begin(a), std::end(a), std::ref(engine)); { std::random_device rd; std::seed_seq seq2{rd(), rd(), rd()}; engine.seed(seq2); } result_type b[kNumOutputs]; std::generate(std::begin(b), std::end(b), std::ref(engine)); size_t changed_bits = 0; size_t unchanged_bits = 0; size_t total_set = 0; size_t total_bits = 0; size_t equal_count = 0; for (size_t i = 0; i < kNumOutputs; ++i) { equal_count += (a[i] == b[i]) ? 1 : 0; std::bitset<sizeof(result_type) * 8> bitset(a[i] ^ b[i]); changed_bits += bitset.count(); unchanged_bits += bitset.size() - bitset.count(); std::bitset<sizeof(result_type) * 8> a_set(a[i]); std::bitset<sizeof(result_type) * 8> b_set(b[i]); total_set += a_set.count() + b_set.count(); total_bits += 2 * 8 * sizeof(result_type); } EXPECT_LE(changed_bits, 0.60 * (changed_bits + unchanged_bits)); EXPECT_GE(changed_bits, 0.40 * (changed_bits + unchanged_bits)); EXPECT_NEAR(total_set, total_bits * 0.5, 4 * std::sqrt(total_bits)) << "@" << total_set / static_cast<double>(total_bits); const double kExpected = kNumOutputs / (1.0 * sizeof(result_type) * 8); EXPECT_LE(equal_count, 1.0 + kExpected); } constexpr size_t kTwoBufferValues = sizeof(randen_u64) / sizeof(uint16_t) + 1; TYPED_TEST(RandenEngineTypedTest, VerifyDiscard) { using randen = typename absl::random_internal::randen_engine<TypeParam>; for (size_t num_used = 0; num_used < kTwoBufferValues; ++num_used) { randen engine_used; for (size_t i = 0; i < num_used; ++i) { engine_used(); } for (size_t num_discard = 0; num_discard < kTwoBufferValues; ++num_discard) { randen engine1 = engine_used; randen engine2 = engine_used; for (size_t i = 0; i < num_discard; ++i) { engine1(); } engine2.discard(num_discard); for (size_t i = 0; i < kTwoBufferValues; ++i) { const auto r1 = engine1(); const auto r2 = engine2(); ASSERT_EQ(r1, r2) << "used=" << num_used << " discard=" << num_discard; } } } } TYPED_TEST(RandenEngineTypedTest, StreamOperatorsResult) { using randen = typename absl::random_internal::randen_engine<TypeParam>; std::wostringstream os; std::wistringstream is; randen engine; EXPECT_EQ(&(os << engine), &os); EXPECT_EQ(&(is >> engine), &is); } TYPED_TEST(RandenEngineTypedTest, StreamSerialization) { using randen = typename absl::random_internal::randen_engine<TypeParam>; for (size_t discard = 0; discard < kTwoBufferValues; ++discard) { ExplicitSeedSeq seed_sequence{12, 34, 56}; randen engine(seed_sequence); engine.discard(discard); std::stringstream stream; stream << engine; randen new_engine; stream >> new_engine; for (size_t i = 0; i < 64; ++i) { EXPECT_EQ(engine(), new_engine()) << " " << i; } } } constexpr size_t kNumGoldenOutputs = 127; TYPED_TEST(RandenEngineTypedTest, RandomNumberEngineInterface) { using randen = typename absl::random_internal::randen_engine<TypeParam>; using E = randen; using T = typename E::result_type; static_assert(std::is_copy_constructible<E>::value, "randen_engine must be copy constructible"); static_assert(absl::is_copy_assignable<E>::value, "randen_engine must be copy assignable"); static_assert(std::is_move_constructible<E>::value, "randen_engine must be move constructible"); static_assert(absl::is_move_assignable<E>::value, "randen_engine must be move assignable"); static_assert(std::is_same<decltype(std::declval<E>()()), T>::value, "return type of operator() must be result_type"); E e, v; const E x, y; T s = 1; std::seed_seq q{1, 2, 3}; unsigned long long z = 1; std::wostringstream os; std::wistringstream is; E{}; E{x}; E{s}; E{q}; e.seed(); EXPECT_TRUE(e == x); e.seed(q); { E tmp(q); EXPECT_TRUE(e == tmp); } e(); { E tmp(q); EXPECT_TRUE(e != tmp); } e.discard(z); static_assert(std::is_same<decltype(x == y), bool>::value, "return type of operator== must be bool"); static_assert(std::is_same<decltype(x != y), bool>::value, "return type of operator== must be bool"); } TYPED_TEST(RandenEngineTypedTest, RandenEngineSFINAETest) { using randen = typename absl::random_internal::randen_engine<TypeParam>; using result_type = typename randen::result_type; { randen engine(result_type(1)); engine.seed(result_type(1)); } { result_type n = 1; randen engine(n); engine.seed(n); } { randen engine(1); engine.seed(1); } { int n = 1; randen engine(n); engine.seed(n); } { std::seed_seq seed_seq; randen engine(seed_seq); engine.seed(seed_seq); } { randen engine{std::seed_seq()}; engine.seed(std::seed_seq()); } } TEST(RandenTest, VerifyGoldenRanden64Default) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0xc3c14f134e433977, 0xdda9f47cd90410ee, 0x887bf3087fd8ca10, 0xf0b780f545c72912, 0x15dbb1d37696599f, 0x30ec63baff3c6d59, 0xb29f73606f7f20a6, 0x02808a316f49a54c, 0x3b8feaf9d5c8e50e, 0x9cbf605e3fd9de8a, 0xc970ae1a78183bbb, 0xd8b2ffd356301ed5, 0xf4b327fe0fc73c37, 0xcdfd8d76eb8f9a19, 0xc3a506eb91420c9d, 0xd5af05dd3eff9556, 0x48db1bb78f83c4a1, 0x7023920e0d6bfe8c, 0x58d3575834956d42, 0xed1ef4c26b87b840, 0x8eef32a23e0b2df3, 0x497cabf3431154fc, 0x4e24370570029a8b, 0xd88b5749f090e5ea, 0xc651a582a970692f, 0x78fcec2cbb6342f5, 0x463cb745612f55db, 0x352ee4ad1816afe3, 0x026ff374c101da7e, 0x811ef0821c3de851, 0x6f7e616704c4fa59, 0xa0660379992d58fc, 0x04b0a374a3b795c7, 0x915f3445685da798, 0x26802a8ac76571ce, 0x4663352533ce1882, 0xb9fdefb4a24dc738, 0x5588ba3a4d6e6c51, 0xa2101a42d35f1956, 0x607195a5e200f5fd, 0x7e100308f3290764, 0xe1e5e03c759c0709, 0x082572cc5da6606f, 0xcbcf585399e432f1, 0xe8a2be4f8335d8f1, 0x0904469acbfee8f2, 0xf08bd31b6daecd51, 0x08e8a1f1a69da69a, 0x6542a20aad57bff5, 0x2e9705bb053d6b46, 0xda2fc9db0713c391, 0x78e3a810213b6ffb, 0xdc16a59cdd85f8a6, 0xc0932718cd55781f, 0xb9bfb29c2b20bfe5, 0xb97289c1be0f2f9c, 0xc0a2a0e403a892d4, 0x5524bb834771435b, 0x8265da3d39d1a750, 0xff4af3ab8d1b78c5, 0xf0ec5f424bcad77f, 0x66e455f627495189, 0xc82d3120b57e3270, 0x3424e47dc22596e3, 0xbc0c95129ccedcdd, 0xc191c595afc4dcbf, 0x120392bd2bb70939, 0x7f90650ea6cd6ab4, 0x7287491832695ad3, 0xa7c8fac5a7917eb0, 0xd088cb9418be0361, 0x7c1bf9839c7c1ce5, 0xe2e991fa58e1e79e, 0x78565cdefd28c4ad, 0x7351b9fef98bafad, 0x2a9eac28b08c96bf, 0x6c4f179696cb2225, 0x13a685861bab87e0, 0x64c6de5aa0501971, 0x30537425cac70991, 0x01590d9dc6c532b7, 0x7e05e3aa8ec720dc, 0x74a07d9c54e3e63f, 0x738184388f3bc1d2, 0x26ffdc5067be3acb, 0x6bcdf185561f255f, 0xa0eaf2e1cf99b1c6, 0x171df81934f68604, 0x7ea5a21665683e5a, 0x5d1cb02075ba1cea, 0x957f38cbd2123fdf, 0xba6364eff80de02f, 0x606e0a0e41d452ee, 0x892d8317de82f7a2, 0xe707b1db50f7b43e, 0x4eb28826766fcf5b, 0x5a362d56e80a0951, 0x6ee217df16527d78, 0xf6737962ba6b23dd, 0x443e63857d4076ca, 0x790d9a5f048adfeb, 0xd796b052151ee94d, 0x033ed95c12b04a03, 0x8b833ff84893da5d, 0x3d6724b1bb15eab9, 0x9877c4225061ca76, 0xd68d6810adf74fb3, 0x42e5352fe30ce989, 0x265b565a7431fde7, 0x3cdbf7e358df4b8b, 0x2922a47f6d3e8779, 0x52d2242f65b37f88, 0x5d836d6e2958d6b5, 0x29d40f00566d5e26, 0x288db0e1124b14a0, 0x6c056608b7d9c1b6, 0x0b9471bdb8f19d32, 0x8fb946504faa6c9d, 0x8943a9464540251c, 0xfd1fe27d144a09e0, 0xea6ac458da141bda, 0x8048f217633fce36, 0xfeda1384ade74d31, 0x4334b8b02ff7612f, 0xdbc8441f5227e216, 0x096d119a3605c85b, 0x2b72b31c21b7d7d0}; randen_u64 engine; #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%016lx, ", engine()); if (i % 3 == 2) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(RandenTest, VerifyGoldenRanden64Seeded) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0x83a9e58f94d3dcd5, 0x70bbdff3d97949fb, 0x0438481f7471c1b4, 0x34fdc58ee5fb5930, 0xceee4f2d2a937d17, 0xb5a26a68e432aea9, 0x8b64774a3fb51740, 0xd89ac1fc74249c74, 0x03910d1d23fc3fdf, 0xd38f630878aa897f, 0x0ee8f0f5615f7e44, 0x98f5a53df8279d52, 0xb403f52c25938d0e, 0x240072996ea6e838, 0xd3a791246190fa61, 0xaaedd3df7a7b4f80, 0xc6eacabe05deaf6e, 0xb7967dd8790edf4d, 0x9a0a8e67e049d279, 0x0494f606aebc23e7, 0x598dcd687bc3e0ee, 0x010ac81802d452a1, 0x6407c87160aa2842, 0x5a56e276486f93a0, 0xc887a399d46a8f02, 0x9e1e6100fe93b740, 0x12d02e330f8901f6, 0xc39ca52b47e790b7, 0xb0b0a2fa11e82e61, 0x1542d841a303806a, 0x1fe659fd7d6e9d86, 0xb8c90d80746541ac, 0x239d56a5669ddc94, 0xd40db57c8123d13c, 0x3abc2414153a0db0, 0x9bad665630cb8d61, 0x0bd1fb90ee3f4bbc, 0x8f0b4d7e079b4e42, 0xfa0fb0e0ee59e793, 0x51080b283e071100, 0x2c4b9e715081cc15, 0xbe10ed49de4941df, 0xf8eaac9d4b1b0d37, 0x4bcce4b54605e139, 0xa64722b76765dda6, 0xb9377d738ca28ab5, 0x779fad81a8ccc1af, 0x65cb3ee61ffd3ba7, 0xd74e79087862836f, 0xd05b9c584c3f25bf, 0x2ba93a4693579827, 0xd81530aff05420ce, 0xec06cea215478621, 0x4b1798a6796d65ad, 0xf142f3fb3a6f6fa6, 0x002b7bf7e237b560, 0xf47f2605ef65b4f8, 0x9804ec5517effc18, 0xaed3d7f8b7d481cd, 0x5651c24c1ce338d1, 0x3e7a38208bf0a3c6, 0x6796a7b614534aed, 0x0d0f3b848358460f, 0x0fa5fe7600b19524, 0x2b0cf38253faaedc, 0x10df9188233a9fd6, 0x3a10033880138b59, 0x5fb0b0d23948e80f, 0x9e76f7b02fbf5350, 0x0816052304b1a985, 0x30c9880db41fd218, 0x14aa399b65e20f28, 0xe1454a8cace787b4, 0x325ac971b6c6f0f5, 0x716b1aa2784f3d36, 0x3d5ce14accfd144f, 0x6c0c97710f651792, 0xbc5b0f59fb333532, 0x2a90a7d2140470bc, 0x8da269f55c1e1c8d, 0xcfc37143895792ca, 0xbe21eab1f30b238f, 0x8c47229dee4d65fd, 0x5743614ed1ed7d54, 0x351372a99e9c476e, 0x2bd5ea15e5db085f, 0x6925fde46e0af4ca, 0xed3eda2bdc1f45bd, 0xdef68c68d460fa6e, 0xe42a0de76253e2b5, 0x4e5176dcbc29c305, 0xbfd85fba9f810f6e, 0x76a5a2a9beb815c6, 0x01edc4ddceaf414c, 0xa4e98904b4bb3b4b, 0x00bd63ac7d2f1ddd, 0xb8491fe6e998ddbb, 0xb386a3463dda6800, 0x0081887688871619, 0x33d394b3344e9a38, 0x815dba65a3a8baf9, 0x4232f6ec02c2fd1a, 0xb5cff603edd20834, 0x580189243f687663, 0xa8d5a2cbdc27fe99, 0x725d881693fa0131, 0xa2be2c13db2c7ac5, 0x7b6a9614b509fd78, 0xb6b136d71e717636, 0x660f1a71aff046ea, 0x0ba10ae346c8ec9e, 0xe66dde53e3145b41, 0x3b18288c88c26be6, 0x4d9d9d2ff02db933, 0x4167da8c70f46e8a, 0xf183beef8c6318b4, 0x4d889e1e71eeeef1, 0x7175c71ad6689b6b, 0xfb9e42beacd1b7dd, 0xc33d0e91b29b5e0d, 0xd39b83291ce47922, 0xc4d570fb8493d12e, 0x23d5a5724f424ae6, 0x5245f161876b6616, 0x38d77dbd21ab578d, 0x9c3423311f4ecbfe, 0x76fe31389bacd9d5, }; ExplicitSeedSeq seed_sequence{12, 34, 56}; randen_u64 engine(seed_sequence); #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%016lx, ", engine()); if (i % 3 == 2) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(seed_sequence); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(RandenTest, VerifyGoldenRanden32Default) { constexpr uint64_t kGolden[2 * kNumGoldenOutputs] = { 0x4e433977, 0xc3c14f13, 0xd90410ee, 0xdda9f47c, 0x7fd8ca10, 0x887bf308, 0x45c72912, 0xf0b780f5, 0x7696599f, 0x15dbb1d3, 0xff3c6d59, 0x30ec63ba, 0x6f7f20a6, 0xb29f7360, 0x6f49a54c, 0x02808a31, 0xd5c8e50e, 0x3b8feaf9, 0x3fd9de8a, 0x9cbf605e, 0x78183bbb, 0xc970ae1a, 0x56301ed5, 0xd8b2ffd3, 0x0fc73c37, 0xf4b327fe, 0xeb8f9a19, 0xcdfd8d76, 0x91420c9d, 0xc3a506eb, 0x3eff9556, 0xd5af05dd, 0x8f83c4a1, 0x48db1bb7, 0x0d6bfe8c, 0x7023920e, 0x34956d42, 0x58d35758, 0x6b87b840, 0xed1ef4c2, 0x3e0b2df3, 0x8eef32a2, 0x431154fc, 0x497cabf3, 0x70029a8b, 0x4e243705, 0xf090e5ea, 0xd88b5749, 0xa970692f, 0xc651a582, 0xbb6342f5, 0x78fcec2c, 0x612f55db, 0x463cb745, 0x1816afe3, 0x352ee4ad, 0xc101da7e, 0x026ff374, 0x1c3de851, 0x811ef082, 0x04c4fa59, 0x6f7e6167, 0x992d58fc, 0xa0660379, 0xa3b795c7, 0x04b0a374, 0x685da798, 0x915f3445, 0xc76571ce, 0x26802a8a, 0x33ce1882, 0x46633525, 0xa24dc738, 0xb9fdefb4, 0x4d6e6c51, 0x5588ba3a, 0xd35f1956, 0xa2101a42, 0xe200f5fd, 0x607195a5, 0xf3290764, 0x7e100308, 0x759c0709, 0xe1e5e03c, 0x5da6606f, 0x082572cc, 0x99e432f1, 0xcbcf5853, 0x8335d8f1, 0xe8a2be4f, 0xcbfee8f2, 0x0904469a, 0x6daecd51, 0xf08bd31b, 0xa69da69a, 0x08e8a1f1, 0xad57bff5, 0x6542a20a, 0x053d6b46, 0x2e9705bb, 0x0713c391, 0xda2fc9db, 0x213b6ffb, 0x78e3a810, 0xdd85f8a6, 0xdc16a59c, 0xcd55781f, 0xc0932718, 0x2b20bfe5, 0xb9bfb29c, 0xbe0f2f9c, 0xb97289c1, 0x03a892d4, 0xc0a2a0e4, 0x4771435b, 0x5524bb83, 0x39d1a750, 0x8265da3d, 0x8d1b78c5, 0xff4af3ab, 0x4bcad77f, 0xf0ec5f42, 0x27495189, 0x66e455f6, 0xb57e3270, 0xc82d3120, 0xc22596e3, 0x3424e47d, 0x9ccedcdd, 0xbc0c9512, 0xafc4dcbf, 0xc191c595, 0x2bb70939, 0x120392bd, 0xa6cd6ab4, 0x7f90650e, 0x32695ad3, 0x72874918, 0xa7917eb0, 0xa7c8fac5, 0x18be0361, 0xd088cb94, 0x9c7c1ce5, 0x7c1bf983, 0x58e1e79e, 0xe2e991fa, 0xfd28c4ad, 0x78565cde, 0xf98bafad, 0x7351b9fe, 0xb08c96bf, 0x2a9eac28, 0x96cb2225, 0x6c4f1796, 0x1bab87e0, 0x13a68586, 0xa0501971, 0x64c6de5a, 0xcac70991, 0x30537425, 0xc6c532b7, 0x01590d9d, 0x8ec720dc, 0x7e05e3aa, 0x54e3e63f, 0x74a07d9c, 0x8f3bc1d2, 0x73818438, 0x67be3acb, 0x26ffdc50, 0x561f255f, 0x6bcdf185, 0xcf99b1c6, 0xa0eaf2e1, 0x34f68604, 0x171df819, 0x65683e5a, 0x7ea5a216, 0x75ba1cea, 0x5d1cb020, 0xd2123fdf, 0x957f38cb, 0xf80de02f, 0xba6364ef, 0x41d452ee, 0x606e0a0e, 0xde82f7a2, 0x892d8317, 0x50f7b43e, 0xe707b1db, 0x766fcf5b, 0x4eb28826, 0xe80a0951, 0x5a362d56, 0x16527d78, 0x6ee217df, 0xba6b23dd, 0xf6737962, 0x7d4076ca, 0x443e6385, 0x048adfeb, 0x790d9a5f, 0x151ee94d, 0xd796b052, 0x12b04a03, 0x033ed95c, 0x4893da5d, 0x8b833ff8, 0xbb15eab9, 0x3d6724b1, 0x5061ca76, 0x9877c422, 0xadf74fb3, 0xd68d6810, 0xe30ce989, 0x42e5352f, 0x7431fde7, 0x265b565a, 0x58df4b8b, 0x3cdbf7e3, 0x6d3e8779, 0x2922a47f, 0x65b37f88, 0x52d2242f, 0x2958d6b5, 0x5d836d6e, 0x566d5e26, 0x29d40f00, 0x124b14a0, 0x288db0e1, 0xb7d9c1b6, 0x6c056608, 0xb8f19d32, 0x0b9471bd, 0x4faa6c9d, 0x8fb94650, 0x4540251c, 0x8943a946, 0x144a09e0, 0xfd1fe27d, 0xda141bda, 0xea6ac458, 0x633fce36, 0x8048f217, 0xade74d31, 0xfeda1384, 0x2ff7612f, 0x4334b8b0, 0x5227e216, 0xdbc8441f, 0x3605c85b, 0x096d119a, 0x21b7d7d0, 0x2b72b31c}; randen_u32 engine; #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < 2 * kNumGoldenOutputs; ++i) { printf("0x%08x, ", engine()); if (i % 6 == 5) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(RandenTest, VerifyGoldenRanden32Seeded) { constexpr uint64_t kGolden[2 * kNumGoldenOutputs] = { 0x94d3dcd5, 0x83a9e58f, 0xd97949fb, 0x70bbdff3, 0x7471c1b4, 0x0438481f, 0xe5fb5930, 0x34fdc58e, 0x2a937d17, 0xceee4f2d, 0xe432aea9, 0xb5a26a68, 0x3fb51740, 0x8b64774a, 0x74249c74, 0xd89ac1fc, 0x23fc3fdf, 0x03910d1d, 0x78aa897f, 0xd38f6308, 0x615f7e44, 0x0ee8f0f5, 0xf8279d52, 0x98f5a53d, 0x25938d0e, 0xb403f52c, 0x6ea6e838, 0x24007299, 0x6190fa61, 0xd3a79124, 0x7a7b4f80, 0xaaedd3df, 0x05deaf6e, 0xc6eacabe, 0x790edf4d, 0xb7967dd8, 0xe049d279, 0x9a0a8e67, 0xaebc23e7, 0x0494f606, 0x7bc3e0ee, 0x598dcd68, 0x02d452a1, 0x010ac818, 0x60aa2842, 0x6407c871, 0x486f93a0, 0x5a56e276, 0xd46a8f02, 0xc887a399, 0xfe93b740, 0x9e1e6100, 0x0f8901f6, 0x12d02e33, 0x47e790b7, 0xc39ca52b, 0x11e82e61, 0xb0b0a2fa, 0xa303806a, 0x1542d841, 0x7d6e9d86, 0x1fe659fd, 0x746541ac, 0xb8c90d80, 0x669ddc94, 0x239d56a5, 0x8123d13c, 0xd40db57c, 0x153a0db0, 0x3abc2414, 0x30cb8d61, 0x9bad6656, 0xee3f4bbc, 0x0bd1fb90, 0x079b4e42, 0x8f0b4d7e, 0xee59e793, 0xfa0fb0e0, 0x3e071100, 0x51080b28, 0x5081cc15, 0x2c4b9e71, 0xde4941df, 0xbe10ed49, 0x4b1b0d37, 0xf8eaac9d, 0x4605e139, 0x4bcce4b5, 0x6765dda6, 0xa64722b7, 0x8ca28ab5, 0xb9377d73, 0xa8ccc1af, 0x779fad81, 0x1ffd3ba7, 0x65cb3ee6, 0x7862836f, 0xd74e7908, 0x4c3f25bf, 0xd05b9c58, 0x93579827, 0x2ba93a46, 0xf05420ce, 0xd81530af, 0x15478621, 0xec06cea2, 0x796d65ad, 0x4b1798a6, 0x3a6f6fa6, 0xf142f3fb, 0xe237b560, 0x002b7bf7, 0xef65b4f8, 0xf47f2605, 0x17effc18, 0x9804ec55, 0xb7d481cd, 0xaed3d7f8, 0x1ce338d1, 0x5651c24c, 0x8bf0a3c6, 0x3e7a3820, 0x14534aed, 0x6796a7b6, 0x8358460f, 0x0d0f3b84, 0x00b19524, 0x0fa5fe76, 0x53faaedc, 0x2b0cf382, 0x233a9fd6, 0x10df9188, 0x80138b59, 0x3a100338, 0x3948e80f, 0x5fb0b0d2, 0x2fbf5350, 0x9e76f7b0, 0x04b1a985, 0x08160523, 0xb41fd218, 0x30c9880d, 0x65e20f28, 0x14aa399b, 0xace787b4, 0xe1454a8c, 0xb6c6f0f5, 0x325ac971, 0x784f3d36, 0x716b1aa2, 0xccfd144f, 0x3d5ce14a, 0x0f651792, 0x6c0c9771, 0xfb333532, 0xbc5b0f59, 0x140470bc, 0x2a90a7d2, 0x5c1e1c8d, 0x8da269f5, 0x895792ca, 0xcfc37143, 0xf30b238f, 0xbe21eab1, 0xee4d65fd, 0x8c47229d, 0xd1ed7d54, 0x5743614e, 0x9e9c476e, 0x351372a9, 0xe5db085f, 0x2bd5ea15, 0x6e0af4ca, 0x6925fde4, 0xdc1f45bd, 0xed3eda2b, 0xd460fa6e, 0xdef68c68, 0x6253e2b5, 0xe42a0de7, 0xbc29c305, 0x4e5176dc, 0x9f810f6e, 0xbfd85fba, 0xbeb815c6, 0x76a5a2a9, 0xceaf414c, 0x01edc4dd, 0xb4bb3b4b, 0xa4e98904, 0x7d2f1ddd, 0x00bd63ac, 0xe998ddbb, 0xb8491fe6, 0x3dda6800, 0xb386a346, 0x88871619, 0x00818876, 0x344e9a38, 0x33d394b3, 0xa3a8baf9, 0x815dba65, 0x02c2fd1a, 0x4232f6ec, 0xedd20834, 0xb5cff603, 0x3f687663, 0x58018924, 0xdc27fe99, 0xa8d5a2cb, 0x93fa0131, 0x725d8816, 0xdb2c7ac5, 0xa2be2c13, 0xb509fd78, 0x7b6a9614, 0x1e717636, 0xb6b136d7, 0xaff046ea, 0x660f1a71, 0x46c8ec9e, 0x0ba10ae3, 0xe3145b41, 0xe66dde53, 0x88c26be6, 0x3b18288c, 0xf02db933, 0x4d9d9d2f, 0x70f46e8a, 0x4167da8c, 0x8c6318b4, 0xf183beef, 0x71eeeef1, 0x4d889e1e, 0xd6689b6b, 0x7175c71a, 0xacd1b7dd, 0xfb9e42be, 0xb29b5e0d, 0xc33d0e91, 0x1ce47922, 0xd39b8329, 0x8493d12e, 0xc4d570fb, 0x4f424ae6, 0x23d5a572, 0x876b6616, 0x5245f161, 0x21ab578d, 0x38d77dbd, 0x1f4ecbfe, 0x9c342331, 0x9bacd9d5, 0x76fe3138, }; ExplicitSeedSeq seed_sequence{12, 34, 56}; randen_u32 engine(seed_sequence); #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < 2 * kNumGoldenOutputs; ++i) { printf("0x%08x, ", engine()); if (i % 6 == 5) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(seed_sequence); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(RandenTest, VerifyGoldenFromDeserializedEngine) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0x067f9f9ab919657a, 0x0534605912988583, 0x8a303f72feaa673f, 0x77b7fd747909185c, 0xd9af90403c56d891, 0xd939c6cb204d14b5, 0x7fbe6b954a47b483, 0x8b31a47cc34c768d, 0x3a9e546da2701a9c, 0x5246539046253e71, 0x417191ffb2a848a1, 0x7b1c7bf5a5001d09, 0x9489b15d194f2361, 0xfcebdeea3bcd2461, 0xd643027c854cec97, 0x5885397f91e0d21c, 0x53173b0efae30d58, 0x1c9c71168449fac1, 0xe358202b711ed8aa, 0x94e3918ed1d8227c, 0x5bb4e251450144cf, 0xb5c7a519b489af3b, 0x6f8b560b1f7b3469, 0xfde11dd4a1c74eef, 0x33383d2f76457dcf, 0x3060c0ec6db9fce1, 0x18f451fcddeec766, 0xe73c5d6b9f26da2a, 0x8d4cc566671b32a4, 0xb8189b73776bc9ff, 0x497a70f9caf0bc23, 0x23afcc509791dcea, 0x18af70dc4b27d306, 0xd3853f955a0ce5b9, 0x441db6c01a0afb17, 0xd0136c3fb8e1f13f, 0x5e4fd6fc2f33783c, 0xe0d24548adb5da51, 0x0f4d8362a7d3485a, 0x9f572d68270fa563, 0x6351fbc823024393, 0xa66dbfc61810e9ab, 0x0ff17fc14b651af8, 0xd74c55dafb99e623, 0x36303bc1ad85c6c2, 0x4920cd6a2af7e897, 0x0b8848addc30fecd, 0x9e1562eda6488e93, 0x197553807d607828, 0xbef5eaeda5e21235, 0x18d91d2616aca527, 0xb7821937f5c873cd, 0x2cd4ae5650dbeefc, 0xb35a64376f75ffdf, 0x9226d414d647fe07, 0x663f3db455bbb35e, 0xa829eead6ae93247, 0x7fd69c204dd0d25f, 0xbe1411f891c9acb1, 0xd476f34a506d5f11, 0xf423d2831649c5ca, 0x1e503962951abd75, 0xeccc9e8b1e34b537, 0xb11a147294044854, 0xc4cf27f0abf4929d, 0xe9193abf6fa24c8c, 0xa94a259e3aba8808, 0x21dc414197deffa3, 0xa2ae211d1ff622ae, 0xfe3995c46be5a4f4, 0xe9984c284bf11128, 0xcb1ce9d2f0851a80, 0x42fee17971d87cd8, 0xac76a98d177adc88, 0xa0973b3dedc4af6f, 0xdf56d6bbcb1b8e86, 0xf1e6485f407b11c9, 0x2c63de4deccb15c0, 0x6fe69db32ed4fad7, 0xaa51a65f84bca1f1, 0x242f2ee81d608afc, 0x8eb88b2b69fc153b, 0x22c20098baf73fd1, 0x57759466f576488c, 0x075ca562cea1be9d, 0x9a74814d73d28891, 0x73d1555fc02f4d3d, 0xc17f8f210ee89337, 0x46cca7999eaeafd4, 0x5db8d6a327a0d8ac, 0xb79b4f93c738d7a1, 0x9994512f0036ded1, 0xd3883026f38747f4, 0xf31f7458078d097c, 0x736ce4d480680669, 0x7a496f4c7e1033e3, 0xecf85bf297fbc68c, 0x9e37e1d0f24f3c4e, 0x15b6e067ca0746fc, 0xdd4a39905c5db81c, 0xb5dfafa7bcfdf7da, 0xca6646fb6f92a276, 0x1c6b35f363ef0efd, 0x6a33d06037ad9f76, 0x45544241afd8f80f, 0x83f8d83f859c90c5, 0x22aea9c5365e8c19, 0xfac35b11f20b6a6a, 0xd1acf49d1a27dd2f, 0xf281cd09c4fed405, 0x076000a42cd38e4f, 0x6ace300565070445, 0x463a62781bddc4db, 0x1477126b46b569ac, 0x127f2bb15035fbb8, 0xdfa30946049c04a8, 0x89072a586ba8dd3e, 0x62c809582bb7e74d, 0x22c0c3641406c28b, 0x9b66e36c47ff004d, 0xb9cd2c7519653330, 0x18608d79cd7a598d, 0x92c0bd1323e53e32, 0x887ff00de8524aa5, 0xa074410b787abd10, 0x18ab41b8057a2063, 0x1560abf26bc5f987}; #if UPDATE_GOLDEN (void)kGolden; std::seed_seq seed_sequence{1, 2, 3, 4, 5}; randen_u64 engine(seed_sequence); std::ostringstream stream; stream << engine; auto str = stream.str(); printf("%s\n\n", str.c_str()); for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%016lx, ", engine()); if (i % 3 == 2) { printf("\n"); } } printf("\n\n\n"); #else randen_u64 engine; std::istringstream stream( "0 0 9824501439887287479 3242284395352394785 243836530774933777 " "4047941804708365596 17165468127298385802 949276103645889255 " "10659970394998657921 1657570836810929787 11697746266668051452 " "9967209969299905230 14140390331161524430 7383014124183271684 " "13146719127702337852 13983155220295807171 11121125587542359264 " "195757810993252695 17138580243103178492 11326030747260920501 " "8585097322474965590 18342582839328350995 15052982824209724634 " "7321861343874683609 1806786911778767826 10100850842665572955 " "9249328950653985078 13600624835326909759 11137960060943860251 " "10208781341792329629 9282723971471525577 16373271619486811032 32"); stream >> engine; for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(RandenTest, IsFastOrSlow) { static constexpr size_t kCount = 100000; randen_u64 engine; randen_u64::result_type sum = 0; auto start = absl::GetCurrentTimeNanos(); for (int i = 0; i < kCount; i++) { sum += engine(); } auto duration = absl::GetCurrentTimeNanos() - start; LOG(INFO) << static_cast<double>(duration) / static_cast<double>(kCount) << "ns"; EXPECT_GT(sum, 0); EXPECT_GE(duration, kCount); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen_engine.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen_engine_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
7159b4fd-095b-4682-92bb-0b9ec2944fde
cpp
abseil/abseil-cpp
salted_seed_seq
absl/random/internal/salted_seed_seq.h
absl/random/internal/salted_seed_seq_test.cc
#ifndef ABSL_RANDOM_INTERNAL_SALTED_SEED_SEQ_H_ #define ABSL_RANDOM_INTERNAL_SALTED_SEED_SEQ_H_ #include <cstdint> #include <cstdlib> #include <initializer_list> #include <iterator> #include <memory> #include <type_traits> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/meta/type_traits.h" #include "absl/random/internal/seed_material.h" #include "absl/types/optional.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename SSeq> class SaltedSeedSeq { public: using inner_sequence_type = SSeq; using result_type = typename SSeq::result_type; SaltedSeedSeq() : seq_(absl::make_unique<SSeq>()) {} template <typename Iterator> SaltedSeedSeq(Iterator begin, Iterator end) : seq_(absl::make_unique<SSeq>(begin, end)) {} template <typename T> SaltedSeedSeq(std::initializer_list<T> il) : SaltedSeedSeq(il.begin(), il.end()) {} SaltedSeedSeq(const SaltedSeedSeq&) = delete; SaltedSeedSeq& operator=(const SaltedSeedSeq&) = delete; SaltedSeedSeq(SaltedSeedSeq&&) = default; SaltedSeedSeq& operator=(SaltedSeedSeq&&) = default; template <typename RandomAccessIterator> void generate(RandomAccessIterator begin, RandomAccessIterator end) { using U = typename std::iterator_traits<RandomAccessIterator>::value_type; using TagType = absl::conditional_t< (std::is_same<U, uint32_t>::value && (std::is_pointer<RandomAccessIterator>::value || std::is_same<RandomAccessIterator, typename std::vector<U>::iterator>::value)), ContiguousAndUint32Tag, DefaultTag>; if (begin != end) { generate_impl(TagType{}, begin, end, std::distance(begin, end)); } } template <typename OutIterator> void param(OutIterator out) const { seq_->param(out); } size_t size() const { return seq_->size(); } private: struct ContiguousAndUint32Tag {}; struct DefaultTag {}; template <typename Contiguous> void generate_impl(ContiguousAndUint32Tag, Contiguous begin, Contiguous end, size_t n) { seq_->generate(begin, end); const uint32_t salt = absl::random_internal::GetSaltMaterial().value_or(0); auto span = absl::Span<uint32_t>(&*begin, n); MixIntoSeedMaterial(absl::MakeConstSpan(&salt, 1), span); } template <typename RandomAccessIterator> void generate_impl(DefaultTag, RandomAccessIterator begin, RandomAccessIterator, size_t n) { absl::InlinedVector<uint32_t, 8> data(n, 0); generate_impl(ContiguousAndUint32Tag{}, data.begin(), data.end(), n); std::copy(data.begin(), data.end(), begin); } std::unique_ptr<SSeq> seq_; }; template <typename T, typename = void> struct is_salted_seed_seq : public std::false_type {}; template <typename T> struct is_salted_seed_seq< T, typename std::enable_if<std::is_same< T, SaltedSeedSeq<typename T::inner_sequence_type>>::value>::type> : public std::true_type {}; template < typename SSeq, typename EnableIf = absl::enable_if_t<is_salted_seed_seq<SSeq>::value>> SSeq MakeSaltedSeedSeq(SSeq&& seq) { return SSeq(std::forward<SSeq>(seq)); } template < typename SSeq, typename EnableIf = absl::enable_if_t<!is_salted_seed_seq<SSeq>::value>> SaltedSeedSeq<typename std::decay<SSeq>::type> MakeSaltedSeedSeq(SSeq&& seq) { using sseq_type = typename std::decay<SSeq>::type; using result_type = typename sseq_type::result_type; absl::InlinedVector<result_type, 8> data; seq.param(std::back_inserter(data)); return SaltedSeedSeq<sseq_type>(data.begin(), data.end()); } } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/salted_seed_seq.h" #include <iterator> #include <random> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" using absl::random_internal::GetSaltMaterial; using absl::random_internal::MakeSaltedSeedSeq; using absl::random_internal::SaltedSeedSeq; using testing::Eq; using testing::Pointwise; namespace { template <typename Sseq> void ConformsToInterface() { { Sseq default_constructed_seq; } { uint32_t init_array[] = {1, 3, 5, 7, 9}; Sseq iterator_constructed_seq(std::begin(init_array), std::end(init_array)); } { Sseq list_constructed_seq = {1, 3, 5, 7, 9, 11, 13}; } { uint32_t init_array[] = {1, 2, 3, 4, 5}; Sseq seq(std::begin(init_array), std::end(init_array)); EXPECT_EQ(seq.size(), ABSL_ARRAYSIZE(init_array)); std::vector<uint32_t> state_vector; seq.param(std::back_inserter(state_vector)); EXPECT_EQ(state_vector.size(), ABSL_ARRAYSIZE(init_array)); for (int i = 0; i < state_vector.size(); i++) { EXPECT_EQ(state_vector[i], i + 1); } } { Sseq seq; uint32_t seeds[5]; seq.generate(std::begin(seeds), std::end(seeds)); } } TEST(SaltedSeedSeq, CheckInterfaces) { ConformsToInterface<std::seed_seq>(); ConformsToInterface<SaltedSeedSeq<std::seed_seq>>(); } TEST(SaltedSeedSeq, CheckConstructingFromOtherSequence) { std::vector<uint32_t> seed_values(10, 1); std::seed_seq seq(seed_values.begin(), seed_values.end()); auto salted_seq = MakeSaltedSeedSeq(std::move(seq)); EXPECT_EQ(seq.size(), salted_seq.size()); std::vector<uint32_t> param_result; seq.param(std::back_inserter(param_result)); EXPECT_EQ(seed_values, param_result); } TEST(SaltedSeedSeq, SaltedSaltedSeedSeqIsNotDoubleSalted) { uint32_t init[] = {1, 3, 5, 7, 9}; std::seed_seq seq(std::begin(init), std::end(init)); SaltedSeedSeq<std::seed_seq> salted_seq = MakeSaltedSeedSeq(std::move(seq)); uint32_t a[16]; salted_seq.generate(std::begin(a), std::end(a)); SaltedSeedSeq<std::seed_seq> salted_salted_seq = MakeSaltedSeedSeq(std::move(salted_seq)); uint32_t b[16]; salted_salted_seq.generate(std::begin(b), std::end(b)); EXPECT_THAT(b, Pointwise(Eq(), a)) << "a[0] " << a[0]; } TEST(SaltedSeedSeq, SeedMaterialIsSalted) { const size_t kNumBlocks = 16; uint32_t seed_material[kNumBlocks]; std::random_device urandom{"/dev/urandom"}; for (uint32_t& seed : seed_material) { seed = urandom(); } std::seed_seq seq(std::begin(seed_material), std::end(seed_material)); SaltedSeedSeq<std::seed_seq> salted_seq(std::begin(seed_material), std::end(seed_material)); bool salt_is_available = GetSaltMaterial().has_value(); if (salt_is_available) { uint32_t outputs[kNumBlocks]; uint32_t salted_outputs[kNumBlocks]; seq.generate(std::begin(outputs), std::end(outputs)); salted_seq.generate(std::begin(salted_outputs), std::end(salted_outputs)); EXPECT_THAT(outputs, Pointwise(testing::Ne(), salted_outputs)); } } TEST(SaltedSeedSeq, GenerateAcceptsDifferentTypes) { const size_t kNumBlocks = 4; SaltedSeedSeq<std::seed_seq> seq({1, 2, 3}); uint32_t expected[kNumBlocks]; seq.generate(std::begin(expected), std::end(expected)); { unsigned long seed_material[kNumBlocks]; seq.generate(std::begin(seed_material), std::end(seed_material)); EXPECT_THAT(seed_material, Pointwise(Eq(), expected)); } { unsigned int seed_material[kNumBlocks]; seq.generate(std::begin(seed_material), std::end(seed_material)); EXPECT_THAT(seed_material, Pointwise(Eq(), expected)); } { uint64_t seed_material[kNumBlocks]; seq.generate(std::begin(seed_material), std::end(seed_material)); EXPECT_THAT(seed_material, Pointwise(Eq(), expected)); } { int64_t seed_material[kNumBlocks]; seq.generate(std::begin(seed_material), std::end(seed_material)); EXPECT_THAT(seed_material, Pointwise(Eq(), expected)); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/salted_seed_seq.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/salted_seed_seq_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
7da9ed7e-56c9-4359-93fe-cc293e9bcce3
cpp
abseil/abseil-cpp
generate_real
absl/random/internal/generate_real.h
absl/random/internal/generate_real_test.cc
#ifndef ABSL_RANDOM_INTERNAL_GENERATE_REAL_H_ #define ABSL_RANDOM_INTERNAL_GENERATE_REAL_H_ #include <cstdint> #include <cstring> #include <limits> #include <type_traits> #include "absl/meta/type_traits.h" #include "absl/numeric/bits.h" #include "absl/random/internal/fastmath.h" #include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { struct GeneratePositiveTag {}; struct GenerateNegativeTag {}; struct GenerateSignedTag {}; template <typename RealType, typename SignedTag = GeneratePositiveTag, bool IncludeZero = true> inline RealType GenerateRealFromBits(uint64_t bits, int exp_bias = 0) { using real_type = RealType; using uint_type = absl::conditional_t<std::is_same<real_type, float>::value, uint32_t, uint64_t>; static_assert( (std::is_same<double, real_type>::value || std::is_same<float, real_type>::value), "GenerateRealFromBits must be parameterized by either float or double."); static_assert(sizeof(uint_type) == sizeof(real_type), "Mismatched unsigned and real types."); static_assert((std::numeric_limits<real_type>::is_iec559 && std::numeric_limits<real_type>::radix == 2), "RealType representation is not IEEE 754 binary."); static_assert((std::is_same<SignedTag, GeneratePositiveTag>::value || std::is_same<SignedTag, GenerateNegativeTag>::value || std::is_same<SignedTag, GenerateSignedTag>::value), ""); static constexpr int kExp = std::numeric_limits<real_type>::digits - 1; static constexpr uint_type kMask = (static_cast<uint_type>(1) << kExp) - 1u; static constexpr int kUintBits = sizeof(uint_type) * 8; int exp = exp_bias + int{std::numeric_limits<real_type>::max_exponent - 2}; uint_type sign = std::is_same<SignedTag, GenerateNegativeTag>::value ? (static_cast<uint_type>(1) << (kUintBits - 1)) : 0; if (std::is_same<SignedTag, GenerateSignedTag>::value) { if (std::is_same<uint_type, uint64_t>::value) { sign = bits & uint64_t{0x8000000000000000}; } if (std::is_same<uint_type, uint32_t>::value) { const uint64_t tmp = bits & uint64_t{0x8000000000000000}; sign = static_cast<uint32_t>(tmp >> 32); } bits = bits & uint64_t{0x7FFFFFFFFFFFFFFF}; exp++; } if (IncludeZero) { if (bits == 0u) return 0; } int clz = countl_zero(bits); bits <<= (IncludeZero ? clz : (clz & 63)); exp -= clz; bits >>= (63 - kExp); uint_type val = sign | (static_cast<uint_type>(exp) << kExp) | (static_cast<uint_type>(bits) & kMask); real_type result; memcpy(static_cast<void*>(&result), static_cast<const void*>(&val), sizeof(result)); return result; } } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/generate_real.h" #include <cfloat> #include <cstddef> #include <cstdint> #include <string> #include "gtest/gtest.h" #include "absl/flags/flag.h" #include "absl/numeric/bits.h" ABSL_FLAG(int64_t, absl_random_test_trials, 50000, "Number of trials for the probability tests."); using absl::random_internal::GenerateNegativeTag; using absl::random_internal::GeneratePositiveTag; using absl::random_internal::GenerateRealFromBits; using absl::random_internal::GenerateSignedTag; namespace { TEST(GenerateRealTest, U64ToFloat_Positive_NoZero_Test) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GeneratePositiveTag, false>(a); }; EXPECT_EQ(ToFloat(0x0000000000000000), 2.710505431e-20f); EXPECT_EQ(ToFloat(0x0000000000000001), 5.421010862e-20f); EXPECT_EQ(ToFloat(0x8000000000000000), 0.5); EXPECT_EQ(ToFloat(0x8000000000000001), 0.5); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), 0.9999999404f); } TEST(GenerateRealTest, U64ToFloat_Positive_Zero_Test) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GeneratePositiveTag, true>(a); }; EXPECT_EQ(ToFloat(0x0000000000000000), 0.0); EXPECT_EQ(ToFloat(0x0000000000000001), 5.421010862e-20f); EXPECT_EQ(ToFloat(0x8000000000000000), 0.5); EXPECT_EQ(ToFloat(0x8000000000000001), 0.5); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), 0.9999999404f); } TEST(GenerateRealTest, U64ToFloat_Negative_NoZero_Test) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GenerateNegativeTag, false>(a); }; EXPECT_EQ(ToFloat(0x0000000000000000), -2.710505431e-20f); EXPECT_EQ(ToFloat(0x0000000000000001), -5.421010862e-20f); EXPECT_EQ(ToFloat(0x8000000000000000), -0.5); EXPECT_EQ(ToFloat(0x8000000000000001), -0.5); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), -0.9999999404f); } TEST(GenerateRealTest, U64ToFloat_Negative_Zero_Test) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GenerateNegativeTag, true>(a); }; EXPECT_EQ(ToFloat(0x0000000000000000), 0.0); EXPECT_EQ(ToFloat(0x0000000000000001), -5.421010862e-20f); EXPECT_EQ(ToFloat(0x8000000000000000), -0.5); EXPECT_EQ(ToFloat(0x8000000000000001), -0.5); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), -0.9999999404f); } TEST(GenerateRealTest, U64ToFloat_Signed_NoZero_Test) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GenerateSignedTag, false>(a); }; EXPECT_EQ(ToFloat(0x0000000000000000), 5.421010862e-20f); EXPECT_EQ(ToFloat(0x0000000000000001), 1.084202172e-19f); EXPECT_EQ(ToFloat(0x7FFFFFFFFFFFFFFF), 0.9999999404f); EXPECT_EQ(ToFloat(0x8000000000000000), -5.421010862e-20f); EXPECT_EQ(ToFloat(0x8000000000000001), -1.084202172e-19f); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), -0.9999999404f); } TEST(GenerateRealTest, U64ToFloat_Signed_Zero_Test) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GenerateSignedTag, true>(a); }; EXPECT_EQ(ToFloat(0x0000000000000000), 0); EXPECT_EQ(ToFloat(0x0000000000000001), 1.084202172e-19f); EXPECT_EQ(ToFloat(0x7FFFFFFFFFFFFFFF), 0.9999999404f); EXPECT_EQ(ToFloat(0x8000000000000000), 0); EXPECT_EQ(ToFloat(0x8000000000000001), -1.084202172e-19f); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), -0.9999999404f); } TEST(GenerateRealTest, U64ToFloat_Signed_Bias_Test) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GenerateSignedTag, true>(a, 1); }; EXPECT_EQ(ToFloat(0x0000000000000000), 0); EXPECT_EQ(ToFloat(0x0000000000000001), 2 * 1.084202172e-19f); EXPECT_EQ(ToFloat(0x7FFFFFFFFFFFFFFF), 2 * 0.9999999404f); EXPECT_EQ(ToFloat(0x8000000000000000), 0); EXPECT_EQ(ToFloat(0x8000000000000001), 2 * -1.084202172e-19f); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), 2 * -0.9999999404f); } TEST(GenerateRealTest, U64ToFloatTest) { auto ToFloat = [](uint64_t a) -> float { return GenerateRealFromBits<float, GeneratePositiveTag, true>(a); }; EXPECT_EQ(ToFloat(0x0000000000000000), 0.0f); EXPECT_EQ(ToFloat(0x8000000000000000), 0.5f); EXPECT_EQ(ToFloat(0x8000000000000001), 0.5f); EXPECT_EQ(ToFloat(0x800000FFFFFFFFFF), 0.5f); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), 0.9999999404f); EXPECT_GT(ToFloat(0x0000000000000001), 0.0f); EXPECT_NE(ToFloat(0x7FFFFF0000000000), ToFloat(0x7FFFFEFFFFFFFFFF)); EXPECT_LT(ToFloat(0xFFFFFFFFFFFFFFFF), 1.0f); int32_t two_to_24 = 1 << 24; EXPECT_EQ(static_cast<int32_t>(ToFloat(0xFFFFFFFFFFFFFFFF) * two_to_24), two_to_24 - 1); EXPECT_NE(static_cast<int32_t>(ToFloat(0xFFFFFFFFFFFFFFFF) * two_to_24 * 2), two_to_24 * 2 - 1); EXPECT_EQ(ToFloat(0xFFFFFFFFFFFFFFFF), ToFloat(0xFFFFFF0000000000)); EXPECT_NE(ToFloat(0xFFFFFFFFFFFFFFFF), ToFloat(0xFFFFFEFFFFFFFFFF)); EXPECT_EQ(ToFloat(0x7FFFFFFFFFFFFFFF), ToFloat(0x7FFFFF8000000000)); EXPECT_NE(ToFloat(0x7FFFFFFFFFFFFFFF), ToFloat(0x7FFFFF7FFFFFFFFF)); EXPECT_EQ(ToFloat(0x3FFFFFFFFFFFFFFF), ToFloat(0x3FFFFFC000000000)); EXPECT_NE(ToFloat(0x3FFFFFFFFFFFFFFF), ToFloat(0x3FFFFFBFFFFFFFFF)); for (int i = 0; i < 100; ++i) { EXPECT_EQ(i * ToFloat(0x0000000000000001), ToFloat(i)); } float exp_values[64]; exp_values[63] = 0.5f; for (int i = 62; i >= 0; --i) exp_values[i] = 0.5f * exp_values[i + 1]; constexpr uint64_t one = 1; for (int i = 0; i < 64; ++i) { EXPECT_EQ(ToFloat(one << i), exp_values[i]); for (int j = 1; j < FLT_MANT_DIG && i - j >= 0; ++j) { EXPECT_NE(exp_values[i] + exp_values[i - j], exp_values[i]); EXPECT_EQ(ToFloat((one << i) + (one << (i - j))), exp_values[i] + exp_values[i - j]); } for (int j = FLT_MANT_DIG; i - j >= 0; ++j) { EXPECT_EQ(exp_values[i] + exp_values[i - j], exp_values[i]); EXPECT_EQ(ToFloat((one << i) + (one << (i - j))), exp_values[i]); } } } TEST(GenerateRealTest, U64ToDouble_Positive_NoZero_Test) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GeneratePositiveTag, false>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), 2.710505431213761085e-20); EXPECT_EQ(ToDouble(0x0000000000000001), 5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x0000000000000002), 1.084202172485504434e-19); EXPECT_EQ(ToDouble(0x8000000000000000), 0.5); EXPECT_EQ(ToDouble(0x8000000000000001), 0.5); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), 0.999999999999999888978); } TEST(GenerateRealTest, U64ToDouble_Positive_Zero_Test) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GeneratePositiveTag, true>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), 0.0); EXPECT_EQ(ToDouble(0x0000000000000001), 5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x8000000000000000), 0.5); EXPECT_EQ(ToDouble(0x8000000000000001), 0.5); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), 0.999999999999999888978); } TEST(GenerateRealTest, U64ToDouble_Negative_NoZero_Test) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GenerateNegativeTag, false>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), -2.710505431213761085e-20); EXPECT_EQ(ToDouble(0x0000000000000001), -5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x0000000000000002), -1.084202172485504434e-19); EXPECT_EQ(ToDouble(0x8000000000000000), -0.5); EXPECT_EQ(ToDouble(0x8000000000000001), -0.5); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), -0.999999999999999888978); } TEST(GenerateRealTest, U64ToDouble_Negative_Zero_Test) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GenerateNegativeTag, true>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), 0.0); EXPECT_EQ(ToDouble(0x0000000000000001), -5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x0000000000000002), -1.084202172485504434e-19); EXPECT_EQ(ToDouble(0x8000000000000000), -0.5); EXPECT_EQ(ToDouble(0x8000000000000001), -0.5); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), -0.999999999999999888978); } TEST(GenerateRealTest, U64ToDouble_Signed_NoZero_Test) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GenerateSignedTag, false>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), 5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x0000000000000001), 1.084202172485504434e-19); EXPECT_EQ(ToDouble(0x7FFFFFFFFFFFFFFF), 0.999999999999999888978); EXPECT_EQ(ToDouble(0x8000000000000000), -5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x8000000000000001), -1.084202172485504434e-19); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), -0.999999999999999888978); } TEST(GenerateRealTest, U64ToDouble_Signed_Zero_Test) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GenerateSignedTag, true>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), 0); EXPECT_EQ(ToDouble(0x0000000000000001), 1.084202172485504434e-19); EXPECT_EQ(ToDouble(0x7FFFFFFFFFFFFFFF), 0.999999999999999888978); EXPECT_EQ(ToDouble(0x8000000000000000), 0); EXPECT_EQ(ToDouble(0x8000000000000001), -1.084202172485504434e-19); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), -0.999999999999999888978); } TEST(GenerateRealTest, U64ToDouble_GenerateSignedTag_Bias_Test) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GenerateSignedTag, true>(a, -1); }; EXPECT_EQ(ToDouble(0x0000000000000000), 0); EXPECT_EQ(ToDouble(0x0000000000000001), 1.084202172485504434e-19 / 2); EXPECT_EQ(ToDouble(0x7FFFFFFFFFFFFFFF), 0.999999999999999888978 / 2); EXPECT_EQ(ToDouble(0x8000000000000000), 0); EXPECT_EQ(ToDouble(0x8000000000000001), -1.084202172485504434e-19 / 2); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), -0.999999999999999888978 / 2); } TEST(GenerateRealTest, U64ToDoubleTest) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GeneratePositiveTag, true>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), 0.0); EXPECT_EQ(ToDouble(0x0000000000000000), 0.0); EXPECT_EQ(ToDouble(0x0000000000000001), 5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x7fffffffffffffef), 0.499999999999999944489); EXPECT_EQ(ToDouble(0x8000000000000000), 0.5); EXPECT_EQ(ToDouble(0x8000000000000001), 0.5); EXPECT_EQ(ToDouble(0x80000000000007FF), 0.5); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), 0.999999999999999888978); EXPECT_NE(ToDouble(0x7FFFFFFFFFFFF800), ToDouble(0x7FFFFFFFFFFFF7FF)); EXPECT_LT(ToDouble(0xFFFFFFFFFFFFFFFF), 1.0); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFF), ToDouble(0xFFFFFFFFFFFFF800)); EXPECT_NE(ToDouble(0xFFFFFFFFFFFFFFFF), ToDouble(0xFFFFFFFFFFFFF7FF)); EXPECT_EQ(ToDouble(0x7FFFFFFFFFFFFFFF), ToDouble(0x7FFFFFFFFFFFFC00)); EXPECT_NE(ToDouble(0x7FFFFFFFFFFFFFFF), ToDouble(0x7FFFFFFFFFFFFBFF)); EXPECT_EQ(ToDouble(0x3FFFFFFFFFFFFFFF), ToDouble(0x3FFFFFFFFFFFFE00)); EXPECT_NE(ToDouble(0x3FFFFFFFFFFFFFFF), ToDouble(0x3FFFFFFFFFFFFDFF)); EXPECT_EQ(ToDouble(0x1000000000000001), 0.0625); EXPECT_EQ(ToDouble(0x2000000000000001), 0.125); EXPECT_EQ(ToDouble(0x3000000000000001), 0.1875); EXPECT_EQ(ToDouble(0x4000000000000001), 0.25); EXPECT_EQ(ToDouble(0x5000000000000001), 0.3125); EXPECT_EQ(ToDouble(0x6000000000000001), 0.375); EXPECT_EQ(ToDouble(0x7000000000000001), 0.4375); EXPECT_EQ(ToDouble(0x8000000000000001), 0.5); EXPECT_EQ(ToDouble(0x9000000000000001), 0.5625); EXPECT_EQ(ToDouble(0xa000000000000001), 0.625); EXPECT_EQ(ToDouble(0xb000000000000001), 0.6875); EXPECT_EQ(ToDouble(0xc000000000000001), 0.75); EXPECT_EQ(ToDouble(0xd000000000000001), 0.8125); EXPECT_EQ(ToDouble(0xe000000000000001), 0.875); EXPECT_EQ(ToDouble(0xf000000000000001), 0.9375); int64_t two_to_53 = int64_t{1} << 53; EXPECT_EQ(static_cast<int64_t>(ToDouble(0xFFFFFFFFFFFFFFFF) * two_to_53), two_to_53 - 1); EXPECT_NE(static_cast<int64_t>(ToDouble(0xFFFFFFFFFFFFFFFF) * two_to_53 * 2), two_to_53 * 2 - 1); for (int i = 0; i < 100; ++i) { EXPECT_EQ(i * ToDouble(0x0000000000000001), ToDouble(i)); } double exp_values[64]; exp_values[63] = 0.5; for (int i = 62; i >= 0; --i) exp_values[i] = 0.5 * exp_values[i + 1]; constexpr uint64_t one = 1; for (int i = 0; i < 64; ++i) { EXPECT_EQ(ToDouble(one << i), exp_values[i]); for (int j = 1; j < DBL_MANT_DIG && i - j >= 0; ++j) { EXPECT_NE(exp_values[i] + exp_values[i - j], exp_values[i]); EXPECT_EQ(ToDouble((one << i) + (one << (i - j))), exp_values[i] + exp_values[i - j]); } for (int j = DBL_MANT_DIG; i - j >= 0; ++j) { EXPECT_EQ(exp_values[i] + exp_values[i - j], exp_values[i]); EXPECT_EQ(ToDouble((one << i) + (one << (i - j))), exp_values[i]); } } } TEST(GenerateRealTest, U64ToDoubleSignedTest) { auto ToDouble = [](uint64_t a) { return GenerateRealFromBits<double, GenerateSignedTag, false>(a); }; EXPECT_EQ(ToDouble(0x0000000000000000), 5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x0000000000000001), 1.084202172485504434e-19); EXPECT_EQ(ToDouble(0x8000000000000000), -5.42101086242752217004e-20); EXPECT_EQ(ToDouble(0x8000000000000001), -1.084202172485504434e-19); const double e_plus = ToDouble(0x0000000000000001); const double e_minus = ToDouble(0x8000000000000001); EXPECT_EQ(e_plus, 1.084202172485504434e-19); EXPECT_EQ(e_minus, -1.084202172485504434e-19); EXPECT_EQ(ToDouble(0x3fffffffffffffef), 0.499999999999999944489); EXPECT_EQ(ToDouble(0xbfffffffffffffef), -0.499999999999999944489); EXPECT_EQ(ToDouble(0x4000000000000000), 0.5); EXPECT_EQ(ToDouble(0x4000000000000001), 0.5); EXPECT_EQ(ToDouble(0x40000000000003FF), 0.5); EXPECT_EQ(ToDouble(0xC000000000000000), -0.5); EXPECT_EQ(ToDouble(0xC000000000000001), -0.5); EXPECT_EQ(ToDouble(0xC0000000000003FF), -0.5); EXPECT_EQ(ToDouble(0x7FFFFFFFFFFFFFFe), 0.999999999999999888978); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFe), -0.999999999999999888978); EXPECT_NE(ToDouble(0x7FFFFFFFFFFFF800), ToDouble(0x7FFFFFFFFFFFF7FF)); EXPECT_LT(ToDouble(0x7FFFFFFFFFFFFFFF), 1.0); EXPECT_GT(ToDouble(0x7FFFFFFFFFFFFFFF), 0.9999999999); EXPECT_GT(ToDouble(0xFFFFFFFFFFFFFFFe), -1.0); EXPECT_LT(ToDouble(0xFFFFFFFFFFFFFFFe), -0.999999999); EXPECT_EQ(ToDouble(0xFFFFFFFFFFFFFFFe), ToDouble(0xFFFFFFFFFFFFFC00)); EXPECT_EQ(ToDouble(0x7FFFFFFFFFFFFFFF), ToDouble(0x7FFFFFFFFFFFFC00)); EXPECT_NE(ToDouble(0xFFFFFFFFFFFFFFFe), ToDouble(0xFFFFFFFFFFFFF3FF)); EXPECT_NE(ToDouble(0x7FFFFFFFFFFFFFFF), ToDouble(0x7FFFFFFFFFFFF3FF)); EXPECT_EQ(ToDouble(0x1000000000000001), 0.125); EXPECT_EQ(ToDouble(0x2000000000000001), 0.25); EXPECT_EQ(ToDouble(0x3000000000000001), 0.375); EXPECT_EQ(ToDouble(0x4000000000000001), 0.5); EXPECT_EQ(ToDouble(0x5000000000000001), 0.625); EXPECT_EQ(ToDouble(0x6000000000000001), 0.75); EXPECT_EQ(ToDouble(0x7000000000000001), 0.875); EXPECT_EQ(ToDouble(0x7800000000000001), 0.9375); EXPECT_EQ(ToDouble(0x7c00000000000001), 0.96875); EXPECT_EQ(ToDouble(0x7e00000000000001), 0.984375); EXPECT_EQ(ToDouble(0x7f00000000000001), 0.9921875); EXPECT_EQ(ToDouble(0x9000000000000001), -0.125); EXPECT_EQ(ToDouble(0xa000000000000001), -0.25); EXPECT_EQ(ToDouble(0xb000000000000001), -0.375); EXPECT_EQ(ToDouble(0xc000000000000001), -0.5); EXPECT_EQ(ToDouble(0xd000000000000001), -0.625); EXPECT_EQ(ToDouble(0xe000000000000001), -0.75); EXPECT_EQ(ToDouble(0xf000000000000001), -0.875); int64_t two_to_53 = int64_t{1} << 53; EXPECT_EQ(static_cast<int64_t>(ToDouble(0x7FFFFFFFFFFFFFFF) * two_to_53), two_to_53 - 1); EXPECT_EQ(static_cast<int64_t>(ToDouble(0xFFFFFFFFFFFFFFFF) * two_to_53), -(two_to_53 - 1)); EXPECT_NE(static_cast<int64_t>(ToDouble(0x7FFFFFFFFFFFFFFF) * two_to_53 * 2), two_to_53 * 2 - 1); for (int i = 1; i < 100; ++i) { EXPECT_EQ(i * e_plus, ToDouble(i)) << i; EXPECT_EQ(i * e_minus, ToDouble(0x8000000000000000 | i)) << i; } } TEST(GenerateRealTest, ExhaustiveFloat) { auto ToFloat = [](uint64_t a) { return GenerateRealFromBits<float, GeneratePositiveTag, true>(a); }; float last_f = 1.0, last_g = 2.0; uint64_t f_collisions = 0, g_collisions = 0; uint64_t f_unique = 0, g_unique = 0; uint64_t total = 0; auto count = [&](const float r) { total++; const float f = 0.0f * (1.0f - r) + 1.0f * r; if (f >= last_f) { f_collisions++; } else { f_unique++; last_f = f; } const float g = 1.0f * (1.0f - r) + 2.0f * r; if (g >= last_g) { g_collisions++; } else { g_unique++; last_g = g; } }; size_t limit = absl::GetFlag(FLAGS_absl_random_test_trials); uint64_t x = ~uint64_t(0); for (; x != 0 && limit > 0;) { constexpr int kDig = (64 - FLT_MANT_DIG); uint64_t dec = 1; uint64_t chk = 0; const int clz = absl::countl_zero(x); if (clz < kDig) { dec <<= (kDig - clz); chk = (~uint64_t(0)) >> (clz + 1); } for (; x > chk && limit > 0; x -= dec) { count(ToFloat(x)); --limit; } } static_assert(FLT_MANT_DIG == 24, "The float type is expected to have a 24 bit mantissa."); if (limit != 0) { EXPECT_LT(1 << 28, f_unique); EXPECT_EQ((1 << 24) + 40 * (1 << 23) - 1, f_unique); EXPECT_EQ(total, f_unique); EXPECT_EQ(0, f_collisions); EXPECT_LE(1 << 23, g_unique); EXPECT_EQ(total - g_unique, g_collisions); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/generate_real.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/generate_real_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
b8e2996a-a6e1-486c-8094-9fb6020f1f32
cpp
abseil/abseil-cpp
pcg_engine
absl/random/internal/pcg_engine.h
absl/random/internal/pcg_engine_test.cc
#ifndef ABSL_RANDOM_INTERNAL_PCG_ENGINE_H_ #define ABSL_RANDOM_INTERNAL_PCG_ENGINE_H_ #include <type_traits> #include "absl/base/config.h" #include "absl/meta/type_traits.h" #include "absl/numeric/bits.h" #include "absl/numeric/int128.h" #include "absl/random/internal/fastmath.h" #include "absl/random/internal/iostream_state_saver.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename Params, typename Mix> class pcg_engine { static_assert(std::is_same<typename Params::state_type, typename Mix::state_type>::value, "Class-template absl::pcg_engine must be parameterized by " "Params and Mix with identical state_type"); static_assert(std::is_unsigned<typename Mix::result_type>::value, "Class-template absl::pcg_engine must be parameterized by " "an unsigned Mix::result_type"); using params_type = Params; using mix_type = Mix; using state_type = typename Mix::state_type; public: using result_type = typename Mix::result_type; static constexpr result_type(min)() { return (std::numeric_limits<result_type>::min)(); } static constexpr result_type(max)() { return (std::numeric_limits<result_type>::max)(); } explicit pcg_engine(uint64_t seed_value = 0) { seed(seed_value); } template <class SeedSequence, typename = typename absl::enable_if_t< !std::is_same<SeedSequence, pcg_engine>::value>> explicit pcg_engine(SeedSequence&& seq) { seed(seq); } pcg_engine(const pcg_engine&) = default; pcg_engine& operator=(const pcg_engine&) = default; pcg_engine(pcg_engine&&) = default; pcg_engine& operator=(pcg_engine&&) = default; result_type operator()() { state_ = lcg(state_); return Mix{}(state_); } void seed(uint64_t seed_value = 0) { state_type tmp = seed_value; state_ = lcg(tmp + Params::increment()); } template <class SeedSequence> typename absl::enable_if_t< !std::is_convertible<SeedSequence, uint64_t>::value, void> seed(SeedSequence&& seq) { reseed(seq); } void discard(uint64_t count) { state_ = advance(state_, count); } bool operator==(const pcg_engine& other) const { return state_ == other.state_; } bool operator!=(const pcg_engine& other) const { return !(*this == other); } template <class CharT, class Traits> friend typename absl::enable_if_t<(sizeof(state_type) == 16), std::basic_ostream<CharT, Traits>&> operator<<( std::basic_ostream<CharT, Traits>& os, const pcg_engine& engine) { auto saver = random_internal::make_ostream_state_saver(os); random_internal::stream_u128_helper<state_type> helper; helper.write(pcg_engine::params_type::multiplier(), os); os << os.fill(); helper.write(pcg_engine::params_type::increment(), os); os << os.fill(); helper.write(engine.state_, os); return os; } template <class CharT, class Traits> friend typename absl::enable_if_t<(sizeof(state_type) <= 8), std::basic_ostream<CharT, Traits>&> operator<<( std::basic_ostream<CharT, Traits>& os, const pcg_engine& engine) { auto saver = random_internal::make_ostream_state_saver(os); os << pcg_engine::params_type::multiplier() << os.fill(); os << pcg_engine::params_type::increment() << os.fill(); os << engine.state_; return os; } template <class CharT, class Traits> friend typename absl::enable_if_t<(sizeof(state_type) == 16), std::basic_istream<CharT, Traits>&> operator>>( std::basic_istream<CharT, Traits>& is, pcg_engine& engine) { random_internal::stream_u128_helper<state_type> helper; auto mult = helper.read(is); auto inc = helper.read(is); auto tmp = helper.read(is); if (mult != pcg_engine::params_type::multiplier() || inc != pcg_engine::params_type::increment()) { is.setstate(is.rdstate() | std::ios_base::failbit); } if (!is.fail()) { engine.state_ = tmp; } return is; } template <class CharT, class Traits> friend typename absl::enable_if_t<(sizeof(state_type) <= 8), std::basic_istream<CharT, Traits>&> operator>>( std::basic_istream<CharT, Traits>& is, pcg_engine& engine) { state_type mult{}, inc{}, tmp{}; is >> mult >> inc >> tmp; if (mult != pcg_engine::params_type::multiplier() || inc != pcg_engine::params_type::increment()) { is.setstate(is.rdstate() | std::ios_base::failbit); } if (!is.fail()) { engine.state_ = tmp; } return is; } private: state_type state_; static inline constexpr state_type lcg(state_type s) { return s * Params::multiplier() + Params::increment(); } inline state_type advance(state_type s, uint64_t n) const { state_type mult = Params::multiplier(); state_type inc = Params::increment(); state_type m = 1; state_type i = 0; while (n > 0) { if (n & 1) { m *= mult; i = i * mult + inc; } inc = (mult + 1) * inc; mult *= mult; n >>= 1; } return m * s + i; } template <class SeedSequence> void reseed(SeedSequence& seq) { using sequence_result_type = typename SeedSequence::result_type; constexpr size_t kBufferSize = sizeof(state_type) / sizeof(sequence_result_type); sequence_result_type buffer[kBufferSize]; seq.generate(std::begin(buffer), std::end(buffer)); state_type tmp = buffer[0]; for (size_t i = 1; i < kBufferSize; i++) { tmp <<= (sizeof(sequence_result_type) * 8); tmp |= buffer[i]; } state_ = lcg(tmp + params_type::increment()); } }; template <uint64_t kMultA, uint64_t kMultB, uint64_t kIncA, uint64_t kIncB> class pcg128_params { public: using state_type = absl::uint128; static inline constexpr state_type multiplier() { return absl::MakeUint128(kMultA, kMultB); } static inline constexpr state_type increment() { return absl::MakeUint128(kIncA, kIncB); } }; struct pcg_xsl_rr_128_64 { using state_type = absl::uint128; using result_type = uint64_t; inline uint64_t operator()(state_type state) { uint64_t rotate = static_cast<uint64_t>(state >> 122u); state ^= state >> 64; uint64_t s = static_cast<uint64_t>(state); return rotr(s, static_cast<int>(rotate)); } }; template <uint64_t kMult, uint64_t kInc> class pcg64_params { public: using state_type = uint64_t; static inline constexpr state_type multiplier() { return kMult; } static inline constexpr state_type increment() { return kInc; } }; struct pcg_xsh_rr_64_32 { using state_type = uint64_t; using result_type = uint32_t; inline uint32_t operator()(uint64_t state) { return rotr(static_cast<uint32_t>(((state >> 18) ^ state) >> 27), state >> 59); } }; using pcg64_2018_engine = pcg_engine< random_internal::pcg128_params<0x2360ed051fc65da4ull, 0x4385df649fccf645ull, 0x5851f42d4c957f2d, 0x14057b7ef767814f>, random_internal::pcg_xsl_rr_128_64>; using pcg32_2018_engine = pcg_engine< random_internal::pcg64_params<0x5851f42d4c957f2dull, 0x14057b7ef767814full>, random_internal::pcg_xsh_rr_64_32>; } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/pcg_engine.h" #include <algorithm> #include <bitset> #include <random> #include <sstream> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/internal/explicit_seed_seq.h" #include "absl/time/clock.h" #define UPDATE_GOLDEN 0 namespace { using absl::random_internal::ExplicitSeedSeq; using absl::random_internal::pcg32_2018_engine; using absl::random_internal::pcg64_2018_engine; template <typename EngineType> class PCGEngineTest : public ::testing::Test {}; using EngineTypes = ::testing::Types<pcg64_2018_engine, pcg32_2018_engine>; TYPED_TEST_SUITE(PCGEngineTest, EngineTypes); TYPED_TEST(PCGEngineTest, VerifyReseedChangesAllValues) { using engine_type = TypeParam; using result_type = typename engine_type::result_type; const size_t kNumOutputs = 16; engine_type engine; { std::seed_seq seq1{1, 2, 3, 4, 5, 6, 7}; engine.seed(seq1); } result_type a[kNumOutputs]; std::generate(std::begin(a), std::end(a), std::ref(engine)); { std::random_device rd; std::seed_seq seq2{rd(), rd(), rd()}; engine.seed(seq2); } result_type b[kNumOutputs]; std::generate(std::begin(b), std::end(b), std::ref(engine)); size_t changed_bits = 0; size_t unchanged_bits = 0; size_t total_set = 0; size_t total_bits = 0; size_t equal_count = 0; for (size_t i = 0; i < kNumOutputs; ++i) { equal_count += (a[i] == b[i]) ? 1 : 0; std::bitset<sizeof(result_type) * 8> bitset(a[i] ^ b[i]); changed_bits += bitset.count(); unchanged_bits += bitset.size() - bitset.count(); std::bitset<sizeof(result_type) * 8> a_set(a[i]); std::bitset<sizeof(result_type) * 8> b_set(b[i]); total_set += a_set.count() + b_set.count(); total_bits += 2 * 8 * sizeof(result_type); } EXPECT_LE(changed_bits, 0.60 * (changed_bits + unchanged_bits)); EXPECT_GE(changed_bits, 0.40 * (changed_bits + unchanged_bits)); EXPECT_NEAR(total_set, total_bits * 0.5, 4 * std::sqrt(total_bits)) << "@" << total_set / static_cast<double>(total_bits); const double kExpected = kNumOutputs / (1.0 * sizeof(result_type) * 8); EXPECT_LE(equal_count, 1.0 + kExpected); } constexpr size_t kTwoBufferValues = 16; TYPED_TEST(PCGEngineTest, VerifyDiscard) { using engine_type = TypeParam; for (size_t num_used = 0; num_used < kTwoBufferValues; ++num_used) { engine_type engine_used; for (size_t i = 0; i < num_used; ++i) { engine_used(); } for (size_t num_discard = 0; num_discard < kTwoBufferValues; ++num_discard) { engine_type engine1 = engine_used; engine_type engine2 = engine_used; for (size_t i = 0; i < num_discard; ++i) { engine1(); } engine2.discard(num_discard); for (size_t i = 0; i < kTwoBufferValues; ++i) { const auto r1 = engine1(); const auto r2 = engine2(); ASSERT_EQ(r1, r2) << "used=" << num_used << " discard=" << num_discard; } } } } TYPED_TEST(PCGEngineTest, StreamOperatorsResult) { using engine_type = TypeParam; std::wostringstream os; std::wistringstream is; engine_type engine; EXPECT_EQ(&(os << engine), &os); EXPECT_EQ(&(is >> engine), &is); } TYPED_TEST(PCGEngineTest, StreamSerialization) { using engine_type = TypeParam; for (size_t discard = 0; discard < kTwoBufferValues; ++discard) { ExplicitSeedSeq seed_sequence{12, 34, 56}; engine_type engine(seed_sequence); engine.discard(discard); std::stringstream stream; stream << engine; engine_type new_engine; stream >> new_engine; for (size_t i = 0; i < 64; ++i) { EXPECT_EQ(engine(), new_engine()) << " " << i; } } } constexpr size_t kNumGoldenOutputs = 127; TYPED_TEST(PCGEngineTest, RandomNumberEngineInterface) { using engine_type = TypeParam; using E = engine_type; using T = typename E::result_type; static_assert(std::is_copy_constructible<E>::value, "engine_type must be copy constructible"); static_assert(absl::is_copy_assignable<E>::value, "engine_type must be copy assignable"); static_assert(std::is_move_constructible<E>::value, "engine_type must be move constructible"); static_assert(absl::is_move_assignable<E>::value, "engine_type must be move assignable"); static_assert(std::is_same<decltype(std::declval<E>()()), T>::value, "return type of operator() must be result_type"); E e, v; const E x, y; T s = 1; std::seed_seq q{1, 2, 3}; unsigned long long z = 1; std::wostringstream os; std::wistringstream is; E{}; E{x}; E{s}; E{q}; e.seed(); EXPECT_TRUE(e == x); e.seed(q); { E tmp(q); EXPECT_TRUE(e == tmp); } e(); { E tmp(q); EXPECT_TRUE(e != tmp); } e.discard(z); static_assert(std::is_same<decltype(x == y), bool>::value, "return type of operator== must be bool"); static_assert(std::is_same<decltype(x != y), bool>::value, "return type of operator== must be bool"); } TYPED_TEST(PCGEngineTest, RandenEngineSFINAETest) { using engine_type = TypeParam; using result_type = typename engine_type::result_type; { engine_type engine(result_type(1)); engine.seed(result_type(1)); } { result_type n = 1; engine_type engine(n); engine.seed(n); } { engine_type engine(1); engine.seed(1); } { int n = 1; engine_type engine(n); engine.seed(n); } { std::seed_seq seed_seq; engine_type engine(seed_seq); engine.seed(seed_seq); } { engine_type engine{std::seed_seq()}; engine.seed(std::seed_seq()); } } TEST(PCG642018EngineTest, VerifyGolden) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0x01070196e695f8f1, 0x703ec840c59f4493, 0xe54954914b3a44fa, 0x96130ff204b9285e, 0x7d9fdef535ceb21a, 0x666feed42e1219a0, 0x981f685721c8326f, 0xad80710d6eab4dda, 0xe202c480b037a029, 0x5d3390eaedd907e2, 0x0756befb39c6b8aa, 0x1fb44ba6634d62a3, 0x8d20423662426642, 0x34ea910167a39fb4, 0x93010b43a80d0ab6, 0x663db08a98fc568a, 0x720b0a1335956fae, 0x2c35483e31e1d3ba, 0x429f39776337409d, 0xb46d99e638687344, 0x105370b96aedcaee, 0x3999e92f811cff71, 0xd230f8bcb591cfc9, 0x0dce3db2ba7bdea5, 0xcf2f52c91eec99af, 0x2bc7c24a8b998a39, 0xbd8af1b0d599a19c, 0x56bc45abc66059f5, 0x170a46dc170f7f1e, 0xc25daf5277b85fad, 0xe629c2e0c948eadb, 0x1720a796915542ed, 0x22fb0caa4f909951, 0x7e0c0f4175acd83d, 0xd9fcab37ff2a860c, 0xab2280fb2054bad1, 0x58e8a06f37fa9e99, 0xc3a52a30b06528c7, 0x0175f773a13fc1bd, 0x731cfc584b00e840, 0x404cc7b2648069cb, 0x5bc29153b0b7f783, 0x771310a38cc999d1, 0x766a572f0a71a916, 0x90f450fb4fc48348, 0xf080ea3e1c7b1a0d, 0x15471a4507d66a44, 0x7d58e55a78f3df69, 0x0130a094576ac99c, 0x46669cb2d04b1d87, 0x17ab5bed20191840, 0x95b177d260adff3e, 0x025fb624b6ee4c07, 0xb35de4330154a95f, 0xe8510fff67e24c79, 0x132c3cbcd76ed2d3, 0x35e7cc145a093904, 0x9f5b5b5f81583b79, 0x3ee749a533966233, 0x4af85886cdeda8cd, 0x0ca5380ecb3ef3aa, 0x4f674eb7661d3192, 0x88a29aad00cd7733, 0x70b627ca045ffac6, 0x5912b43ea887623d, 0x95dc9fc6f62cf221, 0x926081a12a5c905b, 0x9c57d4cd7dfce651, 0x85ab2cbf23e3bb5d, 0xc5cd669f63023152, 0x3067be0fad5d898e, 0x12b56f444cb53d05, 0xbc2e5a640c3434fc, 0x9280bff0e4613fe1, 0x98819094c528743e, 0x999d1c98d829df33, 0x9ff82a012dc89242, 0xf99183ed39c8be94, 0xf0f59161cd421c55, 0x3c705730c2f6c48d, 0x66ad85c6e9278a61, 0x2a3428e4a428d5d0, 0x79207d68fd04940d, 0xea7f2b402edc8430, 0xa06b419ac857f63b, 0xcb1dd0e6fbc47e1c, 0x4f55229200ada6a4, 0x9647b5e6359c927f, 0x30bf8f9197c7efe5, 0xa79519529cc384d0, 0xbb22c4f339ad6497, 0xd7b9782f59d14175, 0x0dff12fff2ec0118, 0xa331ad8305343a7c, 0x48dad7e3f17e0862, 0x324c6fb3fd3c9665, 0xf0e4350e7933dfc4, 0x7ccda2f30b8b03b6, 0xa0afc6179005de40, 0xee65da6d063b3a30, 0xb9506f42f2bfe87a, 0xc9a2e26b0ef5baa0, 0x39fa9d4f495011d6, 0xbecc21a45d023948, 0x6bf484c6593f737f, 0x8065e0070cadc3b7, 0x9ef617ed8d419799, 0xac692cf8c233dd15, 0xd2ed87583c4ebb98, 0xad95ba1bebfedc62, 0x9b60b160a8264e43, 0x0bc8c45f71fcf25b, 0x4a78035cdf1c9931, 0x4602dc106667e029, 0xb335a3c250498ac8, 0x0256ebc4df20cab8, 0x0c61efd153f0c8d9, 0xe5d0150a4f806f88, 0x99d6521d351e7d87, 0x8d4888c9f80f4325, 0x106c5735c1ba868d, 0x73414881b880a878, 0x808a9a58a3064751, 0x339a29f3746de3d5, 0x5410d7fa4f873896, 0xd84623c81d7b8a03, 0x1f7c7e7a7f47f462, }; pcg64_2018_engine engine(0); #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%016lx, ", engine()); if (i % 3 == 2) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(PCG642018EngineTest, VerifyGoldenSeeded) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0xb03988f1e39691ee, 0xbd2a1eb5ac31e97a, 0x8f00d6d433634d02, 0x1823c28d483d5776, 0x000c3ee3e1aeb74a, 0xfa82ef27a4f3df9c, 0xc6f382308654e454, 0x414afb1a238996c2, 0x4703a4bc252eb411, 0x99d64f62c8f7f654, 0xbb07ebe11a34fa44, 0x79eb06a363c06131, 0xf66ad3756f1c6b21, 0x130c01d5e869f457, 0x5ca2b9963aecbc81, 0xfef7bebc1de27e6c, 0x1d174faa5ed2cdbf, 0xd75b7a773f2bb889, 0xc35c872327a170a5, 0x46da6d88646a42fe, 0x4622985e0442dae2, 0xbe3cbd67297f1f9b, 0xe7c37b4a4798bfd1, 0x173d5dfad15a25c3, 0x0eb6849ba2961522, 0xb0ff7246e6700d73, 0x88cb9c42d3afa577, 0xb609731dbd94d917, 0xd3941cda04b40081, 0x28d140f7409bea3a, 0x3c96699a920a124a, 0xdb28be521958b2fd, 0x0a3f44db3d4c5124, 0x7ac8e60ba13b70d2, 0x75f03a41ded5195a, 0xaed10ac7c4e4825d, 0xb92a3b18aadb7adc, 0xda45e0081f2bca46, 0x74d39ab3753143fc, 0xb686038018fac9ca, 0x4cc309fe99542dbb, 0xf3e1a4fcb311097c, 0x58763d6fa698d69d, 0xd11c365dbecd8d60, 0x2c15d55725b1dee7, 0x89805f254d85658c, 0x2374c44dfc62158b, 0x9a8350fa7995328d, 0x198f838970cf91da, 0x96aff569562c0e53, 0xd76c8c52b7ec6e3f, 0x23a01cd9ae4baa81, 0x3adb366b6d02a893, 0xb3313e2a4c5b333f, 0x04c11230b96a5425, 0x1f7f7af04787d571, 0xaddb019365275ec7, 0x5c960468ccb09f42, 0x8438db698c69a44a, 0x492be1e46111637e, 0x9c6c01e18100c610, 0xbfe48e75b7d0aceb, 0xb5e0b89ec1ce6a00, 0x9d280ecbc2fe8997, 0x290d9e991ba5fcab, 0xeec5bec7d9d2a4f0, 0x726e81488f19150e, 0x1a6df7955a7e462c, 0x37a12d174ba46bb5, 0x3cdcdffd96b1b5c5, 0x2c5d5ac10661a26e, 0xa742ed18f22e50c4, 0x00e0ed88ff0d8a35, 0x3d3c1718cb1efc0b, 0x1d70c51ffbccbf11, 0xfbbb895132a4092f, 0x619d27f2fb095f24, 0x69af68200985e5c4, 0xbee4885f57373f8d, 0x10b7a6bfe0587e40, 0xa885e6cf2f7e5f0a, 0x59f879464f767550, 0x24e805d69056990d, 0x860970b911095891, 0xca3189954f84170d, 0x6652a5edd4590134, 0x5e1008cef76174bf, 0xcbd417881f2bcfe5, 0xfd49fc9d706ecd17, 0xeebf540221ebd066, 0x46af7679464504cb, 0xd4028486946956f1, 0xd4f41864b86c2103, 0x7af090e751583372, 0x98cdaa09278cb642, 0xffd42b921215602f, 0x1d05bec8466b1740, 0xf036fa78a0132044, 0x787880589d1ecc78, 0x5644552cfef33230, 0x0a97e275fe06884b, 0x96d1b13333d470b5, 0xc8b3cdad52d3b034, 0x091357b9db7376fd, 0xa5fe4232555edf8c, 0x3371bc3b6ada76b5, 0x7deeb2300477c995, 0x6fc6d4244f2849c1, 0x750e8cc797ca340a, 0x81728613cd79899f, 0x3467f4ee6f9aeb93, 0x5ef0a905f58c640f, 0x432db85e5101c98a, 0x6488e96f46ac80c2, 0x22fddb282625048c, 0x15b287a0bc2d4c5d, 0xa7e2343ef1f28bce, 0xc87ee1aa89bed09e, 0x220610107812c5e9, 0xcbdab6fcd640f586, 0x8d41047970928784, 0x1aa431509ec1ade0, 0xac3f0be53f518ddc, 0x16f4428ad81d0cbb, 0x675b13c2736fc4bb, 0x6db073afdd87e32d, 0x572f3ca2f1a078c6, }; ExplicitSeedSeq seed_sequence{12, 34, 56}; pcg64_2018_engine engine(seed_sequence); #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%016lx, ", engine()); if (i % 3 == 2) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(seed_sequence); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(PCG642018EngineTest, VerifyGoldenFromDeserializedEngine) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0xdd425b47b4113dea, 0x1b07176479d444b0, 0x6b391027586f2e42, 0xa166f2b15f4a2143, 0xffb6dbd7a179ee97, 0xb2c00035365bf0b1, 0x8fbb518b45855521, 0xfc789a55ddf87c3b, 0x429531f0f17ff355, 0xbe708560d603d283, 0x5bff415175c5cb6b, 0xe813491f4ad45394, 0xa853f4506d55880d, 0x7e538453e568172e, 0xe101f1e098ddd0ec, 0x6ee31266ee4c766d, 0xa8786d92d66b39d7, 0xfee622a2acf5e5b0, 0x5fe8e82c102fa7b3, 0x01f10be4cdb53c9d, 0xbe0545366f857022, 0x12e74f010a339bca, 0xb10d85ca40d5ce34, 0xe80d6feba5054875, 0x2b7c1ee6d567d4ee, 0x2a9cd043bfd03b66, 0x5cfc531bd239f3f1, 0x1c4734e4647d70f5, 0x85a8f60f006b5760, 0x6a4239ce76dca387, 0x8da0f86d7339335c, 0xf055b0468551374d, 0x486e8567e9bea9a0, 0x4cb531b8405192dd, 0xf813b1ee3157110b, 0x214c2a664a875d8e, 0x74531237b29b35f7, 0xa6f0267bb77a771e, 0x64b552bff54184a4, 0xa2d6f7af2d75b6fc, 0x460a10018e03b5ab, 0x76fd1fdcb81d0800, 0x76f5f81805070d9d, 0x1fb75cb1a70b289a, 0x9dfd25a022c4b27f, 0x9a31a14a80528e9e, 0x910dc565ddc25820, 0xd6aef8e2b0936c10, 0xe1773c507fe70225, 0xe027fd7aadd632bc, 0xc1fecb427089c8b8, 0xb5c74c69fa9dbf26, 0x71bf9b0e4670227d, 0x25f48fad205dcfdd, 0x905248ec4d689c56, 0x5c2b7631b0de5c9d, 0x9f2ee0f8f485036c, 0xfd6ce4ebb90bf7ea, 0xd435d20046085574, 0x6b7eadcb0625f986, 0x679d7d44b48be89e, 0x49683b8e1cdc49de, 0x4366cf76e9a2f4ca, 0x54026ec1cdad7bed, 0xa9a04385207f28d3, 0xc8e66de4eba074b2, 0x40b08c42de0f4cc0, 0x1d4c5e0e93c5bbc0, 0x19b80792e470ae2d, 0x6fcaaeaa4c2a5bd9, 0xa92cb07c4238438e, 0x8bb5c918a007e298, 0x7cd671e944874cf4, 0x88166470b1ba3cac, 0xd013d476eaeeade6, 0xcee416947189b3c3, 0x5d7c16ab0dce6088, 0xd3578a5c32b13d27, 0x3875db5adc9cc973, 0xfbdaba01c5b5dc56, 0xffc4fdd391b231c3, 0x2334520ecb164fec, 0x361c115e7b6de1fa, 0xeee58106cc3563d7, 0x8b7f35a8db25ebb8, 0xb29d00211e2cafa6, 0x22a39fe4614b646b, 0x92ca6de8b998506d, 0x40922fe3d388d1db, 0x9da47f1e540f802a, 0x811dceebf16a25db, 0xf6524ae22e0e53a9, 0x52d9e780a16eb99d, 0x4f504286bb830207, 0xf6654d4786bd5cc3, 0x00bd98316003a7e1, 0xefda054a6ab8f5f3, 0x46cfb0f4c1872827, 0xc22b316965c0f3b2, 0xd1a28087c7e7562a, 0xaa4f6a094b7f5cff, 0xfe2bc853a041f7da, 0xe9d531402a83c3ba, 0xe545d8663d3ce4dd, 0xfa2dcd7d91a13fa8, 0xda1a080e52a127b8, 0x19c98f1f809c3d84, 0x2cef109af4678c88, 0x53462accab3b9132, 0x176b13a80415394e, 0xea70047ef6bc178b, 0x57bca80506d6dcdf, 0xd853ba09ff09f5c4, 0x75f4df3a7ddd4775, 0x209c367ade62f4fe, 0xa9a0bbc74d5f4682, 0x5dfe34bada86c21a, 0xc2c05bbcd38566d1, 0x6de8088e348c916a, 0x6a7001c6000c2196, 0xd9fb51865fc4a367, 0x12f320e444ece8ff, 0x6d56f7f793d65035, 0x138f31b7a865f8aa, 0x58fc68b4026b9adf, 0xcd48954b79fb6436, 0x27dfce4a0232af87, }; #if UPDATE_GOLDEN (void)kGolden; std::seed_seq seed_sequence{1, 2, 3}; pcg64_2018_engine engine(seed_sequence); std::ostringstream stream; stream << engine; auto str = stream.str(); printf("%s\n\n", str.c_str()); for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%016lx, ", engine()); if (i % 3 == 2) { printf("\n"); } } printf("\n\n\n"); #else pcg64_2018_engine engine; std::istringstream stream( "2549297995355413924 4865540595714422341 6364136223846793005 " "1442695040888963407 18088519957565336995 4845369368158826708"); stream >> engine; for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(PCG322018EngineTest, VerifyGolden) { constexpr uint32_t kGolden[kNumGoldenOutputs] = { 0x7a7ecbd9, 0x89fd6c06, 0xae646aa8, 0xcd3cf945, 0x6204b303, 0x198c8585, 0x49fce611, 0xd1e9297a, 0x142d9440, 0xee75f56b, 0x473a9117, 0xe3a45903, 0xbce807a1, 0xe54e5f4d, 0x497d6c51, 0x61829166, 0xa740474b, 0x031912a8, 0x9de3defa, 0xd266dbf1, 0x0f38bebb, 0xec3c4f65, 0x07c5057d, 0xbbce03c8, 0xfd2ac7a8, 0xffcf4773, 0x5b10affb, 0xede1c842, 0xe22b01b7, 0xda133c8c, 0xaf89b0f4, 0x25d1b8bc, 0x9f625482, 0x7bfd6882, 0x2e2210c0, 0x2c8fb9a6, 0x42cb3b83, 0x40ce0dab, 0x644a3510, 0x36230ef2, 0xe2cb6d43, 0x1012b343, 0x746c6c9f, 0x36714cf8, 0xed1f5026, 0x8bbbf83e, 0xe98710f4, 0x8a2afa36, 0x09035349, 0x6dc1a487, 0x682b634b, 0xc106794f, 0x7dd78beb, 0x628c262b, 0x852fb232, 0xb153ac4c, 0x4f169d1b, 0xa69ab774, 0x4bd4b6f2, 0xdc351dd3, 0x93ff3c8c, 0xa30819ab, 0xff07758c, 0x5ab13c62, 0xd16d7fb5, 0xc4950ffa, 0xd309ae49, 0xb9677a87, 0x4464e317, 0x90dc44f1, 0xc694c1d4, 0x1d5e1168, 0xadf37a2d, 0xda38990d, 0x1ec4bd33, 0x36ca25ce, 0xfa0dc76a, 0x968a9d43, 0x6950ac39, 0xdd3276bc, 0x06d5a71e, 0x1f6f282d, 0x5c626c62, 0xdde3fc31, 0x152194ce, 0xc35ed14c, 0xb1f7224e, 0x47f76bb8, 0xb34fdd08, 0x7011395e, 0x162d2a49, 0x0d1bf09f, 0x9428a952, 0x03c5c344, 0xd3525616, 0x7816fff3, 0x6bceb8a8, 0x8345a081, 0x366420fd, 0x182abeda, 0x70f82745, 0xaf15ded8, 0xc7f52ca2, 0xa98db9c5, 0x919d99ba, 0x9c376c1c, 0xed8d34c2, 0x716ae9f5, 0xef062fa5, 0xee3b6c56, 0x52325658, 0x61afa9c3, 0xfdaf02f0, 0x961cf3ab, 0x9f291565, 0x4fbf3045, 0x0590c899, 0xde901385, 0x45005ffb, 0x509db162, 0x262fa941, 0x4c421653, 0x4b17c21e, 0xea0d1530, 0xde803845, 0x61bfd515, 0x438523ef, }; pcg32_2018_engine engine(0); #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%08x, ", engine()); if (i % 6 == 5) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(PCG322018EngineTest, VerifyGoldenSeeded) { constexpr uint32_t kGolden[kNumGoldenOutputs] = { 0x60b5a64c, 0x978502f9, 0x80a75f60, 0x241f1158, 0xa4cd1dbb, 0xe7284017, 0x3b678da5, 0x5223ec99, 0xe4bdd5d9, 0x72190e6d, 0xe6e702c9, 0xff80c768, 0xcf126ed3, 0x1fbd20ab, 0x60980489, 0xbc72bf89, 0x407ac6c0, 0x00bf3c51, 0xf9087897, 0x172e4eb6, 0xe9e4f443, 0x1a6098bf, 0xbf44f8c2, 0xdd84a0e5, 0xd9a52364, 0xc0e2e786, 0x061ae2ba, 0x9facb8e3, 0x6109432d, 0xd4e0a013, 0xbd8eb9a6, 0x7e86c3b6, 0x629c0e68, 0x05337430, 0xb495b9f4, 0x11ccd65d, 0xb578db25, 0x66f1246d, 0x6ef20a7f, 0x5e429812, 0x11772130, 0xb944b5c2, 0x01624128, 0xa2385ab7, 0xd3e10d35, 0xbe570ec3, 0xc951656f, 0xbe8944a0, 0x7be41062, 0x5709f919, 0xd745feda, 0x9870b9ae, 0xb44b8168, 0x19e7683b, 0xded8017f, 0xc6e4d544, 0x91ae4225, 0xd6745fba, 0xb992f284, 0x65b12b33, 0xa9d5fdb4, 0xf105ce1a, 0x35ca1a6e, 0x2ff70dd0, 0xd8335e49, 0xfb71ddf2, 0xcaeabb89, 0x5c6f5f84, 0x9a811a7d, 0xbcecbbd1, 0x0f661ba0, 0x9ad93b9d, 0xedd23e0b, 0x42062f48, 0xd38dd7e4, 0x6cd63c9c, 0x640b98ae, 0x4bff5653, 0x12626371, 0x13266017, 0xe7a698d8, 0x39c74667, 0xe8fdf2e3, 0x52803bf8, 0x2af6895b, 0x91335b7b, 0x699e4961, 0x00a40fff, 0x253ff2b6, 0x4a6cf672, 0x9584e85f, 0xf2a5000c, 0x4d58aba8, 0xb8513e6a, 0x767fad65, 0x8e326f9e, 0x182f15a1, 0x163dab52, 0xdf99c780, 0x047282a1, 0xee4f90dd, 0xd50394ae, 0x6c9fd5f0, 0xb06a9194, 0x387e3840, 0x04a9487b, 0xf678a4c2, 0xd0a78810, 0xd502c97e, 0xd6a9b12a, 0x4accc5dc, 0x416ed53e, 0x50411536, 0xeeb89c24, 0x813a7902, 0x034ebca6, 0xffa52e7c, 0x7ecd3d0e, 0xfa37a0d2, 0xb1fbe2c1, 0xb7efc6d1, 0xefa4ccee, 0xf6f80424, 0x2283f3d9, 0x68732284, 0x94f3b5c8, 0xbbdeceb9, }; ExplicitSeedSeq seed_sequence{12, 34, 56}; pcg32_2018_engine engine(seed_sequence); #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%08x, ", engine()); if (i % 6 == 5) { printf("\n"); } } printf("\n\n\n"); #else for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } engine.seed(seed_sequence); for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } TEST(PCG322018EngineTest, VerifyGoldenFromDeserializedEngine) { constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0x780f7042, 0xba137215, 0x43ab6f22, 0x0cb55f46, 0x44b2627d, 0x835597af, 0xea973ea1, 0x0d2abd35, 0x4fdd601c, 0xac4342fe, 0x7db7e93c, 0xe56ebcaf, 0x3596470a, 0x7770a9ad, 0x9b893320, 0x57db3415, 0xb432de54, 0xa02baf71, 0xa256aadb, 0x88921fc7, 0xa35fa6b3, 0xde3eca46, 0x605739a7, 0xa890b82b, 0xe457b7ad, 0x335fb903, 0xeb06790c, 0xb3c54bf6, 0x6141e442, 0xa599a482, 0xb78987cc, 0xc61dfe9d, 0x0f1d6ace, 0x17460594, 0x8f6a5061, 0x083dc354, 0xe9c337fb, 0xcfd105f7, 0x926764b6, 0x638d24dc, 0xeaac650a, 0x67d2cb9c, 0xd807733c, 0x205fc52e, 0xf5399e2e, 0x6c46ddcc, 0xb603e875, 0xce113a25, 0x3c8d4813, 0xfb584db8, 0xf6d255ff, 0xea80954f, 0x42e8be85, 0xb2feee72, 0x62bd8d16, 0x1be4a142, 0x97dca1a4, 0xdd6e7333, 0xb2caa20e, 0xa12b1588, 0xeb3a5a1a, 0x6fa5ba89, 0x077ea931, 0x8ddb1713, 0x0dd03079, 0x2c2ba965, 0xa77fac17, 0xc8325742, 0x8bb893bf, 0xc2315741, 0xeaceee92, 0x81dd2ee2, 0xe5214216, 0x1b9b8fb2, 0x01646d03, 0x24facc25, 0xd8c0e0bb, 0xa33fe106, 0xf34fe976, 0xb3b4b44e, 0x65618fed, 0x032c6192, 0xa9dd72ce, 0xf391887b, 0xf41c6a6e, 0x05c4bd6d, 0x37fa260e, 0x46b05659, 0xb5f6348a, 0x62d26d89, 0x39f6452d, 0xb17b30a2, 0xbdd82743, 0x38ecae3b, 0xfe90f0a2, 0xcb2d226d, 0xcf8a0b1c, 0x0eed3d4d, 0xa1f69cfc, 0xd7ac3ba5, 0xce9d9a6b, 0x121deb4c, 0x4a0d03f3, 0xc1821ed1, 0x59c249ac, 0xc0abb474, 0x28149985, 0xfd9a82ba, 0x5960c3b2, 0xeff00cba, 0x6073aa17, 0x25dc0919, 0x9976626e, 0xdd2ccc33, 0x39ecb6ec, 0xc6e15d13, 0xfac94cfd, 0x28cfd34f, 0xf2d2c32d, 0x51c23d08, 0x4fdb2f48, 0x97baa807, 0xf2c1004c, 0xc4ae8136, 0x71f31c94, 0x8c92d601, 0x36caf5cd, }; #if UPDATE_GOLDEN (void)kGolden; std::seed_seq seed_sequence{1, 2, 3}; pcg32_2018_engine engine(seed_sequence); std::ostringstream stream; stream << engine; auto str = stream.str(); printf("%s\n\n", str.c_str()); for (size_t i = 0; i < kNumGoldenOutputs; ++i) { printf("0x%08x, ", engine()); if (i % 6 == 5) { printf("\n"); } } printf("\n\n\n"); EXPECT_FALSE(true); #else pcg32_2018_engine engine; std::istringstream stream( "6364136223846793005 1442695040888963407 6537028157270659894"); stream >> engine; for (const auto& elem : kGolden) { EXPECT_EQ(elem, engine()); } #endif } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/pcg_engine.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/pcg_engine_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f515b3d7-ce2b-46d9-b0e6-1e32e8e5fac1
cpp
abseil/abseil-cpp
wide_multiply
absl/random/internal/wide_multiply.h
absl/random/internal/wide_multiply_test.cc
#ifndef ABSL_RANDOM_INTERNAL_WIDE_MULTIPLY_H_ #define ABSL_RANDOM_INTERNAL_WIDE_MULTIPLY_H_ #include <cstdint> #include <limits> #include <type_traits> #if (defined(_WIN32) || defined(_WIN64)) && defined(_M_IA64) #include <intrin.h> #pragma intrinsic(_umul128) #define ABSL_INTERNAL_USE_UMUL128 1 #endif #include "absl/base/config.h" #include "absl/numeric/bits.h" #include "absl/numeric/int128.h" #include "absl/random/internal/traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { template <typename UIntType> struct wide_multiply { static constexpr size_t kN = std::numeric_limits<UIntType>::digits; using input_type = UIntType; using result_type = typename random_internal::unsigned_bits<kN * 2>::type; static result_type multiply(input_type a, input_type b) { return static_cast<result_type>(a) * b; } static input_type hi(result_type r) { return static_cast<input_type>(r >> kN); } static input_type lo(result_type r) { return static_cast<input_type>(r); } static_assert(std::is_unsigned<UIntType>::value, "Class-template wide_multiply<> argument must be unsigned."); }; inline U256 MultiplyU128ToU256(uint128 a, uint128 b) { const uint128 a00 = static_cast<uint64_t>(a); const uint128 a64 = a >> 64; const uint128 b00 = static_cast<uint64_t>(b); const uint128 b64 = b >> 64; const uint128 c00 = a00 * b00; const uint128 c64a = a00 * b64; const uint128 c64b = a64 * b00; const uint128 c128 = a64 * b64; const uint64_t carry = static_cast<uint64_t>(((c00 >> 64) + static_cast<uint64_t>(c64a) + static_cast<uint64_t>(c64b)) >> 64); return {c128 + (c64a >> 64) + (c64b >> 64) + carry, c00 + (c64a << 64) + (c64b << 64)}; } template <> struct wide_multiply<uint128> { using input_type = uint128; using result_type = U256; static result_type multiply(input_type a, input_type b) { return MultiplyU128ToU256(a, b); } static input_type hi(result_type r) { return r.hi; } static input_type lo(result_type r) { return r.lo; } }; } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/wide_multiply.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/numeric/int128.h" using absl::random_internal::MultiplyU128ToU256; using absl::random_internal::U256; namespace { U256 LeftShift(U256 v, int s) { if (s == 0) { return v; } else if (s < 128) { return {(v.hi << s) | (v.lo >> (128 - s)), v.lo << s}; } else { return {v.lo << (s - 128), 0}; } } MATCHER_P2(Eq256, hi, lo, "") { return arg.hi == hi && arg.lo == lo; } MATCHER_P(Eq256, v, "") { return arg.hi == v.hi && arg.lo == v.lo; } TEST(WideMultiplyTest, MultiplyU128ToU256Test) { using absl::uint128; constexpr uint128 k1 = 1; constexpr uint128 kMax = ~static_cast<uint128>(0); EXPECT_THAT(MultiplyU128ToU256(0, 0), Eq256(0, 0)); EXPECT_THAT(MultiplyU128ToU256(kMax, kMax), Eq256(kMax << 1, 1)); EXPECT_THAT(MultiplyU128ToU256(kMax, 1), Eq256(0, kMax)); EXPECT_THAT(MultiplyU128ToU256(1, kMax), Eq256(0, kMax)); for (int i = 0; i < 64; ++i) { SCOPED_TRACE(i); EXPECT_THAT(MultiplyU128ToU256(kMax, k1 << i), Eq256(LeftShift({0, kMax}, i))); EXPECT_THAT(MultiplyU128ToU256(k1 << i, kMax), Eq256(LeftShift({0, kMax}, i))); } for (int i = 0; i < 64; ++i) { for (int j = 0; j < 64; ++j) { EXPECT_THAT(MultiplyU128ToU256(k1 << i, k1 << j), Eq256(LeftShift({0, 1}, i + j))); } } EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0xc502da0d6ea99fe8, 0xfa3c9141a1f50912), absl::MakeUint128(0x96bcf1ac37f97bd6, 0x27e2cdeb5fb2299e)), Eq256(absl::MakeUint128(0x740113d838f96a64, 0x22e8cfa4d71f89ea), absl::MakeUint128(0x19184a345c62e993, 0x237871b630337b1c))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0x6f29e670cee07230, 0xc3d8e6c3e4d86759), absl::MakeUint128(0x3227d29fa6386db1, 0x231682bb1e4b764f)), Eq256(absl::MakeUint128(0x15c779d9d5d3b07c, 0xd7e6c827f0c81cbe), absl::MakeUint128(0xf88e3914f7fa287a, 0x15b79975137dea77))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0xafb77107215646e1, 0x3b844cb1ac5769e7), absl::MakeUint128(0x1ff7b2d888b62479, 0x92f758ae96fcba0b)), Eq256(absl::MakeUint128(0x15f13b70181f6985, 0x2adb36bbabce7d02), absl::MakeUint128(0x6c470d72e13aad04, 0x63fba3f5841762ed))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0xd85d5558d67ac905, 0xf88c70654dae19b1), absl::MakeUint128(0x17252c6727db3738, 0x399ff658c511eedc)), Eq256(absl::MakeUint128(0x138fcdaf8b0421ee, 0x1b465ddf2a0d03f6), absl::MakeUint128(0x8f573ba68296860f, 0xf327d2738741a21c))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0x46f0421a37ff6bee, 0xa61df89f09d140b1), absl::MakeUint128(0x3d712ec9f37ca2e1, 0x9658a2cba47ef4b1)), Eq256(absl::MakeUint128(0x11069cc48ee7c95d, 0xd35fb1c7aa91c978), absl::MakeUint128(0xbe2f4a6de874b015, 0xd2f7ac1b76746e61))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0x730d27c72d58fa49, 0x3ebeda7498f8827c), absl::MakeUint128(0xa2c959eca9f503af, 0x189c687eb842bbd8)), Eq256(absl::MakeUint128(0x4928d0ea356ba022, 0x1546d34a2963393), absl::MakeUint128(0x7481531e1e0a16d1, 0xdd8025015cf6aca0))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0x6ca41020f856d2f1, 0xb9b0838c04a7f4aa), absl::MakeUint128(0x9cf41d28a8396f54, 0x1d681695e377ffe6)), Eq256(absl::MakeUint128(0x429b92934d9be6f1, 0xea182877157c1e7), absl::MakeUint128(0x7135c23f0a4a475, 0xc1adc366f4a126bc))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0x57472833797c332, 0x6c79272fdec4687a), absl::MakeUint128(0xb5f022ea3838e46b, 0x16face2f003e27a6)), Eq256(absl::MakeUint128(0x3e072e0962b3400, 0x5d9fe8fdc3d0e1f4), absl::MakeUint128(0x7dc0df47cedafd62, 0xbe6501f1acd2551c))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0xf0fb4198322eb1c2, 0xfe7f5f31f3885938), absl::MakeUint128(0xd99012b71bb7aa31, 0xac7a6f9eb190789)), Eq256(absl::MakeUint128(0xcccc998cf075ca01, 0x642d144322fb873a), absl::MakeUint128(0xc79dc12b69d91ed4, 0xa83459132ce046f8))); EXPECT_THAT(MultiplyU128ToU256( absl::MakeUint128(0xb5c04120848cdb47, 0x8aa62a827bf52635), absl::MakeUint128(0x8d07a359be2f1380, 0x467bb90d59da0dea)), Eq256(absl::MakeUint128(0x64205019d139a9ce, 0x99425c5fb6e7a977), absl::MakeUint128(0xd3e99628a9e5fca7, 0x9c7824cb7279d72))); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/wide_multiply.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/wide_multiply_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
3e2c2113-a259-4ad9-9ee0-e4be27194ce0
cpp
abseil/abseil-cpp
bind_front
absl/functional/bind_front.h
absl/functional/bind_front_test.cc
#ifndef ABSL_FUNCTIONAL_BIND_FRONT_H_ #define ABSL_FUNCTIONAL_BIND_FRONT_H_ #if defined(__cpp_lib_bind_front) && __cpp_lib_bind_front >= 201907L #include <functional> #endif #include <utility> #include "absl/functional/internal/front_binder.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN #if defined(__cpp_lib_bind_front) && __cpp_lib_bind_front >= 201907L using std::bind_front; #else template <class F, class... BoundArgs> constexpr functional_internal::bind_front_t<F, BoundArgs...> bind_front( F&& func, BoundArgs&&... args) { return functional_internal::bind_front_t<F, BoundArgs...>( absl::in_place, std::forward<F>(func), std::forward<BoundArgs>(args)...); } #endif ABSL_NAMESPACE_END } #endif
#include "absl/functional/bind_front.h" #include <stddef.h> #include <functional> #include <memory> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" namespace { char CharAt(const char* s, size_t index) { return s[index]; } TEST(BindTest, Basics) { EXPECT_EQ('C', absl::bind_front(CharAt)("ABC", 2)); EXPECT_EQ('C', absl::bind_front(CharAt, "ABC")(2)); EXPECT_EQ('C', absl::bind_front(CharAt, "ABC", 2)()); } TEST(BindTest, Lambda) { auto lambda = [](int x, int y, int z) { return x + y + z; }; EXPECT_EQ(6, absl::bind_front(lambda)(1, 2, 3)); EXPECT_EQ(6, absl::bind_front(lambda, 1)(2, 3)); EXPECT_EQ(6, absl::bind_front(lambda, 1, 2)(3)); EXPECT_EQ(6, absl::bind_front(lambda, 1, 2, 3)()); } struct Functor { std::string operator()() & { return "&"; } std::string operator()() const& { return "const&"; } std::string operator()() && { return "&&"; } std::string operator()() const&& { return "const&&"; } }; TEST(BindTest, PerfectForwardingOfBoundArgs) { auto f = absl::bind_front(Functor()); const auto& cf = f; EXPECT_EQ("&", f()); EXPECT_EQ("const&", cf()); EXPECT_EQ("&&", std::move(f)()); EXPECT_EQ("const&&", std::move(cf)()); } struct ArgDescribe { std::string operator()(int&) const { return "&"; } std::string operator()(const int&) const { return "const&"; } std::string operator()(int&&) const { return "&&"; } std::string operator()(const int&&) const { return "const&&"; } }; TEST(BindTest, PerfectForwardingOfFreeArgs) { ArgDescribe f; int i; EXPECT_EQ("&", absl::bind_front(f)(static_cast<int&>(i))); EXPECT_EQ("const&", absl::bind_front(f)(static_cast<const int&>(i))); EXPECT_EQ("&&", absl::bind_front(f)(static_cast<int&&>(i))); EXPECT_EQ("const&&", absl::bind_front(f)(static_cast<const int&&>(i))); } struct NonCopyableFunctor { NonCopyableFunctor() = default; NonCopyableFunctor(const NonCopyableFunctor&) = delete; NonCopyableFunctor& operator=(const NonCopyableFunctor&) = delete; const NonCopyableFunctor* operator()() const { return this; } }; TEST(BindTest, RefToFunctor) { NonCopyableFunctor ncf; auto bound_ncf = absl::bind_front(std::ref(ncf)); auto bound_ncf_copy = bound_ncf; EXPECT_EQ(&ncf, bound_ncf_copy()); } struct Struct { std::string value; }; TEST(BindTest, StoreByCopy) { Struct s = {"hello"}; auto f = absl::bind_front(&Struct::value, s); auto g = f; EXPECT_EQ("hello", f()); EXPECT_EQ("hello", g()); EXPECT_NE(&s.value, &f()); EXPECT_NE(&s.value, &g()); EXPECT_NE(&g(), &f()); } struct NonCopyable { explicit NonCopyable(const std::string& s) : value(s) {} NonCopyable(const NonCopyable&) = delete; NonCopyable& operator=(const NonCopyable&) = delete; std::string value; }; const std::string& GetNonCopyableValue(const NonCopyable& n) { return n.value; } TEST(BindTest, StoreByRef) { NonCopyable s("hello"); auto f = absl::bind_front(&GetNonCopyableValue, std::ref(s)); EXPECT_EQ("hello", f()); EXPECT_EQ(&s.value, &f()); auto g = std::move(f); EXPECT_EQ("hello", g()); EXPECT_EQ(&s.value, &g()); s.value = "goodbye"; EXPECT_EQ("goodbye", g()); } TEST(BindTest, StoreByCRef) { NonCopyable s("hello"); auto f = absl::bind_front(&GetNonCopyableValue, std::cref(s)); EXPECT_EQ("hello", f()); EXPECT_EQ(&s.value, &f()); auto g = std::move(f); EXPECT_EQ("hello", g()); EXPECT_EQ(&s.value, &g()); s.value = "goodbye"; EXPECT_EQ("goodbye", g()); } const std::string& GetNonCopyableValueByWrapper( std::reference_wrapper<NonCopyable> n) { return n.get().value; } TEST(BindTest, StoreByRefInvokeByWrapper) { NonCopyable s("hello"); auto f = absl::bind_front(GetNonCopyableValueByWrapper, std::ref(s)); EXPECT_EQ("hello", f()); EXPECT_EQ(&s.value, &f()); auto g = std::move(f); EXPECT_EQ("hello", g()); EXPECT_EQ(&s.value, &g()); s.value = "goodbye"; EXPECT_EQ("goodbye", g()); } TEST(BindTest, StoreByPointer) { NonCopyable s("hello"); auto f = absl::bind_front(&NonCopyable::value, &s); EXPECT_EQ("hello", f()); EXPECT_EQ(&s.value, &f()); auto g = std::move(f); EXPECT_EQ("hello", g()); EXPECT_EQ(&s.value, &g()); } int Sink(std::unique_ptr<int> p) { return *p; } std::unique_ptr<int> Factory(int n) { return absl::make_unique<int>(n); } TEST(BindTest, NonCopyableArg) { EXPECT_EQ(42, absl::bind_front(Sink)(absl::make_unique<int>(42))); EXPECT_EQ(42, absl::bind_front(Sink, absl::make_unique<int>(42))()); } TEST(BindTest, NonCopyableResult) { EXPECT_THAT(absl::bind_front(Factory)(42), ::testing::Pointee(42)); EXPECT_THAT(absl::bind_front(Factory, 42)(), ::testing::Pointee(42)); } template <class T> struct FalseCopyable { FalseCopyable() {} FalseCopyable(const FalseCopyable& other) : m(other.m) {} FalseCopyable(FalseCopyable&& other) : m(std::move(other.m)) {} T m; }; int GetMember(FalseCopyable<std::unique_ptr<int>> x) { return *x.m; } TEST(BindTest, WrappedMoveOnly) { FalseCopyable<std::unique_ptr<int>> x; x.m = absl::make_unique<int>(42); auto f = absl::bind_front(&GetMember, std::move(x)); EXPECT_EQ(42, std::move(f)()); } int Plus(int a, int b) { return a + b; } TEST(BindTest, ConstExpr) { constexpr auto f = absl::bind_front(CharAt); EXPECT_EQ(f("ABC", 1), 'B'); static constexpr int five = 5; constexpr auto plus5 = absl::bind_front(Plus, five); EXPECT_EQ(plus5(1), 6); #if !(defined(_MSC_VER) && _MSC_VER < 1910) static constexpr char data[] = "DEF"; constexpr auto g = absl::bind_front(CharAt, data); EXPECT_EQ(g(1), 'E'); #endif } struct ManglingCall { int operator()(int, double, std::string) const { return 0; } }; TEST(BindTest, Mangling) { absl::bind_front(ManglingCall{}, 1, 3.3)("A"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/bind_front.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/bind_front_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
3bfaca7e-473c-4611-9bd8-d56cace758c3
cpp
abseil/abseil-cpp
function_ref
absl/functional/internal/function_ref.h
absl/functional/function_ref_test.cc
#ifndef ABSL_FUNCTIONAL_INTERNAL_FUNCTION_REF_H_ #define ABSL_FUNCTIONAL_INTERNAL_FUNCTION_REF_H_ #include <cassert> #include <functional> #include <type_traits> #include "absl/base/internal/invoke.h" #include "absl/functional/any_invocable.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace functional_internal { union VoidPtr { const void* obj; void (*fun)(); }; template <typename T, bool IsLValueReference = std::is_lvalue_reference<T>::value> struct PassByValue : std::false_type {}; template <typename T> struct PassByValue<T, false> : std::integral_constant<bool, absl::is_trivially_copy_constructible<T>::value && absl::is_trivially_copy_assignable< typename std::remove_cv<T>::type>::value && std::is_trivially_destructible<T>::value && sizeof(T) <= 2 * sizeof(void*)> {}; template <typename T> struct ForwardT : std::conditional<PassByValue<T>::value, T, T&&> {}; template <typename R, typename... Args> using Invoker = R (*)(VoidPtr, typename ForwardT<Args>::type...); template <typename Obj, typename R, typename... Args> R InvokeObject(VoidPtr ptr, typename ForwardT<Args>::type... args) { auto o = static_cast<const Obj*>(ptr.obj); return static_cast<R>( absl::base_internal::invoke(*o, std::forward<Args>(args)...)); } template <typename Fun, typename R, typename... Args> R InvokeFunction(VoidPtr ptr, typename ForwardT<Args>::type... args) { auto f = reinterpret_cast<Fun>(ptr.fun); return static_cast<R>( absl::base_internal::invoke(f, std::forward<Args>(args)...)); } template <typename Sig> void AssertNonNull(const std::function<Sig>& f) { assert(f != nullptr); (void)f; } template <typename Sig> void AssertNonNull(const AnyInvocable<Sig>& f) { assert(f != nullptr); (void)f; } template <typename F> void AssertNonNull(const F&) {} template <typename F, typename C> void AssertNonNull(F C::*f) { assert(f != nullptr); (void)f; } template <bool C> using EnableIf = typename ::std::enable_if<C, int>::type; } ABSL_NAMESPACE_END } #endif
#include "absl/functional/function_ref.h" #include <functional> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/functional/any_invocable.h" #include "absl/memory/memory.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { void RunFun(FunctionRef<void()> f) { f(); } TEST(FunctionRefTest, Lambda) { bool ran = false; RunFun([&] { ran = true; }); EXPECT_TRUE(ran); } int Function() { return 1337; } TEST(FunctionRefTest, Function1) { FunctionRef<int()> ref(&Function); EXPECT_EQ(1337, ref()); } TEST(FunctionRefTest, Function2) { FunctionRef<int()> ref(Function); EXPECT_EQ(1337, ref()); } TEST(FunctionRefTest, ConstFunction) { FunctionRef<int() const> ref(Function); EXPECT_EQ(1337, ref()); } int NoExceptFunction() noexcept { return 1337; } TEST(FunctionRefTest, NoExceptFunction) { FunctionRef<int()> ref(NoExceptFunction); EXPECT_EQ(1337, ref()); } TEST(FunctionRefTest, ForwardsArgs) { auto l = [](std::unique_ptr<int> i) { return *i; }; FunctionRef<int(std::unique_ptr<int>)> ref(l); EXPECT_EQ(42, ref(absl::make_unique<int>(42))); } TEST(FunctionRef, ReturnMoveOnly) { auto l = [] { return absl::make_unique<int>(29); }; FunctionRef<std::unique_ptr<int>()> ref(l); EXPECT_EQ(29, *ref()); } TEST(FunctionRef, ManyArgs) { auto l = [](int a, int b, int c) { return a + b + c; }; FunctionRef<int(int, int, int)> ref(l); EXPECT_EQ(6, ref(1, 2, 3)); } TEST(FunctionRef, VoidResultFromNonVoidFunctor) { bool ran = false; auto l = [&]() -> int { ran = true; return 2; }; FunctionRef<void()> ref(l); ref(); EXPECT_TRUE(ran); } TEST(FunctionRef, CastFromDerived) { struct Base {}; struct Derived : public Base {}; Derived d; auto l1 = [&](Base* b) { EXPECT_EQ(&d, b); }; FunctionRef<void(Derived*)> ref1(l1); ref1(&d); auto l2 = [&]() -> Derived* { return &d; }; FunctionRef<Base*()> ref2(l2); EXPECT_EQ(&d, ref2()); } TEST(FunctionRef, VoidResultFromNonVoidFuncton) { FunctionRef<void()> ref(Function); ref(); } TEST(FunctionRef, MemberPtr) { struct S { int i; }; S s{1100111}; auto mem_ptr = &S::i; FunctionRef<int(const S& s)> ref(mem_ptr); EXPECT_EQ(1100111, ref(s)); } TEST(FunctionRef, MemberFun) { struct S { int i; int get_i() const { return i; } }; S s{22}; auto mem_fun_ptr = &S::get_i; FunctionRef<int(const S& s)> ref(mem_fun_ptr); EXPECT_EQ(22, ref(s)); } TEST(FunctionRef, MemberFunRefqualified) { struct S { int i; int get_i() && { return i; } }; auto mem_fun_ptr = &S::get_i; S s{22}; FunctionRef<int(S && s)> ref(mem_fun_ptr); EXPECT_EQ(22, ref(std::move(s))); } #if !defined(_WIN32) && defined(GTEST_HAS_DEATH_TEST) TEST(FunctionRef, MemberFunRefqualifiedNull) { struct S { int i; int get_i() && { return i; } }; auto mem_fun_ptr = &S::get_i; mem_fun_ptr = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<int(S && s)> ref(mem_fun_ptr); }, ""); } TEST(FunctionRef, NullMemberPtrAssertFails) { struct S { int i; }; using MemberPtr = int S::*; MemberPtr mem_ptr = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<int(const S& s)> ref(mem_ptr); }, ""); } TEST(FunctionRef, NullStdFunctionAssertPasses) { std::function<void()> function = []() {}; FunctionRef<void()> ref(function); } TEST(FunctionRef, NullStdFunctionAssertFails) { std::function<void()> function = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<void()> ref(function); }, ""); } TEST(FunctionRef, NullAnyInvocableAssertPasses) { AnyInvocable<void() const> invocable = []() {}; FunctionRef<void()> ref(invocable); } TEST(FunctionRef, NullAnyInvocableAssertFails) { AnyInvocable<void() const> invocable = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<void()> ref(invocable); }, ""); } #endif TEST(FunctionRef, CopiesAndMovesPerPassByValue) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](absl::test_internal::CopyableMovableInstance) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(instance); EXPECT_EQ(tracker.copies(), 1); EXPECT_EQ(tracker.moves(), 1); } TEST(FunctionRef, CopiesAndMovesPerPassByRef) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](const absl::test_internal::CopyableMovableInstance&) {}; FunctionRef<void(const absl::test_internal::CopyableMovableInstance&)> ref(l); ref(instance); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 0); } TEST(FunctionRef, CopiesAndMovesPerPassByValueCallByMove) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](absl::test_internal::CopyableMovableInstance) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(std::move(instance)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 2); } TEST(FunctionRef, CopiesAndMovesPerPassByValueToRef) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](const absl::test_internal::CopyableMovableInstance&) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(std::move(instance)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); } TEST(FunctionRef, PassByValueTypes) { using absl::functional_internal::Invoker; using absl::functional_internal::VoidPtr; using absl::test_internal::CopyableMovableInstance; struct Trivial { void* p[2]; }; struct LargeTrivial { void* p[3]; }; static_assert(std::is_same<Invoker<void, int>, void (*)(VoidPtr, int)>::value, "Scalar types should be passed by value"); static_assert( std::is_same<Invoker<void, Trivial>, void (*)(VoidPtr, Trivial)>::value, "Small trivial types should be passed by value"); static_assert(std::is_same<Invoker<void, LargeTrivial>, void (*)(VoidPtr, LargeTrivial &&)>::value, "Large trivial types should be passed by rvalue reference"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance>, void (*)(VoidPtr, CopyableMovableInstance &&)>::value, "Types with copy/move ctor should be passed by rvalue reference"); static_assert( std::is_same<Invoker<void, int&>, void (*)(VoidPtr, int&)>::value, "Reference types should be preserved"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance&>, void (*)(VoidPtr, CopyableMovableInstance&)>::value, "Reference types should be preserved"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance&&>, void (*)(VoidPtr, CopyableMovableInstance &&)>::value, "Reference types should be preserved"); { LargeTrivial obj; auto test = [&obj](LargeTrivial& input) { ASSERT_EQ(&input, &obj); }; absl::FunctionRef<void(LargeTrivial&)> ref(test); ref(obj); } { Trivial obj; auto test = [&obj](Trivial& input) { ASSERT_EQ(&input, &obj); }; absl::FunctionRef<void(Trivial&)> ref(test); ref(obj); } } TEST(FunctionRef, ReferenceToIncompleteType) { struct IncompleteType; auto test = [](IncompleteType&) {}; absl::FunctionRef<void(IncompleteType&)> ref(test); struct IncompleteType {}; IncompleteType obj; ref(obj); } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/internal/function_ref.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/function_ref_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ca383435-df24-445b-95ff-5b14437f8c41
cpp
abseil/abseil-cpp
overload
absl/functional/overload.h
absl/functional/overload_test.cc
#ifndef ABSL_FUNCTIONAL_OVERLOAD_H_ #define ABSL_FUNCTIONAL_OVERLOAD_H_ #include "absl/base/config.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L template <typename... T> struct Overload final : T... { using T::operator()...; constexpr explicit Overload(T... ts) : T(std::move(ts))... {} }; template <typename... T> Overload(T...) -> Overload<T...>; #else namespace functional_internal { template <typename T> constexpr bool kDependentFalse = false; } template <typename Dependent = int, typename... T> auto Overload(T&&...) { static_assert(functional_internal::kDependentFalse<Dependent>, "Overload is only usable with C++17 or above."); } #endif ABSL_NAMESPACE_END } #endif
#include "absl/functional/overload.h" #include <cstdint> #include <string> #include <type_traits> #include "absl/base/config.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L #include "gtest/gtest.h" namespace { TEST(OverloadTest, DispatchConsidersTypeWithAutoFallback) { auto overloaded = absl::Overload{ [](int v) { return absl::StrCat("int ", v); }, [](double v) { return absl::StrCat("double ", v); }, [](const char* v) { return absl::StrCat("const char* ", v); }, [](auto v) { return absl::StrCat("auto ", v); }, }; EXPECT_EQ("int 1", overloaded(1)); EXPECT_EQ("double 2.5", overloaded(2.5)); EXPECT_EQ("const char* hello", overloaded("hello")); EXPECT_EQ("auto 1.5", overloaded(1.5f)); } TEST(OverloadTest, DispatchConsidersNumberOfArguments) { auto overloaded = absl::Overload{ [](int a) { return a + 1; }, [](int a, int b) { return a * b; }, []() -> absl::string_view { return "none"; }, }; EXPECT_EQ(3, overloaded(2)); EXPECT_EQ(21, overloaded(3, 7)); EXPECT_EQ("none", overloaded()); } TEST(OverloadTest, SupportsConstantEvaluation) { auto overloaded = absl::Overload{ [](int a) { return a + 1; }, [](int a, int b) { return a * b; }, []() -> absl::string_view { return "none"; }, }; static_assert(overloaded() == "none"); static_assert(overloaded(2) == 3); static_assert(overloaded(3, 7) == 21); } TEST(OverloadTest, PropogatesDefaults) { auto overloaded = absl::Overload{ [](int a, int b = 5) { return a * b; }, [](double c) { return c; }, }; EXPECT_EQ(21, overloaded(3, 7)); EXPECT_EQ(35, overloaded(7)); EXPECT_EQ(2.5, overloaded(2.5)); } TEST(OverloadTest, AmbiguousWithDefaultsNotInvocable) { auto overloaded = absl::Overload{ [](int a, int b = 5) { return a * b; }, [](int c) { return c; }, }; static_assert(!std::is_invocable_v<decltype(overloaded), int>); static_assert(std::is_invocable_v<decltype(overloaded), int, int>); } TEST(OverloadTest, AmbiguousDuplicatesNotInvocable) { auto overloaded = absl::Overload{ [](int a) { return a; }, [](int c) { return c; }, }; static_assert(!std::is_invocable_v<decltype(overloaded), int>); } TEST(OverloadTest, AmbiguousConversionNotInvocable) { auto overloaded = absl::Overload{ [](uint16_t a) { return a; }, [](uint64_t c) { return c; }, }; static_assert(!std::is_invocable_v<decltype(overloaded), int>); } TEST(OverloadTest, AmbiguousConversionWithAutoNotInvocable) { auto overloaded = absl::Overload{ [](auto a) { return a; }, [](auto c) { return c; }, }; static_assert(!std::is_invocable_v<decltype(overloaded), int>); } #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L TEST(OverloadTest, AmbiguousConversionWithAutoAndTemplateNotInvocable) { auto overloaded = absl::Overload{ [](auto a) { return a; }, []<class T>(T c) { return c; }, }; static_assert(!std::is_invocable_v<decltype(overloaded), int>); } TEST(OverloadTest, DispatchConsidersTypeWithTemplateFallback) { auto overloaded = absl::Overload{ [](int a) { return a; }, []<class T>(T c) { return c * 2; }, }; EXPECT_EQ(7, overloaded(7)); EXPECT_EQ(14.0, overloaded(7.0)); } #endif TEST(OverloadTest, DispatchConsidersSfinae) { auto overloaded = absl::Overload{ [](auto a) -> decltype(a + 1) { return a + 1; }, }; static_assert(std::is_invocable_v<decltype(overloaded), int>); static_assert(!std::is_invocable_v<decltype(overloaded), std::string>); } TEST(OverloadTest, VariantVisitDispatchesCorrectly) { absl::variant<int, double, std::string> v(1); auto overloaded = absl::Overload{ [](int) -> absl::string_view { return "int"; }, [](double) -> absl::string_view { return "double"; }, [](const std::string&) -> absl::string_view { return "string"; }, }; EXPECT_EQ("int", absl::visit(overloaded, v)); v = 1.1; EXPECT_EQ("double", absl::visit(overloaded, v)); v = "hello"; EXPECT_EQ("string", absl::visit(overloaded, v)); } TEST(OverloadTest, VariantVisitWithAutoFallbackDispatchesCorrectly) { absl::variant<std::string, int32_t, int64_t> v(int32_t{1}); auto overloaded = absl::Overload{ [](const std::string& s) { return s.size(); }, [](const auto& s) { return sizeof(s); }, }; EXPECT_EQ(4, absl::visit(overloaded, v)); v = int64_t{1}; EXPECT_EQ(8, absl::visit(overloaded, v)); v = std::string("hello"); EXPECT_EQ(5, absl::visit(overloaded, v)); } TEST(OverloadTest, UseWithParentheses) { const auto overloaded = absl::Overload([](const std::string& s) { return s.size(); }, [](const auto& s) { return sizeof(s); }); absl::variant<std::string, int32_t, int64_t> v(int32_t{1}); EXPECT_EQ(4, absl::visit(overloaded, v)); v = int64_t{1}; EXPECT_EQ(8, absl::visit(overloaded, v)); v = std::string("hello"); EXPECT_EQ(5, absl::visit(overloaded, v)); } TEST(OverloadTest, HasConstexprConstructor) { constexpr auto overloaded = absl::Overload{ [](int v) { return absl::StrCat("int ", v); }, [](double v) { return absl::StrCat("double ", v); }, [](const char* v) { return absl::StrCat("const char* ", v); }, [](auto v) { return absl::StrCat("auto ", v); }, }; EXPECT_EQ("int 1", overloaded(1)); EXPECT_EQ("double 2.5", overloaded(2.5)); EXPECT_EQ("const char* hello", overloaded("hello")); EXPECT_EQ("auto 1.5", overloaded(1.5f)); } } #endif
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/overload.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/overload_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
4640a7a9-8921-4f09-a4bb-3add88d26430
cpp
abseil/abseil-cpp
any_invocable
absl/functional/internal/any_invocable.h
absl/functional/any_invocable_test.cc
#ifndef ABSL_FUNCTIONAL_INTERNAL_ANY_INVOCABLE_H_ #define ABSL_FUNCTIONAL_INTERNAL_ANY_INVOCABLE_H_ #include <cassert> #include <cstddef> #include <cstring> #include <exception> #include <functional> #include <memory> #include <new> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/invoke.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L #define ABSL_INTERNAL_NOEXCEPT_SPEC(noex) noexcept(noex) #else #define ABSL_INTERNAL_NOEXCEPT_SPEC(noex) #endif template <class Sig> class AnyInvocable; namespace internal_any_invocable { enum StorageProperty : std::size_t { kAlignment = alignof(std::max_align_t), kStorageSize = sizeof(void*) * 2 }; template <class T> struct IsAnyInvocable : std::false_type {}; template <class Sig> struct IsAnyInvocable<AnyInvocable<Sig>> : std::true_type {}; template <class T> using IsStoredLocally = std::integral_constant< bool, sizeof(T) <= kStorageSize && alignof(T) <= kAlignment && kAlignment % alignof(T) == 0 && std::is_nothrow_move_constructible<T>::value>; template <class T> using RemoveCVRef = typename std::remove_cv<typename std::remove_reference<T>::type>::type; template <class ReturnType, class F, class... P, typename = absl::enable_if_t<std::is_void<ReturnType>::value>> void InvokeR(F&& f, P&&... args) { absl::base_internal::invoke(std::forward<F>(f), std::forward<P>(args)...); } template <class ReturnType, class F, class... P, absl::enable_if_t<!std::is_void<ReturnType>::value, int> = 0> ReturnType InvokeR(F&& f, P&&... args) { #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif return absl::base_internal::invoke(std::forward<F>(f), std::forward<P>(args)...); #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic pop #endif } template <typename T> T ForwardImpl(std::true_type); template <typename T> T&& ForwardImpl(std::false_type); template <class T> struct ForwardedParameter { using type = decltype(( ForwardImpl<T>)(std::integral_constant<bool, std::is_scalar<T>::value>())); }; template <class T> using ForwardedParameterType = typename ForwardedParameter<T>::type; enum class FunctionToCall : bool { relocate_from_to, dispose }; union TypeErasedState { struct { void* target; std::size_t size; } remote; alignas(kAlignment) char storage[kStorageSize]; }; template <class T> T& ObjectInLocalStorage(TypeErasedState* const state) { #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606L return *std::launder(reinterpret_cast<T*>(&state->storage)); #elif ABSL_HAVE_BUILTIN(__builtin_launder) return *__builtin_launder(reinterpret_cast<T*>(&state->storage)); #else #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif return *reinterpret_cast<T*>(&state->storage); #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic pop #endif #endif } using ManagerType = void(FunctionToCall , TypeErasedState* , TypeErasedState* ) ABSL_INTERNAL_NOEXCEPT_SPEC(true); template <bool SigIsNoexcept, class ReturnType, class... P> using InvokerType = ReturnType(TypeErasedState*, ForwardedParameterType<P>...) ABSL_INTERNAL_NOEXCEPT_SPEC(SigIsNoexcept); inline void EmptyManager(FunctionToCall , TypeErasedState* , TypeErasedState* ) noexcept {} inline void LocalManagerTrivial(FunctionToCall , TypeErasedState* const from, TypeErasedState* const to) noexcept { *to = *from; } template <class T> void LocalManagerNontrivial(FunctionToCall operation, TypeErasedState* const from, TypeErasedState* const to) noexcept { static_assert(IsStoredLocally<T>::value, "Local storage must only be used for supported types."); static_assert(!std::is_trivially_copyable<T>::value, "Locally stored types must be trivially copyable."); T& from_object = (ObjectInLocalStorage<T>)(from); switch (operation) { case FunctionToCall::relocate_from_to: ::new (static_cast<void*>(&to->storage)) T(std::move(from_object)); ABSL_FALLTHROUGH_INTENDED; case FunctionToCall::dispose: from_object.~T(); return; } ABSL_UNREACHABLE(); } template <bool SigIsNoexcept, class ReturnType, class QualTRef, class... P> ReturnType LocalInvoker( TypeErasedState* const state, ForwardedParameterType<P>... args) noexcept(SigIsNoexcept) { using RawT = RemoveCVRef<QualTRef>; static_assert( IsStoredLocally<RawT>::value, "Target object must be in local storage in order to be invoked from it."); auto& f = (ObjectInLocalStorage<RawT>)(state); return (InvokeR<ReturnType>)(static_cast<QualTRef>(f), static_cast<ForwardedParameterType<P>>(args)...); } inline void RemoteManagerTrivial(FunctionToCall operation, TypeErasedState* const from, TypeErasedState* const to) noexcept { switch (operation) { case FunctionToCall::relocate_from_to: to->remote = from->remote; return; case FunctionToCall::dispose: #if defined(__cpp_sized_deallocation) ::operator delete(from->remote.target, from->remote.size); #else ::operator delete(from->remote.target); #endif return; } ABSL_UNREACHABLE(); } template <class T> void RemoteManagerNontrivial(FunctionToCall operation, TypeErasedState* const from, TypeErasedState* const to) noexcept { static_assert(!IsStoredLocally<T>::value, "Remote storage must only be used for types that do not " "qualify for local storage."); switch (operation) { case FunctionToCall::relocate_from_to: to->remote.target = from->remote.target; return; case FunctionToCall::dispose: ::delete static_cast<T*>(from->remote.target); return; } ABSL_UNREACHABLE(); } template <bool SigIsNoexcept, class ReturnType, class QualTRef, class... P> ReturnType RemoteInvoker( TypeErasedState* const state, ForwardedParameterType<P>... args) noexcept(SigIsNoexcept) { using RawT = RemoveCVRef<QualTRef>; static_assert(!IsStoredLocally<RawT>::value, "Target object must be in remote storage in order to be " "invoked from it."); auto& f = *static_cast<RawT*>(state->remote.target); return (InvokeR<ReturnType>)(static_cast<QualTRef>(f), static_cast<ForwardedParameterType<P>>(args)...); } template <class T> struct IsInPlaceType : std::false_type {}; template <class T> struct IsInPlaceType<absl::in_place_type_t<T>> : std::true_type {}; template <class QualDecayedTRef> struct TypedConversionConstruct {}; template <class Sig> class Impl {}; #if defined(__cpp_sized_deallocation) class TrivialDeleter { public: explicit TrivialDeleter(std::size_t size) : size_(size) {} void operator()(void* target) const { ::operator delete(target, size_); } private: std::size_t size_; }; #else class TrivialDeleter { public: explicit TrivialDeleter(std::size_t) {} void operator()(void* target) const { ::operator delete(target); } }; #endif template <bool SigIsNoexcept, class ReturnType, class... P> class CoreImpl; constexpr bool IsCompatibleConversion(void*, void*) { return false; } template <bool NoExceptSrc, bool NoExceptDest, class... T> constexpr bool IsCompatibleConversion(CoreImpl<NoExceptSrc, T...>*, CoreImpl<NoExceptDest, T...>*) { return !NoExceptDest || NoExceptSrc; } template <bool SigIsNoexcept, class ReturnType, class... P> class CoreImpl { public: using result_type = ReturnType; CoreImpl() noexcept : manager_(EmptyManager), invoker_(nullptr) {} enum class TargetType { kPointer, kCompatibleAnyInvocable, kIncompatibleAnyInvocable, kOther, }; template <class QualDecayedTRef, class F> explicit CoreImpl(TypedConversionConstruct<QualDecayedTRef>, F&& f) { using DecayedT = RemoveCVRef<QualDecayedTRef>; constexpr TargetType kTargetType = (std::is_pointer<DecayedT>::value || std::is_member_pointer<DecayedT>::value) ? TargetType::kPointer : IsCompatibleAnyInvocable<DecayedT>::value ? TargetType::kCompatibleAnyInvocable : IsAnyInvocable<DecayedT>::value ? TargetType::kIncompatibleAnyInvocable : TargetType::kOther; Initialize<kTargetType, QualDecayedTRef>(std::forward<F>(f)); } template <class QualTRef, class... Args> explicit CoreImpl(absl::in_place_type_t<QualTRef>, Args&&... args) { InitializeStorage<QualTRef>(std::forward<Args>(args)...); } CoreImpl(CoreImpl&& other) noexcept { other.manager_(FunctionToCall::relocate_from_to, &other.state_, &state_); manager_ = other.manager_; invoker_ = other.invoker_; other.manager_ = EmptyManager; other.invoker_ = nullptr; } CoreImpl& operator=(CoreImpl&& other) noexcept { Clear(); other.manager_(FunctionToCall::relocate_from_to, &other.state_, &state_); manager_ = other.manager_; invoker_ = other.invoker_; other.manager_ = EmptyManager; other.invoker_ = nullptr; return *this; } ~CoreImpl() { manager_(FunctionToCall::dispose, &state_, &state_); } bool HasValue() const { return invoker_ != nullptr; } void Clear() { manager_(FunctionToCall::dispose, &state_, &state_); manager_ = EmptyManager; invoker_ = nullptr; } template <TargetType target_type, class QualDecayedTRef, class F, absl::enable_if_t<target_type == TargetType::kPointer, int> = 0> void Initialize(F&& f) { #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Waddress" #pragma GCC diagnostic ignored "-Wnonnull-compare" #endif if (static_cast<RemoveCVRef<QualDecayedTRef>>(f) == nullptr) { #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic pop #endif manager_ = EmptyManager; invoker_ = nullptr; return; } InitializeStorage<QualDecayedTRef>(std::forward<F>(f)); } template <TargetType target_type, class QualDecayedTRef, class F, absl::enable_if_t< target_type == TargetType::kCompatibleAnyInvocable, int> = 0> void Initialize(F&& f) { f.manager_(FunctionToCall::relocate_from_to, &f.state_, &state_); manager_ = f.manager_; invoker_ = f.invoker_; f.manager_ = EmptyManager; f.invoker_ = nullptr; } template <TargetType target_type, class QualDecayedTRef, class F, absl::enable_if_t< target_type == TargetType::kIncompatibleAnyInvocable, int> = 0> void Initialize(F&& f) { if (f.HasValue()) { InitializeStorage<QualDecayedTRef>(std::forward<F>(f)); } else { manager_ = EmptyManager; invoker_ = nullptr; } } template <TargetType target_type, class QualDecayedTRef, class F, typename = absl::enable_if_t<target_type == TargetType::kOther>> void Initialize(F&& f) { InitializeStorage<QualDecayedTRef>(std::forward<F>(f)); } template <class QualTRef, class... Args, typename = absl::enable_if_t< IsStoredLocally<RemoveCVRef<QualTRef>>::value>> void InitializeStorage(Args&&... args) { using RawT = RemoveCVRef<QualTRef>; ::new (static_cast<void*>(&state_.storage)) RawT(std::forward<Args>(args)...); invoker_ = LocalInvoker<SigIsNoexcept, ReturnType, QualTRef, P...>; InitializeLocalManager<RawT>(); } template <class QualTRef, class... Args, absl::enable_if_t<!IsStoredLocally<RemoveCVRef<QualTRef>>::value, int> = 0> void InitializeStorage(Args&&... args) { InitializeRemoteManager<RemoveCVRef<QualTRef>>(std::forward<Args>(args)...); invoker_ = RemoteInvoker<SigIsNoexcept, ReturnType, QualTRef, P...>; } template <class T, typename = absl::enable_if_t<std::is_trivially_copyable<T>::value>> void InitializeLocalManager() { manager_ = LocalManagerTrivial; } template <class T, absl::enable_if_t<!std::is_trivially_copyable<T>::value, int> = 0> void InitializeLocalManager() { manager_ = LocalManagerNontrivial<T>; } template <class T> using HasTrivialRemoteStorage = std::integral_constant<bool, std::is_trivially_destructible<T>::value && alignof(T) <= ABSL_INTERNAL_DEFAULT_NEW_ALIGNMENT>; template <class T, class... Args, typename = absl::enable_if_t<HasTrivialRemoteStorage<T>::value>> void InitializeRemoteManager(Args&&... args) { std::unique_ptr<void, TrivialDeleter> uninitialized_target( ::operator new(sizeof(T)), TrivialDeleter(sizeof(T))); ::new (uninitialized_target.get()) T(std::forward<Args>(args)...); state_.remote.target = uninitialized_target.release(); state_.remote.size = sizeof(T); manager_ = RemoteManagerTrivial; } template <class T, class... Args, absl::enable_if_t<!HasTrivialRemoteStorage<T>::value, int> = 0> void InitializeRemoteManager(Args&&... args) { state_.remote.target = ::new T(std::forward<Args>(args)...); manager_ = RemoteManagerNontrivial<T>; } template <typename Other> struct IsCompatibleAnyInvocable { static constexpr bool value = false; }; template <typename Sig> struct IsCompatibleAnyInvocable<AnyInvocable<Sig>> { static constexpr bool value = (IsCompatibleConversion)(static_cast< typename AnyInvocable<Sig>::CoreImpl*>( nullptr), static_cast<CoreImpl*>(nullptr)); }; TypeErasedState state_; ManagerType* manager_; InvokerType<SigIsNoexcept, ReturnType, P...>* invoker_; }; struct ConversionConstruct {}; template <class T> struct UnwrapStdReferenceWrapperImpl { using type = T; }; template <class T> struct UnwrapStdReferenceWrapperImpl<std::reference_wrapper<T>> { using type = T&; }; template <class T> using UnwrapStdReferenceWrapper = typename UnwrapStdReferenceWrapperImpl<T>::type; template <class... T> using TrueAlias = std::integral_constant<bool, sizeof(absl::void_t<T...>*) != 0>; template <class Sig, class F, class = absl::enable_if_t< !std::is_same<RemoveCVRef<F>, AnyInvocable<Sig>>::value>> using CanConvert = TrueAlias< absl::enable_if_t<!IsInPlaceType<RemoveCVRef<F>>::value>, absl::enable_if_t<Impl<Sig>::template CallIsValid<F>::value>, absl::enable_if_t< Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept<F>::value>, absl::enable_if_t<std::is_constructible<absl::decay_t<F>, F>::value>>; template <class Sig, class F, class... Args> using CanEmplace = TrueAlias< absl::enable_if_t<Impl<Sig>::template CallIsValid<F>::value>, absl::enable_if_t< Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept<F>::value>, absl::enable_if_t<std::is_constructible<absl::decay_t<F>, Args...>::value>>; template <class Sig, class F, class = absl::enable_if_t< !std::is_same<RemoveCVRef<F>, AnyInvocable<Sig>>::value>> using CanAssign = TrueAlias< absl::enable_if_t<Impl<Sig>::template CallIsValid<F>::value>, absl::enable_if_t< Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept<F>::value>, absl::enable_if_t<std::is_constructible<absl::decay_t<F>, F>::value>>; template <class Sig, class F> using CanAssignReferenceWrapper = TrueAlias< absl::enable_if_t< Impl<Sig>::template CallIsValid<std::reference_wrapper<F>>::value>, absl::enable_if_t<Impl<Sig>::template CallIsNoexceptIfSigIsNoexcept< std::reference_wrapper<F>>::value>>; #define ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT(inv_quals, noex) \ ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_##noex(inv_quals) #define ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_true(inv_quals) \ absl::enable_if_t<absl::disjunction< \ std::is_nothrow_invocable_r< \ ReturnType, UnwrapStdReferenceWrapper<absl::decay_t<F>> inv_quals, \ P...>, \ std::conjunction< \ std::is_nothrow_invocable< \ UnwrapStdReferenceWrapper<absl::decay_t<F>> inv_quals, P...>, \ std::is_same< \ ReturnType, \ absl::base_internal::invoke_result_t< \ UnwrapStdReferenceWrapper<absl::decay_t<F>> inv_quals, \ P...>>>>::value> #define ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_false(inv_quals) #define ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, noex) \ template <class ReturnType, class... P> \ class Impl<ReturnType(P...) cv ref ABSL_INTERNAL_NOEXCEPT_SPEC(noex)> \ : public CoreImpl<noex, ReturnType, P...> { \ public: \ \ using Core = CoreImpl<noex, ReturnType, P...>; \ \ \ template <class F> \ using CallIsValid = TrueAlias<absl::enable_if_t<absl::disjunction< \ absl::base_internal::is_invocable_r<ReturnType, \ absl::decay_t<F> inv_quals, P...>, \ std::is_same<ReturnType, \ absl::base_internal::invoke_result_t< \ absl::decay_t<F> inv_quals, P...>>>::value>>; \ \ \ template <class F> \ using CallIsNoexceptIfSigIsNoexcept = \ TrueAlias<ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT(inv_quals, \ noex)>; \ \ \ Impl() = default; \ \ \ \ \ template <class F> \ explicit Impl(ConversionConstruct, F&& f) \ : Core(TypedConversionConstruct< \ typename std::decay<F>::type inv_quals>(), \ std::forward<F>(f)) {} \ \ \ template <class T, class... Args> \ explicit Impl(absl::in_place_type_t<T>, Args&&... args) \ : Core(absl::in_place_type<absl::decay_t<T> inv_quals>, \ std::forward<Args>(args)...) {} \ \ \ static ReturnType InvokedAfterMove( \ TypeErasedState*, \ ForwardedParameterType<P>...) noexcept(noex) { \ ABSL_HARDENING_ASSERT(false && "AnyInvocable use-after-move"); \ std::terminate(); \ } \ \ InvokerType<noex, ReturnType, P...>* ExtractInvoker() cv { \ using QualifiedTestType = int cv ref; \ auto* invoker = this->invoker_; \ if (!std::is_const<QualifiedTestType>::value && \ std::is_rvalue_reference<QualifiedTestType>::value) { \ ABSL_ASSERT([this]() { \ \ const_cast<Impl*>(this)->invoker_ = InvokedAfterMove; \ return this->HasValue(); \ }()); \ } \ return invoker; \ } \ \ \ ReturnType operator()(P... args) cv ref noexcept(noex) { \ assert(this->invoker_ != nullptr); \ return this->ExtractInvoker()( \ const_cast<TypeErasedState*>(&this->state_), \ static_cast<ForwardedParameterType<P>>(args)...); \ } \ } #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L #define ABSL_INTERNAL_ANY_INVOCABLE_IMPL(cv, ref, inv_quals) \ ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, false); \ ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, true) #else #define ABSL_INTERNAL_ANY_INVOCABLE_IMPL(cv, ref, inv_quals) \ ABSL_INTERNAL_ANY_INVOCABLE_IMPL_(cv, ref, inv_quals, false) #endif ABSL_INTERNAL_ANY_INVOCABLE_IMPL(, , &); ABSL_INTERNAL_ANY_INVOCABLE_IMPL(const, , const&); ABSL_INTERNAL_ANY_INVOCABLE_IMPL(, &, &); ABSL_INTERNAL_ANY_INVOCABLE_IMPL(const, &, const&); ABSL_INTERNAL_ANY_INVOCABLE_IMPL(, &&, &&); ABSL_INTERNAL_ANY_INVOCABLE_IMPL(const, &&, const&&); #undef ABSL_INTERNAL_ANY_INVOCABLE_IMPL #undef ABSL_INTERNAL_ANY_INVOCABLE_IMPL_ #undef ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_false #undef ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT_true #undef ABSL_INTERNAL_ANY_INVOCABLE_NOEXCEPT_CONSTRAINT #undef ABSL_INTERNAL_NOEXCEPT_SPEC } ABSL_NAMESPACE_END } #endif
#include "absl/functional/any_invocable.h" #include <cstddef> #include <initializer_list> #include <memory> #include <numeric> #include <type_traits> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" static_assert(absl::internal_any_invocable::kStorageSize >= sizeof(void*), "These tests assume that the small object storage is at least " "the size of a pointer."); namespace { #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L #define ABSL_INTERNAL_NOEXCEPT_SPEC(noex) noexcept(noex) #else #define ABSL_INTERNAL_NOEXCEPT_SPEC(noex) #endif struct _ {}; template <class T> struct Wrapper { template <class U, class = absl::enable_if_t<std::is_convertible<U, T>::value>> Wrapper(U&&); }; static_assert(std::is_constructible<Wrapper<absl::AnyInvocable<void()>>, Wrapper<absl::AnyInvocable<void()>>>::value, ""); template <class Qualifiers, class This> struct QualifiersForThisImpl { static_assert(std::is_object<This>::value, ""); using type = absl::conditional_t<std::is_const<Qualifiers>::value, const This, This>&; }; template <class Qualifiers, class This> struct QualifiersForThisImpl<Qualifiers&, This> : QualifiersForThisImpl<Qualifiers, This> {}; template <class Qualifiers, class This> struct QualifiersForThisImpl<Qualifiers&&, This> { static_assert(std::is_object<This>::value, ""); using type = absl::conditional_t<std::is_const<Qualifiers>::value, const This, This>&&; }; template <class Qualifiers, class This> using QualifiersForThis = typename QualifiersForThisImpl<Qualifiers, This>::type; template <class T, class Fun> struct GiveQualifiersToFunImpl; template <class T, class R, class... P> struct GiveQualifiersToFunImpl<T, R(P...)> { using type = absl::conditional_t<std::is_const<T>::value, R(P...) const, R(P...)>; }; template <class T, class R, class... P> struct GiveQualifiersToFunImpl<T&, R(P...)> { using type = absl::conditional_t<std::is_const<T>::value, R(P...) const&, R(P...)&>; }; template <class T, class R, class... P> struct GiveQualifiersToFunImpl<T&&, R(P...)> { using type = absl::conditional_t<std::is_const<T>::value, R(P...) const&&, R(P...) &&>; }; #if defined(__cpp_noexcept_function_type) template <class T, class R, class... P> struct GiveQualifiersToFunImpl<T, R(P...) noexcept> { using type = absl::conditional_t<std::is_const<T>::value, R(P...) const noexcept, R(P...) noexcept>; }; template <class T, class R, class... P> struct GiveQualifiersToFunImpl<T&, R(P...) noexcept> { using type = absl::conditional_t<std::is_const<T>::value, R(P...) const & noexcept, R(P...) & noexcept>; }; template <class T, class R, class... P> struct GiveQualifiersToFunImpl<T&&, R(P...) noexcept> { using type = absl::conditional_t<std::is_const<T>::value, R(P...) const && noexcept, R(P...) && noexcept>; }; #endif template <class T, class Fun> using GiveQualifiersToFun = typename GiveQualifiersToFunImpl<T, Fun>::type; enum class ObjSize { small, large }; template <ObjSize Size> struct TypeErasedPadding; template <> struct TypeErasedPadding<ObjSize::small> {}; template <> struct TypeErasedPadding<ObjSize::large> { char dummy_data[absl::internal_any_invocable::kStorageSize + 1] = {}; }; struct Int { Int(int v) noexcept : value(v) {} #ifndef _MSC_VER Int(Int&&) noexcept { std::abort(); } #else Int(Int&& v) noexcept = default; #endif operator int() && noexcept { return value; } int MemberFunctionAdd(int const& b, int c) noexcept { return value + b + c; } int value; }; enum class Movable { no, yes, nothrow, trivial }; enum class NothrowCall { no, yes }; enum class Destructible { nothrow, trivial }; enum class ObjAlign : std::size_t { normal = absl::internal_any_invocable::kAlignment, large = absl::internal_any_invocable::kAlignment * 2, }; template <Movable Movability, Destructible Destructibility, class Qual, NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Alignment> struct add; #define ABSL_INTERNALS_ADD(qual) \ template <NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Alignment> \ struct alignas(static_cast<std::size_t>(Alignment)) \ add<Movable::trivial, Destructible::trivial, _ qual, CallExceptionSpec, \ Size, Alignment> : TypeErasedPadding<Size> { \ explicit add(int state_init) : state(state_init) {} \ explicit add(std::initializer_list<int> state_init, int tail) \ : state(std::accumulate(std::begin(state_init), std::end(state_init), \ 0) + \ tail) {} \ add(add&& other) = default; \ Int operator()(int a, int b, int c) qual \ ABSL_INTERNAL_NOEXCEPT_SPEC(CallExceptionSpec == NothrowCall::yes) { \ return state + a + b + c; \ } \ int state; \ }; \ \ template <NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Alignment> \ struct alignas(static_cast<std::size_t>(Alignment)) \ add<Movable::trivial, Destructible::nothrow, _ qual, CallExceptionSpec, \ Size, Alignment> : TypeErasedPadding<Size> { \ explicit add(int state_init) : state(state_init) {} \ explicit add(std::initializer_list<int> state_init, int tail) \ : state(std::accumulate(std::begin(state_init), std::end(state_init), \ 0) + \ tail) {} \ ~add() noexcept {} \ add(add&& other) = default; \ Int operator()(int a, int b, int c) qual \ ABSL_INTERNAL_NOEXCEPT_SPEC(CallExceptionSpec == NothrowCall::yes) { \ return state + a + b + c; \ } \ int state; \ } #define ABSL_INTERNALS_NOARG ABSL_INTERNALS_ADD(ABSL_INTERNALS_NOARG); #undef ABSL_INTERNALS_NOARG ABSL_INTERNALS_ADD(const); ABSL_INTERNALS_ADD(&); ABSL_INTERNALS_ADD(const&); ABSL_INTERNALS_ADD(&&); ABSL_INTERNALS_ADD(const&&); #undef ABSL_INTERNALS_ADD template <Destructible Destructibility, class Qual, NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Alignment> struct add<Movable::no, Destructibility, Qual, CallExceptionSpec, Size, Alignment> : private add<Movable::trivial, Destructibility, Qual, CallExceptionSpec, Size, Alignment> { using Base = add<Movable::trivial, Destructibility, Qual, CallExceptionSpec, Size, Alignment>; explicit add(int state_init) : Base(state_init) {} explicit add(std::initializer_list<int> state_init, int tail) : Base(state_init, tail) {} add(add&&) = delete; using Base::operator(); using Base::state; }; template <Destructible Destructibility, class Qual, NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Alignment> struct add<Movable::yes, Destructibility, Qual, CallExceptionSpec, Size, Alignment> : private add<Movable::trivial, Destructibility, Qual, CallExceptionSpec, Size, Alignment> { using Base = add<Movable::trivial, Destructibility, Qual, CallExceptionSpec, Size, Alignment>; explicit add(int state_init) : Base(state_init) {} explicit add(std::initializer_list<int> state_init, int tail) : Base(state_init, tail) {} add(add&& other) noexcept(false) : Base(other.state) {} using Base::operator(); using Base::state; }; template <Destructible Destructibility, class Qual, NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Alignment> struct add<Movable::nothrow, Destructibility, Qual, CallExceptionSpec, Size, Alignment> : private add<Movable::trivial, Destructibility, Qual, CallExceptionSpec, Size, Alignment> { using Base = add<Movable::trivial, Destructibility, Qual, CallExceptionSpec, Size, Alignment>; explicit add(int state_init) : Base(state_init) {} explicit add(std::initializer_list<int> state_init, int tail) : Base(state_init, tail) {} add(add&& other) noexcept : Base(other.state) {} using Base::operator(); using Base::state; }; Int add_function(Int&& a, int b, int c) noexcept { return a.value + b + c; } Int mult_function(Int&& a, int b, int c) noexcept { return a.value * b * c; } Int square_function(Int const&& a) noexcept { return a.value * a.value; } template <class Sig> using AnyInvocable = absl::AnyInvocable<Sig>; template <Movable Movability, Destructible Destructibility, class Qual, NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Alignment> struct TestParams { static constexpr Movable kMovability = Movability; static constexpr Destructible kDestructibility = Destructibility; using Qualifiers = Qual; static constexpr NothrowCall kCallExceptionSpec = CallExceptionSpec; static constexpr bool kIsNoexcept = kCallExceptionSpec == NothrowCall::yes; static constexpr bool kIsRvalueQualified = std::is_rvalue_reference<Qual>::value; static constexpr ObjSize kSize = Size; static constexpr ObjAlign kAlignment = Alignment; using UnqualifiedUnaryFunType = int(Int const&&) ABSL_INTERNAL_NOEXCEPT_SPEC(CallExceptionSpec == NothrowCall::yes); using UnaryFunType = GiveQualifiersToFun<Qualifiers, UnqualifiedUnaryFunType>; using MemObjPtrType = int(Int::*); using UnaryAnyInvType = AnyInvocable<UnaryFunType>; using UnaryThisParamType = QualifiersForThis<Qualifiers, UnaryAnyInvType>; template <class T> static UnaryThisParamType ToUnaryThisParam(T&& fun) { return static_cast<UnaryThisParamType>(fun); } using ResultType = Int; using AnyInvocableFunTypeNotNoexcept = Int(Int, const int&, int); using UnqualifiedFunType = typename std::conditional<kIsNoexcept, Int(Int, const int&, int) noexcept, Int(Int, const int&, int)>::type; using FunType = GiveQualifiersToFun<Qualifiers, UnqualifiedFunType>; using MemFunPtrType = typename std::conditional<kIsNoexcept, Int (Int::*)(const int&, int) noexcept, Int (Int::*)(const int&, int)>::type; using AnyInvType = AnyInvocable<FunType>; using AddType = add<kMovability, kDestructibility, Qualifiers, kCallExceptionSpec, kSize, kAlignment>; using ThisParamType = QualifiersForThis<Qualifiers, AnyInvType>; template <class T> static ThisParamType ToThisParam(T&& fun) { return static_cast<ThisParamType>(fun); } using UnqualifiedVoidFunType = typename std::conditional<kIsNoexcept, void(Int, const int&, int) noexcept, void(Int, const int&, int)>::type; using VoidFunType = GiveQualifiersToFun<Qualifiers, UnqualifiedVoidFunType>; using VoidAnyInvType = AnyInvocable<VoidFunType>; using VoidThisParamType = QualifiersForThis<Qualifiers, VoidAnyInvType>; template <class T> static VoidThisParamType ToVoidThisParam(T&& fun) { return static_cast<VoidThisParamType>(fun); } using CompatibleAnyInvocableFunType = absl::conditional_t<std::is_rvalue_reference<Qual>::value, GiveQualifiersToFun<const _&&, UnqualifiedFunType>, GiveQualifiersToFun<const _&, UnqualifiedFunType>>; using CompatibleAnyInvType = AnyInvocable<CompatibleAnyInvocableFunType>; using IncompatibleInvocable = absl::conditional_t<std::is_rvalue_reference<Qual>::value, GiveQualifiersToFun<_&, UnqualifiedFunType>(_::*), GiveQualifiersToFun<_&&, UnqualifiedFunType>(_::*)>; }; template <class MemberPtrType> struct MemberTypeOfImpl; template <class Class, class T> struct MemberTypeOfImpl<T(Class::*)> { using type = T; }; template <class MemberPtrType> using MemberTypeOf = typename MemberTypeOfImpl<MemberPtrType>::type; template <class T, class = void> struct IsMemberSwappableImpl : std::false_type { static constexpr bool kIsNothrow = false; }; template <class T> struct IsMemberSwappableImpl< T, absl::void_t<decltype(std::declval<T&>().swap(std::declval<T&>()))>> : std::true_type { static constexpr bool kIsNothrow = noexcept(std::declval<T&>().swap(std::declval<T&>())); }; template <class T> using IsMemberSwappable = IsMemberSwappableImpl<T>; template <class T> using IsNothrowMemberSwappable = std::integral_constant<bool, IsMemberSwappableImpl<T>::kIsNothrow>; template <class T> class AnyInvTestBasic : public ::testing::Test {}; TYPED_TEST_SUITE_P(AnyInvTestBasic); TYPED_TEST_P(AnyInvTestBasic, DefaultConstruction) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun; EXPECT_FALSE(static_cast<bool>(fun)); EXPECT_TRUE(std::is_nothrow_default_constructible<AnyInvType>::value); } TYPED_TEST_P(AnyInvTestBasic, ConstructionNullptr) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun = nullptr; EXPECT_FALSE(static_cast<bool>(fun)); EXPECT_TRUE( (std::is_nothrow_constructible<AnyInvType, std::nullptr_t>::value)); } TYPED_TEST_P(AnyInvTestBasic, ConstructionNullFunctionPtr) { using AnyInvType = typename TypeParam::AnyInvType; using UnqualifiedFunType = typename TypeParam::UnqualifiedFunType; UnqualifiedFunType* const null_fun_ptr = nullptr; AnyInvType fun = null_fun_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, ConstructionNullMemberFunctionPtr) { using AnyInvType = typename TypeParam::AnyInvType; using MemFunPtrType = typename TypeParam::MemFunPtrType; const MemFunPtrType null_mem_fun_ptr = nullptr; AnyInvType fun = null_mem_fun_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, ConstructionNullMemberObjectPtr) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; using MemObjPtrType = typename TypeParam::MemObjPtrType; const MemObjPtrType null_mem_obj_ptr = nullptr; UnaryAnyInvType fun = null_mem_obj_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, ConstructionMemberFunctionPtr) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun = &Int::MemberFunctionAdd; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestBasic, ConstructionMemberObjectPtr) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; UnaryAnyInvType fun = &Int::value; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(13, TypeParam::ToUnaryThisParam(fun)(13)); } TYPED_TEST_P(AnyInvTestBasic, ConstructionFunctionReferenceDecay) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun = add_function; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestBasic, ConstructionCompatibleAnyInvocableEmpty) { using AnyInvType = typename TypeParam::AnyInvType; using CompatibleAnyInvType = typename TypeParam::CompatibleAnyInvType; CompatibleAnyInvType other; AnyInvType fun = std::move(other); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_EQ(other, nullptr); EXPECT_EQ(nullptr, other); EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, ConstructionCompatibleAnyInvocableNonempty) { using AnyInvType = typename TypeParam::AnyInvType; using CompatibleAnyInvType = typename TypeParam::CompatibleAnyInvType; CompatibleAnyInvType other = &add_function; AnyInvType fun = std::move(other); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_EQ(other, nullptr); EXPECT_EQ(nullptr, other); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestBasic, ConversionToBool) { using AnyInvType = typename TypeParam::AnyInvType; { AnyInvType fun; EXPECT_FALSE(fun ? true : false); EXPECT_TRUE( (std::is_nothrow_constructible<bool, const AnyInvType&>::value)); EXPECT_FALSE((std::is_convertible<const AnyInvType&, bool>::value)); } { AnyInvType fun = &add_function; EXPECT_TRUE(fun ? true : false); } } TYPED_TEST_P(AnyInvTestBasic, Invocation) { using AnyInvType = typename TypeParam::AnyInvType; using FunType = typename TypeParam::FunType; using AnyInvCallType = MemberTypeOf<decltype(&AnyInvType::operator())>; EXPECT_TRUE((std::is_same<AnyInvCallType, FunType>::value)); AnyInvType fun = &add_function; EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestBasic, InPlaceConstruction) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType fun(absl::in_place_type<AddType>, 5); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestBasic, InPlaceConstructionInitializerList) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType fun(absl::in_place_type<AddType>, {1, 2, 3, 4}, 5); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(39, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestBasic, InPlaceNullFunPtrConstruction) { using AnyInvType = typename TypeParam::AnyInvType; using UnqualifiedFunType = typename TypeParam::UnqualifiedFunType; AnyInvType fun(absl::in_place_type<UnqualifiedFunType*>, nullptr); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, InPlaceNullFunPtrConstructionValueInit) { using AnyInvType = typename TypeParam::AnyInvType; using UnqualifiedFunType = typename TypeParam::UnqualifiedFunType; AnyInvType fun(absl::in_place_type<UnqualifiedFunType*>); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, InPlaceNullMemFunPtrConstruction) { using AnyInvType = typename TypeParam::AnyInvType; using MemFunPtrType = typename TypeParam::MemFunPtrType; AnyInvType fun(absl::in_place_type<MemFunPtrType>, nullptr); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, InPlaceNullMemFunPtrConstructionValueInit) { using AnyInvType = typename TypeParam::AnyInvType; using MemFunPtrType = typename TypeParam::MemFunPtrType; AnyInvType fun(absl::in_place_type<MemFunPtrType>); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, InPlaceNullMemObjPtrConstruction) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; using MemObjPtrType = typename TypeParam::MemObjPtrType; UnaryAnyInvType fun(absl::in_place_type<MemObjPtrType>, nullptr); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, InPlaceNullMemObjPtrConstructionValueInit) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; using MemObjPtrType = typename TypeParam::MemObjPtrType; UnaryAnyInvType fun(absl::in_place_type<MemObjPtrType>); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, InPlaceVoidCovarianceConstruction) { using VoidAnyInvType = typename TypeParam::VoidAnyInvType; using AddType = typename TypeParam::AddType; VoidAnyInvType fun(absl::in_place_type<AddType>, 5); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestBasic, MoveConstructionFromEmpty) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType source_fun; AnyInvType fun(std::move(source_fun)); EXPECT_FALSE(static_cast<bool>(fun)); EXPECT_TRUE(std::is_nothrow_move_constructible<AnyInvType>::value); } TYPED_TEST_P(AnyInvTestBasic, MoveConstructionFromNonEmpty) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType source_fun(absl::in_place_type<AddType>, 5); AnyInvType fun(std::move(source_fun)); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_TRUE(std::is_nothrow_move_constructible<AnyInvType>::value); } TYPED_TEST_P(AnyInvTestBasic, ComparisonWithNullptrEmpty) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun; EXPECT_TRUE(fun == nullptr); EXPECT_TRUE(nullptr == fun); EXPECT_FALSE(fun != nullptr); EXPECT_FALSE(nullptr != fun); } TYPED_TEST_P(AnyInvTestBasic, ComparisonWithNullptrNonempty) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType fun(absl::in_place_type<AddType>, 5); EXPECT_FALSE(fun == nullptr); EXPECT_FALSE(nullptr == fun); EXPECT_TRUE(fun != nullptr); EXPECT_TRUE(nullptr != fun); } TYPED_TEST_P(AnyInvTestBasic, ResultType) { using AnyInvType = typename TypeParam::AnyInvType; using ExpectedResultType = typename TypeParam::ResultType; EXPECT_TRUE((std::is_same<typename AnyInvType::result_type, ExpectedResultType>::value)); } template <class T> class AnyInvTestCombinatoric : public ::testing::Test {}; TYPED_TEST_SUITE_P(AnyInvTestCombinatoric); TYPED_TEST_P(AnyInvTestCombinatoric, MoveAssignEmptyEmptyLhsRhs) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType source_fun; AnyInvType fun; fun = std::move(source_fun); EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, MoveAssignEmptyLhsNonemptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType source_fun(absl::in_place_type<AddType>, 5); AnyInvType fun; fun = std::move(source_fun); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, MoveAssignNonemptyEmptyLhsRhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType source_fun; AnyInvType fun(absl::in_place_type<AddType>, 5); fun = std::move(source_fun); EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, MoveAssignNonemptyLhsNonemptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType source_fun(absl::in_place_type<AddType>, 5); AnyInvType fun(absl::in_place_type<AddType>, 20); fun = std::move(source_fun); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, SelfMoveAssignEmpty) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType source_fun; source_fun = std::move(source_fun); } TYPED_TEST_P(AnyInvTestCombinatoric, SelfMoveAssignNonempty) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType source_fun(absl::in_place_type<AddType>, 5); source_fun = std::move(source_fun); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullptrEmptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun; fun = nullptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullFunctionPtrEmptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using UnqualifiedFunType = typename TypeParam::UnqualifiedFunType; UnqualifiedFunType* const null_fun_ptr = nullptr; AnyInvType fun; fun = null_fun_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullMemberFunctionPtrEmptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using MemFunPtrType = typename TypeParam::MemFunPtrType; const MemFunPtrType null_mem_fun_ptr = nullptr; AnyInvType fun; fun = null_mem_fun_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullMemberObjectPtrEmptyLhs) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; using MemObjPtrType = typename TypeParam::MemObjPtrType; const MemObjPtrType null_mem_obj_ptr = nullptr; UnaryAnyInvType fun; fun = null_mem_obj_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignMemberFunctionPtrEmptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun; fun = &Int::MemberFunctionAdd; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignMemberObjectPtrEmptyLhs) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; UnaryAnyInvType fun; fun = &Int::value; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(13, TypeParam::ToUnaryThisParam(fun)(13)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignFunctionReferenceDecayEmptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun; fun = add_function; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignCompatibleAnyInvocableEmptyLhsEmptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using CompatibleAnyInvType = typename TypeParam::CompatibleAnyInvType; CompatibleAnyInvType other; AnyInvType fun; fun = std::move(other); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_EQ(other, nullptr); EXPECT_EQ(nullptr, other); EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignCompatibleAnyInvocableEmptyLhsNonemptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using CompatibleAnyInvType = typename TypeParam::CompatibleAnyInvType; CompatibleAnyInvType other = &add_function; AnyInvType fun; fun = std::move(other); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullptrNonemptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun = &mult_function; fun = nullptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullFunctionPtrNonemptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using UnqualifiedFunType = typename TypeParam::UnqualifiedFunType; UnqualifiedFunType* const null_fun_ptr = nullptr; AnyInvType fun = &mult_function; fun = null_fun_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullMemberFunctionPtrNonemptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using MemFunPtrType = typename TypeParam::MemFunPtrType; const MemFunPtrType null_mem_fun_ptr = nullptr; AnyInvType fun = &mult_function; fun = null_mem_fun_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignNullMemberObjectPtrNonemptyLhs) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; using MemObjPtrType = typename TypeParam::MemObjPtrType; const MemObjPtrType null_mem_obj_ptr = nullptr; UnaryAnyInvType fun = &square_function; fun = null_mem_obj_ptr; EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignMemberFunctionPtrNonemptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun = &mult_function; fun = &Int::MemberFunctionAdd; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignMemberObjectPtrNonemptyLhs) { using UnaryAnyInvType = typename TypeParam::UnaryAnyInvType; UnaryAnyInvType fun = &square_function; fun = &Int::value; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(13, TypeParam::ToUnaryThisParam(fun)(13)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignFunctionReferenceDecayNonemptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; AnyInvType fun = &mult_function; fun = add_function; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignCompatibleAnyInvocableNonemptyLhsEmptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using CompatibleAnyInvType = typename TypeParam::CompatibleAnyInvType; CompatibleAnyInvType other; AnyInvType fun = &mult_function; fun = std::move(other); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_EQ(other, nullptr); EXPECT_EQ(nullptr, other); EXPECT_FALSE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestCombinatoric, AssignCompatibleAnyInvocableNonemptyLhsNonemptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using CompatibleAnyInvType = typename TypeParam::CompatibleAnyInvType; CompatibleAnyInvType other = &add_function; AnyInvType fun = &mult_function; fun = std::move(other); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(24, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestCombinatoric, SwapEmptyLhsEmptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; { AnyInvType fun; AnyInvType other; using std::swap; swap(fun, other); EXPECT_FALSE(static_cast<bool>(fun)); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_TRUE( absl::type_traits_internal::IsNothrowSwappable<AnyInvType>::value); } { AnyInvType fun; AnyInvType other; fun.swap(other); EXPECT_FALSE(static_cast<bool>(fun)); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_TRUE(IsNothrowMemberSwappable<AnyInvType>::value); } } TYPED_TEST_P(AnyInvTestCombinatoric, SwapEmptyLhsNonemptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; { AnyInvType fun; AnyInvType other(absl::in_place_type<AddType>, 5); using std::swap; swap(fun, other); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_TRUE( absl::type_traits_internal::IsNothrowSwappable<AnyInvType>::value); } { AnyInvType fun; AnyInvType other(absl::in_place_type<AddType>, 5); fun.swap(other); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_FALSE(static_cast<bool>(other)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_TRUE(IsNothrowMemberSwappable<AnyInvType>::value); } } TYPED_TEST_P(AnyInvTestCombinatoric, SwapNonemptyLhsEmptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; { AnyInvType fun(absl::in_place_type<AddType>, 5); AnyInvType other; using std::swap; swap(fun, other); EXPECT_FALSE(static_cast<bool>(fun)); EXPECT_TRUE(static_cast<bool>(other)); EXPECT_EQ(29, TypeParam::ToThisParam(other)(7, 8, 9).value); EXPECT_TRUE( absl::type_traits_internal::IsNothrowSwappable<AnyInvType>::value); } { AnyInvType fun(absl::in_place_type<AddType>, 5); AnyInvType other; fun.swap(other); EXPECT_FALSE(static_cast<bool>(fun)); EXPECT_TRUE(static_cast<bool>(other)); EXPECT_EQ(29, TypeParam::ToThisParam(other)(7, 8, 9).value); EXPECT_TRUE(IsNothrowMemberSwappable<AnyInvType>::value); } } TYPED_TEST_P(AnyInvTestCombinatoric, SwapNonemptyLhsNonemptyRhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; { AnyInvType fun(absl::in_place_type<AddType>, 5); AnyInvType other(absl::in_place_type<AddType>, 6); using std::swap; swap(fun, other); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_TRUE(static_cast<bool>(other)); EXPECT_EQ(30, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_EQ(29, TypeParam::ToThisParam(other)(7, 8, 9).value); EXPECT_TRUE( absl::type_traits_internal::IsNothrowSwappable<AnyInvType>::value); } { AnyInvType fun(absl::in_place_type<AddType>, 5); AnyInvType other(absl::in_place_type<AddType>, 6); fun.swap(other); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_TRUE(static_cast<bool>(other)); EXPECT_EQ(30, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_EQ(29, TypeParam::ToThisParam(other)(7, 8, 9).value); EXPECT_TRUE(IsNothrowMemberSwappable<AnyInvType>::value); } } template <class T> class AnyInvTestMovable : public ::testing::Test {}; TYPED_TEST_SUITE_P(AnyInvTestMovable); TYPED_TEST_P(AnyInvTestMovable, ConversionConstructionUserDefinedType) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType fun(AddType(5)); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestMovable, ConversionConstructionVoidCovariance) { using VoidAnyInvType = typename TypeParam::VoidAnyInvType; using AddType = typename TypeParam::AddType; VoidAnyInvType fun(AddType(5)); EXPECT_TRUE(static_cast<bool>(fun)); } TYPED_TEST_P(AnyInvTestMovable, ConversionAssignUserDefinedTypeEmptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType fun; fun = AddType(5); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestMovable, ConversionAssignUserDefinedTypeNonemptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType fun = &add_function; fun = AddType(5); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); } TYPED_TEST_P(AnyInvTestMovable, ConversionAssignVoidCovariance) { using VoidAnyInvType = typename TypeParam::VoidAnyInvType; using AddType = typename TypeParam::AddType; VoidAnyInvType fun; fun = AddType(5); EXPECT_TRUE(static_cast<bool>(fun)); } template <class T> class AnyInvTestNoexceptFalse : public ::testing::Test {}; TYPED_TEST_SUITE_P(AnyInvTestNoexceptFalse); TYPED_TEST_P(AnyInvTestNoexceptFalse, ConversionConstructionConstraints) { using AnyInvType = typename TypeParam::AnyInvType; EXPECT_TRUE((std::is_constructible< AnyInvType, typename TypeParam::AnyInvocableFunTypeNotNoexcept*>::value)); EXPECT_FALSE(( std::is_constructible<AnyInvType, typename TypeParam::IncompatibleInvocable>::value)); } TYPED_TEST_P(AnyInvTestNoexceptFalse, ConversionAssignConstraints) { using AnyInvType = typename TypeParam::AnyInvType; EXPECT_TRUE((std::is_assignable< AnyInvType&, typename TypeParam::AnyInvocableFunTypeNotNoexcept*>::value)); EXPECT_FALSE( (std::is_assignable<AnyInvType&, typename TypeParam::IncompatibleInvocable>::value)); } template <class T> class AnyInvTestNoexceptTrue : public ::testing::Test {}; TYPED_TEST_SUITE_P(AnyInvTestNoexceptTrue); TYPED_TEST_P(AnyInvTestNoexceptTrue, ConversionConstructionConstraints) { #if ABSL_INTERNAL_CPLUSPLUS_LANG < 201703L GTEST_SKIP() << "Noexcept was not part of the type system before C++17."; #else using AnyInvType = typename TypeParam::AnyInvType; EXPECT_FALSE((std::is_constructible< AnyInvType, typename TypeParam::AnyInvocableFunTypeNotNoexcept*>::value)); EXPECT_FALSE(( std::is_constructible<AnyInvType, typename TypeParam::IncompatibleInvocable>::value)); #endif } TYPED_TEST_P(AnyInvTestNoexceptTrue, ConversionAssignConstraints) { #if ABSL_INTERNAL_CPLUSPLUS_LANG < 201703L GTEST_SKIP() << "Noexcept was not part of the type system before C++17."; #else using AnyInvType = typename TypeParam::AnyInvType; EXPECT_FALSE((std::is_assignable< AnyInvType&, typename TypeParam::AnyInvocableFunTypeNotNoexcept*>::value)); EXPECT_FALSE( (std::is_assignable<AnyInvType&, typename TypeParam::IncompatibleInvocable>::value)); #endif } template <class T> class AnyInvTestNonRvalue : public ::testing::Test {}; TYPED_TEST_SUITE_P(AnyInvTestNonRvalue); TYPED_TEST_P(AnyInvTestNonRvalue, ConversionConstructionReferenceWrapper) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AddType add(4); AnyInvType fun = std::ref(add); add.state = 5; EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(38, TypeParam::ToThisParam(fun)(10, 11, 12).value); } TYPED_TEST_P(AnyInvTestNonRvalue, NonMoveableResultType) { #if ABSL_INTERNAL_CPLUSPLUS_LANG < 201703L GTEST_SKIP() << "Copy/move elision was not standard before C++17"; #else struct Result { int x; explicit Result(const int x_in) : x(x_in) {} Result(Result&&) = delete; }; static_assert(!std::is_move_constructible<Result>::value, ""); static_assert(!std::is_copy_constructible<Result>::value, ""); const auto return_17 = []() noexcept { return Result(17); }; EXPECT_EQ(17, return_17().x); using UnqualifiedFun = absl::conditional_t<TypeParam::kIsNoexcept, Result() noexcept, Result()>; using Fun = GiveQualifiersToFun<typename TypeParam::Qualifiers, UnqualifiedFun>; AnyInvocable<Fun> any_inv(return_17); EXPECT_EQ(17, any_inv().x); #endif } TYPED_TEST_P(AnyInvTestNonRvalue, ConversionAssignReferenceWrapperEmptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AddType add(4); AnyInvType fun; fun = std::ref(add); add.state = 5; EXPECT_TRUE( (std::is_nothrow_assignable<AnyInvType&, std::reference_wrapper<AddType>>::value)); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(38, TypeParam::ToThisParam(fun)(10, 11, 12).value); } TYPED_TEST_P(AnyInvTestNonRvalue, ConversionAssignReferenceWrapperNonemptyLhs) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AddType add(4); AnyInvType fun = &mult_function; fun = std::ref(add); add.state = 5; EXPECT_TRUE( (std::is_nothrow_assignable<AnyInvType&, std::reference_wrapper<AddType>>::value)); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(29, TypeParam::ToThisParam(fun)(7, 8, 9).value); EXPECT_TRUE(static_cast<bool>(fun)); EXPECT_EQ(38, TypeParam::ToThisParam(fun)(10, 11, 12).value); } template <class T> class AnyInvTestRvalue : public ::testing::Test {}; TYPED_TEST_SUITE_P(AnyInvTestRvalue); TYPED_TEST_P(AnyInvTestRvalue, ConversionConstructionReferenceWrapper) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; EXPECT_FALSE(( std::is_convertible<std::reference_wrapper<AddType>, AnyInvType>::value)); } TYPED_TEST_P(AnyInvTestRvalue, NonMoveableResultType) { #if ABSL_INTERNAL_CPLUSPLUS_LANG < 201703L GTEST_SKIP() << "Copy/move elision was not standard before C++17"; #else struct Result { int x; explicit Result(const int x_in) : x(x_in) {} Result(Result&&) = delete; }; static_assert(!std::is_move_constructible<Result>::value, ""); static_assert(!std::is_copy_constructible<Result>::value, ""); const auto return_17 = []() noexcept { return Result(17); }; EXPECT_EQ(17, return_17().x); using UnqualifiedFun = absl::conditional_t<TypeParam::kIsNoexcept, Result() noexcept, Result()>; using Fun = GiveQualifiersToFun<typename TypeParam::Qualifiers, UnqualifiedFun>; EXPECT_EQ(17, AnyInvocable<Fun>(return_17)().x); #endif } TYPED_TEST_P(AnyInvTestRvalue, ConversionAssignReferenceWrapper) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; EXPECT_FALSE(( std::is_assignable<AnyInvType&, std::reference_wrapper<AddType>>::value)); } TYPED_TEST_P(AnyInvTestRvalue, NonConstCrashesOnSecondCall) { using AnyInvType = typename TypeParam::AnyInvType; using AddType = typename TypeParam::AddType; AnyInvType fun(absl::in_place_type<AddType>, 5); EXPECT_TRUE(static_cast<bool>(fun)); std::move(fun)(7, 8, 9); EXPECT_TRUE(static_cast<bool>(fun)); #if !defined(NDEBUG) EXPECT_DEATH_IF_SUPPORTED(std::move(fun)(7, 8, 9), ""); #endif } TYPED_TEST_P(AnyInvTestRvalue, QualifierIndependentObjectLifetime) { using AnyInvType = typename TypeParam::AnyInvType; auto refs = std::make_shared<std::nullptr_t>(); { AnyInvType fun([refs](auto&&...) noexcept { return 0; }); EXPECT_GT(refs.use_count(), 1); std::move(fun)(7, 8, 9); EXPECT_GT(refs.use_count(), 1); } EXPECT_EQ(refs.use_count(), 1); } template <Movable Mov, Destructible Dest, NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Align> using NonRvalueQualifiedTestParams = ::testing::Types< TestParams<Mov, Dest, _, CallExceptionSpec, Size, Align>, TestParams<Mov, Dest, const _, CallExceptionSpec, Size, Align>, TestParams<Mov, Dest, _&, CallExceptionSpec, Size, Align>, TestParams<Mov, Dest, const _&, CallExceptionSpec, Size, Align>>; template <Movable Mov, Destructible Dest, NothrowCall CallExceptionSpec, ObjSize Size, ObjAlign Align> using RvalueQualifiedTestParams = ::testing::Types< TestParams<Mov, Dest, _&&, CallExceptionSpec, Size, Align>, TestParams<Mov, Dest, const _&&, CallExceptionSpec, Size, Align> >; using TestParameterListNonRvalueQualifiersNothrowCall = NonRvalueQualifiedTestParams<Movable::trivial, Destructible::trivial, NothrowCall::yes, ObjSize::small, ObjAlign::normal>; using TestParameterListRvalueQualifiersNothrowCall = RvalueQualifiedTestParams<Movable::trivial, Destructible::trivial, NothrowCall::yes, ObjSize::small, ObjAlign::normal>; using TestParameterListNonRvalueQualifiersCallMayThrow = NonRvalueQualifiedTestParams<Movable::trivial, Destructible::trivial, NothrowCall::no, ObjSize::small, ObjAlign::normal>; using TestParameterListRvalueQualifiersCallMayThrow = RvalueQualifiedTestParams<Movable::trivial, Destructible::trivial, NothrowCall::no, ObjSize::small, ObjAlign::normal>; using TestParameterListRemoteMovable = ::testing::Types< TestParams<Movable::trivial, Destructible::trivial, _, NothrowCall::no, ObjSize::large, ObjAlign::normal>, TestParams<Movable::nothrow, Destructible::trivial, _, NothrowCall::no, ObjSize::large, ObjAlign::normal>, TestParams<Movable::yes, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::normal>, TestParams<Movable::yes, Destructible::trivial, _, NothrowCall::no, ObjSize::large, ObjAlign::normal>, TestParams<Movable::trivial, Destructible::nothrow, _, NothrowCall::no, ObjSize::large, ObjAlign::normal>, TestParams<Movable::nothrow, Destructible::nothrow, _, NothrowCall::no, ObjSize::large, ObjAlign::normal>, TestParams<Movable::yes, Destructible::nothrow, _, NothrowCall::no, ObjSize::small, ObjAlign::normal>, TestParams<Movable::yes, Destructible::nothrow, _, NothrowCall::no, ObjSize::large, ObjAlign::normal> #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L , TestParams<Movable::trivial, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::large>, TestParams<Movable::nothrow, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::large>, TestParams<Movable::trivial, Destructible::nothrow, _, NothrowCall::no, ObjSize::small, ObjAlign::large>, TestParams<Movable::nothrow, Destructible::nothrow, _, NothrowCall::no, ObjSize::small, ObjAlign::large> #endif >; using TestParameterListRemoteNonMovable = ::testing::Types< TestParams<Movable::no, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::normal>, TestParams<Movable::no, Destructible::trivial, _, NothrowCall::no, ObjSize::large, ObjAlign::normal>, TestParams<Movable::no, Destructible::nothrow, _, NothrowCall::no, ObjSize::small, ObjAlign::normal>, TestParams<Movable::no, Destructible::nothrow, _, NothrowCall::no, ObjSize::large, ObjAlign::normal> >; using TestParameterListLocal = ::testing::Types< TestParams<Movable::trivial, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::normal>, TestParams<Movable::nothrow, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::normal>, TestParams<Movable::trivial, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::normal>, TestParams<Movable::nothrow, Destructible::trivial, _, NothrowCall::no, ObjSize::small, ObjAlign::normal> >; REGISTER_TYPED_TEST_SUITE_P( AnyInvTestBasic, DefaultConstruction, ConstructionNullptr, ConstructionNullFunctionPtr, ConstructionNullMemberFunctionPtr, ConstructionNullMemberObjectPtr, ConstructionMemberFunctionPtr, ConstructionMemberObjectPtr, ConstructionFunctionReferenceDecay, ConstructionCompatibleAnyInvocableEmpty, ConstructionCompatibleAnyInvocableNonempty, InPlaceConstruction, ConversionToBool, Invocation, InPlaceConstructionInitializerList, InPlaceNullFunPtrConstruction, InPlaceNullFunPtrConstructionValueInit, InPlaceNullMemFunPtrConstruction, InPlaceNullMemFunPtrConstructionValueInit, InPlaceNullMemObjPtrConstruction, InPlaceNullMemObjPtrConstructionValueInit, InPlaceVoidCovarianceConstruction, MoveConstructionFromEmpty, MoveConstructionFromNonEmpty, ComparisonWithNullptrEmpty, ComparisonWithNullptrNonempty, ResultType); INSTANTIATE_TYPED_TEST_SUITE_P( NonRvalueCallMayThrow, AnyInvTestBasic, TestParameterListNonRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallMayThrow, AnyInvTestBasic, TestParameterListRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteMovable, AnyInvTestBasic, TestParameterListRemoteMovable); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteNonMovable, AnyInvTestBasic, TestParameterListRemoteNonMovable); INSTANTIATE_TYPED_TEST_SUITE_P(Local, AnyInvTestBasic, TestParameterListLocal); INSTANTIATE_TYPED_TEST_SUITE_P(NonRvalueCallNothrow, AnyInvTestBasic, TestParameterListNonRvalueQualifiersNothrowCall); INSTANTIATE_TYPED_TEST_SUITE_P(CallNothrowRvalue, AnyInvTestBasic, TestParameterListRvalueQualifiersNothrowCall); REGISTER_TYPED_TEST_SUITE_P( AnyInvTestCombinatoric, MoveAssignEmptyEmptyLhsRhs, MoveAssignEmptyLhsNonemptyRhs, MoveAssignNonemptyEmptyLhsRhs, MoveAssignNonemptyLhsNonemptyRhs, SelfMoveAssignEmpty, SelfMoveAssignNonempty, AssignNullptrEmptyLhs, AssignNullFunctionPtrEmptyLhs, AssignNullMemberFunctionPtrEmptyLhs, AssignNullMemberObjectPtrEmptyLhs, AssignMemberFunctionPtrEmptyLhs, AssignMemberObjectPtrEmptyLhs, AssignFunctionReferenceDecayEmptyLhs, AssignCompatibleAnyInvocableEmptyLhsEmptyRhs, AssignCompatibleAnyInvocableEmptyLhsNonemptyRhs, AssignNullptrNonemptyLhs, AssignNullFunctionPtrNonemptyLhs, AssignNullMemberFunctionPtrNonemptyLhs, AssignNullMemberObjectPtrNonemptyLhs, AssignMemberFunctionPtrNonemptyLhs, AssignMemberObjectPtrNonemptyLhs, AssignFunctionReferenceDecayNonemptyLhs, AssignCompatibleAnyInvocableNonemptyLhsEmptyRhs, AssignCompatibleAnyInvocableNonemptyLhsNonemptyRhs, SwapEmptyLhsEmptyRhs, SwapEmptyLhsNonemptyRhs, SwapNonemptyLhsEmptyRhs, SwapNonemptyLhsNonemptyRhs); INSTANTIATE_TYPED_TEST_SUITE_P( NonRvalueCallMayThrow, AnyInvTestCombinatoric, TestParameterListNonRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallMayThrow, AnyInvTestCombinatoric, TestParameterListRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteMovable, AnyInvTestCombinatoric, TestParameterListRemoteMovable); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteNonMovable, AnyInvTestCombinatoric, TestParameterListRemoteNonMovable); INSTANTIATE_TYPED_TEST_SUITE_P(Local, AnyInvTestCombinatoric, TestParameterListLocal); INSTANTIATE_TYPED_TEST_SUITE_P(NonRvalueCallNothrow, AnyInvTestCombinatoric, TestParameterListNonRvalueQualifiersNothrowCall); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallNothrow, AnyInvTestCombinatoric, TestParameterListRvalueQualifiersNothrowCall); REGISTER_TYPED_TEST_SUITE_P(AnyInvTestMovable, ConversionConstructionUserDefinedType, ConversionConstructionVoidCovariance, ConversionAssignUserDefinedTypeEmptyLhs, ConversionAssignUserDefinedTypeNonemptyLhs, ConversionAssignVoidCovariance); INSTANTIATE_TYPED_TEST_SUITE_P( NonRvalueCallMayThrow, AnyInvTestMovable, TestParameterListNonRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallMayThrow, AnyInvTestMovable, TestParameterListRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteMovable, AnyInvTestMovable, TestParameterListRemoteMovable); INSTANTIATE_TYPED_TEST_SUITE_P(Local, AnyInvTestMovable, TestParameterListLocal); INSTANTIATE_TYPED_TEST_SUITE_P(NonRvalueCallNothrow, AnyInvTestMovable, TestParameterListNonRvalueQualifiersNothrowCall); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallNothrow, AnyInvTestMovable, TestParameterListRvalueQualifiersNothrowCall); REGISTER_TYPED_TEST_SUITE_P(AnyInvTestNoexceptFalse, ConversionConstructionConstraints, ConversionAssignConstraints); INSTANTIATE_TYPED_TEST_SUITE_P( NonRvalueCallMayThrow, AnyInvTestNoexceptFalse, TestParameterListNonRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallMayThrow, AnyInvTestNoexceptFalse, TestParameterListRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteMovable, AnyInvTestNoexceptFalse, TestParameterListRemoteMovable); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteNonMovable, AnyInvTestNoexceptFalse, TestParameterListRemoteNonMovable); INSTANTIATE_TYPED_TEST_SUITE_P(Local, AnyInvTestNoexceptFalse, TestParameterListLocal); REGISTER_TYPED_TEST_SUITE_P(AnyInvTestNoexceptTrue, ConversionConstructionConstraints, ConversionAssignConstraints); INSTANTIATE_TYPED_TEST_SUITE_P(NonRvalueCallNothrow, AnyInvTestNoexceptTrue, TestParameterListNonRvalueQualifiersNothrowCall); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallNothrow, AnyInvTestNoexceptTrue, TestParameterListRvalueQualifiersNothrowCall); REGISTER_TYPED_TEST_SUITE_P(AnyInvTestNonRvalue, ConversionConstructionReferenceWrapper, NonMoveableResultType, ConversionAssignReferenceWrapperEmptyLhs, ConversionAssignReferenceWrapperNonemptyLhs); INSTANTIATE_TYPED_TEST_SUITE_P( NonRvalueCallMayThrow, AnyInvTestNonRvalue, TestParameterListNonRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteMovable, AnyInvTestNonRvalue, TestParameterListRemoteMovable); INSTANTIATE_TYPED_TEST_SUITE_P(RemoteNonMovable, AnyInvTestNonRvalue, TestParameterListRemoteNonMovable); INSTANTIATE_TYPED_TEST_SUITE_P(Local, AnyInvTestNonRvalue, TestParameterListLocal); INSTANTIATE_TYPED_TEST_SUITE_P(NonRvalueCallNothrow, AnyInvTestNonRvalue, TestParameterListNonRvalueQualifiersNothrowCall); REGISTER_TYPED_TEST_SUITE_P(AnyInvTestRvalue, ConversionConstructionReferenceWrapper, NonMoveableResultType, ConversionAssignReferenceWrapper, NonConstCrashesOnSecondCall, QualifierIndependentObjectLifetime); INSTANTIATE_TYPED_TEST_SUITE_P(RvalueCallMayThrow, AnyInvTestRvalue, TestParameterListRvalueQualifiersCallMayThrow); INSTANTIATE_TYPED_TEST_SUITE_P(CallNothrowRvalue, AnyInvTestRvalue, TestParameterListRvalueQualifiersNothrowCall); static_assert( std::is_convertible<void (*)(), absl::AnyInvocable<void() &&>>::value, ""); static_assert(!std::is_convertible<void*, absl::AnyInvocable<void() &&>>::value, ""); #undef ABSL_INTERNAL_NOEXCEPT_SPEC }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/internal/any_invocable.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/functional/any_invocable_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5de345ea-4f4f-4de0-b074-411cf3b13b44
cpp
abseil/abseil-cpp
prefetch
absl/base/prefetch.h
absl/base/prefetch_test.cc
#ifndef ABSL_BASE_PREFETCH_H_ #define ABSL_BASE_PREFETCH_H_ #include "absl/base/attributes.h" #include "absl/base/config.h" #if defined(ABSL_INTERNAL_HAVE_SSE) #include <xmmintrin.h> #endif #if defined(_MSC_VER) #include <intrin.h> #if defined(ABSL_INTERNAL_HAVE_SSE) #pragma intrinsic(_mm_prefetch) #endif #endif namespace absl { ABSL_NAMESPACE_BEGIN void PrefetchToLocalCache(const void* addr); void PrefetchToLocalCacheNta(const void* addr); void PrefetchToLocalCacheForWrite(const void* addr); #if ABSL_HAVE_BUILTIN(__builtin_prefetch) || defined(__GNUC__) #define ABSL_HAVE_PREFETCH 1 ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCache( const void* addr) { __builtin_prefetch(addr, 0, 3); } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCacheNta( const void* addr) { __builtin_prefetch(addr, 0, 0); } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCacheForWrite( const void* addr) { #if defined(__x86_64__) && !defined(__PRFCHW__) asm("prefetchw %0" : : "m"(*reinterpret_cast<const char*>(addr))); #else __builtin_prefetch(addr, 1, 3); #endif } #elif defined(ABSL_INTERNAL_HAVE_SSE) #define ABSL_HAVE_PREFETCH 1 ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCache( const void* addr) { _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_T0); } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCacheNta( const void* addr) { _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_NTA); } ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCacheForWrite( const void* addr) { #if defined(_MM_HINT_ET0) _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_ET0); #elif !defined(_MSC_VER) && defined(__x86_64__) asm("prefetchw %0" : : "m"(*reinterpret_cast<const char*>(addr))); #endif } #else ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCache( const void* addr) {} ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCacheNta( const void* addr) {} ABSL_ATTRIBUTE_ALWAYS_INLINE inline void PrefetchToLocalCacheForWrite( const void* addr) {} #endif ABSL_NAMESPACE_END } #endif
#include "absl/base/prefetch.h" #include <memory> #include "gtest/gtest.h" namespace { TEST(PrefetchTest, PrefetchToLocalCache_StackA) { char buf[100] = {}; absl::PrefetchToLocalCache(buf); absl::PrefetchToLocalCacheNta(buf); absl::PrefetchToLocalCacheForWrite(buf); } TEST(PrefetchTest, PrefetchToLocalCache_Heap) { auto memory = std::make_unique<char[]>(200 << 10); memset(memory.get(), 0, 200 << 10); absl::PrefetchToLocalCache(memory.get()); absl::PrefetchToLocalCacheNta(memory.get()); absl::PrefetchToLocalCacheForWrite(memory.get()); absl::PrefetchToLocalCache(memory.get() + (50 << 10)); absl::PrefetchToLocalCacheNta(memory.get() + (50 << 10)); absl::PrefetchToLocalCacheForWrite(memory.get() + (50 << 10)); absl::PrefetchToLocalCache(memory.get() + (100 << 10)); absl::PrefetchToLocalCacheNta(memory.get() + (100 << 10)); absl::PrefetchToLocalCacheForWrite(memory.get() + (100 << 10)); absl::PrefetchToLocalCache(memory.get() + (150 << 10)); absl::PrefetchToLocalCacheNta(memory.get() + (150 << 10)); absl::PrefetchToLocalCacheForWrite(memory.get() + (150 << 10)); } TEST(PrefetchTest, PrefetchToLocalCache_Nullptr) { absl::PrefetchToLocalCache(nullptr); absl::PrefetchToLocalCacheNta(nullptr); absl::PrefetchToLocalCacheForWrite(nullptr); } TEST(PrefetchTest, PrefetchToLocalCache_InvalidPtr) { absl::PrefetchToLocalCache(reinterpret_cast<const void*>(0x785326532L)); absl::PrefetchToLocalCacheNta(reinterpret_cast<const void*>(0x785326532L)); absl::PrefetchToLocalCacheForWrite(reinterpret_cast<const void*>(0x78532L)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/prefetch.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/prefetch_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
1d2a58fc-63cb-4793-9034-d7b62d49516d
cpp
abseil/abseil-cpp
optimization
absl/base/optimization.h
absl/base/optimization_test.cc
#ifndef ABSL_BASE_OPTIMIZATION_H_ #define ABSL_BASE_OPTIMIZATION_H_ #include <assert.h> #ifdef __cplusplus #include <utility> #endif #include "absl/base/config.h" #include "absl/base/options.h" #if defined(__pnacl__) #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; } #elif defined(__clang__) #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("") #elif defined(__GNUC__) #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("") #elif defined(_MSC_VER) #include <intrin.h> #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __nop() #else #define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; } #endif #if defined(__GNUC__) #if defined(__i386__) || defined(__x86_64__) #define ABSL_CACHELINE_SIZE 64 #elif defined(__powerpc64__) #define ABSL_CACHELINE_SIZE 128 #elif defined(__aarch64__) #define ABSL_CACHELINE_SIZE 64 #elif defined(__arm__) #if defined(__ARM_ARCH_5T__) #define ABSL_CACHELINE_SIZE 32 #elif defined(__ARM_ARCH_7A__) #define ABSL_CACHELINE_SIZE 64 #endif #endif #endif #ifndef ABSL_CACHELINE_SIZE #define ABSL_CACHELINE_SIZE 64 #endif #if defined(__clang__) || defined(__GNUC__) #define ABSL_CACHELINE_ALIGNED __attribute__((aligned(ABSL_CACHELINE_SIZE))) #elif defined(_MSC_VER) #define ABSL_CACHELINE_ALIGNED __declspec(align(ABSL_CACHELINE_SIZE)) #else #define ABSL_CACHELINE_ALIGNED #endif #if ABSL_HAVE_BUILTIN(__builtin_expect) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_PREDICT_FALSE(x) (__builtin_expect(false || (x), false)) #define ABSL_PREDICT_TRUE(x) (__builtin_expect(false || (x), true)) #else #define ABSL_PREDICT_FALSE(x) (x) #define ABSL_PREDICT_TRUE(x) (x) #endif #if ABSL_HAVE_BUILTIN(__builtin_trap) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_INTERNAL_IMMEDIATE_ABORT_IMPL() __builtin_trap() #else #define ABSL_INTERNAL_IMMEDIATE_ABORT_IMPL() abort() #endif #if defined(__cpp_lib_unreachable) && __cpp_lib_unreachable >= 202202L #define ABSL_INTERNAL_UNREACHABLE_IMPL() std::unreachable() #elif defined(__GNUC__) || ABSL_HAVE_BUILTIN(__builtin_unreachable) #define ABSL_INTERNAL_UNREACHABLE_IMPL() __builtin_unreachable() #elif ABSL_HAVE_BUILTIN(__builtin_assume) #define ABSL_INTERNAL_UNREACHABLE_IMPL() __builtin_assume(false) #elif defined(_MSC_VER) #define ABSL_INTERNAL_UNREACHABLE_IMPL() __assume(false) #else #define ABSL_INTERNAL_UNREACHABLE_IMPL() #endif #if ABSL_OPTION_HARDENED == 1 && defined(NDEBUG) #define ABSL_UNREACHABLE() \ do { \ ABSL_INTERNAL_IMMEDIATE_ABORT_IMPL(); \ ABSL_INTERNAL_UNREACHABLE_IMPL(); \ } while (false) #else #define ABSL_UNREACHABLE() \ do { \ \ assert(false && "ABSL_UNREACHABLE reached"); \ ABSL_INTERNAL_UNREACHABLE_IMPL(); \ } while (false) #endif #if !defined(NDEBUG) #define ABSL_ASSUME(cond) assert(cond) #elif ABSL_HAVE_BUILTIN(__builtin_assume) #define ABSL_ASSUME(cond) __builtin_assume(cond) #elif defined(_MSC_VER) #define ABSL_ASSUME(cond) __assume(cond) #elif defined(__cpp_lib_unreachable) && __cpp_lib_unreachable >= 202202L #define ABSL_ASSUME(cond) \ do { \ if (!(cond)) std::unreachable(); \ } while (false) #elif defined(__GNUC__) || ABSL_HAVE_BUILTIN(__builtin_unreachable) #define ABSL_ASSUME(cond) \ do { \ if (!(cond)) __builtin_unreachable(); \ } while (false) #else #define ABSL_ASSUME(cond) \ do { \ static_cast<void>(false && (cond)); \ } while (false) #endif #if defined(__GNUC__) #define ABSL_INTERNAL_UNIQUE_SMALL_NAME2(x) #x #define ABSL_INTERNAL_UNIQUE_SMALL_NAME1(x) ABSL_INTERNAL_UNIQUE_SMALL_NAME2(x) #define ABSL_INTERNAL_UNIQUE_SMALL_NAME() \ asm(ABSL_INTERNAL_UNIQUE_SMALL_NAME1(.absl.__COUNTER__)) #else #define ABSL_INTERNAL_UNIQUE_SMALL_NAME() #endif #endif
#include "absl/base/optimization.h" #include "gtest/gtest.h" #include "absl/types/optional.h" namespace { TEST(PredictTest, PredictTrue) { EXPECT_TRUE(ABSL_PREDICT_TRUE(true)); EXPECT_FALSE(ABSL_PREDICT_TRUE(false)); EXPECT_TRUE(ABSL_PREDICT_TRUE(1 == 1)); EXPECT_FALSE(ABSL_PREDICT_TRUE(1 == 2)); if (ABSL_PREDICT_TRUE(false)) ADD_FAILURE(); if (!ABSL_PREDICT_TRUE(true)) ADD_FAILURE(); EXPECT_TRUE(ABSL_PREDICT_TRUE(true) && true); EXPECT_TRUE(ABSL_PREDICT_TRUE(true) || false); } TEST(PredictTest, PredictFalse) { EXPECT_TRUE(ABSL_PREDICT_FALSE(true)); EXPECT_FALSE(ABSL_PREDICT_FALSE(false)); EXPECT_TRUE(ABSL_PREDICT_FALSE(1 == 1)); EXPECT_FALSE(ABSL_PREDICT_FALSE(1 == 2)); if (ABSL_PREDICT_FALSE(false)) ADD_FAILURE(); if (!ABSL_PREDICT_FALSE(true)) ADD_FAILURE(); EXPECT_TRUE(ABSL_PREDICT_FALSE(true) && true); EXPECT_TRUE(ABSL_PREDICT_FALSE(true) || false); } TEST(PredictTest, OneEvaluation) { int x = 0; if (ABSL_PREDICT_TRUE((++x) == 0)) ADD_FAILURE(); EXPECT_EQ(x, 1); if (ABSL_PREDICT_FALSE((++x) == 0)) ADD_FAILURE(); EXPECT_EQ(x, 2); } TEST(PredictTest, OperatorOrder) { EXPECT_TRUE(ABSL_PREDICT_TRUE(1 && 2) == true); EXPECT_TRUE(ABSL_PREDICT_FALSE(1 && 2) == true); EXPECT_TRUE(!ABSL_PREDICT_TRUE(1 == 2)); EXPECT_TRUE(!ABSL_PREDICT_FALSE(1 == 2)); } TEST(PredictTest, Pointer) { const int x = 3; const int *good_intptr = &x; const int *null_intptr = nullptr; EXPECT_TRUE(ABSL_PREDICT_TRUE(good_intptr)); EXPECT_FALSE(ABSL_PREDICT_TRUE(null_intptr)); EXPECT_TRUE(ABSL_PREDICT_FALSE(good_intptr)); EXPECT_FALSE(ABSL_PREDICT_FALSE(null_intptr)); } TEST(PredictTest, Optional) { absl::optional<bool> has_value(false); absl::optional<bool> no_value; EXPECT_TRUE(ABSL_PREDICT_TRUE(has_value)); EXPECT_FALSE(ABSL_PREDICT_TRUE(no_value)); EXPECT_TRUE(ABSL_PREDICT_FALSE(has_value)); EXPECT_FALSE(ABSL_PREDICT_FALSE(no_value)); } class ImplictlyConvertibleToBool { public: explicit ImplictlyConvertibleToBool(bool value) : value_(value) {} operator bool() const { return value_; } private: bool value_; }; TEST(PredictTest, ImplicitBoolConversion) { const ImplictlyConvertibleToBool is_true(true); const ImplictlyConvertibleToBool is_false(false); if (!ABSL_PREDICT_TRUE(is_true)) ADD_FAILURE(); if (ABSL_PREDICT_TRUE(is_false)) ADD_FAILURE(); if (!ABSL_PREDICT_FALSE(is_true)) ADD_FAILURE(); if (ABSL_PREDICT_FALSE(is_false)) ADD_FAILURE(); } class ExplictlyConvertibleToBool { public: explicit ExplictlyConvertibleToBool(bool value) : value_(value) {} explicit operator bool() const { return value_; } private: bool value_; }; TEST(PredictTest, ExplicitBoolConversion) { const ExplictlyConvertibleToBool is_true(true); const ExplictlyConvertibleToBool is_false(false); if (!ABSL_PREDICT_TRUE(is_true)) ADD_FAILURE(); if (ABSL_PREDICT_TRUE(is_false)) ADD_FAILURE(); if (!ABSL_PREDICT_FALSE(is_true)) ADD_FAILURE(); if (ABSL_PREDICT_FALSE(is_false)) ADD_FAILURE(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/optimization.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/optimization_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
2a892248-e2f2-4e15-b37d-ddc783b8833a
cpp
abseil/abseil-cpp
nullability
absl/base/nullability.h
absl/base/nullability_test.cc
#ifndef ABSL_BASE_NULLABILITY_H_ #define ABSL_BASE_NULLABILITY_H_ #include "absl/base/config.h" #include "absl/base/internal/nullability_impl.h" #define ABSL_POINTERS_DEFAULT_NONNULL namespace absl { ABSL_NAMESPACE_BEGIN template <typename T> using Nonnull = nullability_internal::NonnullImpl<T>; template <typename T> using Nullable = nullability_internal::NullableImpl<T>; template <typename T> using NullabilityUnknown = nullability_internal::NullabilityUnknownImpl<T>; ABSL_NAMESPACE_END } #if ABSL_HAVE_FEATURE(nullability_on_classes) #define ABSL_NULLABILITY_COMPATIBLE _Nullable #else #define ABSL_NULLABILITY_COMPATIBLE #endif #endif
#include "absl/base/nullability.h" #include <cassert> #include <memory> #include <utility> #include "gtest/gtest.h" #include "absl/base/attributes.h" namespace { using ::absl::Nonnull; using ::absl::NullabilityUnknown; using ::absl::Nullable; void funcWithNonnullArg(Nonnull<int*> ) {} template <typename T> void funcWithDeducedNonnullArg(Nonnull<T*> ) {} TEST(NonnullTest, NonnullArgument) { int var = 0; funcWithNonnullArg(&var); funcWithDeducedNonnullArg(&var); } Nonnull<int*> funcWithNonnullReturn() { static int var = 0; return &var; } TEST(NonnullTest, NonnullReturn) { auto var = funcWithNonnullReturn(); (void)var; } TEST(PassThroughTest, PassesThroughRawPointerToInt) { EXPECT_TRUE((std::is_same<Nonnull<int*>, int*>::value)); EXPECT_TRUE((std::is_same<Nullable<int*>, int*>::value)); EXPECT_TRUE((std::is_same<NullabilityUnknown<int*>, int*>::value)); } TEST(PassThroughTest, PassesThroughRawPointerToVoid) { EXPECT_TRUE((std::is_same<Nonnull<void*>, void*>::value)); EXPECT_TRUE((std::is_same<Nullable<void*>, void*>::value)); EXPECT_TRUE((std::is_same<NullabilityUnknown<void*>, void*>::value)); } TEST(PassThroughTest, PassesThroughUniquePointerToInt) { using T = std::unique_ptr<int>; EXPECT_TRUE((std::is_same<Nonnull<T>, T>::value)); EXPECT_TRUE((std::is_same<Nullable<T>, T>::value)); EXPECT_TRUE((std::is_same<NullabilityUnknown<T>, T>::value)); } TEST(PassThroughTest, PassesThroughSharedPointerToInt) { using T = std::shared_ptr<int>; EXPECT_TRUE((std::is_same<Nonnull<T>, T>::value)); EXPECT_TRUE((std::is_same<Nullable<T>, T>::value)); EXPECT_TRUE((std::is_same<NullabilityUnknown<T>, T>::value)); } TEST(PassThroughTest, PassesThroughSharedPointerToVoid) { using T = std::shared_ptr<void>; EXPECT_TRUE((std::is_same<Nonnull<T>, T>::value)); EXPECT_TRUE((std::is_same<Nullable<T>, T>::value)); EXPECT_TRUE((std::is_same<NullabilityUnknown<T>, T>::value)); } TEST(PassThroughTest, PassesThroughPointerToMemberObject) { using T = decltype(&std::pair<int, int>::first); EXPECT_TRUE((std::is_same<Nonnull<T>, T>::value)); EXPECT_TRUE((std::is_same<Nullable<T>, T>::value)); EXPECT_TRUE((std::is_same<NullabilityUnknown<T>, T>::value)); } TEST(PassThroughTest, PassesThroughPointerToMemberFunction) { using T = decltype(&std::unique_ptr<int>::reset); EXPECT_TRUE((std::is_same<Nonnull<T>, T>::value)); EXPECT_TRUE((std::is_same<Nullable<T>, T>::value)); EXPECT_TRUE((std::is_same<NullabilityUnknown<T>, T>::value)); } } namespace util { template <typename T> bool DidAdlWin(T*) { return true; } struct MakeAdlWin {}; } namespace { bool DidAdlWin(...) { return false; } TEST(NullableAdlTest, NullableAddsNothingToArgumentDependentLookup) { EXPECT_FALSE(DidAdlWin((int*)nullptr)); EXPECT_FALSE(DidAdlWin((Nullable<int*>)nullptr)); EXPECT_TRUE(DidAdlWin((util::MakeAdlWin*)nullptr)); EXPECT_TRUE(DidAdlWin((Nullable<util::MakeAdlWin*>)nullptr)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/nullability.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/nullability_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
a825c67b-8a6d-413f-913d-432c19137214
cpp
abseil/abseil-cpp
call_once
absl/base/call_once.h
absl/base/call_once_test.cc
#ifndef ABSL_BASE_CALL_ONCE_H_ #define ABSL_BASE_CALL_ONCE_H_ #include <algorithm> #include <atomic> #include <cstdint> #include <type_traits> #include <utility> #include "absl/base/internal/invoke.h" #include "absl/base/internal/low_level_scheduling.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/scheduling_mode.h" #include "absl/base/internal/spinlock_wait.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/base/optimization.h" #include "absl/base/port.h" namespace absl { ABSL_NAMESPACE_BEGIN class once_flag; namespace base_internal { absl::Nonnull<std::atomic<uint32_t>*> ControlWord( absl::Nonnull<absl::once_flag*> flag); } template <typename Callable, typename... Args> void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args); class once_flag { public: constexpr once_flag() : control_(0) {} once_flag(const once_flag&) = delete; once_flag& operator=(const once_flag&) = delete; private: friend absl::Nonnull<std::atomic<uint32_t>*> base_internal::ControlWord( absl::Nonnull<once_flag*> flag); std::atomic<uint32_t> control_; }; namespace base_internal { template <typename Callable, typename... Args> void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn, Args&&... args); class SchedulingHelper { public: explicit SchedulingHelper(base_internal::SchedulingMode mode) : mode_(mode) { if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) { guard_result_ = base_internal::SchedulingGuard::DisableRescheduling(); } } ~SchedulingHelper() { if (mode_ == base_internal::SCHEDULE_KERNEL_ONLY) { base_internal::SchedulingGuard::EnableRescheduling(guard_result_); } } private: base_internal::SchedulingMode mode_; bool guard_result_ = false; }; enum { kOnceInit = 0, kOnceRunning = 0x65C2937B, kOnceWaiter = 0x05A308D2, kOnceDone = 221, }; template <typename Callable, typename... Args> ABSL_ATTRIBUTE_NOINLINE void CallOnceImpl( absl::Nonnull<std::atomic<uint32_t>*> control, base_internal::SchedulingMode scheduling_mode, Callable&& fn, Args&&... args) { #ifndef NDEBUG { uint32_t old_control = control->load(std::memory_order_relaxed); if (old_control != kOnceInit && old_control != kOnceRunning && old_control != kOnceWaiter && old_control != kOnceDone) { ABSL_RAW_LOG(FATAL, "Unexpected value for control word: 0x%lx", static_cast<unsigned long>(old_control)); } } #endif static const base_internal::SpinLockWaitTransition trans[] = { {kOnceInit, kOnceRunning, true}, {kOnceRunning, kOnceWaiter, false}, {kOnceDone, kOnceDone, true}}; base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode); uint32_t old_control = kOnceInit; if (control->compare_exchange_strong(old_control, kOnceRunning, std::memory_order_relaxed) || base_internal::SpinLockWait(control, ABSL_ARRAYSIZE(trans), trans, scheduling_mode) == kOnceInit) { base_internal::invoke(std::forward<Callable>(fn), std::forward<Args>(args)...); old_control = control->exchange(base_internal::kOnceDone, std::memory_order_release); if (old_control == base_internal::kOnceWaiter) { base_internal::SpinLockWake(control, true); } } } inline absl::Nonnull<std::atomic<uint32_t>*> ControlWord( absl::Nonnull<once_flag*> flag) { return &flag->control_; } template <typename Callable, typename... Args> void LowLevelCallOnce(absl::Nonnull<absl::once_flag*> flag, Callable&& fn, Args&&... args) { std::atomic<uint32_t>* once = base_internal::ControlWord(flag); uint32_t s = once->load(std::memory_order_acquire); if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) { base_internal::CallOnceImpl(once, base_internal::SCHEDULE_KERNEL_ONLY, std::forward<Callable>(fn), std::forward<Args>(args)...); } } } template <typename Callable, typename... Args> void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args) { std::atomic<uint32_t>* once = base_internal::ControlWord(&flag); uint32_t s = once->load(std::memory_order_acquire); if (ABSL_PREDICT_FALSE(s != base_internal::kOnceDone)) { base_internal::CallOnceImpl( once, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL, std::forward<Callable>(fn), std::forward<Args>(args)...); } } ABSL_NAMESPACE_END } #endif
#include "absl/base/call_once.h" #include <thread> #include <vector> #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/const_init.h" #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { absl::once_flag once; ABSL_CONST_INIT Mutex counters_mu(absl::kConstInit); int running_thread_count ABSL_GUARDED_BY(counters_mu) = 0; int call_once_invoke_count ABSL_GUARDED_BY(counters_mu) = 0; int call_once_finished_count ABSL_GUARDED_BY(counters_mu) = 0; int call_once_return_count ABSL_GUARDED_BY(counters_mu) = 0; bool done_blocking ABSL_GUARDED_BY(counters_mu) = false; void WaitAndIncrement() { counters_mu.Lock(); ++call_once_invoke_count; counters_mu.Unlock(); counters_mu.LockWhen(Condition(&done_blocking)); ++call_once_finished_count; counters_mu.Unlock(); } void ThreadBody() { counters_mu.Lock(); ++running_thread_count; counters_mu.Unlock(); absl::call_once(once, WaitAndIncrement); counters_mu.Lock(); ++call_once_return_count; counters_mu.Unlock(); } bool ThreadsAreSetup(void*) ABSL_EXCLUSIVE_LOCKS_REQUIRED(counters_mu) { return running_thread_count == 10 && call_once_invoke_count == 1; } TEST(CallOnceTest, ExecutionCount) { std::vector<std::thread> threads; for (int i = 0; i < 10; ++i) { threads.emplace_back(ThreadBody); } counters_mu.LockWhen(Condition(ThreadsAreSetup, nullptr)); EXPECT_EQ(call_once_invoke_count, 1); EXPECT_EQ(call_once_finished_count, 0); EXPECT_EQ(call_once_return_count, 0); done_blocking = true; counters_mu.Unlock(); for (std::thread& thread : threads) { thread.join(); } counters_mu.Lock(); EXPECT_EQ(call_once_invoke_count, 1); EXPECT_EQ(call_once_finished_count, 1); EXPECT_EQ(call_once_return_count, 10); counters_mu.Unlock(); } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/call_once.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/call_once_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
83652685-43bf-41f1-a1cd-a1370e304951
cpp
abseil/abseil-cpp
no_destructor
absl/base/no_destructor.h
absl/base/no_destructor_test.cc
#ifndef ABSL_BASE_NO_DESTRUCTOR_H_ #define ABSL_BASE_NO_DESTRUCTOR_H_ #include <new> #include <type_traits> #include <utility> #include "absl/base/config.h" #include "absl/base/nullability.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename T> class NoDestructor { public: template <typename... Ts, typename std::enable_if<!std::is_same<void(std::decay_t<Ts>&...), void(NoDestructor&)>::value, int>::type = 0> explicit constexpr NoDestructor(Ts&&... args) : impl_(std::forward<Ts>(args)...) {} explicit constexpr NoDestructor(const T& x) : impl_(x) {} explicit constexpr NoDestructor(T&& x) : impl_(std::move(x)) {} NoDestructor(const NoDestructor&) = delete; NoDestructor& operator=(const NoDestructor&) = delete; T& operator*() { return *get(); } absl::Nonnull<T*> operator->() { return get(); } absl::Nonnull<T*> get() { return impl_.get(); } const T& operator*() const { return *get(); } absl::Nonnull<const T*> operator->() const { return get(); } absl::Nonnull<const T*> get() const { return impl_.get(); } private: class DirectImpl { public: template <typename... Args> explicit constexpr DirectImpl(Args&&... args) : value_(std::forward<Args>(args)...) {} absl::Nonnull<const T*> get() const { return &value_; } absl::Nonnull<T*> get() { return &value_; } private: T value_; }; class PlacementImpl { public: template <typename... Args> explicit PlacementImpl(Args&&... args) { new (&space_) T(std::forward<Args>(args)...); } absl::Nonnull<const T*> get() const { return Launder(reinterpret_cast<const T*>(&space_)); } absl::Nonnull<T*> get() { return Launder(reinterpret_cast<T*>(&space_)); } private: template <typename P> static absl::Nonnull<P*> Launder(absl::Nonnull<P*> p) { #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606L return std::launder(p); #elif ABSL_HAVE_BUILTIN(__builtin_launder) return __builtin_launder(p); #else #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif return p; #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic pop #endif #endif } alignas(T) unsigned char space_[sizeof(T)]; }; std::conditional_t<std::is_trivially_destructible<T>::value, DirectImpl, PlacementImpl> impl_; }; #ifdef ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION template <typename T> NoDestructor(T) -> NoDestructor<T>; #endif ABSL_NAMESPACE_END } #endif
#include "absl/base/no_destructor.h" #include <array> #include <initializer_list> #include <string> #include <type_traits> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" namespace { struct Blob { Blob() : val(42) {} Blob(int x, int y) : val(x + y) {} Blob(std::initializer_list<int> xs) { val = 0; for (auto& x : xs) val += x; } Blob(const Blob& ) = delete; Blob(Blob&& b) noexcept : val(b.val) { b.moved_out = true; } ~Blob() { ABSL_INTERNAL_CHECK(moved_out, "~Blob"); } int val; bool moved_out = false; }; struct TypeWithDeletedDestructor { ~TypeWithDeletedDestructor() = delete; }; TEST(NoDestructorTest, DestructorNeverCalled) { absl::NoDestructor<TypeWithDeletedDestructor> a; (void)a; } TEST(NoDestructorTest, Noncopyable) { using T = absl::NoDestructor<int>; EXPECT_FALSE((std::is_constructible<T, T>::value)); EXPECT_FALSE((std::is_constructible<T, const T>::value)); EXPECT_FALSE((std::is_constructible<T, T&>::value)); EXPECT_FALSE((std::is_constructible<T, const T&>::value)); EXPECT_FALSE((std::is_assignable<T&, T>::value)); EXPECT_FALSE((std::is_assignable<T&, const T>::value)); EXPECT_FALSE((std::is_assignable<T&, T&>::value)); EXPECT_FALSE((std::is_assignable<T&, const T&>::value)); } TEST(NoDestructorTest, Interface) { EXPECT_TRUE(std::is_trivially_destructible<absl::NoDestructor<Blob>>::value); EXPECT_TRUE( std::is_trivially_destructible<absl::NoDestructor<const Blob>>::value); { absl::NoDestructor<Blob> b; EXPECT_EQ(42, (*b).val); (*b).val = 55; EXPECT_EQ(55, b->val); b->val = 66; EXPECT_EQ(66, b.get()->val); b.get()->val = 42; EXPECT_EQ(42, (*b).val); } { absl::NoDestructor<const Blob> b(70, 7); EXPECT_EQ(77, (*b).val); EXPECT_EQ(77, b->val); EXPECT_EQ(77, b.get()->val); } { const absl::NoDestructor<Blob> b{ {20, 28, 40}}; EXPECT_EQ(88, (*b).val); EXPECT_EQ(88, b->val); EXPECT_EQ(88, b.get()->val); } } TEST(NoDestructorTest, SfinaeRegressionAbstractArg) { struct Abstract { virtual ~Abstract() = default; virtual int foo() const = 0; }; struct Concrete : Abstract { int foo() const override { return 17; } }; struct UsesAbstractInConstructor { explicit UsesAbstractInConstructor(const Abstract& abstract) : i(abstract.foo()) {} int i; }; Concrete input; absl::NoDestructor<UsesAbstractInConstructor> foo1(input); EXPECT_EQ(foo1->i, 17); absl::NoDestructor<UsesAbstractInConstructor> foo2( static_cast<const Abstract&>(input)); EXPECT_EQ(foo2->i, 17); } std::string* Str0() { static absl::NoDestructor<std::string> x; return x.get(); } extern const std::string& Str2(); const char* Str1() { static absl::NoDestructor<std::string> x(Str2() + "_Str1"); return x->c_str(); } const std::string& Str2() { static absl::NoDestructor<std::string> x("Str2"); return *x; } const std::string& Str2Copy() { static absl::NoDestructor<std::string> x(Str2()); return *x; } typedef std::array<std::string, 3> MyArray; const MyArray& Array() { static absl::NoDestructor<MyArray> x{{{"foo", "bar", "baz"}}}; return *x; } typedef std::vector<int> MyVector; const MyVector& Vector() { static absl::NoDestructor<MyVector> x{{1, 2, 3}}; return *x; } const int& Int() { static absl::NoDestructor<int> x; return *x; } TEST(NoDestructorTest, StaticPattern) { EXPECT_TRUE( std::is_trivially_destructible<absl::NoDestructor<std::string>>::value); EXPECT_TRUE( std::is_trivially_destructible<absl::NoDestructor<MyArray>>::value); EXPECT_TRUE( std::is_trivially_destructible<absl::NoDestructor<MyVector>>::value); EXPECT_TRUE(std::is_trivially_destructible<absl::NoDestructor<int>>::value); EXPECT_EQ(*Str0(), ""); Str0()->append("foo"); EXPECT_EQ(*Str0(), "foo"); EXPECT_EQ(std::string(Str1()), "Str2_Str1"); EXPECT_EQ(Str2(), "Str2"); EXPECT_EQ(Str2Copy(), "Str2"); EXPECT_THAT(Array(), testing::ElementsAre("foo", "bar", "baz")); EXPECT_THAT(Vector(), testing::ElementsAre(1, 2, 3)); EXPECT_EQ(0, Int()); } #ifdef ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION TEST(NoDestructorTest, ClassTemplateArgumentDeduction) { absl::NoDestructor i(1); static_assert(std::is_same<decltype(i), absl::NoDestructor<int>>::value, "Expected deduced type to be int."); } #endif }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/no_destructor.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/no_destructor_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
0814523e-f546-4e68-82e3-41d15849af8a
cpp
abseil/abseil-cpp
errno_saver
absl/base/internal/errno_saver.h
absl/base/internal/errno_saver_test.cc
#ifndef ABSL_BASE_INTERNAL_ERRNO_SAVER_H_ #define ABSL_BASE_INTERNAL_ERRNO_SAVER_H_ #include <cerrno> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { class ErrnoSaver { public: ErrnoSaver() : saved_errno_(errno) {} ~ErrnoSaver() { errno = saved_errno_; } int operator()() const { return saved_errno_; } private: const int saved_errno_; }; } ABSL_NAMESPACE_END } #endif
#include "absl/base/internal/errno_saver.h" #include <cerrno> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/internal/strerror.h" namespace { using ::testing::Eq; struct ErrnoPrinter { int no; }; std::ostream &operator<<(std::ostream &os, ErrnoPrinter ep) { return os << absl::base_internal::StrError(ep.no) << " [" << ep.no << "]"; } bool operator==(ErrnoPrinter one, ErrnoPrinter two) { return one.no == two.no; } TEST(ErrnoSaverTest, Works) { errno = EDOM; { absl::base_internal::ErrnoSaver errno_saver; EXPECT_THAT(ErrnoPrinter{errno}, Eq(ErrnoPrinter{EDOM})); errno = ERANGE; EXPECT_THAT(ErrnoPrinter{errno}, Eq(ErrnoPrinter{ERANGE})); EXPECT_THAT(ErrnoPrinter{errno_saver()}, Eq(ErrnoPrinter{EDOM})); } EXPECT_THAT(ErrnoPrinter{errno}, Eq(ErrnoPrinter{EDOM})); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/errno_saver.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/errno_saver_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
01db218e-89d2-4dfd-b6a3-1d368f61f0d1
cpp
abseil/abseil-cpp
fast_type_id
absl/base/internal/fast_type_id.h
absl/base/internal/fast_type_id_test.cc
#ifndef ABSL_BASE_INTERNAL_FAST_TYPE_ID_H_ #define ABSL_BASE_INTERNAL_FAST_TYPE_ID_H_ #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { template <typename Type> struct FastTypeTag { constexpr static char dummy_var = 0; }; #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL template <typename Type> constexpr char FastTypeTag<Type>::dummy_var; #endif using FastTypeIdType = const void*; template <typename Type> constexpr inline FastTypeIdType FastTypeId() { return &FastTypeTag<Type>::dummy_var; } } ABSL_NAMESPACE_END } #endif
#include "absl/base/internal/fast_type_id.h" #include <cstdint> #include <map> #include <vector> #include "gtest/gtest.h" namespace { namespace bi = absl::base_internal; #define PRIM_TYPES(A) \ A(bool) \ A(short) \ A(unsigned short) \ A(int) \ A(unsigned int) \ A(long) \ A(unsigned long) \ A(long long) \ A(unsigned long long) \ A(float) \ A(double) \ A(long double) TEST(FastTypeIdTest, PrimitiveTypes) { bi::FastTypeIdType type_ids[] = { #define A(T) bi::FastTypeId<T>(), PRIM_TYPES(A) #undef A #define A(T) bi::FastTypeId<const T>(), PRIM_TYPES(A) #undef A #define A(T) bi::FastTypeId<volatile T>(), PRIM_TYPES(A) #undef A #define A(T) bi::FastTypeId<const volatile T>(), PRIM_TYPES(A) #undef A }; size_t total_type_ids = sizeof(type_ids) / sizeof(bi::FastTypeIdType); for (int i = 0; i < total_type_ids; ++i) { EXPECT_EQ(type_ids[i], type_ids[i]); for (int j = 0; j < i; ++j) { EXPECT_NE(type_ids[i], type_ids[j]); } } } #define FIXED_WIDTH_TYPES(A) \ A(int8_t) \ A(uint8_t) \ A(int16_t) \ A(uint16_t) \ A(int32_t) \ A(uint32_t) \ A(int64_t) \ A(uint64_t) TEST(FastTypeIdTest, FixedWidthTypes) { bi::FastTypeIdType type_ids[] = { #define A(T) bi::FastTypeId<T>(), FIXED_WIDTH_TYPES(A) #undef A #define A(T) bi::FastTypeId<const T>(), FIXED_WIDTH_TYPES(A) #undef A #define A(T) bi::FastTypeId<volatile T>(), FIXED_WIDTH_TYPES(A) #undef A #define A(T) bi::FastTypeId<const volatile T>(), FIXED_WIDTH_TYPES(A) #undef A }; size_t total_type_ids = sizeof(type_ids) / sizeof(bi::FastTypeIdType); for (int i = 0; i < total_type_ids; ++i) { EXPECT_EQ(type_ids[i], type_ids[i]); for (int j = 0; j < i; ++j) { EXPECT_NE(type_ids[i], type_ids[j]); } } } TEST(FastTypeIdTest, AliasTypes) { using int_alias = int; EXPECT_EQ(bi::FastTypeId<int_alias>(), bi::FastTypeId<int>()); } TEST(FastTypeIdTest, TemplateSpecializations) { EXPECT_NE(bi::FastTypeId<std::vector<int>>(), bi::FastTypeId<std::vector<long>>()); EXPECT_NE((bi::FastTypeId<std::map<int, float>>()), (bi::FastTypeId<std::map<int, double>>())); } struct Base {}; struct Derived : Base {}; struct PDerived : private Base {}; TEST(FastTypeIdTest, Inheritance) { EXPECT_NE(bi::FastTypeId<Base>(), bi::FastTypeId<Derived>()); EXPECT_NE(bi::FastTypeId<Base>(), bi::FastTypeId<PDerived>()); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/fast_type_id.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/fast_type_id_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
0b0c4542-33f1-461f-bcc9-aba9c6c10683
cpp
abseil/abseil-cpp
endian
absl/base/internal/endian.h
absl/base/internal/endian_test.cc
#ifndef ABSL_BASE_INTERNAL_ENDIAN_H_ #define ABSL_BASE_INTERNAL_ENDIAN_H_ #include <cstdint> #include <cstdlib> #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/internal/unaligned_access.h" #include "absl/base/nullability.h" #include "absl/base/port.h" namespace absl { ABSL_NAMESPACE_BEGIN inline uint64_t gbswap_64(uint64_t host_int) { #if ABSL_HAVE_BUILTIN(__builtin_bswap64) || defined(__GNUC__) return __builtin_bswap64(host_int); #elif defined(_MSC_VER) return _byteswap_uint64(host_int); #else return (((host_int & uint64_t{0xFF}) << 56) | ((host_int & uint64_t{0xFF00}) << 40) | ((host_int & uint64_t{0xFF0000}) << 24) | ((host_int & uint64_t{0xFF000000}) << 8) | ((host_int & uint64_t{0xFF00000000}) >> 8) | ((host_int & uint64_t{0xFF0000000000}) >> 24) | ((host_int & uint64_t{0xFF000000000000}) >> 40) | ((host_int & uint64_t{0xFF00000000000000}) >> 56)); #endif } inline uint32_t gbswap_32(uint32_t host_int) { #if ABSL_HAVE_BUILTIN(__builtin_bswap32) || defined(__GNUC__) return __builtin_bswap32(host_int); #elif defined(_MSC_VER) return _byteswap_ulong(host_int); #else return (((host_int & uint32_t{0xFF}) << 24) | ((host_int & uint32_t{0xFF00}) << 8) | ((host_int & uint32_t{0xFF0000}) >> 8) | ((host_int & uint32_t{0xFF000000}) >> 24)); #endif } inline uint16_t gbswap_16(uint16_t host_int) { #if ABSL_HAVE_BUILTIN(__builtin_bswap16) || defined(__GNUC__) return __builtin_bswap16(host_int); #elif defined(_MSC_VER) return _byteswap_ushort(host_int); #else return (((host_int & uint16_t{0xFF}) << 8) | ((host_int & uint16_t{0xFF00}) >> 8)); #endif } #ifdef ABSL_IS_LITTLE_ENDIAN inline uint16_t ghtons(uint16_t x) { return gbswap_16(x); } inline uint32_t ghtonl(uint32_t x) { return gbswap_32(x); } inline uint64_t ghtonll(uint64_t x) { return gbswap_64(x); } #elif defined ABSL_IS_BIG_ENDIAN inline uint16_t ghtons(uint16_t x) { return x; } inline uint32_t ghtonl(uint32_t x) { return x; } inline uint64_t ghtonll(uint64_t x) { return x; } #else #error \ "Unsupported byte order: Either ABSL_IS_BIG_ENDIAN or " \ "ABSL_IS_LITTLE_ENDIAN must be defined" #endif inline uint16_t gntohs(uint16_t x) { return ghtons(x); } inline uint32_t gntohl(uint32_t x) { return ghtonl(x); } inline uint64_t gntohll(uint64_t x) { return ghtonll(x); } namespace little_endian { #ifdef ABSL_IS_LITTLE_ENDIAN inline uint16_t FromHost16(uint16_t x) { return x; } inline uint16_t ToHost16(uint16_t x) { return x; } inline uint32_t FromHost32(uint32_t x) { return x; } inline uint32_t ToHost32(uint32_t x) { return x; } inline uint64_t FromHost64(uint64_t x) { return x; } inline uint64_t ToHost64(uint64_t x) { return x; } inline constexpr bool IsLittleEndian() { return true; } #elif defined ABSL_IS_BIG_ENDIAN inline uint16_t FromHost16(uint16_t x) { return gbswap_16(x); } inline uint16_t ToHost16(uint16_t x) { return gbswap_16(x); } inline uint32_t FromHost32(uint32_t x) { return gbswap_32(x); } inline uint32_t ToHost32(uint32_t x) { return gbswap_32(x); } inline uint64_t FromHost64(uint64_t x) { return gbswap_64(x); } inline uint64_t ToHost64(uint64_t x) { return gbswap_64(x); } inline constexpr bool IsLittleEndian() { return false; } #endif inline uint8_t FromHost(uint8_t x) { return x; } inline uint16_t FromHost(uint16_t x) { return FromHost16(x); } inline uint32_t FromHost(uint32_t x) { return FromHost32(x); } inline uint64_t FromHost(uint64_t x) { return FromHost64(x); } inline uint8_t ToHost(uint8_t x) { return x; } inline uint16_t ToHost(uint16_t x) { return ToHost16(x); } inline uint32_t ToHost(uint32_t x) { return ToHost32(x); } inline uint64_t ToHost(uint64_t x) { return ToHost64(x); } inline int8_t FromHost(int8_t x) { return x; } inline int16_t FromHost(int16_t x) { return bit_cast<int16_t>(FromHost16(bit_cast<uint16_t>(x))); } inline int32_t FromHost(int32_t x) { return bit_cast<int32_t>(FromHost32(bit_cast<uint32_t>(x))); } inline int64_t FromHost(int64_t x) { return bit_cast<int64_t>(FromHost64(bit_cast<uint64_t>(x))); } inline int8_t ToHost(int8_t x) { return x; } inline int16_t ToHost(int16_t x) { return bit_cast<int16_t>(ToHost16(bit_cast<uint16_t>(x))); } inline int32_t ToHost(int32_t x) { return bit_cast<int32_t>(ToHost32(bit_cast<uint32_t>(x))); } inline int64_t ToHost(int64_t x) { return bit_cast<int64_t>(ToHost64(bit_cast<uint64_t>(x))); } inline uint16_t Load16(absl::Nonnull<const void *> p) { return ToHost16(ABSL_INTERNAL_UNALIGNED_LOAD16(p)); } inline void Store16(absl::Nonnull<void *> p, uint16_t v) { ABSL_INTERNAL_UNALIGNED_STORE16(p, FromHost16(v)); } inline uint32_t Load32(absl::Nonnull<const void *> p) { return ToHost32(ABSL_INTERNAL_UNALIGNED_LOAD32(p)); } inline void Store32(absl::Nonnull<void *> p, uint32_t v) { ABSL_INTERNAL_UNALIGNED_STORE32(p, FromHost32(v)); } inline uint64_t Load64(absl::Nonnull<const void *> p) { return ToHost64(ABSL_INTERNAL_UNALIGNED_LOAD64(p)); } inline void Store64(absl::Nonnull<void *> p, uint64_t v) { ABSL_INTERNAL_UNALIGNED_STORE64(p, FromHost64(v)); } } namespace big_endian { #ifdef ABSL_IS_LITTLE_ENDIAN inline uint16_t FromHost16(uint16_t x) { return gbswap_16(x); } inline uint16_t ToHost16(uint16_t x) { return gbswap_16(x); } inline uint32_t FromHost32(uint32_t x) { return gbswap_32(x); } inline uint32_t ToHost32(uint32_t x) { return gbswap_32(x); } inline uint64_t FromHost64(uint64_t x) { return gbswap_64(x); } inline uint64_t ToHost64(uint64_t x) { return gbswap_64(x); } inline constexpr bool IsLittleEndian() { return true; } #elif defined ABSL_IS_BIG_ENDIAN inline uint16_t FromHost16(uint16_t x) { return x; } inline uint16_t ToHost16(uint16_t x) { return x; } inline uint32_t FromHost32(uint32_t x) { return x; } inline uint32_t ToHost32(uint32_t x) { return x; } inline uint64_t FromHost64(uint64_t x) { return x; } inline uint64_t ToHost64(uint64_t x) { return x; } inline constexpr bool IsLittleEndian() { return false; } #endif inline uint8_t FromHost(uint8_t x) { return x; } inline uint16_t FromHost(uint16_t x) { return FromHost16(x); } inline uint32_t FromHost(uint32_t x) { return FromHost32(x); } inline uint64_t FromHost(uint64_t x) { return FromHost64(x); } inline uint8_t ToHost(uint8_t x) { return x; } inline uint16_t ToHost(uint16_t x) { return ToHost16(x); } inline uint32_t ToHost(uint32_t x) { return ToHost32(x); } inline uint64_t ToHost(uint64_t x) { return ToHost64(x); } inline int8_t FromHost(int8_t x) { return x; } inline int16_t FromHost(int16_t x) { return bit_cast<int16_t>(FromHost16(bit_cast<uint16_t>(x))); } inline int32_t FromHost(int32_t x) { return bit_cast<int32_t>(FromHost32(bit_cast<uint32_t>(x))); } inline int64_t FromHost(int64_t x) { return bit_cast<int64_t>(FromHost64(bit_cast<uint64_t>(x))); } inline int8_t ToHost(int8_t x) { return x; } inline int16_t ToHost(int16_t x) { return bit_cast<int16_t>(ToHost16(bit_cast<uint16_t>(x))); } inline int32_t ToHost(int32_t x) { return bit_cast<int32_t>(ToHost32(bit_cast<uint32_t>(x))); } inline int64_t ToHost(int64_t x) { return bit_cast<int64_t>(ToHost64(bit_cast<uint64_t>(x))); } inline uint16_t Load16(absl::Nonnull<const void *> p) { return ToHost16(ABSL_INTERNAL_UNALIGNED_LOAD16(p)); } inline void Store16(absl::Nonnull<void *> p, uint16_t v) { ABSL_INTERNAL_UNALIGNED_STORE16(p, FromHost16(v)); } inline uint32_t Load32(absl::Nonnull<const void *> p) { return ToHost32(ABSL_INTERNAL_UNALIGNED_LOAD32(p)); } inline void Store32(absl::Nonnull<void *>p, uint32_t v) { ABSL_INTERNAL_UNALIGNED_STORE32(p, FromHost32(v)); } inline uint64_t Load64(absl::Nonnull<const void *> p) { return ToHost64(ABSL_INTERNAL_UNALIGNED_LOAD64(p)); } inline void Store64(absl::Nonnull<void *> p, uint64_t v) { ABSL_INTERNAL_UNALIGNED_STORE64(p, FromHost64(v)); } } ABSL_NAMESPACE_END } #endif
#include "absl/base/internal/endian.h" #include <algorithm> #include <cstdint> #include <limits> #include <random> #include <vector> #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { const uint64_t kInitialNumber{0x0123456789abcdef}; const uint64_t k64Value{kInitialNumber}; const uint32_t k32Value{0x01234567}; const uint16_t k16Value{0x0123}; const int kNumValuesToTest = 1000000; const int kRandomSeed = 12345; #if defined(ABSL_IS_BIG_ENDIAN) const uint64_t kInitialInNetworkOrder{kInitialNumber}; const uint64_t k64ValueLE{0xefcdab8967452301}; const uint32_t k32ValueLE{0x67452301}; const uint16_t k16ValueLE{0x2301}; const uint64_t k64ValueBE{kInitialNumber}; const uint32_t k32ValueBE{k32Value}; const uint16_t k16ValueBE{k16Value}; #elif defined(ABSL_IS_LITTLE_ENDIAN) const uint64_t kInitialInNetworkOrder{0xefcdab8967452301}; const uint64_t k64ValueLE{kInitialNumber}; const uint32_t k32ValueLE{k32Value}; const uint16_t k16ValueLE{k16Value}; const uint64_t k64ValueBE{0xefcdab8967452301}; const uint32_t k32ValueBE{0x67452301}; const uint16_t k16ValueBE{0x2301}; #endif std::vector<uint16_t> GenerateAllUint16Values() { std::vector<uint16_t> result; result.reserve(size_t{1} << (sizeof(uint16_t) * 8)); for (uint32_t i = std::numeric_limits<uint16_t>::min(); i <= std::numeric_limits<uint16_t>::max(); ++i) { result.push_back(static_cast<uint16_t>(i)); } return result; } template<typename T> std::vector<T> GenerateRandomIntegers(size_t num_values_to_test) { std::vector<T> result; result.reserve(num_values_to_test); std::mt19937_64 rng(kRandomSeed); for (size_t i = 0; i < num_values_to_test; ++i) { result.push_back(rng()); } return result; } void ManualByteSwap(char* bytes, int length) { if (length == 1) return; EXPECT_EQ(0, length % 2); for (int i = 0; i < length / 2; ++i) { int j = (length - 1) - i; using std::swap; swap(bytes[i], bytes[j]); } } template<typename T> inline T UnalignedLoad(const char* p) { static_assert( sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8, "Unexpected type size"); switch (sizeof(T)) { case 1: return *reinterpret_cast<const T*>(p); case 2: return ABSL_INTERNAL_UNALIGNED_LOAD16(p); case 4: return ABSL_INTERNAL_UNALIGNED_LOAD32(p); case 8: return ABSL_INTERNAL_UNALIGNED_LOAD64(p); default: return {}; } } template <typename T, typename ByteSwapper> static void GBSwapHelper(const std::vector<T>& host_values_to_test, const ByteSwapper& byte_swapper) { for (typename std::vector<T>::const_iterator it = host_values_to_test.begin(); it != host_values_to_test.end(); ++it) { T host_value = *it; char actual_value[sizeof(host_value)]; memcpy(actual_value, &host_value, sizeof(host_value)); byte_swapper(actual_value); char expected_value[sizeof(host_value)]; memcpy(expected_value, &host_value, sizeof(host_value)); ManualByteSwap(expected_value, sizeof(host_value)); ASSERT_EQ(0, memcmp(actual_value, expected_value, sizeof(host_value))) << "Swap output for 0x" << std::hex << host_value << " does not match. " << "Expected: 0x" << UnalignedLoad<T>(expected_value) << "; " << "actual: 0x" << UnalignedLoad<T>(actual_value); } } void Swap16(char* bytes) { ABSL_INTERNAL_UNALIGNED_STORE16( bytes, gbswap_16(ABSL_INTERNAL_UNALIGNED_LOAD16(bytes))); } void Swap32(char* bytes) { ABSL_INTERNAL_UNALIGNED_STORE32( bytes, gbswap_32(ABSL_INTERNAL_UNALIGNED_LOAD32(bytes))); } void Swap64(char* bytes) { ABSL_INTERNAL_UNALIGNED_STORE64( bytes, gbswap_64(ABSL_INTERNAL_UNALIGNED_LOAD64(bytes))); } TEST(EndianessTest, Uint16) { GBSwapHelper(GenerateAllUint16Values(), &Swap16); } TEST(EndianessTest, Uint32) { GBSwapHelper(GenerateRandomIntegers<uint32_t>(kNumValuesToTest), &Swap32); } TEST(EndianessTest, Uint64) { GBSwapHelper(GenerateRandomIntegers<uint64_t>(kNumValuesToTest), &Swap64); } TEST(EndianessTest, ghtonll_gntohll) { uint32_t test = 0x01234567; EXPECT_EQ(absl::gntohl(absl::ghtonl(test)), test); uint64_t comp = absl::ghtonll(kInitialNumber); EXPECT_EQ(comp, kInitialInNetworkOrder); comp = absl::gntohll(kInitialInNetworkOrder); EXPECT_EQ(comp, kInitialNumber); uint64_t value = 1; for (int i = 0; i < 100; ++i) { comp = absl::ghtonll(absl::gntohll(value)); EXPECT_EQ(value, comp); comp = absl::gntohll(absl::ghtonll(value)); EXPECT_EQ(value, comp); value *= 37; } } TEST(EndianessTest, little_endian) { uint64_t comp = little_endian::FromHost16(k16Value); EXPECT_EQ(comp, k16ValueLE); comp = little_endian::ToHost16(k16ValueLE); EXPECT_EQ(comp, k16Value); comp = little_endian::FromHost32(k32Value); EXPECT_EQ(comp, k32ValueLE); comp = little_endian::ToHost32(k32ValueLE); EXPECT_EQ(comp, k32Value); comp = little_endian::FromHost64(k64Value); EXPECT_EQ(comp, k64ValueLE); comp = little_endian::ToHost64(k64ValueLE); EXPECT_EQ(comp, k64Value); uint16_t u16Buf; uint32_t u32Buf; uint64_t u64Buf; little_endian::Store16(&u16Buf, k16Value); EXPECT_EQ(u16Buf, k16ValueLE); comp = little_endian::Load16(&u16Buf); EXPECT_EQ(comp, k16Value); little_endian::Store32(&u32Buf, k32Value); EXPECT_EQ(u32Buf, k32ValueLE); comp = little_endian::Load32(&u32Buf); EXPECT_EQ(comp, k32Value); little_endian::Store64(&u64Buf, k64Value); EXPECT_EQ(u64Buf, k64ValueLE); comp = little_endian::Load64(&u64Buf); EXPECT_EQ(comp, k64Value); } TEST(EndianessTest, big_endian) { uint16_t u16Buf; uint32_t u32Buf; uint64_t u64Buf; unsigned char buffer[10]; big_endian::Store16(&u16Buf, k16Value); EXPECT_EQ(u16Buf, k16ValueBE); uint64_t comp = big_endian::Load16(&u16Buf); EXPECT_EQ(comp, k16Value); big_endian::Store32(&u32Buf, k32Value); EXPECT_EQ(u32Buf, k32ValueBE); comp = big_endian::Load32(&u32Buf); EXPECT_EQ(comp, k32Value); big_endian::Store64(&u64Buf, k64Value); EXPECT_EQ(u64Buf, k64ValueBE); comp = big_endian::Load64(&u64Buf); EXPECT_EQ(comp, k64Value); big_endian::Store16(buffer + 1, k16Value); EXPECT_EQ(u16Buf, k16ValueBE); comp = big_endian::Load16(buffer + 1); EXPECT_EQ(comp, k16Value); big_endian::Store32(buffer + 1, k32Value); EXPECT_EQ(u32Buf, k32ValueBE); comp = big_endian::Load32(buffer + 1); EXPECT_EQ(comp, k32Value); big_endian::Store64(buffer + 1, k64Value); EXPECT_EQ(u64Buf, k64ValueBE); comp = big_endian::Load64(buffer + 1); EXPECT_EQ(comp, k64Value); } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/endian.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/endian_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
9ebf61e1-2594-4952-877e-18440a751526
cpp
abseil/abseil-cpp
invoke
absl/base/internal/invoke.h
absl/base/invoke_test.cc
#ifndef ABSL_BASE_INTERNAL_INVOKE_H_ #define ABSL_BASE_INTERNAL_INVOKE_H_ #include "absl/base/config.h" #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L #include <functional> namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { using std::invoke; using std::invoke_result_t; using std::is_invocable_r; } ABSL_NAMESPACE_END } #else #include <algorithm> #include <type_traits> #include <utility> #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { template <typename Derived> struct StrippedAccept { template <typename... Args> struct Accept : Derived::template AcceptImpl<typename std::remove_cv< typename std::remove_reference<Args>::type>::type...> {}; }; struct MemFunAndRef : StrippedAccept<MemFunAndRef> { template <typename... Args> struct AcceptImpl : std::false_type {}; template <typename MemFunType, typename C, typename Obj, typename... Args> struct AcceptImpl<MemFunType C::*, Obj, Args...> : std::integral_constant<bool, std::is_base_of<C, Obj>::value && absl::is_function<MemFunType>::value> { }; template <typename MemFun, typename Obj, typename... Args> static decltype((std::declval<Obj>().* std::declval<MemFun>())(std::declval<Args>()...)) Invoke(MemFun&& mem_fun, Obj&& obj, Args&&... args) { #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(11, 0) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif return (std::forward<Obj>(obj).* std::forward<MemFun>(mem_fun))(std::forward<Args>(args)...); #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(11, 0) #pragma GCC diagnostic pop #endif } }; struct MemFunAndPtr : StrippedAccept<MemFunAndPtr> { template <typename... Args> struct AcceptImpl : std::false_type {}; template <typename MemFunType, typename C, typename Ptr, typename... Args> struct AcceptImpl<MemFunType C::*, Ptr, Args...> : std::integral_constant<bool, !std::is_base_of<C, Ptr>::value && absl::is_function<MemFunType>::value> { }; template <typename MemFun, typename Ptr, typename... Args> static decltype(((*std::declval<Ptr>()).* std::declval<MemFun>())(std::declval<Args>()...)) Invoke(MemFun&& mem_fun, Ptr&& ptr, Args&&... args) { return ((*std::forward<Ptr>(ptr)).* std::forward<MemFun>(mem_fun))(std::forward<Args>(args)...); } }; struct DataMemAndRef : StrippedAccept<DataMemAndRef> { template <typename... Args> struct AcceptImpl : std::false_type {}; template <typename R, typename C, typename Obj> struct AcceptImpl<R C::*, Obj> : std::integral_constant<bool, std::is_base_of<C, Obj>::value && !absl::is_function<R>::value> {}; template <typename DataMem, typename Ref> static decltype(std::declval<Ref>().*std::declval<DataMem>()) Invoke( DataMem&& data_mem, Ref&& ref) { return std::forward<Ref>(ref).*std::forward<DataMem>(data_mem); } }; struct DataMemAndPtr : StrippedAccept<DataMemAndPtr> { template <typename... Args> struct AcceptImpl : std::false_type {}; template <typename R, typename C, typename Ptr> struct AcceptImpl<R C::*, Ptr> : std::integral_constant<bool, !std::is_base_of<C, Ptr>::value && !absl::is_function<R>::value> {}; template <typename DataMem, typename Ptr> static decltype((*std::declval<Ptr>()).*std::declval<DataMem>()) Invoke( DataMem&& data_mem, Ptr&& ptr) { return (*std::forward<Ptr>(ptr)).*std::forward<DataMem>(data_mem); } }; struct Callable { template <typename F, typename... Args> static decltype(std::declval<F>()(std::declval<Args>()...)) Invoke( F&& f, Args&&... args) { return std::forward<F>(f)(std::forward<Args>(args)...); } }; template <typename... Args> struct Invoker { typedef typename std::conditional< MemFunAndRef::Accept<Args...>::value, MemFunAndRef, typename std::conditional< MemFunAndPtr::Accept<Args...>::value, MemFunAndPtr, typename std::conditional< DataMemAndRef::Accept<Args...>::value, DataMemAndRef, typename std::conditional<DataMemAndPtr::Accept<Args...>::value, DataMemAndPtr, Callable>::type>::type>:: type>::type type; }; template <typename F, typename... Args> using invoke_result_t = decltype(Invoker<F, Args...>::type::Invoke( std::declval<F>(), std::declval<Args>()...)); template <typename F, typename... Args> invoke_result_t<F, Args...> invoke(F&& f, Args&&... args) { return Invoker<F, Args...>::type::Invoke(std::forward<F>(f), std::forward<Args>(args)...); } template <typename AlwaysVoid, typename, typename, typename...> struct IsInvocableRImpl : std::false_type {}; template <typename R, typename F, typename... Args> struct IsInvocableRImpl< absl::void_t<absl::base_internal::invoke_result_t<F, Args...> >, R, F, Args...> : std::integral_constant< bool, std::is_convertible<absl::base_internal::invoke_result_t<F, Args...>, R>::value || std::is_void<R>::value> {}; template <typename R, typename F, typename... Args> using is_invocable_r = IsInvocableRImpl<void, R, F, Args...>; } ABSL_NAMESPACE_END } #endif #endif
#include "absl/base/internal/invoke.h" #include <functional> #include <memory> #include <string> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { int Function(int a, int b) { return a - b; } void VoidFunction(int& a, int& b) { a += b; b = a - b; a -= b; } int ZeroArgFunction() { return -1937; } int Sink(std::unique_ptr<int> p) { return *p; } std::unique_ptr<int> Factory(int n) { return make_unique<int>(n); } void NoOp() {} struct ConstFunctor { int operator()(int a, int b) const { return a - b; } }; struct MutableFunctor { int operator()(int a, int b) { return a - b; } }; struct EphemeralFunctor { int operator()(int a, int b) && { return a - b; } }; struct OverloadedFunctor { template <typename... Args> std::string operator()(const Args&... args) & { return StrCat("&", args...); } template <typename... Args> std::string operator()(const Args&... args) const& { return StrCat("const&", args...); } template <typename... Args> std::string operator()(const Args&... args) && { return StrCat("&&", args...); } }; struct Class { int Method(int a, int b) { return a - b; } int ConstMethod(int a, int b) const { return a - b; } int RefMethod(int a, int b) & { return a - b; } int RefRefMethod(int a, int b) && { return a - b; } int NoExceptMethod(int a, int b) noexcept { return a - b; } int VolatileMethod(int a, int b) volatile { return a - b; } int member; }; struct FlipFlop { int ConstMethod() const { return member; } FlipFlop operator*() const { return {-member}; } int member; }; template <typename F> decltype(base_internal::invoke(std::declval<const F&>())) CallMaybeWithArg( const F& f) { return base_internal::invoke(f); } template <typename F> decltype(base_internal::invoke(std::declval<const F&>(), 42)) CallMaybeWithArg( const F& f) { return base_internal::invoke(f, 42); } TEST(InvokeTest, Function) { EXPECT_EQ(1, base_internal::invoke(Function, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Function, 3, 2)); } TEST(InvokeTest, NonCopyableArgument) { EXPECT_EQ(42, base_internal::invoke(Sink, make_unique<int>(42))); } TEST(InvokeTest, NonCopyableResult) { EXPECT_THAT(base_internal::invoke(Factory, 42), ::testing::Pointee(42)); } TEST(InvokeTest, VoidResult) { base_internal::invoke(NoOp); } TEST(InvokeTest, ConstFunctor) { EXPECT_EQ(1, base_internal::invoke(ConstFunctor(), 3, 2)); } TEST(InvokeTest, MutableFunctor) { MutableFunctor f; EXPECT_EQ(1, base_internal::invoke(f, 3, 2)); EXPECT_EQ(1, base_internal::invoke(MutableFunctor(), 3, 2)); } TEST(InvokeTest, EphemeralFunctor) { EphemeralFunctor f; EXPECT_EQ(1, base_internal::invoke(std::move(f), 3, 2)); EXPECT_EQ(1, base_internal::invoke(EphemeralFunctor(), 3, 2)); } TEST(InvokeTest, OverloadedFunctor) { OverloadedFunctor f; const OverloadedFunctor& cf = f; EXPECT_EQ("&", base_internal::invoke(f)); EXPECT_EQ("& 42", base_internal::invoke(f, " 42")); EXPECT_EQ("const&", base_internal::invoke(cf)); EXPECT_EQ("const& 42", base_internal::invoke(cf, " 42")); EXPECT_EQ("&&", base_internal::invoke(std::move(f))); OverloadedFunctor f2; EXPECT_EQ("&& 42", base_internal::invoke(std::move(f2), " 42")); } TEST(InvokeTest, ReferenceWrapper) { ConstFunctor cf; MutableFunctor mf; EXPECT_EQ(1, base_internal::invoke(std::cref(cf), 3, 2)); EXPECT_EQ(1, base_internal::invoke(std::ref(cf), 3, 2)); EXPECT_EQ(1, base_internal::invoke(std::ref(mf), 3, 2)); } TEST(InvokeTest, MemberFunction) { std::unique_ptr<Class> p(new Class); std::unique_ptr<const Class> cp(new Class); std::unique_ptr<volatile Class> vp(new Class); EXPECT_EQ(1, base_internal::invoke(&Class::Method, p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::Method, p.get(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::Method, *p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::RefMethod, p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::RefMethod, p.get(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::RefMethod, *p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::RefRefMethod, std::move(*p), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::NoExceptMethod, p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::NoExceptMethod, p.get(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::NoExceptMethod, *p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, p.get(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, *p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, cp, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, cp.get(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, *cp, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, p.get(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, *p, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, vp, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, vp.get(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::VolatileMethod, *vp, 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::Method, make_unique<Class>(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, make_unique<Class>(), 3, 2)); EXPECT_EQ(1, base_internal::invoke(&Class::ConstMethod, make_unique<const Class>(), 3, 2)); } TEST(InvokeTest, DataMember) { std::unique_ptr<Class> p(new Class{42}); std::unique_ptr<const Class> cp(new Class{42}); EXPECT_EQ(42, base_internal::invoke(&Class::member, p)); EXPECT_EQ(42, base_internal::invoke(&Class::member, *p)); EXPECT_EQ(42, base_internal::invoke(&Class::member, p.get())); base_internal::invoke(&Class::member, p) = 42; base_internal::invoke(&Class::member, p.get()) = 42; EXPECT_EQ(42, base_internal::invoke(&Class::member, cp)); EXPECT_EQ(42, base_internal::invoke(&Class::member, *cp)); EXPECT_EQ(42, base_internal::invoke(&Class::member, cp.get())); } TEST(InvokeTest, FlipFlop) { FlipFlop obj = {42}; EXPECT_EQ(42, base_internal::invoke(&FlipFlop::ConstMethod, obj)); EXPECT_EQ(42, base_internal::invoke(&FlipFlop::member, obj)); } TEST(InvokeTest, SfinaeFriendly) { CallMaybeWithArg(NoOp); EXPECT_THAT(CallMaybeWithArg(Factory), ::testing::Pointee(42)); } TEST(IsInvocableRTest, CallableExactMatch) { static_assert( base_internal::is_invocable_r<int, decltype(Function), int, int>::value, "Should be true for exact match of types on a free function"); } TEST(IsInvocableRTest, CallableArgumentConversionMatch) { static_assert( base_internal::is_invocable_r<int, decltype(Function), char, int>::value, "Should be true for convertible argument type"); } TEST(IsInvocableRTest, CallableReturnConversionMatch) { static_assert(base_internal::is_invocable_r<double, decltype(Function), int, int>::value, "Should be true for convertible return type"); } TEST(IsInvocableRTest, CallableReturnVoid) { static_assert(base_internal::is_invocable_r<void, decltype(VoidFunction), int&, int&>::value, "Should be true for void expected and actual return types"); static_assert( base_internal::is_invocable_r<void, decltype(Function), int, int>::value, "Should be true for void expected and non-void actual return types"); } TEST(IsInvocableRTest, CallableRefQualifierMismatch) { static_assert(!base_internal::is_invocable_r<void, decltype(VoidFunction), int&, const int&>::value, "Should be false for reference constness mismatch"); static_assert(!base_internal::is_invocable_r<void, decltype(VoidFunction), int&&, int&>::value, "Should be false for reference value category mismatch"); } TEST(IsInvocableRTest, CallableArgumentTypeMismatch) { static_assert(!base_internal::is_invocable_r<int, decltype(Function), std::string, int>::value, "Should be false for argument type mismatch"); } TEST(IsInvocableRTest, CallableReturnTypeMismatch) { static_assert(!base_internal::is_invocable_r<std::string, decltype(Function), int, int>::value, "Should be false for return type mismatch"); } TEST(IsInvocableRTest, CallableTooFewArgs) { static_assert( !base_internal::is_invocable_r<int, decltype(Function), int>::value, "Should be false for too few arguments"); } TEST(IsInvocableRTest, CallableTooManyArgs) { static_assert(!base_internal::is_invocable_r<int, decltype(Function), int, int, int>::value, "Should be false for too many arguments"); } TEST(IsInvocableRTest, MemberFunctionAndReference) { static_assert(base_internal::is_invocable_r<int, decltype(&Class::Method), Class&, int, int>::value, "Should be true for exact match of types on a member function " "and class reference"); } TEST(IsInvocableRTest, MemberFunctionAndPointer) { static_assert(base_internal::is_invocable_r<int, decltype(&Class::Method), Class*, int, int>::value, "Should be true for exact match of types on a member function " "and class pointer"); } TEST(IsInvocableRTest, DataMemberAndReference) { static_assert(base_internal::is_invocable_r<int, decltype(&Class::member), Class&>::value, "Should be true for exact match of types on a data member and " "class reference"); } TEST(IsInvocableRTest, DataMemberAndPointer) { static_assert(base_internal::is_invocable_r<int, decltype(&Class::member), Class*>::value, "Should be true for exact match of types on a data member and " "class pointer"); } TEST(IsInvocableRTest, CallableZeroArgs) { static_assert( base_internal::is_invocable_r<int, decltype(ZeroArgFunction)>::value, "Should be true for exact match for a zero-arg free function"); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/invoke.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/invoke_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
085ce812-51f1-4c00-90f7-ec5e49d65dd9
cpp
abseil/abseil-cpp
inline_variable
absl/base/internal/inline_variable.h
absl/base/inline_variable_test.cc
#ifndef ABSL_BASE_INTERNAL_INLINE_VARIABLE_H_ #define ABSL_BASE_INTERNAL_INLINE_VARIABLE_H_ #include <type_traits> #include "absl/base/internal/identity.h" #ifdef __cpp_inline_variables #if defined(__clang__) #define ABSL_INTERNAL_EXTERN_DECL(type, name) \ extern const ::absl::internal::type_identity_t<type> name; #else #define ABSL_INTERNAL_EXTERN_DECL(type, name) #endif #define ABSL_INTERNAL_INLINE_CONSTEXPR(type, name, init) \ ABSL_INTERNAL_EXTERN_DECL(type, name) \ inline constexpr ::absl::internal::type_identity_t<type> name = init #else #define ABSL_INTERNAL_INLINE_CONSTEXPR(var_type, name, init) \ template <class = void> \ struct AbslInternalInlineVariableHolder##name { \ static constexpr ::absl::internal::type_identity_t<var_type> kInstance = \ init; \ }; \ \ template <class AbslInternalDummy> \ constexpr ::absl::internal::type_identity_t<var_type> \ AbslInternalInlineVariableHolder##name<AbslInternalDummy>::kInstance; \ \ static constexpr const ::absl::internal::type_identity_t<var_type>& \ name = \ AbslInternalInlineVariableHolder##name<>::kInstance; \ static_assert(sizeof(void (*)(decltype(name))) != 0, \ "Silence unused variable warnings.") #endif #endif
#include <type_traits> #include "absl/base/internal/inline_variable.h" #include "absl/base/internal/inline_variable_testing.h" #include "gtest/gtest.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace inline_variable_testing_internal { namespace { TEST(InlineVariableTest, Constexpr) { static_assert(inline_variable_foo.value == 5, ""); static_assert(other_inline_variable_foo.value == 5, ""); static_assert(inline_variable_int == 5, ""); static_assert(other_inline_variable_int == 5, ""); } TEST(InlineVariableTest, DefaultConstructedIdentityEquality) { EXPECT_EQ(get_foo_a().value, 5); EXPECT_EQ(get_foo_b().value, 5); EXPECT_EQ(&get_foo_a(), &get_foo_b()); } TEST(InlineVariableTest, DefaultConstructedIdentityInequality) { EXPECT_NE(&inline_variable_foo, &other_inline_variable_foo); } TEST(InlineVariableTest, InitializedIdentityEquality) { EXPECT_EQ(get_int_a(), 5); EXPECT_EQ(get_int_b(), 5); EXPECT_EQ(&get_int_a(), &get_int_b()); } TEST(InlineVariableTest, InitializedIdentityInequality) { EXPECT_NE(&inline_variable_int, &other_inline_variable_int); } TEST(InlineVariableTest, FunPtrType) { static_assert( std::is_same<void(*)(), std::decay<decltype(inline_variable_fun_ptr)>::type>::value, ""); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/inline_variable.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/inline_variable_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
138ea3dc-4705-493e-91f7-16b9d6230197
cpp
abseil/abseil-cpp
atomic_hook
absl/base/internal/atomic_hook.h
absl/base/internal/atomic_hook_test.cc
#ifndef ABSL_BASE_INTERNAL_ATOMIC_HOOK_H_ #define ABSL_BASE_INTERNAL_ATOMIC_HOOK_H_ #include <atomic> #include <cassert> #include <cstdint> #include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" #if defined(_MSC_VER) && !defined(__clang__) #define ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT 0 #else #define ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT 1 #endif #if defined(_MSC_VER) #define ABSL_HAVE_WORKING_ATOMIC_POINTER 0 #else #define ABSL_HAVE_WORKING_ATOMIC_POINTER 1 #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { template <typename T> class AtomicHook; #if ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT #define ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_CONST_INIT #else #define ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES #endif template <typename ReturnType, typename... Args> class AtomicHook<ReturnType (*)(Args...)> { public: using FnPtr = ReturnType (*)(Args...); constexpr AtomicHook() : AtomicHook(DummyFunction) {} #if ABSL_HAVE_WORKING_ATOMIC_POINTER && ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT explicit constexpr AtomicHook(FnPtr default_fn) : hook_(default_fn), default_fn_(default_fn) {} #elif ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT explicit constexpr AtomicHook(FnPtr default_fn) : hook_(kUninitialized), default_fn_(default_fn) {} #else explicit constexpr AtomicHook(FnPtr default_fn) : default_fn_(default_fn) { static_assert(kUninitialized == 0, "here we rely on zero-initialization"); } #endif void Store(FnPtr fn) { bool success = DoStore(fn); static_cast<void>(success); assert(success); } template <typename... CallArgs> ReturnType operator()(CallArgs&&... args) const { return DoLoad()(std::forward<CallArgs>(args)...); } FnPtr Load() const { FnPtr ptr = DoLoad(); return (ptr == DummyFunction) ? nullptr : ptr; } private: static ReturnType DummyFunction(Args...) { return ReturnType(); } #if ABSL_HAVE_WORKING_ATOMIC_POINTER FnPtr DoLoad() const { return hook_.load(std::memory_order_acquire); } bool DoStore(FnPtr fn) { assert(fn); FnPtr expected = default_fn_; const bool store_succeeded = hook_.compare_exchange_strong( expected, fn, std::memory_order_acq_rel, std::memory_order_acquire); const bool same_value_already_stored = (expected == fn); return store_succeeded || same_value_already_stored; } std::atomic<FnPtr> hook_; #else static constexpr intptr_t kUninitialized = 0; static_assert(sizeof(intptr_t) >= sizeof(FnPtr), "intptr_t can't contain a function pointer"); FnPtr DoLoad() const { const intptr_t value = hook_.load(std::memory_order_acquire); if (value == kUninitialized) { return default_fn_; } return reinterpret_cast<FnPtr>(value); } bool DoStore(FnPtr fn) { assert(fn); const auto value = reinterpret_cast<intptr_t>(fn); intptr_t expected = kUninitialized; const bool store_succeeded = hook_.compare_exchange_strong( expected, value, std::memory_order_acq_rel, std::memory_order_acquire); const bool same_value_already_stored = (expected == value); return store_succeeded || same_value_already_stored; } std::atomic<intptr_t> hook_; #endif const FnPtr default_fn_; }; #undef ABSL_HAVE_WORKING_ATOMIC_POINTER #undef ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT } ABSL_NAMESPACE_END } #endif
#include "absl/base/internal/atomic_hook.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/internal/atomic_hook_test_helper.h" namespace { using ::testing::Eq; int value = 0; void TestHook(int x) { value = x; } TEST(AtomicHookTest, NoDefaultFunction) { ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static absl::base_internal::AtomicHook< void (*)(int)> hook; value = 0; EXPECT_TRUE(hook.Load() == nullptr); EXPECT_EQ(value, 0); hook(1); EXPECT_EQ(value, 0); hook.Store(TestHook); EXPECT_TRUE(hook.Load() == TestHook); EXPECT_EQ(value, 0); hook(1); EXPECT_EQ(value, 1); hook.Store(TestHook); EXPECT_TRUE(hook.Load() == TestHook); EXPECT_EQ(value, 1); hook(2); EXPECT_EQ(value, 2); } TEST(AtomicHookTest, WithDefaultFunction) { ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static absl::base_internal::AtomicHook< void (*)(int)> hook(TestHook); value = 0; EXPECT_TRUE(hook.Load() == TestHook); EXPECT_EQ(value, 0); hook(1); EXPECT_EQ(value, 1); hook.Store(TestHook); EXPECT_TRUE(hook.Load() == TestHook); EXPECT_EQ(value, 1); hook(2); EXPECT_EQ(value, 2); } ABSL_CONST_INIT int override_func_calls = 0; void OverrideFunc() { override_func_calls++; } static struct OverrideInstaller { OverrideInstaller() { absl::atomic_hook_internal::func.Store(OverrideFunc); } } override_installer; TEST(AtomicHookTest, DynamicInitFromAnotherTU) { EXPECT_THAT(absl::atomic_hook_internal::default_func_calls, Eq(0)); EXPECT_THAT(override_func_calls, Eq(0)); absl::atomic_hook_internal::func(); EXPECT_THAT(absl::atomic_hook_internal::default_func_calls, Eq(0)); EXPECT_THAT(override_func_calls, Eq(1)); EXPECT_THAT(absl::atomic_hook_internal::func.Load(), Eq(OverrideFunc)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/atomic_hook.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/atomic_hook_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e50c6436-3cc2-4531-a08c-393da93254c3
cpp
abseil/abseil-cpp
utility
absl/utility/utility.h
absl/utility/utility_test.cc
#ifndef ABSL_UTILITY_UTILITY_H_ #define ABSL_UTILITY_UTILITY_H_ #include <cstddef> #include <cstdlib> #include <tuple> #include <utility> #include "absl/base/config.h" #include "absl/base/internal/inline_variable.h" #include "absl/base/internal/invoke.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN using std::exchange; using std::forward; using std::index_sequence; using std::index_sequence_for; using std::integer_sequence; using std::make_index_sequence; using std::make_integer_sequence; using std::move; namespace utility_internal { template <typename T> struct InPlaceTypeTag { explicit InPlaceTypeTag() = delete; InPlaceTypeTag(const InPlaceTypeTag&) = delete; InPlaceTypeTag& operator=(const InPlaceTypeTag&) = delete; }; template <size_t I> struct InPlaceIndexTag { explicit InPlaceIndexTag() = delete; InPlaceIndexTag(const InPlaceIndexTag&) = delete; InPlaceIndexTag& operator=(const InPlaceIndexTag&) = delete; }; } #ifdef ABSL_USES_STD_OPTIONAL using std::in_place_t; using std::in_place; #else struct in_place_t {}; ABSL_INTERNAL_INLINE_CONSTEXPR(in_place_t, in_place, {}); #endif #if defined(ABSL_USES_STD_ANY) || defined(ABSL_USES_STD_VARIANT) using std::in_place_type; using std::in_place_type_t; #else template <typename T> using in_place_type_t = void (*)(utility_internal::InPlaceTypeTag<T>); template <typename T> void in_place_type(utility_internal::InPlaceTypeTag<T>) {} #endif #ifdef ABSL_USES_STD_VARIANT using std::in_place_index; using std::in_place_index_t; #else template <size_t I> using in_place_index_t = void (*)(utility_internal::InPlaceIndexTag<I>); template <size_t I> void in_place_index(utility_internal::InPlaceIndexTag<I>) {} #endif namespace utility_internal { template <typename Functor, typename Tuple, std::size_t... Indexes> auto apply_helper(Functor&& functor, Tuple&& t, index_sequence<Indexes...>) -> decltype(absl::base_internal::invoke( absl::forward<Functor>(functor), std::get<Indexes>(absl::forward<Tuple>(t))...)) { return absl::base_internal::invoke( absl::forward<Functor>(functor), std::get<Indexes>(absl::forward<Tuple>(t))...); } } template <typename Functor, typename Tuple> auto apply(Functor&& functor, Tuple&& t) -> decltype(utility_internal::apply_helper( absl::forward<Functor>(functor), absl::forward<Tuple>(t), absl::make_index_sequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>{})) { return utility_internal::apply_helper( absl::forward<Functor>(functor), absl::forward<Tuple>(t), absl::make_index_sequence<std::tuple_size< typename std::remove_reference<Tuple>::type>::value>{}); } namespace utility_internal { template <typename T, typename Tuple, size_t... I> T make_from_tuple_impl(Tuple&& tup, absl::index_sequence<I...>) { return T(std::get<I>(std::forward<Tuple>(tup))...); } } template <typename T, typename Tuple> constexpr T make_from_tuple(Tuple&& tup) { return utility_internal::make_from_tuple_impl<T>( std::forward<Tuple>(tup), absl::make_index_sequence< std::tuple_size<absl::decay_t<Tuple>>::value>{}); } ABSL_NAMESPACE_END } #endif
#include "absl/utility/utility.h" #include <memory> #include <sstream> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" namespace { using ::testing::ElementsAre; using ::testing::Pointee; using ::testing::StaticAssertTypeEq; int Function(int a, int b) { return a - b; } int Sink(std::unique_ptr<int> p) { return *p; } std::unique_ptr<int> Factory(int n) { return absl::make_unique<int>(n); } void NoOp() {} struct ConstFunctor { int operator()(int a, int b) const { return a - b; } }; struct MutableFunctor { int operator()(int a, int b) { return a - b; } }; struct EphemeralFunctor { EphemeralFunctor() {} EphemeralFunctor(const EphemeralFunctor&) {} EphemeralFunctor(EphemeralFunctor&&) {} int operator()(int a, int b) && { return a - b; } }; struct OverloadedFunctor { OverloadedFunctor() {} OverloadedFunctor(const OverloadedFunctor&) {} OverloadedFunctor(OverloadedFunctor&&) {} template <typename... Args> std::string operator()(const Args&... args) & { return absl::StrCat("&", args...); } template <typename... Args> std::string operator()(const Args&... args) const& { return absl::StrCat("const&", args...); } template <typename... Args> std::string operator()(const Args&... args) && { return absl::StrCat("&&", args...); } }; struct Class { int Method(int a, int b) { return a - b; } int ConstMethod(int a, int b) const { return a - b; } int member; }; struct FlipFlop { int ConstMethod() const { return member; } FlipFlop operator*() const { return {-member}; } int member; }; TEST(ApplyTest, Function) { EXPECT_EQ(1, absl::apply(Function, std::make_tuple(3, 2))); EXPECT_EQ(1, absl::apply(&Function, std::make_tuple(3, 2))); } TEST(ApplyTest, NonCopyableArgument) { EXPECT_EQ(42, absl::apply(Sink, std::make_tuple(absl::make_unique<int>(42)))); } TEST(ApplyTest, NonCopyableResult) { EXPECT_THAT(absl::apply(Factory, std::make_tuple(42)), Pointee(42)); } TEST(ApplyTest, VoidResult) { absl::apply(NoOp, std::tuple<>()); } TEST(ApplyTest, ConstFunctor) { EXPECT_EQ(1, absl::apply(ConstFunctor(), std::make_tuple(3, 2))); } TEST(ApplyTest, MutableFunctor) { MutableFunctor f; EXPECT_EQ(1, absl::apply(f, std::make_tuple(3, 2))); EXPECT_EQ(1, absl::apply(MutableFunctor(), std::make_tuple(3, 2))); } TEST(ApplyTest, EphemeralFunctor) { EphemeralFunctor f; EXPECT_EQ(1, absl::apply(std::move(f), std::make_tuple(3, 2))); EXPECT_EQ(1, absl::apply(EphemeralFunctor(), std::make_tuple(3, 2))); } TEST(ApplyTest, OverloadedFunctor) { OverloadedFunctor f; const OverloadedFunctor& cf = f; EXPECT_EQ("&", absl::apply(f, std::tuple<>{})); EXPECT_EQ("& 42", absl::apply(f, std::make_tuple(" 42"))); EXPECT_EQ("const&", absl::apply(cf, std::tuple<>{})); EXPECT_EQ("const& 42", absl::apply(cf, std::make_tuple(" 42"))); EXPECT_EQ("&&", absl::apply(std::move(f), std::tuple<>{})); OverloadedFunctor f2; EXPECT_EQ("&& 42", absl::apply(std::move(f2), std::make_tuple(" 42"))); } TEST(ApplyTest, ReferenceWrapper) { ConstFunctor cf; MutableFunctor mf; EXPECT_EQ(1, absl::apply(std::cref(cf), std::make_tuple(3, 2))); EXPECT_EQ(1, absl::apply(std::ref(cf), std::make_tuple(3, 2))); EXPECT_EQ(1, absl::apply(std::ref(mf), std::make_tuple(3, 2))); } TEST(ApplyTest, MemberFunction) { std::unique_ptr<Class> p(new Class); std::unique_ptr<const Class> cp(new Class); EXPECT_EQ( 1, absl::apply(&Class::Method, std::tuple<std::unique_ptr<Class>&, int, int>(p, 3, 2))); EXPECT_EQ(1, absl::apply(&Class::Method, std::tuple<Class*, int, int>(p.get(), 3, 2))); EXPECT_EQ( 1, absl::apply(&Class::Method, std::tuple<Class&, int, int>(*p, 3, 2))); EXPECT_EQ( 1, absl::apply(&Class::ConstMethod, std::tuple<std::unique_ptr<Class>&, int, int>(p, 3, 2))); EXPECT_EQ(1, absl::apply(&Class::ConstMethod, std::tuple<Class*, int, int>(p.get(), 3, 2))); EXPECT_EQ(1, absl::apply(&Class::ConstMethod, std::tuple<Class&, int, int>(*p, 3, 2))); EXPECT_EQ(1, absl::apply(&Class::ConstMethod, std::tuple<std::unique_ptr<const Class>&, int, int>( cp, 3, 2))); EXPECT_EQ(1, absl::apply(&Class::ConstMethod, std::tuple<const Class*, int, int>(cp.get(), 3, 2))); EXPECT_EQ(1, absl::apply(&Class::ConstMethod, std::tuple<const Class&, int, int>(*cp, 3, 2))); EXPECT_EQ(1, absl::apply(&Class::Method, std::make_tuple(absl::make_unique<Class>(), 3, 2))); EXPECT_EQ(1, absl::apply(&Class::ConstMethod, std::make_tuple(absl::make_unique<Class>(), 3, 2))); EXPECT_EQ( 1, absl::apply(&Class::ConstMethod, std::make_tuple(absl::make_unique<const Class>(), 3, 2))); } TEST(ApplyTest, DataMember) { std::unique_ptr<Class> p(new Class{42}); std::unique_ptr<const Class> cp(new Class{42}); EXPECT_EQ( 42, absl::apply(&Class::member, std::tuple<std::unique_ptr<Class>&>(p))); EXPECT_EQ(42, absl::apply(&Class::member, std::tuple<Class&>(*p))); EXPECT_EQ(42, absl::apply(&Class::member, std::tuple<Class*>(p.get()))); absl::apply(&Class::member, std::tuple<std::unique_ptr<Class>&>(p)) = 42; absl::apply(&Class::member, std::tuple<Class*>(p.get())) = 42; absl::apply(&Class::member, std::tuple<Class&>(*p)) = 42; EXPECT_EQ(42, absl::apply(&Class::member, std::tuple<std::unique_ptr<const Class>&>(cp))); EXPECT_EQ(42, absl::apply(&Class::member, std::tuple<const Class&>(*cp))); EXPECT_EQ(42, absl::apply(&Class::member, std::tuple<const Class*>(cp.get()))); } TEST(ApplyTest, FlipFlop) { FlipFlop obj = {42}; EXPECT_EQ(42, absl::apply(&FlipFlop::ConstMethod, std::make_tuple(obj))); EXPECT_EQ(42, absl::apply(&FlipFlop::member, std::make_tuple(obj))); } TEST(MakeFromTupleTest, String) { EXPECT_EQ( absl::make_from_tuple<std::string>(std::make_tuple("hello world", 5)), "hello"); } TEST(MakeFromTupleTest, MoveOnlyParameter) { struct S { S(std::unique_ptr<int> n, std::unique_ptr<int> m) : value(*n + *m) {} int value = 0; }; auto tup = std::make_tuple(absl::make_unique<int>(3), absl::make_unique<int>(4)); auto s = absl::make_from_tuple<S>(std::move(tup)); EXPECT_EQ(s.value, 7); } TEST(MakeFromTupleTest, NoParameters) { struct S { S() : value(1) {} int value = 2; }; EXPECT_EQ(absl::make_from_tuple<S>(std::make_tuple()).value, 1); } TEST(MakeFromTupleTest, Pair) { EXPECT_EQ( (absl::make_from_tuple<std::pair<bool, int>>(std::make_tuple(true, 17))), std::make_pair(true, 17)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/utility/utility.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/utility/utility_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5e496d9c-b87f-43ee-8d8a-c81eda25d937
cpp
abseil/abseil-cpp
if_constexpr
absl/utility/internal/if_constexpr.h
absl/utility/internal/if_constexpr_test.cc
#ifndef ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_ #define ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_ #include <tuple> #include <utility> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace utility_internal { template <bool condition, typename TrueFunc, typename FalseFunc, typename... Args> auto IfConstexprElse(TrueFunc&& true_func, FalseFunc&& false_func, Args&&... args) { return std::get<condition>(std::forward_as_tuple( std::forward<FalseFunc>(false_func), std::forward<TrueFunc>(true_func)))( std::forward<Args>(args)...); } template <bool condition, typename Func, typename... Args> void IfConstexpr(Func&& func, Args&&... args) { IfConstexprElse<condition>(std::forward<Func>(func), [](auto&&...){}, std::forward<Args>(args)...); } } ABSL_NAMESPACE_END } #endif
#include "absl/utility/internal/if_constexpr.h" #include <utility> #include "gtest/gtest.h" namespace { struct Empty {}; struct HasFoo { int foo() const { return 1; } }; TEST(IfConstexpr, Basic) { int i = 0; absl::utility_internal::IfConstexpr<false>( [&](const auto& t) { i = t.foo(); }, Empty{}); EXPECT_EQ(i, 0); absl::utility_internal::IfConstexpr<false>( [&](const auto& t) { i = t.foo(); }, HasFoo{}); EXPECT_EQ(i, 0); absl::utility_internal::IfConstexpr<true>( [&](const auto& t) { i = t.foo(); }, HasFoo{}); EXPECT_EQ(i, 1); } TEST(IfConstexprElse, Basic) { EXPECT_EQ(absl::utility_internal::IfConstexprElse<false>( [&](const auto& t) { return t.foo(); }, [&](const auto&) { return 2; }, Empty{}), 2); EXPECT_EQ(absl::utility_internal::IfConstexprElse<false>( [&](const auto& t) { return t.foo(); }, [&](const auto&) { return 2; }, HasFoo{}), 2); EXPECT_EQ(absl::utility_internal::IfConstexprElse<true>( [&](const auto& t) { return t.foo(); }, [&](const auto&) { return 2; }, HasFoo{}), 1); } struct HasFooRValue { int foo() && { return 1; } }; struct RValueFunc { void operator()(HasFooRValue&& t) && { *i = std::move(t).foo(); } int* i = nullptr; }; TEST(IfConstexpr, RValues) { int i = 0; RValueFunc func = {&i}; absl::utility_internal::IfConstexpr<false>( std::move(func), HasFooRValue{}); EXPECT_EQ(i, 0); func = RValueFunc{&i}; absl::utility_internal::IfConstexpr<true>( std::move(func), HasFooRValue{}); EXPECT_EQ(i, 1); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/utility/internal/if_constexpr.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/utility/internal/if_constexpr_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
1eef252f-b593-42e7-a947-2258d0d1a228
cpp
google/libphonenumber
generate_geocoding_data
tools/cpp/src/cpp-build/generate_geocoding_data.cc
tools/cpp/test/cpp-build/generate_geocoding_data_test.cc
#include "cpp-build/generate_geocoding_data.h" #include <dirent.h> #include <errno.h> #include <locale> #include <sys/stat.h> #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstring> #include <iomanip> #include <iterator> #include <map> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "absl/container/btree_map.h" #include "absl/container/btree_set.h" namespace i18n { namespace phonenumbers { using std::map; using std::string; using std::vector; using std::set; using std::pair; template <typename ResourceType> class AutoCloser { public: typedef int (*ReleaseFunction) (ResourceType* resource); AutoCloser(ResourceType** resource, ReleaseFunction release_function) : resource_(resource), release_function_(release_function) {} ~AutoCloser() { Close(); } ResourceType* get_resource() const { return *resource_; } void Close() { if (*resource_) { release_function_(*resource_); *resource_ = NULL; } } private: ResourceType** resource_; ReleaseFunction release_function_; }; enum DirEntryKinds { kFile = 0, kDirectory = 1, }; class DirEntry { public: DirEntry(const char* n, DirEntryKinds k) : name_(n), kind_(k) {} const std::string& name() const { return name_; } DirEntryKinds kind() const { return kind_; } private: std::string name_; DirEntryKinds kind_; }; bool ListDirectory(const string& path, vector<DirEntry>* entries) { entries->clear(); DIR* dir = opendir(path.c_str()); if (!dir) { return false; } AutoCloser<DIR> dir_closer(&dir, closedir); struct dirent *entry; struct stat entry_stat; while (true) { errno = 0; entry = readdir(dir); if (entry == NULL) { return errno == 0; } if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } const string entry_path = path + "/" + entry->d_name; if (stat(entry_path.c_str(), &entry_stat)) { return false; } DirEntryKinds kind = kFile; if (S_ISDIR(entry_stat.st_mode)) { kind = kDirectory; } else if (!S_ISREG(entry_stat.st_mode)) { continue; } entries->push_back(DirEntry(entry->d_name, kind)); } } bool EndsWith(const string& s, const string& suffix) { if (suffix.length() > s.length()) { return false; } return std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } bool StrToInt(const string& s, int32* n) { std::stringstream stream; stream << s; stream >> *n; return !stream.fail(); } bool IntToStr(int32 n, string* s) { std::stringstream stream; stream << n; stream >> *s; return !stream.fail(); } bool ParsePrefixes(const string& path, absl::btree_map<int32, string>* prefixes) { prefixes->clear(); FILE* input = fopen(path.c_str(), "r"); if (!input) { return false; } AutoCloser<FILE> input_closer(&input, fclose); const int kMaxLineLength = 2*1024; vector<char> buffer(kMaxLineLength); vector<char>::iterator begin, end, sep; string prefix, description; int32 prefix_code; while (fgets(&buffer[0], buffer.size(), input)) { begin = buffer.begin(); end = std::find(begin, buffer.end(), '\0'); if (end == begin) { continue; } --end; if (*end != '\n' && !feof(input)) { return false; } for (; begin != end && std::isspace(*begin); ++begin) {} for (; end != begin && std::isspace(*(end - 1)); --end) {} if (begin == end || *begin == '#') { continue; } sep = std::find(begin, end, '|'); if (sep == end) { continue; } prefix = string(begin, sep); if (!StrToInt(prefix, &prefix_code)) { return false; } (*prefixes)[prefix_code] = string(sep + 1, end); } return ferror(input) == 0; } string MakeStringLiteral(const string& s) { std::stringstream buffer; int prev_is_hex = 0; buffer << std::hex << std::setfill('0'); buffer << "\""; for (string::const_iterator it = s.begin(); it != s.end(); ++it) { const char c = *it; if (c >= 32 && c < 127) { if (prev_is_hex == 2) { buffer << "\"\""; } if (c == '\'') { buffer << "\\"; } buffer << c; prev_is_hex = 1; } else { if (prev_is_hex != 0) { buffer << "\"\""; } buffer << "\\x" << std::setw(2) << (c < 0 ? c + 256 : c); prev_is_hex = 2; } } buffer << "\""; return buffer.str(); } void WriteStringLiteral(const string& s, FILE* output) { string literal = MakeStringLiteral(s); fprintf(output, "%s", literal.c_str()); } const char kLicense[] = " " " " " " " " " " " "implied.\n" " " " " "\n"; void WriteLicense(FILE* output) { fprintf(output, "%s", kLicense); } const char kI18NNS[] = "i18n"; const char kPhoneNumbersNS[] = "phonenumbers"; void WriteNSHeader(FILE* output) { fprintf(output, "namespace %s {\n", kI18NNS); fprintf(output, "namespace %s {\n", kPhoneNumbersNS); } void WriteNSFooter(FILE* output) { fprintf(output, "} fprintf(output, "} } void WriteCppHeader(const string& base_name, FILE* output) { fprintf(output, "#include \"phonenumbers/geocoding/%s.h\"\n", base_name.c_str()); fprintf(output, "\n"); fprintf(output, "#include <cstdint>\n"); fprintf(output, "\n"); } void WriteArrayAndSize(const string& name, FILE* output) { fprintf(output, " %s,\n", name.c_str()); fprintf(output, " sizeof(%s)/sizeof(*%s),\n", name.c_str(), name.c_str()); } void WritePrefixDescriptionsDefinition( const string& name, const string& prefixes_name, const string& desc_name, const string& possible_lengths_name, FILE* output) { fprintf(output, "const PrefixDescriptions %s = {\n", name.c_str()); WriteArrayAndSize(prefixes_name, output); fprintf(output, " %s,\n", desc_name.c_str()); WriteArrayAndSize(possible_lengths_name, output); fprintf(output, "};\n"); } void WritePrefixDescriptions(const string& var_name, const absl::btree_map<int, string>& prefixes, FILE* output) { absl::btree_set<int> possible_lengths; const string prefixes_name = var_name + "_prefixes"; fprintf(output, "const int32_t %s[] = {\n", prefixes_name.c_str()); for (absl::btree_map<int, string>::const_iterator it = prefixes.begin(); it != prefixes.end(); ++it) { fprintf(output, " %d,\n", it->first); possible_lengths.insert(static_cast<int>(log10(it->first) + 1)); } fprintf(output, "};\n" "\n"); const string desc_name = var_name + "_descriptions"; fprintf(output, "const char* %s[] = {\n", desc_name.c_str()); for (absl::btree_map<int, string>::const_iterator it = prefixes.begin(); it != prefixes.end(); ++it) { fprintf(output, " "); WriteStringLiteral(it->second, output); fprintf(output, ",\n"); } fprintf(output, "};\n" "\n"); const string possible_lengths_name = var_name + "_possible_lengths"; fprintf(output, "const int32_t %s[] = {\n ", possible_lengths_name.c_str()); for (absl::btree_set<int>::const_iterator it = possible_lengths.begin(); it != possible_lengths.end(); ++it) { fprintf(output, " %d,", *it); } fprintf(output, "\n" "};\n" "\n"); WritePrefixDescriptionsDefinition(var_name, prefixes_name, desc_name, possible_lengths_name, output); fprintf(output, "\n"); } void WritePrefixesDescriptions( const absl::btree_map<string, string>& prefix_var_names, FILE* output) { fprintf(output, "const char* prefix_language_code_pairs[] = {\n"); for (absl::btree_map<string, string>::const_iterator it = prefix_var_names.begin(); it != prefix_var_names.end(); ++it) { fprintf(output, " \"%s\",\n", it->first.c_str()); } fprintf(output, "};\n" "\n" "const PrefixDescriptions* prefixes_descriptions[] = {\n"); for (absl::btree_map<string, string>::const_iterator it = prefix_var_names.begin(); it != prefix_var_names.end(); ++it) { fprintf(output, " &%s,\n", it->second.c_str()); } fprintf(output, "};\n" "\n"); } bool WriteCountryLanguages(const map<int32, set<string> >& languages, FILE* output) { vector<string> country_languages_vars; vector<string> countries; for (map<int32, set<string> >::const_iterator it = languages.begin(); it != languages.end(); ++it) { string country_code; if (!IntToStr(it->first, &country_code)) { return false; } const string country_var = "country_" + country_code; fprintf(output, "const char* %s[] = {\n", country_var.c_str()); for (set<string>::const_iterator it_lang = it->second.begin(); it_lang != it->second.end(); ++it_lang) { fprintf(output, " \"%s\",\n", it_lang->c_str()); } fprintf(output, "};\n" "\n"); const string country_languages_var = country_var + "_languages"; fprintf(output, "const CountryLanguages %s = {\n", country_languages_var.c_str()); WriteArrayAndSize(country_var, output); fprintf(output, "};\n" "\n"); country_languages_vars.push_back(country_languages_var); countries.push_back(country_code); } fprintf(output, "\n" "const CountryLanguages* countries_languages[] = {\n"); for (vector<string>::const_iterator it_languages_var = country_languages_vars.begin(); it_languages_var != country_languages_vars.end(); ++it_languages_var) { fprintf(output, " &%s,\n", it_languages_var->c_str()); } fprintf(output, "};\n" "\n" "const int country_calling_codes[] = {\n"); for (vector<string>::const_iterator it_country = countries.begin(); it_country != countries.end(); ++it_country) { fprintf(output, " %s,\n", it_country->c_str()); } fprintf(output, "};\n" "\n"); return true; } string ReplaceAll(const string& input, const string& pattern, const string& value) { if (pattern.size() == 0) { return input; } string replaced; std::back_insert_iterator<string> output = std::back_inserter(replaced); string::const_iterator begin = input.begin(), end = begin; while (true) { const size_t pos = input.find(pattern, begin - input.begin()); if (pos == string::npos) { std::copy(begin, input.end(), output); break; } end = input.begin() + pos; std::copy(begin, end, output); std::copy(value.begin(), value.end(), output); begin = end + pattern.length(); } return replaced; } void WriteAccessorsDefinitions(const string& accessor_prefix, FILE* output) { string templ = "const int* get$prefix$_country_calling_codes() {\n" " return country_calling_codes;\n" "}\n" "\n" "int get$prefix$_country_calling_codes_size() {\n" " return sizeof(country_calling_codes)\n" " /sizeof(*country_calling_codes);\n" "}\n" "\n" "const CountryLanguages* get$prefix$_country_languages(int index) {\n" " return countries_languages[index];\n" "}\n" "\n" "const char** get$prefix$_prefix_language_code_pairs() {\n" " return prefix_language_code_pairs;\n" "}\n" "\n" "int get$prefix$_prefix_language_code_pairs_size() {\n" " return sizeof(prefix_language_code_pairs)\n" " /sizeof(*prefix_language_code_pairs);\n" "}\n" "\n" "const PrefixDescriptions* get$prefix$_prefix_descriptions(int index) {\n" " return prefixes_descriptions[index];\n" "}\n"; string defs = ReplaceAll(templ, "$prefix$", accessor_prefix); fprintf(output, "%s", defs.c_str()); } bool WriteSource(const string& data_path, const string& base_name, const string& accessor_prefix, FILE* output) { WriteLicense(output); WriteCppHeader(base_name, output); WriteNSHeader(output); fprintf(output, "namespace {\n" "\n"); absl::btree_map<string, string> prefix_vars; map<int32, set<string> > country_languages; vector<DirEntry> entries; if (!ListDirectory(data_path, &entries)) { fprintf(stderr, "failed to read directory entries"); return false; } for (vector<DirEntry>::const_iterator it = entries.begin(); it != entries.end(); ++it) { if (it->kind() != kDirectory) { continue; } const string dir_path = data_path + "/" + it->name(); vector<DirEntry> files; if (!ListDirectory(dir_path, &files)) { fprintf(stderr, "failed to read file entries\n"); return false; } for (vector<DirEntry>::const_iterator it_files = files.begin(); it_files != files.end(); ++it_files) { const string fname = it_files->name(); if (!EndsWith(fname, ".txt")) { continue; } int32 country_code; const string country_code_str = fname.substr(0, fname.length() - 4); if (!StrToInt(country_code_str, &country_code)) { return false; } const string path = dir_path + "/" + fname; absl::btree_map<int32, string> prefixes; if (!ParsePrefixes(path, &prefixes)) { return false; } const string prefix_var = "prefix_" + country_code_str + "_" + it->name(); WritePrefixDescriptions(prefix_var, prefixes, output); prefix_vars[country_code_str + "_" + it->name()] = prefix_var; country_languages[country_code].insert(it->name()); } } WritePrefixesDescriptions(prefix_vars, output); if (!WriteCountryLanguages(country_languages, output)) { return false; } fprintf(output, "} fprintf(output, "\n"); WriteAccessorsDefinitions(accessor_prefix, output); WriteNSFooter(output); return ferror(output) == 0; } int PrintHelp(const string& message) { fprintf(stderr, "error: %s\n", message.c_str()); fprintf(stderr, "generate_geocoding_data DATADIR CCPATH"); return 1; } int Main(int argc, const char* argv[]) { if (argc < 2) { return PrintHelp("geocoding data root directory expected"); } if (argc < 3) { return PrintHelp("output source path expected"); } string accessor_prefix = ""; if (argc > 3) { accessor_prefix = argv[3]; } const string root_path(argv[1]); string source_path(argv[2]); std::replace(source_path.begin(), source_path.end(), '\\', '/'); string base_name = source_path; if (base_name.rfind('/') != string::npos) { base_name = base_name.substr(base_name.rfind('/') + 1); } base_name = base_name.substr(0, base_name.rfind('.')); FILE* source_fp = fopen(source_path.c_str(), "w"); if (!source_fp) { fprintf(stderr, "failed to open %s\n", source_path.c_str()); return 1; } AutoCloser<FILE> source_closer(&source_fp, fclose); if (!WriteSource(root_path, base_name, accessor_prefix, source_fp)) { return 1; } return 0; } } }
#include "cpp-build/generate_geocoding_data.h" #include <gtest/gtest.h> namespace i18n { namespace phonenumbers { TEST(GenerateGeocodingDataTest, TestMakeStringLiteral) { EXPECT_EQ("\"\"", MakeStringLiteral("")); EXPECT_EQ("\"Op\"\"\\xc3\"\"\\xa9\"\"ra\"", MakeStringLiteral("Op\xc3\xa9ra")); } TEST(GenerateGeocodingDataTest, TestReplaceAll) { EXPECT_EQ("", ReplaceAll("", "$input$", "cc")); EXPECT_EQ("accb", ReplaceAll("a$input$b", "$input$", "cc")); EXPECT_EQ("ab", ReplaceAll("a$input$b", "$input$", "")); EXPECT_EQ("ab", ReplaceAll("ab", "", "cc")); EXPECT_EQ("acdc", ReplaceAll("a$input$d$input$", "$input$", "c")); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/tools/cpp/src/cpp-build/generate_geocoding_data.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/tools/cpp/test/cpp-build/generate_geocoding_data_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
6475b107-a6ce-4c24-b567-5dba680f88ba
cpp
google/libphonenumber
phonenumbermatch
cpp/src/phonenumbers/phonenumbermatch.cc
cpp/test/phonenumbers/phonenumbermatch_test.cc
#include "phonenumbers/phonenumbermatch.h" #include <string> #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/stringutil.h" namespace i18n { namespace phonenumbers { PhoneNumberMatch::PhoneNumberMatch(int start, const string& raw_string, const PhoneNumber& number) : start_(start), raw_string_(raw_string), number_(number) { } PhoneNumberMatch::PhoneNumberMatch() : start_(-1), raw_string_(""), number_(PhoneNumber::default_instance()) { } const PhoneNumber& PhoneNumberMatch::number() const { return number_; } int PhoneNumberMatch::start() const { return start_; } int PhoneNumberMatch::end() const { return static_cast<int>(start_ + raw_string_.length()); } int PhoneNumberMatch::length() const { return static_cast<int>(raw_string_.length()); } const string& PhoneNumberMatch::raw_string() const { return raw_string_; } void PhoneNumberMatch::set_start(int start) { start_ = start; } void PhoneNumberMatch::set_raw_string(const string& raw_string) { raw_string_ = raw_string; } void PhoneNumberMatch::set_number(const PhoneNumber& number) { number_.CopyFrom(number); } string PhoneNumberMatch::ToString() const { return StrCat("PhoneNumberMatch [", start(), ",", end(), ") ", raw_string_.c_str()); } bool PhoneNumberMatch::Equals(const PhoneNumberMatch& match) const { return ExactlySameAs(match.number_, number_) && match.raw_string_.compare(raw_string_) == 0 && match.start_ == start_; } void PhoneNumberMatch::CopyFrom(const PhoneNumberMatch& match) { raw_string_ = match.raw_string(); start_ = match.start(); number_ = match.number(); } } }
#include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumbermatch.h" #include <gtest/gtest.h> #include "phonenumbers/phonenumber.pb.h" namespace i18n { namespace phonenumbers { TEST(PhoneNumberMatch, TestGetterMethods) { PhoneNumber number; const int start_index = 10; const string raw_phone_number("1 800 234 45 67"); PhoneNumberMatch match1(start_index, raw_phone_number, number); EXPECT_EQ(start_index, match1.start()); EXPECT_EQ(start_index + static_cast<int>(raw_phone_number.length()), match1.end()); EXPECT_EQ(static_cast<int>(raw_phone_number.length()), match1.length()); EXPECT_EQ(raw_phone_number, match1.raw_string()); EXPECT_EQ("PhoneNumberMatch [10,25) 1 800 234 45 67", match1.ToString()); } TEST(PhoneNumberMatch, TestEquals) { PhoneNumber number; PhoneNumberMatch match1(10, "1 800 234 45 67", number); PhoneNumberMatch match2(10, "1 800 234 45 67", number); match2.set_start(11); ASSERT_FALSE(match1.Equals(match2)); match2.set_start(match1.start()); EXPECT_TRUE(match1.Equals(match2)); PhoneNumber number2; number2.set_raw_input("123"); match2.set_number(number2); ASSERT_FALSE(match1.Equals(match2)); match2.set_number(match1.number()); EXPECT_TRUE(ExactlySameAs(match1.number(), match2.number())); EXPECT_TRUE(match1.Equals(match2)); match2.set_raw_string("123"); ASSERT_FALSE(match1.Equals(match2)); } TEST(PhoneNumberMatch, TestAssignmentOverload) { PhoneNumber number; PhoneNumberMatch match1(10, "1 800 234 45 67", number); PhoneNumberMatch match2; ASSERT_FALSE(match1.Equals(match2)); match2.CopyFrom(match1); ASSERT_TRUE(match1.Equals(match2)); PhoneNumberMatch match3; PhoneNumberMatch match4; match4.CopyFrom(match2); match3.CopyFrom(match2); ASSERT_TRUE(match3.Equals(match4)); ASSERT_TRUE(match4.Equals(match2)); } TEST(PhoneNumberMatch, TestCopyConstructor) { PhoneNumber number; PhoneNumberMatch match1(10, "1 800 234 45 67", number); PhoneNumberMatch match2; match2.CopyFrom(match1); ASSERT_TRUE(match1.Equals(match2)); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/phonenumbermatch.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/phonenumbermatch_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
17e61239-1dca-4b8b-a5dd-20c400f1ed09
cpp
google/libphonenumber
phonenumberutil
cpp/src/phonenumbers/phonenumberutil.cc
cpp/test/phonenumbers/phonenumberutil_test.cc
#include "phonenumbers/phonenumberutil.h" #include <algorithm> #include <cctype> #include <cstring> #include <iterator> #include <map> #include <utility> #include <vector> #include <unicode/uchar.h> #include <unicode/utf8.h> #include "phonenumbers/asyoutypeformatter.h" #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/logging.h" #include "phonenumbers/base/memory/singleton.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/encoding_utils.h" #include "phonenumbers/matcher_api.h" #include "phonenumbers/metadata.h" #include "phonenumbers/normalize_utf8.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/regex_based_matcher.h" #include "phonenumbers/regexp_adapter.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/regexp_factory.h" #include "phonenumbers/region_code.h" #include "phonenumbers/stl_util.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/utf/unicodetext.h" #include "phonenumbers/utf/utf.h" namespace i18n { namespace phonenumbers { using google::protobuf::RepeatedField; using gtl::OrderByFirst; const size_t PhoneNumberUtil::kMinLengthForNsn; const size_t PhoneNumberUtil::kMaxLengthForNsn; const size_t PhoneNumberUtil::kMaxLengthCountryCode; const int PhoneNumberUtil::kNanpaCountryCode; const char PhoneNumberUtil::kPlusChars[] = "+\xEF\xBC\x8B"; const char PhoneNumberUtil::kValidPunctuation[] = "-x\xE2\x80\x90-\xE2\x80\x95\xE2\x88\x92\xE3\x83\xBC\xEF\xBC\x8D-\xEF\xBC" "\x8F \xC2\xA0\xC2\xAD\xE2\x80\x8B\xE2\x81\xA0\xE3\x80\x80()\xEF\xBC\x88" "\xEF\xBC\x89\xEF\xBC\xBB\xEF\xBC\xBD.\\[\\]/~\xE2\x81\x93\xE2\x88\xBC"; const char PhoneNumberUtil::kCaptureUpToSecondNumberStart[] = "(.*)[\\\\/] *x"; const char PhoneNumberUtil::kRegionCodeForNonGeoEntity[] = "001"; namespace { const char kPlusSign[] = "+"; const char kStarSign[] = "*"; const char kRfc3966ExtnPrefix[] = ";ext="; const char kRfc3966Prefix[] = "tel:"; const char kRfc3966PhoneContext[] = ";phone-context="; const char kRfc3966IsdnSubaddress[] = ";isub="; const char kRfc3966VisualSeparator[] = "[\\-\\.\\(\\)]?"; const char kDigits[] = "\\p{Nd}"; const char kValidAlpha[] = "a-z"; const char kValidAlphaInclUppercase[] = "A-Za-z"; const char kDefaultExtnPrefix[] = " ext. "; const char kPossibleSeparatorsBetweenNumberAndExtLabel[] = "[ \xC2\xA0\\t,]*"; const char kPossibleCharsAfterExtLabel[] = "[:\\.\xEF\xBC\x8E]?[ \xC2\xA0\\t,-]*"; const char kOptionalExtSuffix[] = "#?"; bool LoadCompiledInMetadata(PhoneMetadataCollection* metadata) { if (!metadata->ParseFromArray(metadata_get(), metadata_size())) { LOG(ERROR) << "Could not parse binary data."; return false; } return true; } const PhoneNumberDesc* GetNumberDescByType( const PhoneMetadata& metadata, PhoneNumberUtil::PhoneNumberType type) { switch (type) { case PhoneNumberUtil::PREMIUM_RATE: return &metadata.premium_rate(); case PhoneNumberUtil::TOLL_FREE: return &metadata.toll_free(); case PhoneNumberUtil::MOBILE: return &metadata.mobile(); case PhoneNumberUtil::FIXED_LINE: case PhoneNumberUtil::FIXED_LINE_OR_MOBILE: return &metadata.fixed_line(); case PhoneNumberUtil::SHARED_COST: return &metadata.shared_cost(); case PhoneNumberUtil::VOIP: return &metadata.voip(); case PhoneNumberUtil::PERSONAL_NUMBER: return &metadata.personal_number(); case PhoneNumberUtil::PAGER: return &metadata.pager(); case PhoneNumberUtil::UAN: return &metadata.uan(); case PhoneNumberUtil::VOICEMAIL: return &metadata.voicemail(); default: return &metadata.general_desc(); } } void PrefixNumberWithCountryCallingCode( int country_calling_code, PhoneNumberUtil::PhoneNumberFormat number_format, std::string* formatted_number) { switch (number_format) { case PhoneNumberUtil::E164: formatted_number->insert(0, StrCat(kPlusSign, country_calling_code)); return; case PhoneNumberUtil::INTERNATIONAL: formatted_number->insert(0, StrCat(kPlusSign, country_calling_code, " ")); return; case PhoneNumberUtil::RFC3966: formatted_number->insert(0, StrCat(kRfc3966Prefix, kPlusSign, country_calling_code, "-")); return; case PhoneNumberUtil::NATIONAL: default: return; } } bool IsNationalNumberSuffixOfTheOther(const PhoneNumber& first_number, const PhoneNumber& second_number) { const std::string& first_number_national_number = SimpleItoa(static_cast<uint64>(first_number.national_number())); const std::string& second_number_national_number = SimpleItoa(static_cast<uint64>(second_number.national_number())); return HasSuffixString(first_number_national_number, second_number_national_number) || HasSuffixString(second_number_national_number, first_number_national_number); } char32 ToUnicodeCodepoint(const char* unicode_char) { char32 codepoint; EncodingUtils::DecodeUTF8Char(unicode_char, &codepoint); return codepoint; } std::string ExtnDigits(int max_length) { return StrCat("([", kDigits, "]{1,", max_length, "})"); } std::string CreateExtnPattern(bool for_parsing) { int ext_limit_after_explicit_label = 20; int ext_limit_after_likely_label = 15; int ext_limit_after_ambiguous_char = 9; int ext_limit_when_not_sure = 6; std::string explicit_ext_labels = "(?:e?xt(?:ensi(?:o\xCC\x81?|\xC3\xB3))?n?|(?:\xEF\xBD\x85)?" "\xEF\xBD\x98\xEF\xBD\x94(?:\xEF\xBD\x8E)?|\xD0\xB4\xD0\xBE\xD0\xB1|" "anexo)"; std::string ambiguous_ext_labels = "(?:[x\xEF\xBD\x98#\xEF\xBC\x83~\xEF\xBD\x9E]|int|" "\xEF\xBD\x89\xEF\xBD\x8E\xEF\xBD\x94)"; std::string ambiguous_separator = "[- ]+"; std::string rfc_extn = StrCat( kRfc3966ExtnPrefix, ExtnDigits(ext_limit_after_explicit_label)); std::string explicit_extn = StrCat( kPossibleSeparatorsBetweenNumberAndExtLabel, explicit_ext_labels, kPossibleCharsAfterExtLabel, ExtnDigits(ext_limit_after_explicit_label), kOptionalExtSuffix); std::string ambiguous_extn = StrCat( kPossibleSeparatorsBetweenNumberAndExtLabel, ambiguous_ext_labels, kPossibleCharsAfterExtLabel, ExtnDigits(ext_limit_after_ambiguous_char), kOptionalExtSuffix); std::string american_style_extn_with_suffix = StrCat( ambiguous_separator, ExtnDigits(ext_limit_when_not_sure), "#"); std::string extension_pattern = StrCat(rfc_extn, "|", explicit_extn, "|", ambiguous_extn, "|", american_style_extn_with_suffix); if (for_parsing) { std::string auto_dialling_and_ext_labels_found = "(?:,{2}|;)"; std::string possible_separators_number_extLabel_no_comma = "[ \xC2\xA0\\t]*"; std::string auto_dialling_extn = StrCat( possible_separators_number_extLabel_no_comma, auto_dialling_and_ext_labels_found, kPossibleCharsAfterExtLabel, ExtnDigits(ext_limit_after_likely_label), kOptionalExtSuffix); std::string only_commas_extn = StrCat( possible_separators_number_extLabel_no_comma, "(?:,)+", kPossibleCharsAfterExtLabel, ExtnDigits(ext_limit_after_ambiguous_char), kOptionalExtSuffix); return StrCat(extension_pattern, "|", auto_dialling_extn, "|", only_commas_extn); } return extension_pattern; } void NormalizeHelper(const std::map<char32, char>& normalization_replacements, bool remove_non_matches, string* number) { DCHECK(number); UnicodeText number_as_unicode; number_as_unicode.PointToUTF8(number->data(), static_cast<int>(number->size())); if (!number_as_unicode.UTF8WasValid()) { number->clear(); return; } std::string normalized_number; char unicode_char[5]; for (UnicodeText::const_iterator it = number_as_unicode.begin(); it != number_as_unicode.end(); ++it) { std::map<char32, char>::const_iterator found_glyph_pair = normalization_replacements.find(*it); if (found_glyph_pair != normalization_replacements.end()) { normalized_number.push_back(found_glyph_pair->second); } else if (!remove_non_matches) { int char_len = it.get_utf8(unicode_char); normalized_number.append(unicode_char, char_len); } } number->assign(normalized_number); } bool DescHasPossibleNumberData(const PhoneNumberDesc& desc) { return desc.possible_length_size() != 1 || desc.possible_length(0) != -1; } bool DescHasData(const PhoneNumberDesc& desc) { return desc.has_example_number() || DescHasPossibleNumberData(desc) || desc.has_national_number_pattern(); } void GetSupportedTypesForMetadata( const PhoneMetadata& metadata, std::set<PhoneNumberUtil::PhoneNumberType>* types) { DCHECK(types); for (int i = 0; i <= static_cast<int>(PhoneNumberUtil::kMaxNumberType); ++i) { PhoneNumberUtil::PhoneNumberType type = static_cast<PhoneNumberUtil::PhoneNumberType>(i); if (type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE || type == PhoneNumberUtil::UNKNOWN) { continue; } if (DescHasData(*GetNumberDescByType(metadata, type))) { types->insert(type); } } } PhoneNumberUtil::ValidationResult TestNumberLength( const std::string& number, const PhoneMetadata& metadata, PhoneNumberUtil::PhoneNumberType type) { const PhoneNumberDesc* desc_for_type = GetNumberDescByType(metadata, type); RepeatedField<int> possible_lengths = desc_for_type->possible_length_size() == 0 ? metadata.general_desc().possible_length() : desc_for_type->possible_length(); RepeatedField<int> local_lengths = desc_for_type->possible_length_local_only(); if (type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE) { const PhoneNumberDesc* fixed_line_desc = GetNumberDescByType(metadata, PhoneNumberUtil::FIXED_LINE); if (!DescHasPossibleNumberData(*fixed_line_desc)) { return TestNumberLength(number, metadata, PhoneNumberUtil::MOBILE); } else { const PhoneNumberDesc* mobile_desc = GetNumberDescByType(metadata, PhoneNumberUtil::MOBILE); if (DescHasPossibleNumberData(*mobile_desc)) { possible_lengths.MergeFrom( mobile_desc->possible_length_size() == 0 ? metadata.general_desc().possible_length() : mobile_desc->possible_length()); std::sort(possible_lengths.begin(), possible_lengths.end()); if (local_lengths.size() == 0) { local_lengths = mobile_desc->possible_length_local_only(); } else { local_lengths.MergeFrom(mobile_desc->possible_length_local_only()); std::sort(local_lengths.begin(), local_lengths.end()); } } } } if (possible_lengths.Get(0) == -1) { return PhoneNumberUtil::INVALID_LENGTH; } int actual_length = static_cast<int>(number.length()); if (std::find(local_lengths.begin(), local_lengths.end(), actual_length) != local_lengths.end()) { return PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY; } int minimum_length = possible_lengths.Get(0); if (minimum_length == actual_length) { return PhoneNumberUtil::IS_POSSIBLE; } else if (minimum_length > actual_length) { return PhoneNumberUtil::TOO_SHORT; } else if (*(possible_lengths.end() - 1) < actual_length) { return PhoneNumberUtil::TOO_LONG; } return std::find(possible_lengths.begin() + 1, possible_lengths.end(), actual_length) != possible_lengths.end() ? PhoneNumberUtil::IS_POSSIBLE : PhoneNumberUtil::INVALID_LENGTH; } PhoneNumberUtil::ValidationResult TestNumberLength( const std::string& number, const PhoneMetadata& metadata) { return TestNumberLength(number, metadata, PhoneNumberUtil::UNKNOWN); } void CopyCoreFieldsOnly(const PhoneNumber& number, PhoneNumber* pruned_number) { pruned_number->set_country_code(number.country_code()); pruned_number->set_national_number(number.national_number()); if (!number.extension().empty()) { pruned_number->set_extension(number.extension()); } if (number.italian_leading_zero()) { pruned_number->set_italian_leading_zero(true); pruned_number->set_number_of_leading_zeros( number.number_of_leading_zeros()); } } bool IsMatch(const MatcherApi& matcher_api, const std::string& number, const PhoneNumberDesc& desc) { return matcher_api.MatchNationalNumber(number, desc, false); } } void PhoneNumberUtil::SetLogger(Logger* logger) { logger_.reset(logger); Logger::set_logger_impl(logger_.get()); } class PhoneNumberRegExpsAndMappings { private: void InitializeMapsAndSets() { diallable_char_mappings_.insert(std::make_pair('+', '+')); diallable_char_mappings_.insert(std::make_pair('*', '*')); diallable_char_mappings_.insert(std::make_pair('#', '#')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("-"), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xEF\xBC\x8D" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x80\x90" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x80\x91" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x80\x92" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x80\x93" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x80\x94" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x80\x95" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x88\x92" ), '-')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("/"), '/')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xEF\xBC\x8F" ), '/')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint(" "), ' ')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE3\x80\x80" ), ' ')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xE2\x81\xA0"), ' ')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("."), '.')); all_plus_number_grouping_symbols_.insert( std::make_pair(ToUnicodeCodepoint("\xEF\xBC\x8E" ), '.')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("A"), '2')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("B"), '2')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("C"), '2')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("D"), '3')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("E"), '3')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("F"), '3')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("G"), '4')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("H"), '4')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("I"), '4')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("J"), '5')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("K"), '5')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("L"), '5')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("M"), '6')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("N"), '6')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("O"), '6')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("P"), '7')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("Q"), '7')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("R"), '7')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("S"), '7')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("T"), '8')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("U"), '8')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("V"), '8')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("W"), '9')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("X"), '9')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("Y"), '9')); alpha_mappings_.insert(std::make_pair(ToUnicodeCodepoint("Z"), '9')); std::map<char32, char> lower_case_mappings; std::map<char32, char> alpha_letters; for (std::map<char32, char>::const_iterator it = alpha_mappings_.begin(); it != alpha_mappings_.end(); ++it) { if (it->first < 128) { char letter_as_upper = static_cast<char>(it->first); char32 letter_as_lower = static_cast<char32>(tolower(letter_as_upper)); lower_case_mappings.insert(std::make_pair(letter_as_lower, it->second)); alpha_letters.insert(std::make_pair(letter_as_lower, letter_as_upper)); alpha_letters.insert(std::make_pair(it->first, letter_as_upper)); } } alpha_mappings_.insert(lower_case_mappings.begin(), lower_case_mappings.end()); alpha_phone_mappings_.insert(alpha_mappings_.begin(), alpha_mappings_.end()); all_plus_number_grouping_symbols_.insert(alpha_letters.begin(), alpha_letters.end()); for (char c = '0'; c <= '9'; ++c) { diallable_char_mappings_.insert(std::make_pair(c, c)); alpha_phone_mappings_.insert(std::make_pair(c, c)); all_plus_number_grouping_symbols_.insert(std::make_pair(c, c)); } mobile_token_mappings_.insert(std::make_pair(54, '9')); countries_without_national_prefix_with_area_codes_.insert(52); geo_mobile_countries_without_mobile_area_codes_.insert(86); geo_mobile_countries_.insert(52); geo_mobile_countries_.insert(54); geo_mobile_countries_.insert(55); geo_mobile_countries_.insert(62); geo_mobile_countries_.insert( geo_mobile_countries_without_mobile_area_codes_.begin(), geo_mobile_countries_without_mobile_area_codes_.end()); } const std::string valid_phone_number_; const std::string extn_patterns_for_parsing_; const std::string rfc3966_phone_digit_; const std::string alphanum_; const std::string rfc3966_domainlabel_; const std::string rfc3966_toplabel_; public: scoped_ptr<const AbstractRegExpFactory> regexp_factory_; scoped_ptr<RegExpCache> regexp_cache_; std::map<char32, char> diallable_char_mappings_; std::map<char32, char> alpha_mappings_; std::map<char32, char> alpha_phone_mappings_; std::map<char32, char> all_plus_number_grouping_symbols_; std::map<int, char> mobile_token_mappings_; std::set<int> countries_without_national_prefix_with_area_codes_; std::set<int> geo_mobile_countries_without_mobile_area_codes_; std::set<int> geo_mobile_countries_; scoped_ptr<const RegExp> single_international_prefix_; scoped_ptr<const RegExp> digits_pattern_; scoped_ptr<const RegExp> capturing_digit_pattern_; scoped_ptr<const RegExp> capturing_ascii_digits_pattern_; scoped_ptr<const RegExp> valid_start_char_pattern_; scoped_ptr<const RegExp> capture_up_to_second_number_start_pattern_; scoped_ptr<const RegExp> unwanted_end_char_pattern_; scoped_ptr<const RegExp> separator_pattern_; const std::string extn_patterns_for_matching_; scoped_ptr<const RegExp> extn_pattern_; scoped_ptr<const RegExp> valid_phone_number_pattern_; scoped_ptr<const RegExp> valid_alpha_phone_pattern_; scoped_ptr<const RegExp> first_group_capturing_pattern_; scoped_ptr<const RegExp> carrier_code_pattern_; scoped_ptr<const RegExp> plus_chars_pattern_; std::unique_ptr<const RegExp> rfc3966_global_number_digits_pattern_; std::unique_ptr<const RegExp> rfc3966_domainname_pattern_; PhoneNumberRegExpsAndMappings() : valid_phone_number_( StrCat(kDigits, "{", PhoneNumberUtil::kMinLengthForNsn, "}|[", PhoneNumberUtil::kPlusChars, "]*(?:[", PhoneNumberUtil::kValidPunctuation, kStarSign, "]*", kDigits, "){3,}[", PhoneNumberUtil::kValidPunctuation, kStarSign, kValidAlpha, kDigits, "]*")), extn_patterns_for_parsing_(CreateExtnPattern( true)), rfc3966_phone_digit_( StrCat("(", kDigits, "|", kRfc3966VisualSeparator, ")")), alphanum_(StrCat(kValidAlphaInclUppercase, kDigits)), rfc3966_domainlabel_( StrCat("[", alphanum_, "]+((\\-)*[", alphanum_, "])*")), rfc3966_toplabel_(StrCat("[", kValidAlphaInclUppercase, "]+((\\-)*[", alphanum_, "])*")), regexp_factory_(new RegExpFactory()), regexp_cache_(new RegExpCache(*regexp_factory_.get(), 128)), diallable_char_mappings_(), alpha_mappings_(), alpha_phone_mappings_(), all_plus_number_grouping_symbols_(), mobile_token_mappings_(), countries_without_national_prefix_with_area_codes_(), geo_mobile_countries_without_mobile_area_codes_(), geo_mobile_countries_(), single_international_prefix_(regexp_factory_->CreateRegExp( "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?")), digits_pattern_( regexp_factory_->CreateRegExp(StrCat("[", kDigits, "]*"))), capturing_digit_pattern_( regexp_factory_->CreateRegExp(StrCat("([", kDigits, "])"))), capturing_ascii_digits_pattern_( regexp_factory_->CreateRegExp("(\\d+)")), valid_start_char_pattern_(regexp_factory_->CreateRegExp( StrCat("[", PhoneNumberUtil::kPlusChars, kDigits, "]"))), capture_up_to_second_number_start_pattern_( regexp_factory_->CreateRegExp( PhoneNumberUtil::kCaptureUpToSecondNumberStart)), unwanted_end_char_pattern_( regexp_factory_->CreateRegExp("[^\\p{N}\\p{L}#]")), separator_pattern_(regexp_factory_->CreateRegExp( StrCat("[", PhoneNumberUtil::kValidPunctuation, "]+"))), extn_patterns_for_matching_( CreateExtnPattern( false)), extn_pattern_(regexp_factory_->CreateRegExp( StrCat("(?i)(?:", extn_patterns_for_parsing_, ")$"))), valid_phone_number_pattern_(regexp_factory_->CreateRegExp( StrCat("(?i)", valid_phone_number_, "(?:", extn_patterns_for_parsing_, ")?"))), valid_alpha_phone_pattern_(regexp_factory_->CreateRegExp( StrCat("(?i)(?:.*?[", kValidAlpha, "]){3}"))), first_group_capturing_pattern_( regexp_factory_->CreateRegExp("(\\$\\d)")), carrier_code_pattern_(regexp_factory_->CreateRegExp("\\$CC")), plus_chars_pattern_(regexp_factory_->CreateRegExp( StrCat("[", PhoneNumberUtil::kPlusChars, "]+"))), rfc3966_global_number_digits_pattern_(regexp_factory_->CreateRegExp( StrCat("^\\", kPlusSign, rfc3966_phone_digit_, "*", kDigits, rfc3966_phone_digit_, "*$"))), rfc3966_domainname_pattern_(regexp_factory_->CreateRegExp(StrCat( "^(", rfc3966_domainlabel_, "\\.)*", rfc3966_toplabel_, "\\.?$"))) { InitializeMapsAndSets(); } PhoneNumberRegExpsAndMappings(const PhoneNumberRegExpsAndMappings&) = delete; PhoneNumberRegExpsAndMappings& operator=( const PhoneNumberRegExpsAndMappings&) = delete; }; PhoneNumberUtil::PhoneNumberUtil() : logger_(Logger::set_logger_impl(new NullLogger())), matcher_api_(new RegexBasedMatcher()), reg_exps_(new PhoneNumberRegExpsAndMappings), country_calling_code_to_region_code_map_( new std::vector<IntRegionsPair>()), nanpa_regions_(new absl::node_hash_set<std::string>()), region_to_metadata_map_(new absl::node_hash_map<std::string, PhoneMetadata>()), country_code_to_non_geographical_metadata_map_( new absl::node_hash_map<int, PhoneMetadata>) { Logger::set_logger_impl(logger_.get()); PhoneMetadataCollection metadata_collection; if (!LoadCompiledInMetadata(&metadata_collection)) { LOG(DFATAL) << "Could not parse compiled-in metadata."; return; } std::map<int, std::list<std::string>* > country_calling_code_to_region_map; for (RepeatedPtrField<PhoneMetadata>::const_iterator it = metadata_collection.metadata().begin(); it != metadata_collection.metadata().end(); ++it) { const std::string& region_code = it->id(); if (region_code == RegionCode::GetUnknown()) { continue; } int country_calling_code = it->country_code(); if (kRegionCodeForNonGeoEntity == region_code) { country_code_to_non_geographical_metadata_map_->insert( std::make_pair(country_calling_code, *it)); } else { region_to_metadata_map_->insert(std::make_pair(region_code, *it)); } std::map<int, std::list<std::string>* >::iterator calling_code_in_map = country_calling_code_to_region_map.find(country_calling_code); if (calling_code_in_map != country_calling_code_to_region_map.end()) { if (it->main_country_for_code()) { calling_code_in_map->second->push_front(region_code); } else { calling_code_in_map->second->push_back(region_code); } } else { std::list<std::string>* list_with_region_code = new std::list<std::string>(); list_with_region_code->push_back(region_code); country_calling_code_to_region_map.insert( std::make_pair(country_calling_code, list_with_region_code)); } if (country_calling_code == kNanpaCountryCode) { nanpa_regions_->insert(region_code); } } country_calling_code_to_region_code_map_->insert( country_calling_code_to_region_code_map_->begin(), country_calling_code_to_region_map.begin(), country_calling_code_to_region_map.end()); std::sort(country_calling_code_to_region_code_map_->begin(), country_calling_code_to_region_code_map_->end(), OrderByFirst()); } PhoneNumberUtil::~PhoneNumberUtil() { gtl::STLDeleteContainerPairSecondPointers( country_calling_code_to_region_code_map_->begin(), country_calling_code_to_region_code_map_->end()); } void PhoneNumberUtil::GetSupportedRegions(std::set<std::string>* regions) const { DCHECK(regions); for (absl::node_hash_map<std::string, PhoneMetadata>::const_iterator it = region_to_metadata_map_->begin(); it != region_to_metadata_map_->end(); ++it) { regions->insert(it->first); } } void PhoneNumberUtil::GetSupportedGlobalNetworkCallingCodes( std::set<int>* calling_codes) const { DCHECK(calling_codes); for (absl::node_hash_map<int, PhoneMetadata>::const_iterator it = country_code_to_non_geographical_metadata_map_->begin(); it != country_code_to_non_geographical_metadata_map_->end(); ++it) { calling_codes->insert(it->first); } } void PhoneNumberUtil::GetSupportedCallingCodes( std::set<int>* calling_codes) const { DCHECK(calling_codes); for (std::vector<IntRegionsPair>::const_iterator it = country_calling_code_to_region_code_map_->begin(); it != country_calling_code_to_region_code_map_->end(); ++it) { calling_codes->insert(it->first); } } void PhoneNumberUtil::GetSupportedTypesForRegion( const std::string& region_code, std::set<PhoneNumberType>* types) const { DCHECK(types); if (!IsValidRegionCode(region_code)) { LOG(WARNING) << "Invalid or unknown region code provided: " << region_code; return; } const PhoneMetadata* metadata = GetMetadataForRegion(region_code); GetSupportedTypesForMetadata(*metadata, types); } void PhoneNumberUtil::GetSupportedTypesForNonGeoEntity( int country_calling_code, std::set<PhoneNumberType>* types) const { DCHECK(types); const PhoneMetadata* metadata = GetMetadataForNonGeographicalRegion(country_calling_code); if (metadata == NULL) { LOG(WARNING) << "Unknown country calling code for a non-geographical " << "entity provided: " << country_calling_code; return; } GetSupportedTypesForMetadata(*metadata, types); } PhoneNumberUtil* PhoneNumberUtil::GetInstance() { return Singleton<PhoneNumberUtil>::GetInstance(); } const std::string& PhoneNumberUtil::GetExtnPatternsForMatching() const { return reg_exps_->extn_patterns_for_matching_; } bool PhoneNumberUtil::StartsWithPlusCharsPattern( const std::string& number) const { const scoped_ptr<RegExpInput> number_string_piece( reg_exps_->regexp_factory_->CreateInput(number)); return reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get()); } bool PhoneNumberUtil::ContainsOnlyValidDigits(const std::string& s) const { return reg_exps_->digits_pattern_->FullMatch(s); } void PhoneNumberUtil::TrimUnwantedEndChars(std::string* number) const { DCHECK(number); UnicodeText number_as_unicode; number_as_unicode.PointToUTF8(number->data(), static_cast<int>(number->size())); if (!number_as_unicode.UTF8WasValid()) { number->clear(); return; } char current_char[5]; int len; UnicodeText::const_reverse_iterator reverse_it(number_as_unicode.end()); for (; reverse_it.base() != number_as_unicode.begin(); ++reverse_it) { len = reverse_it.get_utf8(current_char); current_char[len] = '\0'; if (!reg_exps_->unwanted_end_char_pattern_->FullMatch(current_char)) { break; } } number->assign(UnicodeText::UTF8Substring(number_as_unicode.begin(), reverse_it.base())); } bool PhoneNumberUtil::IsFormatEligibleForAsYouTypeFormatter( const std::string& format) const { const RegExp& eligible_format_pattern = reg_exps_->regexp_cache_->GetRegExp( StrCat("[", kValidPunctuation, "]*", "\\$1", "[", kValidPunctuation, "]*", "(\\$\\d", "[", kValidPunctuation, "]*)*")); return eligible_format_pattern.FullMatch(format); } bool PhoneNumberUtil::FormattingRuleHasFirstGroupOnly( const std::string& national_prefix_formatting_rule) const { const RegExp& first_group_only_prefix_pattern = reg_exps_->regexp_cache_->GetRegExp("\\(?\\$1\\)?"); return national_prefix_formatting_rule.empty() || first_group_only_prefix_pattern.FullMatch( national_prefix_formatting_rule); } void PhoneNumberUtil::GetNddPrefixForRegion( const std::string& region_code, bool strip_non_digits, std::string* national_prefix) const { DCHECK(national_prefix); const PhoneMetadata* metadata = GetMetadataForRegion(region_code); if (!metadata) { LOG(WARNING) << "Invalid or unknown region code (" << region_code << ") provided."; return; } national_prefix->assign(metadata->national_prefix()); if (strip_non_digits) { strrmm(national_prefix, "~"); } } bool PhoneNumberUtil::IsValidRegionCode(const std::string& region_code) const { return (region_to_metadata_map_->find(region_code) != region_to_metadata_map_->end()); } bool PhoneNumberUtil::HasValidCountryCallingCode( int country_calling_code) const { IntRegionsPair target_pair; target_pair.first = country_calling_code; return (std::binary_search(country_calling_code_to_region_code_map_->begin(), country_calling_code_to_region_code_map_->end(), target_pair, OrderByFirst())); } const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegion( const std::string& region_code) const { absl::node_hash_map<std::string, PhoneMetadata>::const_iterator it = region_to_metadata_map_->find(region_code); if (it != region_to_metadata_map_->end()) { return &it->second; } return NULL; } const PhoneMetadata* PhoneNumberUtil::GetMetadataForNonGeographicalRegion( int country_calling_code) const { absl::node_hash_map<int, PhoneMetadata>::const_iterator it = country_code_to_non_geographical_metadata_map_->find( country_calling_code); if (it != country_code_to_non_geographical_metadata_map_->end()) { return &it->second; } return NULL; } void PhoneNumberUtil::Format(const PhoneNumber& number, PhoneNumberFormat number_format, std::string* formatted_number) const { DCHECK(formatted_number); if (number.national_number() == 0) { const std::string& raw_input = number.raw_input(); if (!raw_input.empty()) { formatted_number->assign(raw_input); return; } } int country_calling_code = number.country_code(); std::string national_significant_number; GetNationalSignificantNumber(number, &national_significant_number); if (number_format == E164) { formatted_number->assign(national_significant_number); PrefixNumberWithCountryCallingCode(country_calling_code, E164, formatted_number); return; } if (!HasValidCountryCallingCode(country_calling_code)) { formatted_number->assign(national_significant_number); return; } std::string region_code; GetRegionCodeForCountryCode(country_calling_code, &region_code); const PhoneMetadata* metadata = GetMetadataForRegionOrCallingCode(country_calling_code, region_code); FormatNsn(national_significant_number, *metadata, number_format, formatted_number); MaybeAppendFormattedExtension(number, *metadata, number_format, formatted_number); PrefixNumberWithCountryCallingCode(country_calling_code, number_format, formatted_number); } void PhoneNumberUtil::FormatByPattern( const PhoneNumber& number, PhoneNumberFormat number_format, const RepeatedPtrField<NumberFormat>& user_defined_formats, std::string* formatted_number) const { DCHECK(formatted_number); int country_calling_code = number.country_code(); std::string national_significant_number; GetNationalSignificantNumber(number, &national_significant_number); if (!HasValidCountryCallingCode(country_calling_code)) { formatted_number->assign(national_significant_number); return; } std::string region_code; GetRegionCodeForCountryCode(country_calling_code, &region_code); const PhoneMetadata* metadata = GetMetadataForRegionOrCallingCode(country_calling_code, region_code); const NumberFormat* formatting_pattern = ChooseFormattingPatternForNumber(user_defined_formats, national_significant_number); if (!formatting_pattern) { formatted_number->assign(national_significant_number); } else { NumberFormat num_format_copy; num_format_copy.MergeFrom(*formatting_pattern); std::string national_prefix_formatting_rule( formatting_pattern->national_prefix_formatting_rule()); if (!national_prefix_formatting_rule.empty()) { const std::string& national_prefix = metadata->national_prefix(); if (!national_prefix.empty()) { GlobalReplaceSubstring("$NP", national_prefix, &national_prefix_formatting_rule); GlobalReplaceSubstring("$FG", "$1", &national_prefix_formatting_rule); num_format_copy.set_national_prefix_formatting_rule( national_prefix_formatting_rule); } else { num_format_copy.clear_national_prefix_formatting_rule(); } } FormatNsnUsingPattern(national_significant_number, num_format_copy, number_format, formatted_number); } MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number); PrefixNumberWithCountryCallingCode(country_calling_code, number_format, formatted_number); } void PhoneNumberUtil::FormatNationalNumberWithCarrierCode( const PhoneNumber& number, const std::string& carrier_code, std::string* formatted_number) const { int country_calling_code = number.country_code(); std::string national_significant_number; GetNationalSignificantNumber(number, &national_significant_number); if (!HasValidCountryCallingCode(country_calling_code)) { formatted_number->assign(national_significant_number); return; } std::string region_code; GetRegionCodeForCountryCode(country_calling_code, &region_code); const PhoneMetadata* metadata = GetMetadataForRegionOrCallingCode(country_calling_code, region_code); FormatNsnWithCarrier(national_significant_number, *metadata, NATIONAL, carrier_code, formatted_number); MaybeAppendFormattedExtension(number, *metadata, NATIONAL, formatted_number); PrefixNumberWithCountryCallingCode(country_calling_code, NATIONAL, formatted_number); } const PhoneMetadata* PhoneNumberUtil::GetMetadataForRegionOrCallingCode( int country_calling_code, const std::string& region_code) const { return kRegionCodeForNonGeoEntity == region_code ? GetMetadataForNonGeographicalRegion(country_calling_code) : GetMetadataForRegion(region_code); } void PhoneNumberUtil::FormatNationalNumberWithPreferredCarrierCode( const PhoneNumber& number, const std::string& fallback_carrier_code, std::string* formatted_number) const { FormatNationalNumberWithCarrierCode( number, !number.preferred_domestic_carrier_code().empty() ? number.preferred_domestic_carrier_code() : fallback_carrier_code, formatted_number); } void PhoneNumberUtil::FormatNumberForMobileDialing( const PhoneNumber& number, const std::string& calling_from, bool with_formatting, std::string* formatted_number) const { int country_calling_code = number.country_code(); if (!HasValidCountryCallingCode(country_calling_code)) { formatted_number->assign(number.has_raw_input() ? number.raw_input() : ""); return; } formatted_number->assign(""); PhoneNumber number_no_extension(number); number_no_extension.clear_extension(); std::string region_code; GetRegionCodeForCountryCode(country_calling_code, &region_code); PhoneNumberType number_type = GetNumberType(number_no_extension); bool is_valid_number = (number_type != UNKNOWN); if (calling_from == region_code) { bool is_fixed_line_or_mobile = (number_type == FIXED_LINE) || (number_type == MOBILE) || (number_type == FIXED_LINE_OR_MOBILE); if ((region_code == "BR") && (is_fixed_line_or_mobile)) { if (!number_no_extension.preferred_domestic_carrier_code().empty()) { FormatNationalNumberWithPreferredCarrierCode(number_no_extension, "", formatted_number); } else { formatted_number->assign(""); } } else if (country_calling_code == kNanpaCountryCode) { const PhoneMetadata* region_metadata = GetMetadataForRegion(calling_from); std::string national_number; GetNationalSignificantNumber(number_no_extension, &national_number); if (CanBeInternationallyDialled(number_no_extension) && TestNumberLength(national_number, *region_metadata) != TOO_SHORT) { Format(number_no_extension, INTERNATIONAL, formatted_number); } else { Format(number_no_extension, NATIONAL, formatted_number); } } else { if ((region_code == kRegionCodeForNonGeoEntity || ((region_code == "MX" || region_code == "CL" || region_code == "UZ") && is_fixed_line_or_mobile)) && CanBeInternationallyDialled(number_no_extension)) { Format(number_no_extension, INTERNATIONAL, formatted_number); } else { Format(number_no_extension, NATIONAL, formatted_number); } } } else if (is_valid_number && CanBeInternationallyDialled(number_no_extension)) { with_formatting ? Format(number_no_extension, INTERNATIONAL, formatted_number) : Format(number_no_extension, E164, formatted_number); return; } if (!with_formatting) { NormalizeDiallableCharsOnly(formatted_number); } } void PhoneNumberUtil::FormatOutOfCountryCallingNumber( const PhoneNumber& number, const std::string& calling_from, std::string* formatted_number) const { DCHECK(formatted_number); if (!IsValidRegionCode(calling_from)) { VLOG(1) << "Trying to format number from invalid region " << calling_from << ". International formatting applied."; Format(number, INTERNATIONAL, formatted_number); return; } int country_code = number.country_code(); std::string national_significant_number; GetNationalSignificantNumber(number, &national_significant_number); if (!HasValidCountryCallingCode(country_code)) { formatted_number->assign(national_significant_number); return; } if (country_code == kNanpaCountryCode) { if (IsNANPACountry(calling_from)) { Format(number, NATIONAL, formatted_number); formatted_number->insert(0, StrCat(country_code, " ")); return; } } else if (country_code == GetCountryCodeForValidRegion(calling_from)) { Format(number, NATIONAL, formatted_number); return; } const PhoneMetadata* metadata_calling_from = GetMetadataForRegion(calling_from); const std::string& international_prefix = metadata_calling_from->international_prefix(); std::string international_prefix_for_formatting; if (metadata_calling_from->has_preferred_international_prefix()) { international_prefix_for_formatting = metadata_calling_from->preferred_international_prefix(); } else if (reg_exps_->single_international_prefix_->FullMatch( international_prefix)) { international_prefix_for_formatting = international_prefix; } std::string region_code; GetRegionCodeForCountryCode(country_code, &region_code); const PhoneMetadata* metadata_for_region = GetMetadataForRegionOrCallingCode(country_code, region_code); FormatNsn(national_significant_number, *metadata_for_region, INTERNATIONAL, formatted_number); MaybeAppendFormattedExtension(number, *metadata_for_region, INTERNATIONAL, formatted_number); if (!international_prefix_for_formatting.empty()) { formatted_number->insert( 0, StrCat(international_prefix_for_formatting, " ", country_code, " ")); } else { PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL, formatted_number); } } void PhoneNumberUtil::FormatInOriginalFormat( const PhoneNumber& number, const std::string& region_calling_from, std::string* formatted_number) const { DCHECK(formatted_number); if (number.has_raw_input() && !HasFormattingPatternForNumber(number)) { formatted_number->assign(number.raw_input()); return; } if (!number.has_country_code_source()) { Format(number, NATIONAL, formatted_number); return; } switch (number.country_code_source()) { case PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN: Format(number, INTERNATIONAL, formatted_number); break; case PhoneNumber::FROM_NUMBER_WITH_IDD: FormatOutOfCountryCallingNumber(number, region_calling_from, formatted_number); break; case PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN: Format(number, INTERNATIONAL, formatted_number); formatted_number->erase(formatted_number->begin()); break; case PhoneNumber::FROM_DEFAULT_COUNTRY: default: std::string region_code; GetRegionCodeForCountryCode(number.country_code(), &region_code); std::string national_prefix; GetNddPrefixForRegion(region_code, true , &national_prefix); if (national_prefix.empty()) { Format(number, NATIONAL, formatted_number); break; } if (RawInputContainsNationalPrefix(number.raw_input(), national_prefix, region_code)) { Format(number, NATIONAL, formatted_number); break; } const PhoneMetadata* metadata = GetMetadataForRegion(region_code); std::string national_number; GetNationalSignificantNumber(number, &national_number); const NumberFormat* format_rule = ChooseFormattingPatternForNumber(metadata->number_format(), national_number); if (!format_rule) { Format(number, NATIONAL, formatted_number); break; } std::string candidate_national_prefix_rule( format_rule->national_prefix_formatting_rule()); if (!candidate_national_prefix_rule.empty()) { size_t index_of_first_group = candidate_national_prefix_rule.find("$1"); if (index_of_first_group == std::string::npos) { LOG(ERROR) << "First group missing in national prefix rule: " << candidate_national_prefix_rule; Format(number, NATIONAL, formatted_number); break; } candidate_national_prefix_rule.erase(index_of_first_group); NormalizeDigitsOnly(&candidate_national_prefix_rule); } if (candidate_national_prefix_rule.empty()) { Format(number, NATIONAL, formatted_number); break; } RepeatedPtrField<NumberFormat> number_formats; NumberFormat* number_format = number_formats.Add(); number_format->MergeFrom(*format_rule); number_format->clear_national_prefix_formatting_rule(); FormatByPattern(number, NATIONAL, number_formats, formatted_number); break; } if (!formatted_number->empty() && !number.raw_input().empty()) { std::string normalized_formatted_number(*formatted_number); NormalizeDiallableCharsOnly(&normalized_formatted_number); std::string normalized_raw_input(number.raw_input()); NormalizeDiallableCharsOnly(&normalized_raw_input); if (normalized_formatted_number != normalized_raw_input) { formatted_number->assign(number.raw_input()); } } } bool PhoneNumberUtil::RawInputContainsNationalPrefix( const std::string& raw_input, const std::string& national_prefix, const std::string& region_code) const { std::string normalized_national_number(raw_input); NormalizeDigitsOnly(&normalized_national_number); if (HasPrefixString(normalized_national_number, national_prefix)) { PhoneNumber number_without_national_prefix; if (Parse(normalized_national_number.substr(national_prefix.length()), region_code, &number_without_national_prefix) == NO_PARSING_ERROR) { return IsValidNumber(number_without_national_prefix); } } return false; } bool PhoneNumberUtil::HasFormattingPatternForNumber( const PhoneNumber& number) const { int country_calling_code = number.country_code(); std::string region_code; GetRegionCodeForCountryCode(country_calling_code, &region_code); const PhoneMetadata* metadata = GetMetadataForRegionOrCallingCode(country_calling_code, region_code); if (!metadata) { return false; } std::string national_number; GetNationalSignificantNumber(number, &national_number); const NumberFormat* format_rule = ChooseFormattingPatternForNumber(metadata->number_format(), national_number); return format_rule; } void PhoneNumberUtil::FormatOutOfCountryKeepingAlphaChars( const PhoneNumber& number, const std::string& calling_from, std::string* formatted_number) const { if (number.raw_input().empty()) { FormatOutOfCountryCallingNumber(number, calling_from, formatted_number); return; } int country_code = number.country_code(); if (!HasValidCountryCallingCode(country_code)) { formatted_number->assign(number.raw_input()); return; } std::string raw_input_copy(number.raw_input()); NormalizeHelper(reg_exps_->all_plus_number_grouping_symbols_, true, &raw_input_copy); std::string national_number; GetNationalSignificantNumber(number, &national_number); if (national_number.length() > 3) { size_t first_national_number_digit = raw_input_copy.find(national_number.substr(0, 3)); if (first_national_number_digit != std::string::npos) { raw_input_copy = raw_input_copy.substr(first_national_number_digit); } } const PhoneMetadata* metadata = GetMetadataForRegion(calling_from); if (country_code == kNanpaCountryCode) { if (IsNANPACountry(calling_from)) { StrAppend(formatted_number, country_code, " ", raw_input_copy); return; } } else if (metadata && country_code == GetCountryCodeForValidRegion(calling_from)) { const NumberFormat* formatting_pattern = ChooseFormattingPatternForNumber(metadata->number_format(), national_number); if (!formatting_pattern) { formatted_number->assign(raw_input_copy); return; } NumberFormat new_format; new_format.MergeFrom(*formatting_pattern); new_format.set_pattern("(\\d+)(.*)"); new_format.set_format("$1$2"); FormatNsnUsingPattern(raw_input_copy, new_format, NATIONAL, formatted_number); return; } std::string international_prefix_for_formatting; if (metadata) { const std::string& international_prefix = metadata->international_prefix(); international_prefix_for_formatting = reg_exps_->single_international_prefix_->FullMatch(international_prefix) ? international_prefix : metadata->preferred_international_prefix(); } if (!international_prefix_for_formatting.empty()) { StrAppend(formatted_number, international_prefix_for_formatting, " ", country_code, " ", raw_input_copy); } else { if (!IsValidRegionCode(calling_from)) { VLOG(1) << "Trying to format number from invalid region " << calling_from << ". International formatting applied."; } formatted_number->assign(raw_input_copy); PrefixNumberWithCountryCallingCode(country_code, INTERNATIONAL, formatted_number); } } const NumberFormat* PhoneNumberUtil::ChooseFormattingPatternForNumber( const RepeatedPtrField<NumberFormat>& available_formats, const std::string& national_number) const { for (RepeatedPtrField<NumberFormat>::const_iterator it = available_formats.begin(); it != available_formats.end(); ++it) { int size = it->leading_digits_pattern_size(); if (size > 0) { const scoped_ptr<RegExpInput> number_copy( reg_exps_->regexp_factory_->CreateInput(national_number)); if (!reg_exps_->regexp_cache_->GetRegExp( it->leading_digits_pattern(size - 1)).Consume( number_copy.get())) { continue; } } const RegExp& pattern_to_match( reg_exps_->regexp_cache_->GetRegExp(it->pattern())); if (pattern_to_match.FullMatch(national_number)) { return &(*it); } } return NULL; } void PhoneNumberUtil::FormatNsnUsingPatternWithCarrier( const std::string& national_number, const NumberFormat& formatting_pattern, PhoneNumberUtil::PhoneNumberFormat number_format, const std::string& carrier_code, std::string* formatted_number) const { DCHECK(formatted_number); std::string number_format_rule(formatting_pattern.format()); if (number_format == PhoneNumberUtil::NATIONAL && carrier_code.length() > 0 && formatting_pattern.domestic_carrier_code_formatting_rule().length() > 0) { std::string carrier_code_formatting_rule = formatting_pattern.domestic_carrier_code_formatting_rule(); reg_exps_->carrier_code_pattern_->Replace(&carrier_code_formatting_rule, carrier_code); reg_exps_->first_group_capturing_pattern_-> Replace(&number_format_rule, carrier_code_formatting_rule); } else { std::string national_prefix_formatting_rule = formatting_pattern.national_prefix_formatting_rule(); if (number_format == PhoneNumberUtil::NATIONAL && national_prefix_formatting_rule.length() > 0) { reg_exps_->first_group_capturing_pattern_->Replace( &number_format_rule, national_prefix_formatting_rule); } } formatted_number->assign(national_number); const RegExp& pattern_to_match( reg_exps_->regexp_cache_->GetRegExp(formatting_pattern.pattern())); pattern_to_match.GlobalReplace(formatted_number, number_format_rule); if (number_format == RFC3966) { const scoped_ptr<RegExpInput> number( reg_exps_->regexp_factory_->CreateInput(*formatted_number)); if (reg_exps_->separator_pattern_->Consume(number.get())) { formatted_number->assign(number->ToString()); } reg_exps_->separator_pattern_->GlobalReplace(formatted_number, "-"); } } void PhoneNumberUtil::FormatNsnUsingPattern( const std::string& national_number, const NumberFormat& formatting_pattern, PhoneNumberUtil::PhoneNumberFormat number_format, std::string* formatted_number) const { DCHECK(formatted_number); FormatNsnUsingPatternWithCarrier(national_number, formatting_pattern, number_format, "", formatted_number); } void PhoneNumberUtil::FormatNsn(const std::string& number, const PhoneMetadata& metadata, PhoneNumberFormat number_format, std::string* formatted_number) const { DCHECK(formatted_number); FormatNsnWithCarrier(number, metadata, number_format, "", formatted_number); } void PhoneNumberUtil::FormatNsnWithCarrier( const std::string& number, const PhoneMetadata& metadata, PhoneNumberFormat number_format, const std::string& carrier_code, std::string* formatted_number) const { DCHECK(formatted_number); const RepeatedPtrField<NumberFormat> available_formats = (metadata.intl_number_format_size() == 0 || number_format == NATIONAL) ? metadata.number_format() : metadata.intl_number_format(); const NumberFormat* formatting_pattern = ChooseFormattingPatternForNumber(available_formats, number); if (!formatting_pattern) { formatted_number->assign(number); } else { FormatNsnUsingPatternWithCarrier(number, *formatting_pattern, number_format, carrier_code, formatted_number); } } void PhoneNumberUtil::MaybeAppendFormattedExtension( const PhoneNumber& number, const PhoneMetadata& metadata, PhoneNumberFormat number_format, std::string* formatted_number) const { DCHECK(formatted_number); if (number.has_extension() && number.extension().length() > 0) { if (number_format == RFC3966) { StrAppend(formatted_number, kRfc3966ExtnPrefix, number.extension()); } else { if (metadata.has_preferred_extn_prefix()) { StrAppend(formatted_number, metadata.preferred_extn_prefix(), number.extension()); } else { StrAppend(formatted_number, kDefaultExtnPrefix, number.extension()); } } } } bool PhoneNumberUtil::IsNANPACountry(const std::string& region_code) const { return nanpa_regions_->find(region_code) != nanpa_regions_->end(); } void PhoneNumberUtil::GetRegionCodesForCountryCallingCode( int country_calling_code, std::list<std::string>* region_codes) const { DCHECK(region_codes); IntRegionsPair target_pair; target_pair.first = country_calling_code; typedef std::vector<IntRegionsPair>::const_iterator ConstIterator; std::pair<ConstIterator, ConstIterator> range = std::equal_range(country_calling_code_to_region_code_map_->begin(), country_calling_code_to_region_code_map_->end(), target_pair, OrderByFirst()); if (range.first != range.second) { region_codes->insert(region_codes->begin(), range.first->second->begin(), range.first->second->end()); } } void PhoneNumberUtil::GetRegionCodeForCountryCode( int country_calling_code, std::string* region_code) const { DCHECK(region_code); std::list<std::string> region_codes; GetRegionCodesForCountryCallingCode(country_calling_code, &region_codes); *region_code = (region_codes.size() > 0) ? region_codes.front() : RegionCode::GetUnknown(); } void PhoneNumberUtil::GetRegionCodeForNumber( const PhoneNumber& number, std::string* region_code) const { DCHECK(region_code); int country_calling_code = number.country_code(); std::list<std::string> region_codes; GetRegionCodesForCountryCallingCode(country_calling_code, &region_codes); if (region_codes.size() == 0) { VLOG(1) << "Missing/invalid country calling code (" << country_calling_code << ")"; *region_code = RegionCode::GetUnknown(); return; } if (region_codes.size() == 1) { *region_code = region_codes.front(); } else { GetRegionCodeForNumberFromRegionList(number, region_codes, region_code); } } void PhoneNumberUtil::GetRegionCodeForNumberFromRegionList( const PhoneNumber& number, const std::list<std::string>& region_codes, std::string* region_code) const { DCHECK(region_code); std::string national_number; GetNationalSignificantNumber(number, &national_number); for (std::list<std::string>::const_iterator it = region_codes.begin(); it != region_codes.end(); ++it) { const PhoneMetadata* metadata = GetMetadataForRegion(*it); if (metadata->has_leading_digits()) { const scoped_ptr<RegExpInput> number( reg_exps_->regexp_factory_->CreateInput(national_number)); if (reg_exps_->regexp_cache_-> GetRegExp(metadata->leading_digits()).Consume(number.get())) { *region_code = *it; return; } } else if (GetNumberTypeHelper(national_number, *metadata) != UNKNOWN) { *region_code = *it; return; } } *region_code = RegionCode::GetUnknown(); } int PhoneNumberUtil::GetCountryCodeForRegion(const std::string& region_code) const { if (!IsValidRegionCode(region_code)) { LOG(WARNING) << "Invalid or unknown region code (" << region_code << ") provided."; return 0; } return GetCountryCodeForValidRegion(region_code); } int PhoneNumberUtil::GetCountryCodeForValidRegion( const std::string& region_code) const { const PhoneMetadata* metadata = GetMetadataForRegion(region_code); return metadata->country_code(); } bool PhoneNumberUtil::GetExampleNumber(const std::string& region_code, PhoneNumber* number) const { DCHECK(number); return GetExampleNumberForType(region_code, FIXED_LINE, number); } bool PhoneNumberUtil::GetInvalidExampleNumber(const std::string& region_code, PhoneNumber* number) const { DCHECK(number); if (!IsValidRegionCode(region_code)) { LOG(WARNING) << "Invalid or unknown region code (" << region_code << ") provided."; return false; } const PhoneMetadata* region_metadata = GetMetadataForRegion(region_code); const PhoneNumberDesc* desc = GetNumberDescByType(*region_metadata, FIXED_LINE); if (!desc->has_example_number()) { return false; } const std::string& example_number = desc->example_number(); for (size_t phone_number_length = example_number.length() - 1; phone_number_length >= kMinLengthForNsn; phone_number_length--) { std::string number_to_try = example_number.substr(0, phone_number_length); PhoneNumber possibly_valid_number; Parse(number_to_try, region_code, &possibly_valid_number); if (!IsValidNumber(possibly_valid_number)) { number->MergeFrom(possibly_valid_number); return true; } } return false; } bool PhoneNumberUtil::GetExampleNumberForType( const std::string& region_code, PhoneNumberUtil::PhoneNumberType type, PhoneNumber* number) const { DCHECK(number); if (!IsValidRegionCode(region_code)) { LOG(WARNING) << "Invalid or unknown region code (" << region_code << ") provided."; return false; } const PhoneMetadata* region_metadata = GetMetadataForRegion(region_code); const PhoneNumberDesc* desc = GetNumberDescByType(*region_metadata, type); if (desc && desc->has_example_number()) { ErrorType success = Parse(desc->example_number(), region_code, number); if (success == NO_PARSING_ERROR) { return true; } else { LOG(ERROR) << "Error parsing example number (" << static_cast<int>(success) << ")"; } } return false; } bool PhoneNumberUtil::GetExampleNumberForType( PhoneNumberUtil::PhoneNumberType type, PhoneNumber* number) const { DCHECK(number); std::set<std::string> regions; GetSupportedRegions(&regions); for (const std::string& region_code : regions) { if (GetExampleNumberForType(region_code, type, number)) { return true; } } std::set<int> global_network_calling_codes; GetSupportedGlobalNetworkCallingCodes(&global_network_calling_codes); for (std::set<int>::const_iterator it = global_network_calling_codes.begin(); it != global_network_calling_codes.end(); ++it) { int country_calling_code = *it; const PhoneMetadata* metadata = GetMetadataForNonGeographicalRegion(country_calling_code); const PhoneNumberDesc* desc = GetNumberDescByType(*metadata, type); if (desc->has_example_number()) { ErrorType success = Parse(StrCat(kPlusSign, country_calling_code, desc->example_number()), RegionCode::GetUnknown(), number); if (success == NO_PARSING_ERROR) { return true; } else { LOG(ERROR) << "Error parsing example number (" << static_cast<int>(success) << ")"; } } } return false; } bool PhoneNumberUtil::GetExampleNumberForNonGeoEntity( int country_calling_code, PhoneNumber* number) const { DCHECK(number); const PhoneMetadata* metadata = GetMetadataForNonGeographicalRegion(country_calling_code); if (metadata) { const int kNumberTypes = 7; PhoneNumberDesc types[kNumberTypes] = { metadata->mobile(), metadata->toll_free(), metadata->shared_cost(), metadata->voip(), metadata->voicemail(), metadata->uan(), metadata->premium_rate()}; for (int i = 0; i < kNumberTypes; ++i) { if (types[i].has_example_number()) { ErrorType success = Parse(StrCat(kPlusSign, SimpleItoa(country_calling_code), types[i].example_number()), RegionCode::GetUnknown(), number); if (success == NO_PARSING_ERROR) { return true; } else { LOG(ERROR) << "Error parsing example number (" << static_cast<int>(success) << ")"; } } } } else { LOG(WARNING) << "Invalid or unknown country calling code provided: " << country_calling_code; } return false; } PhoneNumberUtil::ErrorType PhoneNumberUtil::Parse( absl::string_view number_to_parse, const std::string& default_region, PhoneNumber* number) const { DCHECK(number); return ParseHelper(number_to_parse, default_region, false, true, number); } PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseAndKeepRawInput( absl::string_view number_to_parse, const std::string& default_region, PhoneNumber* number) const { DCHECK(number); return ParseHelper(number_to_parse, default_region, true, true, number); } bool PhoneNumberUtil::CheckRegionForParsing( const std::string& number_to_parse, const std::string& default_region) const { if (!IsValidRegionCode(default_region) && !number_to_parse.empty()) { const scoped_ptr<RegExpInput> number( reg_exps_->regexp_factory_->CreateInput(number_to_parse)); if (!reg_exps_->plus_chars_pattern_->Consume(number.get())) { return false; } } return true; } absl::optional<absl::string_view> PhoneNumberUtil::ExtractPhoneContext( const absl::string_view number_to_extract_from, const size_t index_of_phone_context) const { if (index_of_phone_context == std::string::npos) { return absl::nullopt; } size_t phone_context_start = index_of_phone_context + strlen(kRfc3966PhoneContext); if (phone_context_start >= number_to_extract_from.length()) { return ""; } size_t phone_context_end = number_to_extract_from.find(';', phone_context_start); if (phone_context_end != std::string::npos) { return number_to_extract_from.substr( phone_context_start, phone_context_end - phone_context_start); } else { return number_to_extract_from.substr(phone_context_start); } } bool PhoneNumberUtil::IsPhoneContextValid( const absl::optional<absl::string_view> phone_context) const { if (!phone_context.has_value()) { return true; } if (phone_context.value().empty()) { return false; } return reg_exps_->rfc3966_global_number_digits_pattern_->FullMatch( std::string{phone_context.value()}) || reg_exps_->rfc3966_domainname_pattern_->FullMatch( std::string{phone_context.value()}); } PhoneNumberUtil::ErrorType PhoneNumberUtil::BuildNationalNumberForParsing( absl::string_view number_to_parse, std::string* national_number) const { size_t index_of_phone_context = number_to_parse.find(kRfc3966PhoneContext); absl::optional<absl::string_view> phone_context = ExtractPhoneContext(number_to_parse, index_of_phone_context); if (!IsPhoneContextValid(phone_context)) { VLOG(2) << "The phone-context value is invalid."; return NOT_A_NUMBER; } if (phone_context.has_value()) { if (phone_context.value().at(0) == kPlusSign[0]) { StrAppend(national_number, phone_context.value()); } size_t index_of_rfc_prefix = number_to_parse.find(kRfc3966Prefix); int index_of_national_number = (index_of_rfc_prefix != std::string::npos) ? static_cast<int>(index_of_rfc_prefix + strlen(kRfc3966Prefix)) : 0; StrAppend( national_number, number_to_parse.substr( index_of_national_number, index_of_phone_context - index_of_national_number)); } else { ExtractPossibleNumber(number_to_parse, national_number); } size_t index_of_isdn = national_number->find(kRfc3966IsdnSubaddress); if (index_of_isdn != std::string::npos) { national_number->erase(index_of_isdn); } return NO_PARSING_ERROR; } PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseHelper( absl::string_view number_to_parse, const std::string& default_region, bool keep_raw_input, bool check_region, PhoneNumber* phone_number) const { DCHECK(phone_number); std::string national_number; PhoneNumberUtil::ErrorType build_national_number_for_parsing_return = BuildNationalNumberForParsing(number_to_parse, &national_number); if (build_national_number_for_parsing_return != NO_PARSING_ERROR) { return build_national_number_for_parsing_return; } if (!IsViablePhoneNumber(national_number)) { VLOG(2) << "The string supplied did not seem to be a phone number."; return NOT_A_NUMBER; } if (check_region && !CheckRegionForParsing(national_number, default_region)) { VLOG(1) << "Missing or invalid default country."; return INVALID_COUNTRY_CODE_ERROR; } PhoneNumber temp_number; if (keep_raw_input) { temp_number.set_raw_input(number_to_parse.data(), number_to_parse.size()); } std::string extension; MaybeStripExtension(&national_number, &extension); if (!extension.empty()) { temp_number.set_extension(extension); } const PhoneMetadata* country_metadata = GetMetadataForRegion(default_region); std::string normalized_national_number(national_number); ErrorType country_code_error = MaybeExtractCountryCode(country_metadata, keep_raw_input, &normalized_national_number, &temp_number); if (country_code_error != NO_PARSING_ERROR) { const scoped_ptr<RegExpInput> number_string_piece( reg_exps_->regexp_factory_->CreateInput(national_number)); if ((country_code_error == INVALID_COUNTRY_CODE_ERROR) && (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get()))) { normalized_national_number.assign(number_string_piece->ToString()); MaybeExtractCountryCode(country_metadata, keep_raw_input, &normalized_national_number, &temp_number); if (temp_number.country_code() == 0) { return INVALID_COUNTRY_CODE_ERROR; } } else { return country_code_error; } } int country_code = temp_number.country_code(); if (country_code != 0) { std::string phone_number_region; GetRegionCodeForCountryCode(country_code, &phone_number_region); if (phone_number_region != default_region) { country_metadata = GetMetadataForRegionOrCallingCode(country_code, phone_number_region); } } else if (country_metadata) { country_code = country_metadata->country_code(); } if (normalized_national_number.length() < kMinLengthForNsn) { VLOG(2) << "The string supplied is too short to be a phone number."; return TOO_SHORT_NSN; } if (country_metadata) { std::string carrier_code; std::string potential_national_number(normalized_national_number); MaybeStripNationalPrefixAndCarrierCode(*country_metadata, &potential_national_number, &carrier_code); ValidationResult validation_result = TestNumberLength(potential_national_number, *country_metadata); if (validation_result != TOO_SHORT && validation_result != IS_POSSIBLE_LOCAL_ONLY && validation_result != INVALID_LENGTH) { normalized_national_number.assign(potential_national_number); if (keep_raw_input && !carrier_code.empty()) { temp_number.set_preferred_domestic_carrier_code(carrier_code); } } } size_t normalized_national_number_length = normalized_national_number.length(); if (normalized_national_number_length < kMinLengthForNsn) { VLOG(2) << "The string supplied is too short to be a phone number."; return TOO_SHORT_NSN; } if (normalized_national_number_length > kMaxLengthForNsn) { VLOG(2) << "The string supplied is too long to be a phone number."; return TOO_LONG_NSN; } temp_number.set_country_code(country_code); SetItalianLeadingZerosForPhoneNumber(normalized_national_number, &temp_number); uint64 number_as_int; safe_strtou64(normalized_national_number, &number_as_int); temp_number.set_national_number(number_as_int); phone_number->Swap(&temp_number); return NO_PARSING_ERROR; } void PhoneNumberUtil::ExtractPossibleNumber( absl::string_view number, std::string* extracted_number) const { DCHECK(extracted_number); UnicodeText number_as_unicode; number_as_unicode.PointToUTF8(number.data(), static_cast<int>(number.size())); if (!number_as_unicode.UTF8WasValid()) { extracted_number->clear(); return; } char current_char[5]; int len; UnicodeText::const_iterator it; for (it = number_as_unicode.begin(); it != number_as_unicode.end(); ++it) { len = it.get_utf8(current_char); current_char[len] = '\0'; if (reg_exps_->valid_start_char_pattern_->FullMatch(current_char)) { break; } } if (it == number_as_unicode.end()) { extracted_number->clear(); return; } extracted_number->assign( UnicodeText::UTF8Substring(it, number_as_unicode.end())); TrimUnwantedEndChars(extracted_number); if (extracted_number->length() == 0) { return; } reg_exps_->capture_up_to_second_number_start_pattern_-> PartialMatch(*extracted_number, extracted_number); } bool PhoneNumberUtil::IsPossibleNumber(const PhoneNumber& number) const { ValidationResult result = IsPossibleNumberWithReason(number); return result == IS_POSSIBLE || result == IS_POSSIBLE_LOCAL_ONLY; } bool PhoneNumberUtil::IsPossibleNumberForType( const PhoneNumber& number, const PhoneNumberType type) const { ValidationResult result = IsPossibleNumberForTypeWithReason(number, type); return result == IS_POSSIBLE || result == IS_POSSIBLE_LOCAL_ONLY; } bool PhoneNumberUtil::IsPossibleNumberForString( absl::string_view number, const std::string& region_dialing_from) const { PhoneNumber number_proto; if (Parse(number, region_dialing_from, &number_proto) == NO_PARSING_ERROR) { return IsPossibleNumber(number_proto); } else { return false; } } PhoneNumberUtil::ValidationResult PhoneNumberUtil::IsPossibleNumberWithReason( const PhoneNumber& number) const { return IsPossibleNumberForTypeWithReason(number, PhoneNumberUtil::UNKNOWN); } PhoneNumberUtil::ValidationResult PhoneNumberUtil::IsPossibleNumberForTypeWithReason(const PhoneNumber& number, PhoneNumberType type) const { std::string national_number; GetNationalSignificantNumber(number, &national_number); int country_code = number.country_code(); if (!HasValidCountryCallingCode(country_code)) { return INVALID_COUNTRY_CODE; } std::string region_code; GetRegionCodeForCountryCode(country_code, &region_code); const PhoneMetadata* metadata = GetMetadataForRegionOrCallingCode(country_code, region_code); return TestNumberLength(national_number, *metadata, type); } bool PhoneNumberUtil::TruncateTooLongNumber(PhoneNumber* number) const { if (IsValidNumber(*number)) { return true; } PhoneNumber number_copy(*number); uint64 national_number = number->national_number(); do { national_number /= 10; number_copy.set_national_number(national_number); if (IsPossibleNumberWithReason(number_copy) == TOO_SHORT || national_number == 0) { return false; } } while (!IsValidNumber(number_copy)); number->set_national_number(national_number); return true; } PhoneNumberUtil::PhoneNumberType PhoneNumberUtil::GetNumberType( const PhoneNumber& number) const { std::string region_code; GetRegionCodeForNumber(number, &region_code); const PhoneMetadata* metadata = GetMetadataForRegionOrCallingCode(number.country_code(), region_code); if (!metadata) { return UNKNOWN; } std::string national_significant_number; GetNationalSignificantNumber(number, &national_significant_number); return GetNumberTypeHelper(national_significant_number, *metadata); } bool PhoneNumberUtil::IsValidNumber(const PhoneNumber& number) const { std::string region_code; GetRegionCodeForNumber(number, &region_code); return IsValidNumberForRegion(number, region_code); } bool PhoneNumberUtil::IsValidNumberForRegion(const PhoneNumber& number, const std::string& region_code) const { int country_code = number.country_code(); const PhoneMetadata* metadata = GetMetadataForRegionOrCallingCode(country_code, region_code); if (!metadata || ((kRegionCodeForNonGeoEntity != region_code) && country_code != GetCountryCodeForValidRegion(region_code))) { return false; } std::string national_number; GetNationalSignificantNumber(number, &national_number); return GetNumberTypeHelper(national_number, *metadata) != UNKNOWN; } bool PhoneNumberUtil::IsNumberGeographical( const PhoneNumber& phone_number) const { return IsNumberGeographical(GetNumberType(phone_number), phone_number.country_code()); } bool PhoneNumberUtil::IsNumberGeographical( PhoneNumberType phone_number_type, int country_calling_code) const { return phone_number_type == PhoneNumberUtil::FIXED_LINE || phone_number_type == PhoneNumberUtil::FIXED_LINE_OR_MOBILE || (reg_exps_->geo_mobile_countries_.find(country_calling_code) != reg_exps_->geo_mobile_countries_.end() && phone_number_type == PhoneNumberUtil::MOBILE); } void PhoneNumberUtil::SetItalianLeadingZerosForPhoneNumber( const std::string& national_number, PhoneNumber* phone_number) const { if (national_number.length() > 1 && national_number[0] == '0') { phone_number->set_italian_leading_zero(true); size_t number_of_leading_zeros = 1; while (number_of_leading_zeros < national_number.length() - 1 && national_number[number_of_leading_zeros] == '0') { number_of_leading_zeros++; } if (number_of_leading_zeros != 1) { phone_number->set_number_of_leading_zeros(static_cast<int32_t>(number_of_leading_zeros)); } } } bool PhoneNumberUtil::IsNumberMatchingDesc( const std::string& national_number, const PhoneNumberDesc& number_desc) const { int actual_length = static_cast<int>(national_number.length()); if (number_desc.possible_length_size() > 0 && std::find(number_desc.possible_length().begin(), number_desc.possible_length().end(), actual_length) == number_desc.possible_length().end()) { return false; } return IsMatch(*matcher_api_, national_number, number_desc); } PhoneNumberUtil::PhoneNumberType PhoneNumberUtil::GetNumberTypeHelper( const std::string& national_number, const PhoneMetadata& metadata) const { if (!IsNumberMatchingDesc(national_number, metadata.general_desc())) { VLOG(4) << "Number type unknown - doesn't match general national number" << " pattern."; return PhoneNumberUtil::UNKNOWN; } if (IsNumberMatchingDesc(national_number, metadata.premium_rate())) { VLOG(4) << "Number is a premium number."; return PhoneNumberUtil::PREMIUM_RATE; } if (IsNumberMatchingDesc(national_number, metadata.toll_free())) { VLOG(4) << "Number is a toll-free number."; return PhoneNumberUtil::TOLL_FREE; } if (IsNumberMatchingDesc(national_number, metadata.shared_cost())) { VLOG(4) << "Number is a shared cost number."; return PhoneNumberUtil::SHARED_COST; } if (IsNumberMatchingDesc(national_number, metadata.voip())) { VLOG(4) << "Number is a VOIP (Voice over IP) number."; return PhoneNumberUtil::VOIP; } if (IsNumberMatchingDesc(national_number, metadata.personal_number())) { VLOG(4) << "Number is a personal number."; return PhoneNumberUtil::PERSONAL_NUMBER; } if (IsNumberMatchingDesc(national_number, metadata.pager())) { VLOG(4) << "Number is a pager number."; return PhoneNumberUtil::PAGER; } if (IsNumberMatchingDesc(national_number, metadata.uan())) { VLOG(4) << "Number is a UAN."; return PhoneNumberUtil::UAN; } if (IsNumberMatchingDesc(national_number, metadata.voicemail())) { VLOG(4) << "Number is a voicemail number."; return PhoneNumberUtil::VOICEMAIL; } bool is_fixed_line = IsNumberMatchingDesc(national_number, metadata.fixed_line()); if (is_fixed_line) { if (metadata.same_mobile_and_fixed_line_pattern()) { VLOG(4) << "Fixed-line and mobile patterns equal, number is fixed-line" << " or mobile"; return PhoneNumberUtil::FIXED_LINE_OR_MOBILE; } else if (IsNumberMatchingDesc(national_number, metadata.mobile())) { VLOG(4) << "Fixed-line and mobile patterns differ, but number is " << "still fixed-line or mobile"; return PhoneNumberUtil::FIXED_LINE_OR_MOBILE; } VLOG(4) << "Number is a fixed line number."; return PhoneNumberUtil::FIXED_LINE; } if (!metadata.same_mobile_and_fixed_line_pattern() && IsNumberMatchingDesc(national_number, metadata.mobile())) { VLOG(4) << "Number is a mobile number."; return PhoneNumberUtil::MOBILE; } VLOG(4) << "Number type unknown - doesn\'t match any specific number type" << " pattern."; return PhoneNumberUtil::UNKNOWN; } void PhoneNumberUtil::GetNationalSignificantNumber( const PhoneNumber& number, std::string* national_number) const { DCHECK(national_number); StrAppend(national_number, number.italian_leading_zero() ? std::string(std::max(number.number_of_leading_zeros(), 0), '0') : ""); StrAppend(national_number, number.national_number()); } int PhoneNumberUtil::GetLengthOfGeographicalAreaCode( const PhoneNumber& number) const { std::string region_code; GetRegionCodeForNumber(number, &region_code); const PhoneMetadata* metadata = GetMetadataForRegion(region_code); if (!metadata) { return 0; } PhoneNumberType type = GetNumberType(number); int country_calling_code = number.country_code(); if (!metadata->has_national_prefix() && !number.italian_leading_zero() && reg_exps_->countries_without_national_prefix_with_area_codes_.find( country_calling_code) == reg_exps_->countries_without_national_prefix_with_area_codes_.end()) { return 0; } if (type == PhoneNumberUtil::MOBILE && reg_exps_->geo_mobile_countries_without_mobile_area_codes_.find( country_calling_code) != reg_exps_->geo_mobile_countries_without_mobile_area_codes_.end()) { return 0; } if (!IsNumberGeographical(type, country_calling_code)) { return 0; } return GetLengthOfNationalDestinationCode(number); } int PhoneNumberUtil::GetLengthOfNationalDestinationCode( const PhoneNumber& number) const { PhoneNumber copied_proto(number); if (number.has_extension()) { copied_proto.clear_extension(); } std::string formatted_number; Format(copied_proto, INTERNATIONAL, &formatted_number); const scoped_ptr<RegExpInput> i18n_number( reg_exps_->regexp_factory_->CreateInput(formatted_number)); std::string digit_group; std::string ndc; std::string third_group; for (int i = 0; i < 3; ++i) { if (!reg_exps_->capturing_ascii_digits_pattern_->FindAndConsume( i18n_number.get(), &digit_group)) { return 0; } if (i == 1) { ndc = digit_group; } else if (i == 2) { third_group = digit_group; } } if (GetNumberType(number) == MOBILE) { std::string mobile_token; GetCountryMobileToken(number.country_code(), &mobile_token); if (!mobile_token.empty()) { return static_cast<int>(third_group.size() + mobile_token.size()); } } return static_cast<int>(ndc.size()); } void PhoneNumberUtil::GetCountryMobileToken(int country_calling_code, std::string* mobile_token) const { DCHECK(mobile_token); std::map<int, char>::iterator it = reg_exps_->mobile_token_mappings_.find( country_calling_code); if (it != reg_exps_->mobile_token_mappings_.end()) { *mobile_token = it->second; } else { mobile_token->assign(""); } } void PhoneNumberUtil::NormalizeDigitsOnly(std::string* number) const { DCHECK(number); const RegExp& non_digits_pattern = reg_exps_->regexp_cache_->GetRegExp( StrCat("[^", kDigits, "]")); non_digits_pattern.GlobalReplace(number, ""); number->assign(NormalizeUTF8::NormalizeDecimalDigits(*number)); } void PhoneNumberUtil::NormalizeDiallableCharsOnly(std::string* number) const { DCHECK(number); NormalizeHelper(reg_exps_->diallable_char_mappings_, true , number); } bool PhoneNumberUtil::IsAlphaNumber(const std::string& number) const { if (!IsViablePhoneNumber(number)) { return false; } std::string number_copy(number); std::string extension; MaybeStripExtension(&number_copy, &extension); return reg_exps_->valid_alpha_phone_pattern_->FullMatch(number_copy); } void PhoneNumberUtil::ConvertAlphaCharactersInNumber( std::string* number) const { DCHECK(number); NormalizeHelper(reg_exps_->alpha_phone_mappings_, false, number); } void PhoneNumberUtil::Normalize(std::string* number) const { DCHECK(number); if (reg_exps_->valid_alpha_phone_pattern_->PartialMatch(*number)) { NormalizeHelper(reg_exps_->alpha_phone_mappings_, true, number); } NormalizeDigitsOnly(number); } bool PhoneNumberUtil::IsViablePhoneNumber(const std::string& number) const { if (number.length() < kMinLengthForNsn) { return false; } return reg_exps_->valid_phone_number_pattern_->FullMatch(number); } bool PhoneNumberUtil::ParsePrefixAsIdd(const RegExp& idd_pattern, std::string* number) const { DCHECK(number); const scoped_ptr<RegExpInput> number_copy( reg_exps_->regexp_factory_->CreateInput(*number)); if (idd_pattern.Consume(number_copy.get())) { std::string extracted_digit; if (reg_exps_->capturing_digit_pattern_->PartialMatch( number_copy->ToString(), &extracted_digit)) { NormalizeDigitsOnly(&extracted_digit); if (extracted_digit == "0") { return false; } } number->assign(number_copy->ToString()); return true; } return false; } PhoneNumber::CountryCodeSource PhoneNumberUtil::MaybeStripInternationalPrefixAndNormalize( const std::string& possible_idd_prefix, std::string* number) const { DCHECK(number); if (number->empty()) { return PhoneNumber::FROM_DEFAULT_COUNTRY; } const scoped_ptr<RegExpInput> number_string_piece( reg_exps_->regexp_factory_->CreateInput(*number)); if (reg_exps_->plus_chars_pattern_->Consume(number_string_piece.get())) { number->assign(number_string_piece->ToString()); Normalize(number); return PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN; } const RegExp& idd_pattern = reg_exps_->regexp_cache_->GetRegExp(possible_idd_prefix); Normalize(number); return ParsePrefixAsIdd(idd_pattern, number) ? PhoneNumber::FROM_NUMBER_WITH_IDD : PhoneNumber::FROM_DEFAULT_COUNTRY; } bool PhoneNumberUtil::MaybeStripNationalPrefixAndCarrierCode( const PhoneMetadata& metadata, std::string* number, std::string* carrier_code) const { DCHECK(number); std::string carrier_code_temp; const std::string& possible_national_prefix = metadata.national_prefix_for_parsing(); if (number->empty() || possible_national_prefix.empty()) { return false; } const scoped_ptr<RegExpInput> number_copy( reg_exps_->regexp_factory_->CreateInput(*number)); const scoped_ptr<RegExpInput> number_copy_without_transform( reg_exps_->regexp_factory_->CreateInput(*number)); std::string number_string_copy(*number); std::string captured_part_of_prefix; const PhoneNumberDesc& general_desc = metadata.general_desc(); bool is_viable_original_number = IsMatch(*matcher_api_, *number, general_desc); const std::string& transform_rule = metadata.national_prefix_transform_rule(); const RegExp& possible_national_prefix_pattern = reg_exps_->regexp_cache_->GetRegExp(possible_national_prefix); if (!transform_rule.empty() && (possible_national_prefix_pattern.Consume( number_copy.get(), &carrier_code_temp, &captured_part_of_prefix) || possible_national_prefix_pattern.Consume( number_copy.get(), &captured_part_of_prefix)) && !captured_part_of_prefix.empty()) { possible_national_prefix_pattern.Replace(&number_string_copy, transform_rule); if (is_viable_original_number && !IsMatch(*matcher_api_, number_string_copy, general_desc)) { return false; } number->assign(number_string_copy); if (carrier_code) { carrier_code->assign(carrier_code_temp); } } else if (possible_national_prefix_pattern.Consume( number_copy_without_transform.get(), &carrier_code_temp) || possible_national_prefix_pattern.Consume( number_copy_without_transform.get())) { VLOG(4) << "Parsed the first digits as a national prefix."; const std::string number_copy_as_string = number_copy_without_transform->ToString(); if (is_viable_original_number && !IsMatch(*matcher_api_, number_copy_as_string, general_desc)) { return false; } number->assign(number_copy_as_string); if (carrier_code) { carrier_code->assign(carrier_code_temp); } } else { return false; VLOG(4) << "The first digits did not match the national prefix."; } return true; } bool PhoneNumberUtil::MaybeStripExtension(std::string* number, std::string* extension) const { DCHECK(number); DCHECK(extension); std::string possible_extension_one; std::string possible_extension_two; std::string possible_extension_three; std::string possible_extension_four; std::string possible_extension_five; std::string possible_extension_six; std::string number_copy(*number); const scoped_ptr<RegExpInput> number_copy_as_regexp_input( reg_exps_->regexp_factory_->CreateInput(number_copy)); if (reg_exps_->extn_pattern_->Consume( number_copy_as_regexp_input.get(), false, &possible_extension_one, &possible_extension_two, &possible_extension_three, &possible_extension_four, &possible_extension_five, &possible_extension_six)) { reg_exps_->extn_pattern_->Replace(&number_copy, ""); if ((!possible_extension_one.empty() || !possible_extension_two.empty() || !possible_extension_three.empty() || !possible_extension_four.empty() || !possible_extension_five.empty() || !possible_extension_six.empty()) && IsViablePhoneNumber(number_copy)) { number->assign(number_copy); if (!possible_extension_one.empty()) { extension->assign(possible_extension_one); } else if (!possible_extension_two.empty()) { extension->assign(possible_extension_two); } else if (!possible_extension_three.empty()) { extension->assign(possible_extension_three); } else if (!possible_extension_four.empty()) { extension->assign(possible_extension_four); } else if (!possible_extension_five.empty()) { extension->assign(possible_extension_five); } else if (!possible_extension_six.empty()) { extension->assign(possible_extension_six); } return true; } } return false; } int PhoneNumberUtil::ExtractCountryCode(std::string* national_number) const { int potential_country_code; if (national_number->empty() || (national_number->at(0) == '0')) { return 0; } for (size_t i = 1; i <= kMaxLengthCountryCode; ++i) { safe_strto32(national_number->substr(0, i), &potential_country_code); std::string region_code; GetRegionCodeForCountryCode(potential_country_code, &region_code); if (region_code != RegionCode::GetUnknown()) { national_number->erase(0, i); return potential_country_code; } } return 0; } PhoneNumberUtil::ErrorType PhoneNumberUtil::MaybeExtractCountryCode( const PhoneMetadata* default_region_metadata, bool keep_raw_input, std::string* national_number, PhoneNumber* phone_number) const { DCHECK(national_number); DCHECK(phone_number); std::string possible_country_idd_prefix = default_region_metadata ? default_region_metadata->international_prefix() : "NonMatch"; PhoneNumber::CountryCodeSource country_code_source = MaybeStripInternationalPrefixAndNormalize(possible_country_idd_prefix, national_number); if (keep_raw_input) { phone_number->set_country_code_source(country_code_source); } if (country_code_source != PhoneNumber::FROM_DEFAULT_COUNTRY) { if (national_number->length() <= kMinLengthForNsn) { VLOG(2) << "Phone number had an IDD, but after this was not " << "long enough to be a viable phone number."; return TOO_SHORT_AFTER_IDD; } int potential_country_code = ExtractCountryCode(national_number); if (potential_country_code != 0) { phone_number->set_country_code(potential_country_code); return NO_PARSING_ERROR; } return INVALID_COUNTRY_CODE_ERROR; } else if (default_region_metadata) { int default_country_code = default_region_metadata->country_code(); std::string default_country_code_string(SimpleItoa(default_country_code)); VLOG(4) << "Possible country calling code: " << default_country_code_string; std::string potential_national_number; if (TryStripPrefixString(*national_number, default_country_code_string, &potential_national_number)) { const PhoneNumberDesc& general_num_desc = default_region_metadata->general_desc(); MaybeStripNationalPrefixAndCarrierCode(*default_region_metadata, &potential_national_number, NULL); VLOG(4) << "Number without country calling code prefix"; if ((!IsMatch(*matcher_api_, *national_number, general_num_desc) && IsMatch( *matcher_api_, potential_national_number, general_num_desc)) || TestNumberLength(*national_number, *default_region_metadata) == TOO_LONG) { national_number->assign(potential_national_number); if (keep_raw_input) { phone_number->set_country_code_source( PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN); } phone_number->set_country_code(default_country_code); return NO_PARSING_ERROR; } } } phone_number->set_country_code(0); return NO_PARSING_ERROR; } PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatch( const PhoneNumber& first_number_in, const PhoneNumber& second_number_in) const { PhoneNumber first_number; CopyCoreFieldsOnly(first_number_in, &first_number); PhoneNumber second_number; CopyCoreFieldsOnly(second_number_in, &second_number); if (first_number.has_extension() && second_number.has_extension() && first_number.extension() != second_number.extension()) { return NO_MATCH; } int first_number_country_code = first_number.country_code(); int second_number_country_code = second_number.country_code(); if (first_number_country_code != 0 && second_number_country_code != 0) { if (ExactlySameAs(first_number, second_number)) { return EXACT_MATCH; } else if (first_number_country_code == second_number_country_code && IsNationalNumberSuffixOfTheOther(first_number, second_number)) { return SHORT_NSN_MATCH; } return NO_MATCH; } first_number.set_country_code(second_number_country_code); if (ExactlySameAs(first_number, second_number)) { return NSN_MATCH; } if (IsNationalNumberSuffixOfTheOther(first_number, second_number)) { return SHORT_NSN_MATCH; } return NO_MATCH; } PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithTwoStrings( absl::string_view first_number, absl::string_view second_number) const { PhoneNumber first_number_as_proto; ErrorType error_type = Parse(first_number, RegionCode::GetUnknown(), &first_number_as_proto); if (error_type == NO_PARSING_ERROR) { return IsNumberMatchWithOneString(first_number_as_proto, second_number); } if (error_type == INVALID_COUNTRY_CODE_ERROR) { PhoneNumber second_number_as_proto; ErrorType error_type = Parse(second_number, RegionCode::GetUnknown(), &second_number_as_proto); if (error_type == NO_PARSING_ERROR) { return IsNumberMatchWithOneString(second_number_as_proto, first_number); } if (error_type == INVALID_COUNTRY_CODE_ERROR) { error_type = ParseHelper(first_number, RegionCode::GetUnknown(), false, false, &first_number_as_proto); if (error_type == NO_PARSING_ERROR) { error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false, false, &second_number_as_proto); if (error_type == NO_PARSING_ERROR) { return IsNumberMatch(first_number_as_proto, second_number_as_proto); } } } } return INVALID_NUMBER; } PhoneNumberUtil::MatchType PhoneNumberUtil::IsNumberMatchWithOneString( const PhoneNumber& first_number, absl::string_view second_number) const { PhoneNumber second_number_as_proto; ErrorType error_type = Parse(second_number, RegionCode::GetUnknown(), &second_number_as_proto); if (error_type == NO_PARSING_ERROR) { return IsNumberMatch(first_number, second_number_as_proto); } if (error_type == INVALID_COUNTRY_CODE_ERROR) { std::string first_number_region; GetRegionCodeForCountryCode(first_number.country_code(), &first_number_region); if (first_number_region != RegionCode::GetUnknown()) { PhoneNumber second_number_with_first_number_region; Parse(second_number, first_number_region, &second_number_with_first_number_region); MatchType match = IsNumberMatch(first_number, second_number_with_first_number_region); if (match == EXACT_MATCH) { return NSN_MATCH; } return match; } else { error_type = ParseHelper(second_number, RegionCode::GetUnknown(), false, false, &second_number_as_proto); if (error_type == NO_PARSING_ERROR) { return IsNumberMatch(first_number, second_number_as_proto); } } } return INVALID_NUMBER; } AsYouTypeFormatter* PhoneNumberUtil::GetAsYouTypeFormatter( const std::string& region_code) const { return new AsYouTypeFormatter(region_code); } bool PhoneNumberUtil::CanBeInternationallyDialled( const PhoneNumber& number) const { std::string region_code; GetRegionCodeForNumber(number, &region_code); const PhoneMetadata* metadata = GetMetadataForRegion(region_code); if (!metadata) { return true; } std::string national_significant_number; GetNationalSignificantNumber(number, &national_significant_number); return !IsNumberMatchingDesc( national_significant_number, metadata->no_international_dialling()); } } }
#include "phonenumbers/phonenumberutil.h" #include <algorithm> #include <iostream> #include <list> #include <set> #include <string> #include <gtest/gtest.h> #include <unicode/uchar.h> #include "phonenumbers/default_logger.h" #include "phonenumbers/normalize_utf8.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { using std::find; using std::ostream; using google::protobuf::RepeatedPtrField; static const int kInvalidCountryCode = 2; class PhoneNumberUtilTest : public testing::Test { public: PhoneNumberUtilTest(const PhoneNumberUtilTest&) = delete; PhoneNumberUtilTest& operator=(const PhoneNumberUtilTest&) = delete; protected: PhoneNumberUtilTest() : phone_util_(*PhoneNumberUtil::GetInstance()) { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } const PhoneMetadata* GetPhoneMetadata(const string& region_code) const { return phone_util_.GetMetadataForRegion(region_code); } const PhoneMetadata* GetMetadataForNonGeographicalRegion( int country_code) const { return phone_util_.GetMetadataForNonGeographicalRegion(country_code); } void ExtractPossibleNumber(const string& number, string* extracted_number) const { phone_util_.ExtractPossibleNumber(number, extracted_number); } bool IsViablePhoneNumber(const string& number) const { return phone_util_.IsViablePhoneNumber(number); } void Normalize(string* number) const { phone_util_.Normalize(number); } PhoneNumber::CountryCodeSource MaybeStripInternationalPrefixAndNormalize( const string& possible_idd_prefix, string* number) const { return phone_util_.MaybeStripInternationalPrefixAndNormalize( possible_idd_prefix, number); } void MaybeStripNationalPrefixAndCarrierCode(const PhoneMetadata& metadata, string* number, string* carrier_code) const { phone_util_.MaybeStripNationalPrefixAndCarrierCode(metadata, number, carrier_code); } bool MaybeStripExtension(string* number, string* extension) const { return phone_util_.MaybeStripExtension(number, extension); } PhoneNumberUtil::ErrorType MaybeExtractCountryCode( const PhoneMetadata* default_region_metadata, bool keep_raw_input, string* national_number, PhoneNumber* phone_number) const { return phone_util_.MaybeExtractCountryCode(default_region_metadata, keep_raw_input, national_number, phone_number); } bool ContainsOnlyValidDigits(const string& s) const { return phone_util_.ContainsOnlyValidDigits(s); } void AssertThrowsForInvalidPhoneContext(const string number_to_parse) { PhoneNumber actual_number; EXPECT_EQ( PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(number_to_parse, RegionCode::ZZ(), &actual_number)); } const PhoneNumberUtil& phone_util_; }; TEST_F(PhoneNumberUtilTest, ContainsOnlyValidDigits) { EXPECT_TRUE(ContainsOnlyValidDigits("")); EXPECT_TRUE(ContainsOnlyValidDigits("2")); EXPECT_TRUE(ContainsOnlyValidDigits("25")); EXPECT_TRUE(ContainsOnlyValidDigits("\xEF\xBC\x96" )); EXPECT_FALSE(ContainsOnlyValidDigits("a")); EXPECT_FALSE(ContainsOnlyValidDigits("2a")); } TEST_F(PhoneNumberUtilTest, InterchangeInvalidCodepoints) { PhoneNumber phone_number; std::vector<string> valid_inputs = { "+44" "\xE2\x80\x93" "2087654321", }; for (auto input : valid_inputs) { EXPECT_EQ(input, NormalizeUTF8::NormalizeDecimalDigits(input)); EXPECT_TRUE(IsViablePhoneNumber(input)); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(input, RegionCode::GB(), &phone_number)); } std::vector<string> invalid_inputs = { "+44" "\x96" "2087654321", "+44" "\xC2\x96" "2087654321", "+44" "\xEF\xBF\xBE" "2087654321", }; for (auto input : invalid_inputs) { EXPECT_TRUE(NormalizeUTF8::NormalizeDecimalDigits(input).empty()); EXPECT_FALSE(IsViablePhoneNumber(input)); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(input, RegionCode::GB(), &phone_number)); } } TEST_F(PhoneNumberUtilTest, GetSupportedRegions) { std::set<string> regions; phone_util_.GetSupportedRegions(&regions); EXPECT_GT(regions.size(), 0U); } TEST_F(PhoneNumberUtilTest, GetSupportedGlobalNetworkCallingCodes) { std::set<int> calling_codes; phone_util_.GetSupportedGlobalNetworkCallingCodes(&calling_codes); EXPECT_GT(calling_codes.size(), 0U); for (std::set<int>::const_iterator it = calling_codes.begin(); it != calling_codes.end(); ++it) { EXPECT_GT(*it, 0); string region_code; phone_util_.GetRegionCodeForCountryCode(*it, &region_code); EXPECT_EQ(RegionCode::UN001(), region_code); } } TEST_F(PhoneNumberUtilTest, GetSupportedCallingCodes) { std::set<int> calling_codes; phone_util_.GetSupportedCallingCodes(&calling_codes); EXPECT_GT(calling_codes.size(), 0U); for (std::set<int>::const_iterator it = calling_codes.begin(); it != calling_codes.end(); ++it) { EXPECT_GT(*it, 0); string region_code; phone_util_.GetRegionCodeForCountryCode(*it, &region_code); EXPECT_NE(RegionCode::ZZ(), region_code); } std::set<int> supported_global_network_calling_codes; phone_util_.GetSupportedGlobalNetworkCallingCodes( &supported_global_network_calling_codes); EXPECT_GT(calling_codes.size(), supported_global_network_calling_codes.size()); EXPECT_NE(calling_codes.find(979), calling_codes.end()); } TEST_F(PhoneNumberUtilTest, GetSupportedTypesForRegion) { std::set<PhoneNumberUtil::PhoneNumberType> types; phone_util_.GetSupportedTypesForRegion(RegionCode::BR(), &types); EXPECT_NE(types.find(PhoneNumberUtil::FIXED_LINE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::MOBILE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::UNKNOWN), types.end()); types.clear(); phone_util_.GetSupportedTypesForRegion(RegionCode::US(), &types); EXPECT_NE(types.find(PhoneNumberUtil::FIXED_LINE), types.end()); EXPECT_NE(types.find(PhoneNumberUtil::MOBILE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::FIXED_LINE_OR_MOBILE), types.end()); types.clear(); phone_util_.GetSupportedTypesForRegion(RegionCode::ZZ(), &types); EXPECT_EQ(0u, types.size()); } TEST_F(PhoneNumberUtilTest, GetSupportedTypesForNonGeoEntity) { std::set<PhoneNumberUtil::PhoneNumberType> types; phone_util_.GetSupportedTypesForNonGeoEntity(999, &types); EXPECT_EQ(0u, types.size()); types.clear(); phone_util_.GetSupportedTypesForNonGeoEntity(979, &types); EXPECT_NE(types.find(PhoneNumberUtil::PREMIUM_RATE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::MOBILE), types.end()); EXPECT_EQ(types.find(PhoneNumberUtil::UNKNOWN), types.end()); } TEST_F(PhoneNumberUtilTest, GetRegionCodesForCountryCallingCode) { std::list<string> regions; phone_util_.GetRegionCodesForCountryCallingCode(1, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::US()) != regions.end()); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::BS()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode(44, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::GB()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode(49, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::DE()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode(800, &regions); EXPECT_TRUE(find(regions.begin(), regions.end(), RegionCode::UN001()) != regions.end()); regions.clear(); phone_util_.GetRegionCodesForCountryCallingCode( kInvalidCountryCode, &regions); EXPECT_TRUE(regions.empty()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadUSMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::US()); EXPECT_EQ("US", metadata->id()); EXPECT_EQ(1, metadata->country_code()); EXPECT_EQ("011", metadata->international_prefix()); EXPECT_TRUE(metadata->has_national_prefix()); ASSERT_EQ(2, metadata->number_format_size()); EXPECT_EQ("(\\d{3})(\\d{3})(\\d{4})", metadata->number_format(1).pattern()); EXPECT_EQ("$1 $2 $3", metadata->number_format(1).format()); EXPECT_EQ("[13-689]\\d{9}|2[0-35-9]\\d{8}", metadata->general_desc().national_number_pattern()); EXPECT_EQ("[13-689]\\d{9}|2[0-35-9]\\d{8}", metadata->fixed_line().national_number_pattern()); EXPECT_EQ(1, metadata->general_desc().possible_length_size()); EXPECT_EQ(10, metadata->general_desc().possible_length(0)); EXPECT_EQ(0, metadata->toll_free().possible_length_size()); EXPECT_EQ("900\\d{7}", metadata->premium_rate().national_number_pattern()); EXPECT_FALSE(metadata->shared_cost().has_national_number_pattern()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadDEMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::DE()); EXPECT_EQ("DE", metadata->id()); EXPECT_EQ(49, metadata->country_code()); EXPECT_EQ("00", metadata->international_prefix()); EXPECT_EQ("0", metadata->national_prefix()); ASSERT_EQ(6, metadata->number_format_size()); EXPECT_EQ(1, metadata->number_format(5).leading_digits_pattern_size()); EXPECT_EQ("900", metadata->number_format(5).leading_digits_pattern(0)); EXPECT_EQ("(\\d{3})(\\d{3,4})(\\d{4})", metadata->number_format(5).pattern()); EXPECT_EQ(2, metadata->general_desc().possible_length_local_only_size()); EXPECT_EQ(8, metadata->general_desc().possible_length_size()); EXPECT_EQ(0, metadata->fixed_line().possible_length_size()); EXPECT_EQ(2, metadata->mobile().possible_length_size()); EXPECT_EQ("$1 $2 $3", metadata->number_format(5).format()); EXPECT_EQ("(?:[24-6]\\d{2}|3[03-9]\\d|[789](?:0[2-9]|[1-9]\\d))\\d{1,8}", metadata->fixed_line().national_number_pattern()); EXPECT_EQ("30123456", metadata->fixed_line().example_number()); EXPECT_EQ(10, metadata->toll_free().possible_length(0)); EXPECT_EQ("900([135]\\d{6}|9\\d{7})", metadata->premium_rate().national_number_pattern()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadARMetadata) { const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::AR()); EXPECT_EQ("AR", metadata->id()); EXPECT_EQ(54, metadata->country_code()); EXPECT_EQ("00", metadata->international_prefix()); EXPECT_EQ("0", metadata->national_prefix()); EXPECT_EQ("0(?:(11|343|3715)15)?", metadata->national_prefix_for_parsing()); EXPECT_EQ("9$1", metadata->national_prefix_transform_rule()); ASSERT_EQ(5, metadata->number_format_size()); EXPECT_EQ("$2 15 $3-$4", metadata->number_format(2).format()); EXPECT_EQ("(\\d)(\\d{4})(\\d{2})(\\d{4})", metadata->number_format(3).pattern()); EXPECT_EQ("(\\d)(\\d{4})(\\d{2})(\\d{4})", metadata->intl_number_format(3).pattern()); EXPECT_EQ("$1 $2 $3 $4", metadata->intl_number_format(3).format()); } TEST_F(PhoneNumberUtilTest, GetInstanceLoadInternationalTollFreeMetadata) { const PhoneMetadata* metadata = GetMetadataForNonGeographicalRegion(800); EXPECT_FALSE(metadata == NULL); EXPECT_EQ("001", metadata->id()); EXPECT_EQ(800, metadata->country_code()); EXPECT_EQ("$1 $2", metadata->number_format(0).format()); EXPECT_EQ("(\\d{4})(\\d{4})", metadata->number_format(0).pattern()); EXPECT_EQ(0, metadata->general_desc().possible_length_local_only_size()); EXPECT_EQ(1, metadata->general_desc().possible_length_size()); EXPECT_EQ("12345678", metadata->toll_free().example_number()); } TEST_F(PhoneNumberUtilTest, GetNationalSignificantNumber) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{6502530000}); string national_significant_number; phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("6502530000", national_significant_number); national_significant_number.clear(); number.set_country_code(39); number.set_national_number(uint64{312345678}); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("312345678", national_significant_number); national_significant_number.clear(); number.set_country_code(39); number.set_national_number(uint64{236618300}); number.set_italian_leading_zero(true); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("0236618300", national_significant_number); national_significant_number.clear(); number.Clear(); number.set_country_code(800); number.set_national_number(uint64{12345678}); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("12345678", national_significant_number); } TEST_F(PhoneNumberUtilTest, GetNationalSignificantNumber_ManyLeadingZeros) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{650}); number.set_italian_leading_zero(true); number.set_number_of_leading_zeros(2); string national_significant_number; phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("00650", national_significant_number); number.set_number_of_leading_zeros(-3); national_significant_number.clear(); phone_util_.GetNationalSignificantNumber(number, &national_significant_number); EXPECT_EQ("650", national_significant_number); } TEST_F(PhoneNumberUtilTest, GetExampleNumber) { PhoneNumber de_number; de_number.set_country_code(49); de_number.set_national_number(uint64{30123456}); PhoneNumber test_number; bool success = phone_util_.GetExampleNumber(RegionCode::DE(), &test_number); EXPECT_TRUE(success); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType( RegionCode::DE(), PhoneNumberUtil::FIXED_LINE, &test_number); EXPECT_TRUE(success); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType( RegionCode::DE(), PhoneNumberUtil::FIXED_LINE_OR_MOBILE, &test_number); EXPECT_EQ(de_number, test_number); success = phone_util_.GetExampleNumberForType( RegionCode::DE(), PhoneNumberUtil::MOBILE, &test_number); success = phone_util_.GetExampleNumberForType( RegionCode::US(), PhoneNumberUtil::VOICEMAIL, &test_number); test_number.Clear(); EXPECT_FALSE(success); EXPECT_EQ(PhoneNumber::default_instance(), test_number); success = phone_util_.GetExampleNumberForType( RegionCode::US(), PhoneNumberUtil::FIXED_LINE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); success = phone_util_.GetExampleNumberForType( RegionCode::US(), PhoneNumberUtil::MOBILE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); test_number.Clear(); EXPECT_FALSE(phone_util_.GetExampleNumberForType( RegionCode::CS(), PhoneNumberUtil::MOBILE, &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_FALSE(phone_util_.GetExampleNumber(RegionCode::UN001(), &test_number)); } TEST_F(PhoneNumberUtilTest, GetInvalidExampleNumber) { PhoneNumber test_number; EXPECT_FALSE(phone_util_.GetInvalidExampleNumber(RegionCode::UN001(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_FALSE(phone_util_.GetInvalidExampleNumber(RegionCode::CS(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_TRUE(phone_util_.GetInvalidExampleNumber(RegionCode::US(), &test_number)); EXPECT_EQ(1, test_number.country_code()); EXPECT_NE(0u, test_number.national_number()); } TEST_F(PhoneNumberUtilTest, GetExampleNumberForNonGeoEntity) { PhoneNumber toll_free_number; toll_free_number.set_country_code(800); toll_free_number.set_national_number(uint64{12345678}); PhoneNumber test_number; bool success = phone_util_.GetExampleNumberForNonGeoEntity(800 , &test_number); EXPECT_TRUE(success); EXPECT_EQ(toll_free_number, test_number); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(uint64{123456789}); success = phone_util_.GetExampleNumberForNonGeoEntity(979 , &test_number); EXPECT_TRUE(success); EXPECT_EQ(universal_premium_rate, test_number); } TEST_F(PhoneNumberUtilTest, GetExampleNumberWithoutRegion) { PhoneNumber test_number; bool success = phone_util_.GetExampleNumberForType( PhoneNumberUtil::FIXED_LINE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); test_number.Clear(); success = phone_util_.GetExampleNumberForType(PhoneNumberUtil::MOBILE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); test_number.Clear(); success = phone_util_.GetExampleNumberForType(PhoneNumberUtil::PREMIUM_RATE, &test_number); EXPECT_TRUE(success); EXPECT_NE(PhoneNumber::default_instance(), test_number); } TEST_F(PhoneNumberUtilTest, FormatUSNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{6502530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("650 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 650 253 0000", formatted_number); test_number.set_national_number(uint64{8002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("800 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 800 253 0000", formatted_number); test_number.set_national_number(uint64{9002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("900 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 900 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ("tel:+1-900-253-0000", formatted_number); test_number.set_national_number(uint64{0}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("0", formatted_number); test_number.set_raw_input("000-000-0000"); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("000-000-0000", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatBSNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{2421234567}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("242 123 4567", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 242 123 4567", formatted_number); test_number.set_national_number(uint64{8002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("800 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 800 253 0000", formatted_number); test_number.set_national_number(uint64{9002530000}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("900 253 0000", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+1 900 253 0000", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatGBNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(44); test_number.set_national_number(uint64{2087389353}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("(020) 8738 9353", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+44 20 8738 9353", formatted_number); test_number.set_national_number(uint64{7912345678}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("(07912) 345 678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+44 7912 345 678", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatDENumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(49); test_number.set_national_number(uint64{301234}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("030/1234", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 30/1234", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ("tel:+49-30-1234", formatted_number); test_number.set_national_number(uint64{291123}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("0291 123", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 291 123", formatted_number); test_number.set_national_number(uint64{29112345678}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("0291 12345678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 291 12345678", formatted_number); test_number.set_national_number(uint64{9123123}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("09123 123", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 9123 123", formatted_number); test_number.set_national_number(uint64{80212345}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("08021 2345", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 8021 2345", formatted_number); test_number.set_national_number(uint64{1234}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("1234", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+49 1234", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatITNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(39); test_number.set_national_number(uint64{236618300}); test_number.set_italian_leading_zero(true); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("02 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+39 02 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+390236618300", formatted_number); test_number.set_national_number(uint64{345678901}); test_number.set_italian_leading_zero(false); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("345 678 901", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+39 345 678 901", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+39345678901", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatAUNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(61); test_number.set_national_number(uint64{236618300}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("02 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+61 2 3661 8300", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+61236618300", formatted_number); test_number.set_national_number(uint64{1800123456}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("1800 123 456", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+61 1800 123 456", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+611800123456", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatARNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(54); test_number.set_national_number(uint64{1187654321}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("011 8765-4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+54 11 8765-4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+541187654321", formatted_number); test_number.set_national_number(uint64{91187654321}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("011 15 8765-4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+54 9 11 8765 4321", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+5491187654321", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatMXNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(52); test_number.set_national_number(uint64{12345678900}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("045 234 567 8900", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 1 234 567 8900", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+5212345678900", formatted_number); test_number.set_national_number(uint64{15512345678}); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("045 55 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 1 55 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+5215512345678", formatted_number); test_number.set_national_number(3312345678LL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("01 33 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 33 1234 5678", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+523312345678", formatted_number); test_number.set_national_number(8211234567LL); phone_util_.Format(test_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("01 821 123 4567", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+52 821 123 4567", formatted_number); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+528211234567", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryCallingNumber) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{9002530000}); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::DE(), &formatted_number); EXPECT_EQ("00 1 900 253 0000", formatted_number); test_number.set_national_number(uint64{6502530000}); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::BS(), &formatted_number); EXPECT_EQ("1 650 253 0000", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::PL(), &formatted_number); EXPECT_EQ("00 1 650 253 0000", formatted_number); test_number.set_country_code(44); test_number.set_national_number(uint64{7912345678}); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ("011 44 7912 345 678", formatted_number); test_number.set_country_code(49); test_number.set_national_number(uint64{1234}); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::GB(), &formatted_number); EXPECT_EQ("00 49 1234", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::DE(), &formatted_number); EXPECT_EQ("1234", formatted_number); test_number.set_country_code(39); test_number.set_national_number(uint64{236618300}); test_number.set_italian_leading_zero(true); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ("011 39 02 3661 8300", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::IT(), &formatted_number); EXPECT_EQ("02 3661 8300", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::SG(), &formatted_number); EXPECT_EQ("+39 02 3661 8300", formatted_number); test_number.set_country_code(65); test_number.set_national_number(uint64{94777892}); test_number.set_italian_leading_zero(false); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::SG(), &formatted_number); EXPECT_EQ("9477 7892", formatted_number); test_number.set_country_code(800); test_number.set_national_number(uint64{12345678}); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ("011 800 1234 5678", formatted_number); test_number.set_country_code(54); test_number.set_national_number(uint64{91187654321}); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ("011 54 9 11 8765 4321", formatted_number); test_number.set_extension("1234"); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::US(), &formatted_number); EXPECT_EQ("011 54 9 11 8765 4321 ext. 1234", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0011 54 9 11 8765 4321 ext. 1234", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AR(), &formatted_number); EXPECT_EQ("011 15 8765-4321 ext. 1234", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryWithInvalidRegion) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{6502530000}); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AQ(), &formatted_number); EXPECT_EQ("+1 650 253 0000", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::UN001(), &formatted_number); EXPECT_EQ("+1 650 253 0000", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryWithPreferredIntlPrefix) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(39); test_number.set_national_number(uint64{236618300}); test_number.set_italian_leading_zero(true); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0011 39 02 3661 8300", formatted_number); phone_util_.FormatOutOfCountryCallingNumber(test_number, RegionCode::UZ(), &formatted_number); EXPECT_EQ("8~10 39 02 3661 8300", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatOutOfCountryKeepingAlphaChars) { PhoneNumber alpha_numeric_number; string formatted_number; alpha_numeric_number.set_country_code(1); alpha_numeric_number.set_national_number(uint64{8007493524}); alpha_numeric_number.set_raw_input("1800 six-flag"); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0011 1 800 SIX-FLAG", formatted_number); formatted_number.clear(); alpha_numeric_number.set_raw_input("1-800-SIX-flag"); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0011 1 800-SIX-FLAG", formatted_number); formatted_number.clear(); alpha_numeric_number.set_raw_input("Call us from UK: 00 1 800 SIX-flag"); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0011 1 800 SIX-FLAG", formatted_number); formatted_number.clear(); alpha_numeric_number.set_raw_input("800 SIX-flag"); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0011 1 800 SIX-FLAG", formatted_number); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::US(), &formatted_number); EXPECT_EQ("1 800 SIX-FLAG", formatted_number); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::BS(), &formatted_number); EXPECT_EQ("1 800 SIX-FLAG", formatted_number); alpha_numeric_number.clear_raw_input(); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::DE(), &formatted_number); EXPECT_EQ("00 1 800 749 3524", formatted_number); alpha_numeric_number.set_country_code(61); alpha_numeric_number.set_national_number(uint64{827493524}); alpha_numeric_number.set_raw_input("+61 82749-FLAG"); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("082749-FLAG", formatted_number); alpha_numeric_number.set_raw_input("082749-FLAG"); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("082749-FLAG", formatted_number); alpha_numeric_number.set_national_number(uint64{18007493524}); alpha_numeric_number.set_raw_input("1-800-SIX-flag"); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("1-800-SIX-FLAG", formatted_number); formatted_number.clear(); alpha_numeric_number.set_national_number(uint64{1800749352}); phone_util_.FormatOutOfCountryCallingNumber(alpha_numeric_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("1800 749 352", formatted_number); formatted_number.clear(); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::SG(), &formatted_number); EXPECT_EQ("+61 1-800-SIX-FLAG", formatted_number); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AQ(), &formatted_number); EXPECT_EQ("+61 1-800-SIX-FLAG", formatted_number); formatted_number.clear(); alpha_numeric_number.set_country_code(0); alpha_numeric_number.set_national_number(uint64{18007493524}); alpha_numeric_number.set_raw_input("1-800-SIX-flag"); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::DE(), &formatted_number); EXPECT_EQ("1-800-SIX-flag", formatted_number); formatted_number.clear(); alpha_numeric_number.set_country_code(1); alpha_numeric_number.set_national_number(uint64{80749}); alpha_numeric_number.set_raw_input("180-SIX"); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::DE(), &formatted_number); EXPECT_EQ("00 1 180-SIX", formatted_number); phone_util_.FormatOutOfCountryKeepingAlphaChars(alpha_numeric_number, RegionCode::AQ(), &formatted_number); EXPECT_EQ("+1 180-SIX", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatWithCarrierCode) { PhoneNumber ar_number; string formatted_number; ar_number.set_country_code(54); ar_number.set_national_number(uint64{91234125678}); phone_util_.Format(ar_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("01234 12-5678", formatted_number); phone_util_.FormatNationalNumberWithCarrierCode(ar_number, "15", &formatted_number); EXPECT_EQ("01234 15 12-5678", formatted_number); phone_util_.FormatNationalNumberWithCarrierCode(ar_number, "", &formatted_number); EXPECT_EQ("01234 12-5678", formatted_number); phone_util_.Format(ar_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+5491234125678", formatted_number); PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{4241231234}); phone_util_.Format(us_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("424 123 1234", formatted_number); phone_util_.FormatNationalNumberWithCarrierCode(us_number, "15", &formatted_number); EXPECT_EQ("424 123 1234", formatted_number); PhoneNumber invalid_number; invalid_number.set_country_code(kInvalidCountryCode); invalid_number.set_national_number(uint64{12345}); phone_util_.FormatNationalNumberWithCarrierCode(invalid_number, "89", &formatted_number); EXPECT_EQ("12345", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatWithPreferredCarrierCode) { PhoneNumber ar_number; string formatted_number; ar_number.set_country_code(54); ar_number.set_national_number(uint64{91234125678}); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15", &formatted_number); EXPECT_EQ("01234 15 12-5678", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "", &formatted_number); EXPECT_EQ("01234 12-5678", formatted_number); ar_number.set_preferred_domestic_carrier_code("19"); phone_util_.Format(ar_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("01234 12-5678", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15", &formatted_number); EXPECT_EQ("01234 19 12-5678", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "", &formatted_number); EXPECT_EQ("01234 19 12-5678", formatted_number); ar_number.set_preferred_domestic_carrier_code(" "); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15", &formatted_number); EXPECT_EQ("01234 12-5678", formatted_number); ar_number.set_preferred_domestic_carrier_code(""); phone_util_.FormatNationalNumberWithPreferredCarrierCode(ar_number, "15", &formatted_number); EXPECT_EQ("01234 15 12-5678", formatted_number); PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{4241231234}); us_number.set_preferred_domestic_carrier_code("99"); phone_util_.Format(us_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("424 123 1234", formatted_number); phone_util_.FormatNationalNumberWithPreferredCarrierCode(us_number, "15", &formatted_number); EXPECT_EQ("424 123 1234", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatNumberForMobileDialing) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(57); test_number.set_national_number(uint64{6012345678}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CO(), false, &formatted_number); EXPECT_EQ("6012345678", formatted_number); test_number.set_country_code(49); test_number.set_national_number(uint64{30123456}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::DE(), false, &formatted_number); EXPECT_EQ("030123456", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CH(), false, &formatted_number); EXPECT_EQ("+4930123456", formatted_number); test_number.set_extension("1234"); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::DE(), false, &formatted_number); EXPECT_EQ("030123456", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CH(), false, &formatted_number); EXPECT_EQ("+4930123456", formatted_number); test_number.set_country_code(1); test_number.clear_extension(); test_number.set_national_number(uint64{8002530000}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, &formatted_number); EXPECT_EQ("800 253 0000", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CN(), true, &formatted_number); EXPECT_EQ("", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("8002530000", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CN(), false, &formatted_number); EXPECT_EQ("", formatted_number); test_number.set_national_number(uint64{6502530000}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, &formatted_number); EXPECT_EQ("+1 650 253 0000", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("+16502530000", formatted_number); test_number.set_extension("1234"); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, &formatted_number); EXPECT_EQ("+1 650 253 0000", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("+16502530000", formatted_number); test_number.set_national_number(uint64{65025300001}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), true, &formatted_number); EXPECT_EQ("+1 65025300001", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("+165025300001", formatted_number); test_number.set_country_code(81); test_number.set_national_number(uint64{2345}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), true, &formatted_number); EXPECT_EQ("*2345", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ("*2345", formatted_number); test_number.set_country_code(800); test_number.set_national_number(uint64{12345678}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ("+80012345678", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), true, &formatted_number); EXPECT_EQ("+800 1234 5678", formatted_number); test_number.set_country_code(971); test_number.set_national_number(uint64{600123456}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::JP(), false, &formatted_number); EXPECT_EQ("+971600123456", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::AE(), true, &formatted_number); EXPECT_EQ("600123456", formatted_number); test_number.set_country_code(52); test_number.set_national_number(uint64{3312345678}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::MX(), false, &formatted_number); EXPECT_EQ("+523312345678", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("+523312345678", formatted_number); test_number.set_country_code(998); test_number.set_national_number(uint64{612201234}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::UZ(), false, &formatted_number); EXPECT_EQ("+998612201234", formatted_number); test_number.set_country_code(998); test_number.set_national_number(uint64{950123456}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::UZ(), false, &formatted_number); EXPECT_EQ("+998950123456", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("+998950123456", formatted_number); test_number.set_country_code(800); test_number.set_national_number(uint64{12345678}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("+80012345678", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::UN001(), false, &formatted_number); EXPECT_EQ("+80012345678", formatted_number); test_number.set_country_code(49); test_number.set_national_number(123L); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::DE(), false, &formatted_number); EXPECT_EQ("123", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::IT(), false, &formatted_number); EXPECT_EQ("", formatted_number); test_number.set_country_code(1); test_number.set_national_number(uint64{6502530000}); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("+16502530000", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CA(), false, &formatted_number); EXPECT_EQ("+16502530000", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::BR(), false, &formatted_number); EXPECT_EQ("+16502530000", formatted_number); test_number.set_national_number(911L); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::US(), false, &formatted_number); EXPECT_EQ("911", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::CA(), false, &formatted_number); EXPECT_EQ("", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::BR(), false, &formatted_number); EXPECT_EQ("", formatted_number); test_number.set_country_code(61); test_number.set_national_number(0L); test_number.set_italian_leading_zero(true); test_number.set_number_of_leading_zeros(2); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::AU(), false, &formatted_number); EXPECT_EQ("000", formatted_number); phone_util_.FormatNumberForMobileDialing( test_number, RegionCode::NZ(), false, &formatted_number); EXPECT_EQ("", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatByPattern) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{6502530000}); RepeatedPtrField<NumberFormat> number_formats; NumberFormat* number_format = number_formats.Add(); number_format->set_pattern("(\\d{3})(\\d{3})(\\d{4})"); number_format->set_format("($1) $2-$3"); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ("(650) 253-0000", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ("+1 (650) 253-0000", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::RFC3966, number_formats, &formatted_number); EXPECT_EQ("tel:+1-650-253-0000", formatted_number); number_format->set_national_prefix_formatting_rule("$NP ($FG)"); number_format->set_format("$1 $2-$3"); test_number.set_country_code(1); test_number.set_national_number(uint64{4168819999}); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ("1 (416) 881-9999", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ("+1 416 881-9999", formatted_number); test_number.set_country_code(39); test_number.set_national_number(uint64{236618300}); test_number.set_italian_leading_zero(true); number_format->set_pattern("(\\d{2})(\\d{5})(\\d{3})"); number_format->set_format("$1-$2 $3"); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ("02-36618 300", formatted_number); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ("+39 02-36618 300", formatted_number); test_number.set_country_code(44); test_number.set_national_number(uint64{2012345678}); test_number.set_italian_leading_zero(false); number_format->set_national_prefix_formatting_rule("$NP$FG"); number_format->set_pattern("(\\d{2})(\\d{4})(\\d{4})"); number_format->set_format("$1 $2 $3"); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ("020 1234 5678", formatted_number); number_format->set_national_prefix_formatting_rule("($NP$FG)"); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ("(020) 1234 5678", formatted_number); number_format->set_national_prefix_formatting_rule(""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::NATIONAL, number_formats, &formatted_number); EXPECT_EQ("20 1234 5678", formatted_number); number_format->set_national_prefix_formatting_rule(""); phone_util_.FormatByPattern(test_number, PhoneNumberUtil::INTERNATIONAL, number_formats, &formatted_number); EXPECT_EQ("+44 20 1234 5678", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatE164Number) { PhoneNumber test_number; string formatted_number; test_number.set_country_code(1); test_number.set_national_number(uint64{6502530000}); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+16502530000", formatted_number); test_number.set_country_code(49); test_number.set_national_number(uint64{301234}); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+49301234", formatted_number); test_number.set_country_code(800); test_number.set_national_number(uint64{12345678}); phone_util_.Format(test_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+80012345678", formatted_number); } TEST_F(PhoneNumberUtilTest, FormatNumberWithExtension) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{33316005}); nz_number.set_extension("1234"); string formatted_number; phone_util_.Format(nz_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("03-331 6005 ext. 1234", formatted_number); phone_util_.Format(nz_number, PhoneNumberUtil::RFC3966, &formatted_number); EXPECT_EQ("tel:+64-3-331-6005;ext=1234", formatted_number); PhoneNumber us_number_with_extension; us_number_with_extension.set_country_code(1); us_number_with_extension.set_national_number(uint64{6502530000}); us_number_with_extension.set_extension("4567"); phone_util_.Format(us_number_with_extension, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("650 253 0000 extn. 4567", formatted_number); } TEST_F(PhoneNumberUtilTest, GetLengthOfGeographicalAreaCode) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{6502530000}); EXPECT_EQ(3, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(1); number.set_national_number(uint64{8002530000}); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(1); number.set_national_number(uint64{650253000}); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(44); number.set_national_number(uint64{2070313000}); EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(44); number.set_national_number(uint64{7912345678}); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(54); number.set_national_number(uint64{1155303000}); EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(54); number.set_national_number(uint64{91187654321}); EXPECT_EQ(3, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(61); number.set_national_number(uint64{293744000}); EXPECT_EQ(1, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(52); number.set_national_number(uint64_t{3312345678}); EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(39); number.set_national_number(uint64{236618300}); number.set_italian_leading_zero(true); EXPECT_EQ(2, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(65); number.set_national_number(uint64{65218000}); number.set_italian_leading_zero(false); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); number.set_country_code(800); number.set_national_number(uint64{12345678}); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(number)); PhoneNumber cn_mobile; cn_mobile.set_country_code(86); cn_mobile.set_national_number(uint64{18912341234}); EXPECT_EQ(0, phone_util_.GetLengthOfGeographicalAreaCode(cn_mobile)); } TEST_F(PhoneNumberUtilTest, GetLengthOfNationalDestinationCode) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{6502530000}); EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(1); number.set_national_number(uint64{8002530000}); EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(44); number.set_national_number(uint64{2070313000}); EXPECT_EQ(2, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(44); number.set_national_number(uint64{7912345678}); EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(54); number.set_national_number(uint64{1155303000}); EXPECT_EQ(2, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(54); number.set_national_number(uint64{91187654321}); EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(61); number.set_national_number(uint64{293744000}); EXPECT_EQ(1, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(65); number.set_national_number(uint64{65218000}); EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(1); number.set_national_number(uint64{650253000}); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(123); number.set_national_number(uint64{650253000}); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(376); number.set_national_number(uint64{12345}); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); number.set_country_code(376); number.set_national_number(uint64{12345}); number.set_extension("321"); EXPECT_EQ(0, phone_util_.GetLengthOfNationalDestinationCode(number)); number.Clear(); number.set_country_code(800); number.set_national_number(uint64{12345678}); EXPECT_EQ(4, phone_util_.GetLengthOfNationalDestinationCode(number)); PhoneNumber cn_mobile; cn_mobile.set_country_code(86); cn_mobile.set_national_number(uint64{18912341234}); EXPECT_EQ(3, phone_util_.GetLengthOfNationalDestinationCode(cn_mobile)); } TEST_F(PhoneNumberUtilTest, GetCountryMobileToken) { int country_calling_code; string mobile_token; country_calling_code = phone_util_.GetCountryCodeForRegion(RegionCode::AR()); phone_util_.GetCountryMobileToken(country_calling_code, &mobile_token); EXPECT_EQ("9", mobile_token); country_calling_code = phone_util_.GetCountryCodeForRegion(RegionCode::SE()); phone_util_.GetCountryMobileToken(country_calling_code, &mobile_token); EXPECT_EQ("", mobile_token); } TEST_F(PhoneNumberUtilTest, ExtractPossibleNumber) { string extracted_number; ExtractPossibleNumber("Tel:0800-345-600", &extracted_number); EXPECT_EQ("0800-345-600", extracted_number); ExtractPossibleNumber("Tel:0800 FOR PIZZA", &extracted_number); EXPECT_EQ("0800 FOR PIZZA", extracted_number); ExtractPossibleNumber("Tel:+800-345-600", &extracted_number); EXPECT_EQ("+800-345-600", extracted_number); ExtractPossibleNumber("\xEF\xBC\x90\xEF\xBC\x92\xEF\xBC\x93" , &extracted_number); EXPECT_EQ("\xEF\xBC\x90\xEF\xBC\x92\xEF\xBC\x93" , extracted_number); ExtractPossibleNumber("Num-\xEF\xBC\x91\xEF\xBC\x92\xEF\xBC\x93" , &extracted_number); EXPECT_EQ("\xEF\xBC\x91\xEF\xBC\x92\xEF\xBC\x93" , extracted_number); ExtractPossibleNumber("Num-....", &extracted_number); EXPECT_EQ("", extracted_number); ExtractPossibleNumber("(650) 253-0000", &extracted_number); EXPECT_EQ("650) 253-0000", extracted_number); ExtractPossibleNumber("(650) 253-0000..- ..", &extracted_number); EXPECT_EQ("650) 253-0000", extracted_number); ExtractPossibleNumber("(650) 253-0000.", &extracted_number); EXPECT_EQ("650) 253-0000", extracted_number); ExtractPossibleNumber("(650) 253-0000\xE2\x80\x8F" , &extracted_number); EXPECT_EQ("650) 253-0000", extracted_number); } TEST_F(PhoneNumberUtilTest, IsNANPACountry) { EXPECT_TRUE(phone_util_.IsNANPACountry(RegionCode::US())); EXPECT_TRUE(phone_util_.IsNANPACountry(RegionCode::BS())); EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::DE())); EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::GetUnknown())); EXPECT_FALSE(phone_util_.IsNANPACountry(RegionCode::UN001())); } TEST_F(PhoneNumberUtilTest, IsValidNumber) { PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{6502530000}); EXPECT_TRUE(phone_util_.IsValidNumber(us_number)); PhoneNumber it_number; it_number.set_country_code(39); it_number.set_national_number(uint64{236618300}); it_number.set_italian_leading_zero(true); EXPECT_TRUE(phone_util_.IsValidNumber(it_number)); PhoneNumber gb_number; gb_number.set_country_code(44); gb_number.set_national_number(uint64{7912345678}); EXPECT_TRUE(phone_util_.IsValidNumber(gb_number)); PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{21387835}); EXPECT_TRUE(phone_util_.IsValidNumber(nz_number)); PhoneNumber intl_toll_free_number; intl_toll_free_number.set_country_code(800); intl_toll_free_number.set_national_number(uint64{12345678}); EXPECT_TRUE(phone_util_.IsValidNumber(intl_toll_free_number)); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(uint64{123456789}); EXPECT_TRUE(phone_util_.IsValidNumber(universal_premium_rate)); } TEST_F(PhoneNumberUtilTest, IsValidForRegion) { PhoneNumber bs_number; bs_number.set_country_code(1); bs_number.set_national_number(uint64{2423232345}); EXPECT_TRUE(phone_util_.IsValidNumber(bs_number)); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(bs_number, RegionCode::BS())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(bs_number, RegionCode::US())); bs_number.set_national_number(uint64{2421232345}); EXPECT_FALSE(phone_util_.IsValidNumber(bs_number)); PhoneNumber re_number; re_number.set_country_code(262); re_number.set_national_number(uint64{262123456}); EXPECT_TRUE(phone_util_.IsValidNumber(re_number)); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); re_number.set_national_number(uint64{269601234}); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); re_number.set_national_number(uint64{269123456}); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); EXPECT_FALSE(phone_util_.IsValidNumber(re_number)); string region_code; phone_util_.GetRegionCodeForNumber(re_number, &region_code); EXPECT_EQ(RegionCode::YT(), region_code); re_number.set_national_number(uint64{800123456}); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::YT())); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(re_number, RegionCode::RE())); PhoneNumber intl_toll_free_number; intl_toll_free_number.set_country_code(800); intl_toll_free_number.set_national_number(uint64{12345678}); EXPECT_TRUE(phone_util_.IsValidNumberForRegion(intl_toll_free_number, RegionCode::UN001())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(intl_toll_free_number, RegionCode::US())); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(intl_toll_free_number, RegionCode::ZZ())); PhoneNumber invalid_number; invalid_number.set_country_code(3923); invalid_number.set_national_number(uint64{2366}); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::ZZ())); invalid_number.set_country_code(3923); invalid_number.set_national_number(uint64{2366}); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::UN001())); invalid_number.set_country_code(0); invalid_number.set_national_number(uint64{2366}); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::UN001())); invalid_number.set_country_code(0); EXPECT_FALSE(phone_util_.IsValidNumberForRegion(invalid_number, RegionCode::ZZ())); } TEST_F(PhoneNumberUtilTest, IsNotValidNumber) { PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{2530000}); EXPECT_FALSE(phone_util_.IsValidNumber(us_number)); PhoneNumber it_number; it_number.set_country_code(39); it_number.set_national_number(uint64{23661830000}); it_number.set_italian_leading_zero(true); EXPECT_FALSE(phone_util_.IsValidNumber(it_number)); PhoneNumber gb_number; gb_number.set_country_code(44); gb_number.set_national_number(uint64{791234567}); EXPECT_FALSE(phone_util_.IsValidNumber(gb_number)); PhoneNumber de_number; de_number.set_country_code(49); de_number.set_national_number(uint64{1234}); EXPECT_FALSE(phone_util_.IsValidNumber(de_number)); PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{3316005}); EXPECT_FALSE(phone_util_.IsValidNumber(nz_number)); PhoneNumber invalid_number; invalid_number.set_country_code(3923); invalid_number.set_national_number(uint64{2366}); EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number)); invalid_number.set_country_code(0); EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number)); PhoneNumber intl_toll_free_number_too_long; intl_toll_free_number_too_long.set_country_code(800); intl_toll_free_number_too_long.set_national_number(uint64{123456789}); EXPECT_FALSE(phone_util_.IsValidNumber(intl_toll_free_number_too_long)); } TEST_F(PhoneNumberUtilTest, GetRegionCodeForCountryCode) { string region_code; phone_util_.GetRegionCodeForCountryCode(1, &region_code); EXPECT_EQ(RegionCode::US(), region_code); phone_util_.GetRegionCodeForCountryCode(44, &region_code); EXPECT_EQ(RegionCode::GB(), region_code); phone_util_.GetRegionCodeForCountryCode(49, &region_code); EXPECT_EQ(RegionCode::DE(), region_code); phone_util_.GetRegionCodeForCountryCode(800, &region_code); EXPECT_EQ(RegionCode::UN001(), region_code); phone_util_.GetRegionCodeForCountryCode(979, &region_code); EXPECT_EQ(RegionCode::UN001(), region_code); } TEST_F(PhoneNumberUtilTest, GetRegionCodeForNumber) { string region_code; PhoneNumber bs_number; bs_number.set_country_code(1); bs_number.set_national_number(uint64{2423232345}); phone_util_.GetRegionCodeForNumber(bs_number, &region_code); EXPECT_EQ(RegionCode::BS(), region_code); PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{4241231234}); phone_util_.GetRegionCodeForNumber(us_number, &region_code); EXPECT_EQ(RegionCode::US(), region_code); PhoneNumber gb_mobile; gb_mobile.set_country_code(44); gb_mobile.set_national_number(uint64{7912345678}); phone_util_.GetRegionCodeForNumber(gb_mobile, &region_code); EXPECT_EQ(RegionCode::GB(), region_code); PhoneNumber intl_toll_free_number; intl_toll_free_number.set_country_code(800); intl_toll_free_number.set_national_number(uint64{12345678}); phone_util_.GetRegionCodeForNumber(intl_toll_free_number, &region_code); EXPECT_EQ(RegionCode::UN001(), region_code); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(uint64{123456789}); phone_util_.GetRegionCodeForNumber(universal_premium_rate, &region_code); EXPECT_EQ(RegionCode::UN001(), region_code); } TEST_F(PhoneNumberUtilTest, IsPossibleNumber) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{6502530000}); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); number.set_country_code(1); number.set_national_number(uint64{2530000}); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); number.set_country_code(44); number.set_national_number(uint64{2070313000}); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); number.set_country_code(800); number.set_national_number(uint64{12345678}); EXPECT_TRUE(phone_util_.IsPossibleNumber(number)); EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+1 650 253 0000", RegionCode::US())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+1 650 GOO OGLE", RegionCode::US())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString("(650) 253-0000", RegionCode::US())); EXPECT_TRUE( phone_util_.IsPossibleNumberForString("253-0000", RegionCode::US())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+1 650 253 0000", RegionCode::GB())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+44 20 7031 3000", RegionCode::GB())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString("(020) 7031 300", RegionCode::GB())); EXPECT_TRUE( phone_util_.IsPossibleNumberForString("7031 3000", RegionCode::GB())); EXPECT_TRUE( phone_util_.IsPossibleNumberForString("3331 6005", RegionCode::NZ())); EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+800 1234 5678", RegionCode::UN001())); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForType_DifferentTypeLengths) { PhoneNumber number; number.set_country_code(54); number.set_national_number(uint64{12345}); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); number.set_national_number(uint64{123456}); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE)); number.set_national_number(uint64{123456789}); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE)); number.set_national_number(uint64{1234567890}); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE)); number.set_national_number(uint64{12345678901}); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::TOLL_FREE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForType_LocalOnly) { PhoneNumber number; number.set_country_code(49); number.set_national_number(uint64{12}); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForType_DataMissingForSizeReasons) { PhoneNumber number; number.set_country_code(55); number.set_national_number(uint64{12345678}); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); number.set_national_number(uint64{1234567890}); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::UNKNOWN)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForType_NumberTypeNotSupportedForRegion) { PhoneNumber number; number.set_country_code(55); number.set_national_number(12345678L); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE)); EXPECT_TRUE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_TRUE(phone_util_.IsPossibleNumberForType( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); number.set_country_code(979); number.set_national_number(123456789L); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::MOBILE)); EXPECT_FALSE( phone_util_.IsPossibleNumberForType(number, PhoneNumberUtil::FIXED_LINE)); EXPECT_FALSE(phone_util_.IsPossibleNumberForType( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); EXPECT_TRUE(phone_util_.IsPossibleNumberForType( number, PhoneNumberUtil::PREMIUM_RATE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberWithReason) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{6502530000}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(1); number.set_national_number(uint64{2530000}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(0); number.set_national_number(uint64{2530000}); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(1); number.set_national_number(uint64{253000}); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(1); number.set_national_number(uint64{65025300000}); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(44); number.set_national_number(uint64{2070310000}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(49); number.set_national_number(uint64{30123456}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(65); number.set_national_number(uint64{1234567890}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberWithReason(number)); number.set_country_code(800); number.set_national_number(uint64{123456789}); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberWithReason(number)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForTypeWithReason_DifferentTypeLengths) { PhoneNumber number; number.set_country_code(54); number.set_national_number(uint64{12345}); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); number.set_national_number(uint64{123456}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::TOLL_FREE)); number.set_national_number(uint64{123456789}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::TOLL_FREE)); number.set_national_number(uint64{1234567890}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::TOLL_FREE)); number.set_national_number(uint64{12345678901}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::TOLL_FREE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForTypeWithReason_LocalOnly) { PhoneNumber number; number.set_country_code(49); number.set_national_number(uint64{12}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForTypeWithReason_DataMissingForSizeReasons) { PhoneNumber number; number.set_country_code(55); number.set_national_number(uint64{12345678}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); number.set_national_number(uint64{1234567890}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::UNKNOWN)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForTypeWithReason_NumberTypeNotSupportedForRegion) { PhoneNumber number; number.set_country_code(55); number.set_national_number(uint64{12345678}); EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE_LOCAL_ONLY, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); number.set_national_number(uint64{1234567}); EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); number.set_country_code(882); number.set_national_number(uint64{1234567}); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); number.set_country_code(979); number.set_national_number(uint64{123456789}); EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::PREMIUM_RATE)); } TEST_F(PhoneNumberUtilTest, IsPossibleNumberForTypeWithReason_FixedLineOrMobile) { PhoneNumber number; number.set_country_code(290); number.set_national_number(uint64{1234}); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); number.set_national_number(uint64{12345}); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::INVALID_LENGTH, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); number.set_national_number(uint64{123456}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); number.set_national_number(uint64{1234567}); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE)); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::MOBILE)); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); number.set_national_number(uint64{12345678}); EXPECT_EQ(PhoneNumberUtil::IS_POSSIBLE, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::TOLL_FREE)); EXPECT_EQ(PhoneNumberUtil::TOO_LONG, phone_util_.IsPossibleNumberForTypeWithReason( number, PhoneNumberUtil::FIXED_LINE_OR_MOBILE)); } TEST_F(PhoneNumberUtilTest, IsNotPossibleNumber) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{65025300000}); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); number.set_country_code(800); number.set_national_number(uint64{123456789}); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); number.set_country_code(1); number.set_national_number(uint64{253000}); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); number.set_country_code(44); number.set_national_number(uint64{300}); EXPECT_FALSE(phone_util_.IsPossibleNumber(number)); EXPECT_FALSE(phone_util_.IsPossibleNumberForString("+1 650 253 00000", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString("(650) 253-00000", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString("I want a Pizza", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString("253-000", RegionCode::US())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString("1 3000", RegionCode::GB())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString("+44 300", RegionCode::GB())); EXPECT_FALSE(phone_util_.IsPossibleNumberForString("+800 1234 5678 9", RegionCode::UN001())); } TEST_F(PhoneNumberUtilTest, TruncateTooLongNumber) { PhoneNumber too_long_number; too_long_number.set_country_code(1); too_long_number.set_national_number(uint64{65025300001}); PhoneNumber valid_number; valid_number.set_country_code(1); valid_number.set_national_number(uint64{6502530000}); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); too_long_number.set_country_code(800); too_long_number.set_national_number(uint64{123456789}); valid_number.set_country_code(800); valid_number.set_national_number(uint64{12345678}); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); too_long_number.set_country_code(44); too_long_number.set_national_number(uint64{80123456780123}); valid_number.set_country_code(44); valid_number.set_national_number(uint64{8012345678}); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); too_long_number.set_country_code(39); too_long_number.set_national_number(uint64{2234567890123}); too_long_number.set_italian_leading_zero(true); valid_number.set_country_code(39); valid_number.set_national_number(uint64{2234567890}); valid_number.set_italian_leading_zero(true); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&too_long_number)); EXPECT_EQ(valid_number, too_long_number); PhoneNumber valid_number_copy(valid_number); EXPECT_TRUE(phone_util_.TruncateTooLongNumber(&valid_number)); EXPECT_EQ(valid_number_copy, valid_number); PhoneNumber number_with_invalid_prefix; number_with_invalid_prefix.set_country_code(1); number_with_invalid_prefix.set_national_number(uint64{2401234567}); PhoneNumber invalid_number_copy(number_with_invalid_prefix); EXPECT_FALSE(phone_util_.TruncateTooLongNumber(&number_with_invalid_prefix)); EXPECT_EQ(invalid_number_copy, number_with_invalid_prefix); PhoneNumber too_short_number; too_short_number.set_country_code(1); too_short_number.set_national_number(uint64{1234}); PhoneNumber too_short_number_copy(too_short_number); EXPECT_FALSE(phone_util_.TruncateTooLongNumber(&too_short_number)); EXPECT_EQ(too_short_number_copy, too_short_number); } TEST_F(PhoneNumberUtilTest, IsNumberGeographical) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{2423570000}); EXPECT_FALSE(phone_util_.IsNumberGeographical(number)); number.set_country_code(61); number.set_national_number(uint64{236618300}); EXPECT_TRUE(phone_util_.IsNumberGeographical(number)); number.set_country_code(800); number.set_national_number(uint64{12345678}); EXPECT_FALSE(phone_util_.IsNumberGeographical(number)); number.set_country_code(54); number.set_national_number(uint64{91187654321}); EXPECT_TRUE(phone_util_.IsNumberGeographical(number)); number.set_country_code(52); number.set_national_number(uint64{12345678900}); EXPECT_TRUE(phone_util_.IsNumberGeographical(number)); number.set_country_code(52); number.set_national_number(uint64{15512345678}); EXPECT_TRUE(phone_util_.IsNumberGeographical(number)); } TEST_F(PhoneNumberUtilTest, FormatInOriginalFormat) { PhoneNumber phone_number; string formatted_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("+442087654321", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ("+44 20 8765 4321", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("02087654321", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ("(020) 8765 4321", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("011442087654321", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ("011 44 20 8765 4321", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("442087654321", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ("44 20 8765 4321", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+442087654321", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ("(020) 8765 4321", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("7345678901", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ("734 567 8901", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("0734567 8901", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ("0734567 8901", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("02-4567-8900", RegionCode::KR(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::KR(), &formatted_number); EXPECT_EQ("02-4567-8900", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("01180012345678", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ("011 800 1234 5678", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("+80012345678", RegionCode::KR(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::KR(), &formatted_number); EXPECT_EQ("+800 1234 5678", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("2530000", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ("253 0000", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("18003456789", RegionCode::US(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ("1 800 345 6789", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("2087654321", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ("20 8765 4321", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+442087654321", RegionCode::GB(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::GB(), &formatted_number); EXPECT_EQ("(020) 8765 4321", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("013312345678", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ("01 33 1234 5678", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("3312345678", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ("33 1234 5678", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("0212345678", RegionCode::IT(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::IT(), &formatted_number); EXPECT_EQ("02 1234 5678", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("00777012", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ("0077-7012", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("0777012", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ("0777012", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("012 3121286979", RegionCode::BR(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::BR(), &formatted_number); EXPECT_EQ("012 3121286979", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("044(33)1234-5678", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ("044(33)1234-5678", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("045(33)1234-5678", RegionCode::MX(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::MX(), &formatted_number); EXPECT_EQ("045 33 1234 5678", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("0012 16502530000", RegionCode::AU(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0012 16502530000", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("0011 16502530000", RegionCode::AU(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::AU(), &formatted_number); EXPECT_EQ("0011 1 650 253 0000", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("*1234", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ("*1234", formatted_number); phone_number.Clear(); formatted_number.clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("1234", RegionCode::JP(), &phone_number)); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::JP(), &formatted_number); EXPECT_EQ("1234", formatted_number); phone_number.Clear(); formatted_number.clear(); phone_number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); phone_number.set_country_code(1); phone_number.set_national_number(uint64{650253000}); phone_util_.FormatInOriginalFormat(phone_number, RegionCode::US(), &formatted_number); EXPECT_EQ("650253000", formatted_number); } TEST_F(PhoneNumberUtilTest, IsPremiumRate) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{9004433030}); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(39); number.set_national_number(uint64{892123}); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(44); number.set_national_number(uint64{9187654321}); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(uint64{9001654321}); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(uint64{90091234567}); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); number.set_country_code(979); number.set_national_number(uint64{123456789}); EXPECT_EQ(PhoneNumberUtil::PREMIUM_RATE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsTollFree) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{8881234567}); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(39); number.set_national_number(uint64{803123}); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(44); number.set_national_number(uint64{8012345678}); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(uint64{8001234567}); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); number.set_country_code(800); number.set_national_number(uint64{12345678}); EXPECT_EQ(PhoneNumberUtil::TOLL_FREE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsMobile) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{2423570000}); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(39); number.set_national_number(uint64{312345678}); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(44); number.set_national_number(uint64{7912345678}); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(uint64{15123456789}); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(54); number.set_national_number(uint64{91187654321}); EXPECT_EQ(PhoneNumberUtil::MOBILE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsFixedLine) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{2423651234}); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); number.Clear(); number.set_country_code(39); number.set_national_number(uint64{236618300}); number.set_italian_leading_zero(true); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); number.Clear(); number.set_country_code(44); number.set_national_number(uint64{2012345678}); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); number.set_country_code(49); number.set_national_number(uint64{301234}); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsFixedLineAndMobile) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{6502531111}); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE_OR_MOBILE, phone_util_.GetNumberType(number)); number.set_country_code(54); number.set_national_number(uint64{1987654321}); EXPECT_EQ(PhoneNumberUtil::FIXED_LINE_OR_MOBILE, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsSharedCost) { PhoneNumber number; number.set_country_code(44); number.set_national_number(uint64{8431231234}); EXPECT_EQ(PhoneNumberUtil::SHARED_COST, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsVoip) { PhoneNumber number; number.set_country_code(44); number.set_national_number(uint64{5631231234}); EXPECT_EQ(PhoneNumberUtil::VOIP, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsPersonalNumber) { PhoneNumber number; number.set_country_code(44); number.set_national_number(uint64{7031231234}); EXPECT_EQ(PhoneNumberUtil::PERSONAL_NUMBER, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, IsUnknown) { PhoneNumber number; number.set_country_code(1); number.set_national_number(uint64{65025311111}); EXPECT_EQ(PhoneNumberUtil::UNKNOWN, phone_util_.GetNumberType(number)); } TEST_F(PhoneNumberUtilTest, GetCountryCodeForRegion) { EXPECT_EQ(1, phone_util_.GetCountryCodeForRegion(RegionCode::US())); EXPECT_EQ(64, phone_util_.GetCountryCodeForRegion(RegionCode::NZ())); EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::GetUnknown())); EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::UN001())); EXPECT_EQ(0, phone_util_.GetCountryCodeForRegion(RegionCode::CS())); } TEST_F(PhoneNumberUtilTest, GetNationalDiallingPrefixForRegion) { string ndd_prefix; phone_util_.GetNddPrefixForRegion(RegionCode::US(), false, &ndd_prefix); EXPECT_EQ("1", ndd_prefix); ndd_prefix.clear(); phone_util_.GetNddPrefixForRegion(RegionCode::BS(), false, &ndd_prefix); EXPECT_EQ("1", ndd_prefix); ndd_prefix.clear(); phone_util_.GetNddPrefixForRegion(RegionCode::NZ(), false, &ndd_prefix); EXPECT_EQ("0", ndd_prefix); ndd_prefix.clear(); phone_util_.GetNddPrefixForRegion(RegionCode::AO(), false, &ndd_prefix); EXPECT_EQ("0~0", ndd_prefix); ndd_prefix.clear(); phone_util_.GetNddPrefixForRegion(RegionCode::AO(), true, &ndd_prefix); EXPECT_EQ("00", ndd_prefix); ndd_prefix.clear(); phone_util_.GetNddPrefixForRegion(RegionCode::GetUnknown(), false, &ndd_prefix); EXPECT_EQ("", ndd_prefix); ndd_prefix.clear(); phone_util_.GetNddPrefixForRegion(RegionCode::UN001(), false, &ndd_prefix); EXPECT_EQ("", ndd_prefix); ndd_prefix.clear(); phone_util_.GetNddPrefixForRegion(RegionCode::CS(), false, &ndd_prefix); EXPECT_EQ("", ndd_prefix); } TEST_F(PhoneNumberUtilTest, IsViablePhoneNumber) { EXPECT_FALSE(IsViablePhoneNumber("1")); EXPECT_FALSE(IsViablePhoneNumber("1+1+1")); EXPECT_FALSE(IsViablePhoneNumber("80+0")); EXPECT_TRUE(IsViablePhoneNumber("00")); EXPECT_TRUE(IsViablePhoneNumber("111")); EXPECT_TRUE(IsViablePhoneNumber("0800-4-pizza")); EXPECT_TRUE(IsViablePhoneNumber("0800-4-PIZZA")); EXPECT_FALSE(IsViablePhoneNumber("08-PIZZA")); EXPECT_FALSE(IsViablePhoneNumber("8-PIZZA")); EXPECT_FALSE(IsViablePhoneNumber("12. March")); } TEST_F(PhoneNumberUtilTest, IsViablePhoneNumberNonAscii) { EXPECT_TRUE(IsViablePhoneNumber("1\xE3\x80\x80" "34" )); EXPECT_FALSE(IsViablePhoneNumber("1\xE3\x80\x80" "3+4" )); EXPECT_TRUE(IsViablePhoneNumber("\xEF\xBC\x88" "1\xEF\xBC\x89\xE3\x80\x80" "3456789" )); EXPECT_TRUE(IsViablePhoneNumber("+1\xEF\xBC\x89\xE3\x80\x80" "3456789" )); } TEST_F(PhoneNumberUtilTest, ConvertAlphaCharactersInNumber) { string input("1800-ABC-DEF"); phone_util_.ConvertAlphaCharactersInNumber(&input); static const string kExpectedOutput = "1800-222-333"; EXPECT_EQ(kExpectedOutput, input); input.assign("1\xE3\x80\x80\xEF\xBC\x88" "800) ABC-DEF" ); static const string kExpectedFullwidthOutput = "1\xE3\x80\x80\xEF\xBC\x88" "800) 222-333" ; phone_util_.ConvertAlphaCharactersInNumber(&input); EXPECT_EQ(kExpectedFullwidthOutput, input); } TEST_F(PhoneNumberUtilTest, NormaliseRemovePunctuation) { string input_number("034-56&+#2" "\xC2\xAD" "34"); Normalize(&input_number); static const string kExpectedOutput("03456234"); EXPECT_EQ(kExpectedOutput, input_number) << "Conversion did not correctly remove punctuation"; } TEST_F(PhoneNumberUtilTest, NormaliseReplaceAlphaCharacters) { string input_number("034-I-am-HUNGRY"); Normalize(&input_number); static const string kExpectedOutput("034426486479"); EXPECT_EQ(kExpectedOutput, input_number) << "Conversion did not correctly replace alpha characters"; } TEST_F(PhoneNumberUtilTest, NormaliseOtherDigits) { string input_number("\xEF\xBC\x92" "5\xD9\xA5" ); Normalize(&input_number); static const string kExpectedOutput("255"); EXPECT_EQ(kExpectedOutput, input_number) << "Conversion did not correctly replace non-latin digits"; string eastern_arabic_input_number("\xDB\xB5" "2\xDB\xB0" ); Normalize(&eastern_arabic_input_number); static const string kExpectedOutput2("520"); EXPECT_EQ(kExpectedOutput2, eastern_arabic_input_number) << "Conversion did not correctly replace non-latin digits"; } TEST_F(PhoneNumberUtilTest, NormaliseStripAlphaCharacters) { string input_number("034-56&+a#234"); phone_util_.NormalizeDigitsOnly(&input_number); static const string kExpectedOutput("03456234"); EXPECT_EQ(kExpectedOutput, input_number) << "Conversion did not correctly remove alpha characters"; } TEST_F(PhoneNumberUtilTest, NormaliseStripNonDiallableCharacters) { string input_number("03*4-56&+1a#234"); phone_util_.NormalizeDiallableCharsOnly(&input_number); static const string kExpectedOutput("03*456+1#234"); EXPECT_EQ(kExpectedOutput, input_number) << "Conversion did not correctly remove non-diallable characters"; } TEST_F(PhoneNumberUtilTest, MaybeStripInternationalPrefix) { string international_prefix("00[39]"); string number_to_strip("0034567700-3898003"); string stripped_number("45677003898003"); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << "The number was not stripped of its international prefix."; EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); number_to_strip.assign("00945677003898003"); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << "The number was not stripped of its international prefix."; number_to_strip.assign("00 9 45677003898003"); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << "The number was not stripped of its international prefix."; EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); number_to_strip.assign("+45677003898003"); stripped_number.assign("45677003898003"); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << "The number supplied was not stripped of the plus symbol."; number_to_strip.assign("0090112-3123"); stripped_number.assign("00901123123"); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); EXPECT_EQ(stripped_number, number_to_strip) << "The number had a 0 after the match so shouldn't be stripped."; number_to_strip.assign("009 0-112-3123"); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, MaybeStripInternationalPrefixAndNormalize(international_prefix, &number_to_strip)); } TEST_F(PhoneNumberUtilTest, MaybeStripNationalPrefixAndCarrierCode) { PhoneMetadata metadata; metadata.set_national_prefix_for_parsing("34"); metadata.mutable_general_desc()->set_national_number_pattern("\\d{4,8}"); string number_to_strip("34356778"); string stripped_number("356778"); string carrier_code; MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << "Should have had national prefix stripped."; EXPECT_EQ("", carrier_code) << "Should have had no carrier code stripped."; MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << "Should have had no change - no national prefix present."; metadata.clear_national_prefix_for_parsing(); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << "Should have had no change - empty national prefix."; metadata.set_national_prefix_for_parsing("3"); number_to_strip.assign("3123"); stripped_number.assign("3123"); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(stripped_number, number_to_strip) << "Should have had no change - after stripping, it wouldn't have " << "matched the national rule."; metadata.set_national_prefix_for_parsing("0(81)?"); number_to_strip.assign("08122123456"); stripped_number.assign("22123456"); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ("81", carrier_code) << "Should have had carrier code stripped."; EXPECT_EQ(stripped_number, number_to_strip) << "Should have had national prefix and carrier code stripped."; metadata.set_national_prefix_transform_rule("5$15"); metadata.set_national_prefix_for_parsing("0(\\d{2})"); number_to_strip.assign("031123"); string transformed_number("5315123"); MaybeStripNationalPrefixAndCarrierCode(metadata, &number_to_strip, &carrier_code); EXPECT_EQ(transformed_number, number_to_strip) << "Was not successfully transformed."; } TEST_F(PhoneNumberUtilTest, MaybeStripExtension) { string number("1234576 ext. 1234"); string extension; string expected_extension("1234"); string stripped_number("1234576"); EXPECT_TRUE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_EQ(expected_extension, extension); number.assign("1234-576"); extension.clear(); stripped_number.assign("1234-576"); EXPECT_FALSE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_TRUE(extension.empty()); number.assign("1234576-123#"); extension.clear(); expected_extension.assign("123"); stripped_number.assign("1234576"); EXPECT_TRUE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_EQ(expected_extension, extension); number.assign("1234576 ext.123#"); extension.clear(); EXPECT_TRUE(MaybeStripExtension(&number, &extension)); EXPECT_EQ(stripped_number, number); EXPECT_EQ(expected_extension, extension); } TEST_F(PhoneNumberUtilTest, MaybeExtractCountryCode) { PhoneNumber number; const PhoneMetadata* metadata = GetPhoneMetadata(RegionCode::US()); string phone_number("011112-3456789"); string stripped_number("123456789"); int expected_country_code = 1; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_IDD, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign("+80012345678"); stripped_number.assign("12345678"); expected_country_code = 800; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign("+6423456789"); stripped_number.assign("23456789"); expected_country_code = 64; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); expected_country_code = 0; phone_number.assign("2345-6789"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); expected_country_code = 0; phone_number.assign("0119991123456789"); stripped_number.assign(phone_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); number.Clear(); phone_number.assign("(1 610) 619 4466"); stripped_number.assign("6106194466"); expected_country_code = 1; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign("(1 610) 619 4466"); stripped_number.assign("6106194466"); expected_country_code = 1; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, false, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_FALSE(number.has_country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign("(1 610) 619 446"); stripped_number.assign("1610619446"); expected_country_code = 0; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, false, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_FALSE(number.has_country_code_source()); EXPECT_EQ(stripped_number, phone_number); number.Clear(); phone_number.assign("(1 610) 619"); stripped_number.assign("1610619"); expected_country_code = 0; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, MaybeExtractCountryCode(metadata, true, &phone_number, &number)); EXPECT_EQ(expected_country_code, number.country_code()); EXPECT_EQ(PhoneNumber::FROM_DEFAULT_COUNTRY, number.country_code_source()); EXPECT_EQ(stripped_number, phone_number); } TEST_F(PhoneNumberUtilTest, CountryWithNoNumberDesc) { string formatted_number; PhoneNumber ad_number; ad_number.set_country_code(376); ad_number.set_national_number(uint64{12345}); phone_util_.Format(ad_number, PhoneNumberUtil::INTERNATIONAL, &formatted_number); EXPECT_EQ("+376 12345", formatted_number); phone_util_.Format(ad_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+37612345", formatted_number); phone_util_.Format(ad_number, PhoneNumberUtil::NATIONAL, &formatted_number); EXPECT_EQ("12345", formatted_number); EXPECT_EQ(PhoneNumberUtil::UNKNOWN, phone_util_.GetNumberType(ad_number)); EXPECT_FALSE(phone_util_.IsValidNumber(ad_number)); PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{6502530000}); phone_util_.FormatOutOfCountryCallingNumber(us_number, RegionCode::AD(), &formatted_number); EXPECT_EQ("00 1 650 253 0000", formatted_number); } TEST_F(PhoneNumberUtilTest, UnknownCountryCallingCode) { PhoneNumber invalid_number; invalid_number.set_country_code(kInvalidCountryCode); invalid_number.set_national_number(uint64{12345}); EXPECT_FALSE(phone_util_.IsValidNumber(invalid_number)); string formatted_number; phone_util_.Format(invalid_number, PhoneNumberUtil::E164, &formatted_number); EXPECT_EQ("+212345", formatted_number); } TEST_F(PhoneNumberUtilTest, IsNumberMatchMatches) { EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331 6005", "+64 03 331 6005")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+800 1234 5678", "+80012345678")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 03 331-6005", "+64 03331 6005")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+643 331-6005", "+64033316005")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+643 331-6005", "+6433316005")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005", "+6433316005")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "+64 3 331-6005", "tel:+64-3-331-6005;isub=123")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+1800 siX-Flags", "+1 800 7493 5247")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 extn 1234", "+6433316005#1234")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 extn 1234", "+6433316005;1234")); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "+7 423 202-25-11 ext 100", "+7 4232022511 \xd0\xb4\xd0\xbe\xd0\xb1. 100")); PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{33316005}); nz_number.set_extension("3456"); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, "+643 331 6005 ext 3456")); nz_number.clear_extension(); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, "+643 331 6005")); nz_number.set_extension(""); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, "+643 331 6005")); PhoneNumber nz_number_2; nz_number_2.set_country_code(64); nz_number_2.set_national_number(uint64{33316005}); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatch(nz_number, nz_number_2)); } TEST_F(PhoneNumberUtilTest, IsNumberMatchShortMatchIfDiffNumLeadingZeros) { PhoneNumber nz_number_one; nz_number_one.set_country_code(64); nz_number_one.set_national_number(uint64{33316005}); nz_number_one.set_italian_leading_zero(true); PhoneNumber nz_number_two; nz_number_two.set_country_code(64); nz_number_two.set_national_number(uint64{33316005}); nz_number_two.set_italian_leading_zero(true); nz_number_two.set_number_of_leading_zeros(2); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatch(nz_number_one, nz_number_two)); nz_number_one.set_italian_leading_zero(false); nz_number_one.set_number_of_leading_zeros(1); nz_number_two.set_italian_leading_zero(true); nz_number_two.set_number_of_leading_zeros(1); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatch(nz_number_one, nz_number_two)); } TEST_F(PhoneNumberUtilTest, IsNumberMatchAcceptsProtoDefaultsAsMatch) { PhoneNumber nz_number_one; nz_number_one.set_country_code(64); nz_number_one.set_national_number(uint64{33316005}); nz_number_one.set_italian_leading_zero(true); PhoneNumber nz_number_two; nz_number_two.set_country_code(64); nz_number_two.set_national_number(uint64{33316005}); nz_number_two.set_italian_leading_zero(true); nz_number_two.set_number_of_leading_zeros(1); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatch(nz_number_one, nz_number_two)); } TEST_F(PhoneNumberUtilTest, IsNumberMatchMatchesDiffLeadingZerosIfItalianLeadingZeroFalse) { PhoneNumber nz_number_one; nz_number_one.set_country_code(64); nz_number_one.set_national_number(uint64{33316005}); PhoneNumber nz_number_two; nz_number_two.set_country_code(64); nz_number_two.set_national_number(uint64{33316005}); nz_number_two.set_number_of_leading_zeros(1); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatch(nz_number_one, nz_number_two)); nz_number_two.set_number_of_leading_zeros(10); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatch(nz_number_one, nz_number_two)); } TEST_F(PhoneNumberUtilTest, IsNumberMatchIgnoresSomeFields) { PhoneNumber br_number_1; PhoneNumber br_number_2; br_number_1.set_country_code(55); br_number_1.set_national_number(uint64{3121286979}); br_number_1.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); br_number_1.set_preferred_domestic_carrier_code("12"); br_number_1.set_raw_input("012 3121286979"); br_number_2.set_country_code(55); br_number_2.set_national_number(uint64{3121286979}); br_number_2.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); br_number_2.set_preferred_domestic_carrier_code("14"); br_number_2.set_raw_input("143121286979"); EXPECT_EQ(PhoneNumberUtil::EXACT_MATCH, phone_util_.IsNumberMatch(br_number_1, br_number_2)); } TEST_F(PhoneNumberUtilTest, IsNumberMatchNonMatches) { EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings("03 331 6005", "03 331 6006")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+800 1234 5678", "+1 800 1234 5678")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005", "+16433316005")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005", "+6133316005")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 extn 1234", "+0116433316005#1235")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "+64 3 331-6005 extn 1234", "tel:+64-3-331-6005;ext=1235")); EXPECT_EQ(PhoneNumberUtil::NO_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005 ext.1235", "3 331 6005#1234")); EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings("4", "3 331 6043")); EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings("+43", "+64 3 331 6005")); EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings("+43", "64 3 331 6005")); EXPECT_EQ(PhoneNumberUtil::INVALID_NUMBER, phone_util_.IsNumberMatchWithTwoStrings("Dog", "64 3 331 6005")); } TEST_F(PhoneNumberUtilTest, IsNumberMatchNsnMatches) { EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005", "03 331 6005")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "+64 3 331-6005", "tel:03-331-6005;isub=1234;phone-context=abc.nz")); PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{33316005}); nz_number.set_extension(""); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, "03 331 6005")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(nz_number, "(64-3) 331 6005")); PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{2345678901}); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(us_number, "1-234-567-8901")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithOneString(us_number, "2345678901")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+1 234-567 8901", "1 234 567 8901")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("1 234-567 8901", "1 234 567 8901")); EXPECT_EQ(PhoneNumberUtil::NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("1 234-567 8901", "+1 234 567 8901")); PhoneNumber random_number; random_number.set_country_code(41); random_number.set_national_number(uint64{2345678901}); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithOneString(random_number, "1-234-567-8901")); } TEST_F(PhoneNumberUtilTest, IsNumberMatchShortNsnMatches) { EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005", "331 6005")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "+64 3 331-6005", "tel:331-6005;phone-context=abc.nz")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "+64 3 331-6005", "tel:331-6005;isub=1234;phone-context=abc.nz")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "+64 3 331-6005", "tel:331-6005;isub=1234;phone-context=abc.nz;a=%A1")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("3 331-6005", "03 331 6005")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("3 331-6005", "331 6005")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings( "3 331-6005", "tel:331-6005;phone-context=abc.nz")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("3 331-6005", "+64 331 6005")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("03 331-6005", "331 6005")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("1 234 345 6789", "345 6789")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+1 (234) 345 6789", "345 6789")); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatchWithTwoStrings("+64 3 331-6005", "3 331 6005#1234")); PhoneNumber it_number_1, it_number_2; it_number_1.set_country_code(39); it_number_1.set_national_number(uint64{1234}); it_number_1.set_italian_leading_zero(true); it_number_2.set_country_code(39); it_number_2.set_national_number(uint64{1234}); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatch(it_number_1, it_number_2)); it_number_1.set_extension("1234"); it_number_1.clear_italian_leading_zero(); it_number_2.set_extension(""); EXPECT_EQ(PhoneNumberUtil::SHORT_NSN_MATCH, phone_util_.IsNumberMatch(it_number_1, it_number_2)); } TEST_F(PhoneNumberUtilTest, ParseNationalNumber) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{33316005}); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("033316005", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_FALSE(nz_number.has_country_code_source()); EXPECT_EQ(PhoneNumber::UNSPECIFIED, nz_number.country_code_source()); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("33316005", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03-331 6005", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 331 6005", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:03-331-6005;phone-context=+64", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:331-6005;phone-context=+64-3", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:331-6005;phone-context=+64-3", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("My number is tel:03-331-6005;phone-context=+64", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:03-331-6005;phone-context=+64;a=%A1", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:03-331-6005;isub=12345;phone-context=+64", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:+64-3-331-6005;isub=12345", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03-331-6005;phone-context=+64", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0064 3 331 6005", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("01164 3 331 6005", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+64 3 331 6005", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+01164 3 331 6005", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+0064 3 331 6005", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+ 00 64 3 331 6005", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); PhoneNumber us_local_number; us_local_number.set_country_code(1); us_local_number.set_national_number(uint64{2530000}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:253-0000;phone-context=www.google.com", RegionCode::US(), &test_number)); EXPECT_EQ(us_local_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "tel:253-0000;isub=12345;phone-context=www.google.com", RegionCode::US(), &test_number)); EXPECT_EQ(us_local_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:2530000;isub=12345;phone-context=1234.com", RegionCode::US(), &test_number)); EXPECT_EQ(us_local_number, test_number); nz_number.Clear(); nz_number.set_country_code(64); nz_number.set_national_number(uint64{64123456}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+64(0)64123456", RegionCode::US(), &test_number)); EXPECT_EQ(nz_number, test_number); PhoneNumber de_number; de_number.set_country_code(49); de_number.set_national_number(uint64{12345678}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("123/45678", RegionCode::DE(), &test_number)); EXPECT_EQ(de_number, test_number); PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{1234567890}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("123-456-7890", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); PhoneNumber star_number; star_number.set_country_code(81); star_number.set_national_number(uint64{2345}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+81 *2345", RegionCode::JP(), &test_number)); EXPECT_EQ(star_number, test_number); PhoneNumber short_number; short_number.set_country_code(64); short_number.set_national_number(uint64{12}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("12", RegionCode::NZ(), &test_number)); EXPECT_EQ(short_number, test_number); short_number.set_country_code(44); short_number.set_national_number(123456); short_number.set_italian_leading_zero(true); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0123456", RegionCode::GB(), &test_number)); EXPECT_EQ(short_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseNumberWithAlphaCharacters) { PhoneNumber test_number; PhoneNumber tollfree_number; tollfree_number.set_country_code(64); tollfree_number.set_national_number(uint64{800332005}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0800 DDA 005", RegionCode::NZ(), &test_number)); EXPECT_EQ(tollfree_number, test_number); PhoneNumber premium_number; premium_number.set_country_code(64); premium_number.set_national_number(uint64{9003326005}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0900 DDA 6005", RegionCode::NZ(), &test_number)); EXPECT_EQ(premium_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0900 332 6005a", RegionCode::NZ(), &test_number)); EXPECT_EQ(premium_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0900 332 600a5", RegionCode::NZ(), &test_number)); EXPECT_EQ(premium_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0900 332 600A5", RegionCode::NZ(), &test_number)); EXPECT_EQ(premium_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0900 a332 600A5", RegionCode::NZ(), &test_number)); EXPECT_EQ(premium_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseWithInternationalPrefixes) { PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(uint64{6503336000}); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+1 (650) 333-6000", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+1-650-333-6000", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0011-650-333-6000", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0081-650-333-6000", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0191-650-333-6000", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0~01-650-333-6000", RegionCode::PL(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("++1 (650) 333-6000", RegionCode::PL(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("\xEF\xBC\x8B" "1 (650) 333-6000", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("1 (650) 333" "\xC2\xAD" "-6000", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88" "\xEF\xBC\x96\xEF\xBC\x95\xEF\xBC\x90\xEF\xBC\x89" "\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93" "\xEF\xBC\x8D\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90" "\xEF\xBC\x90", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88" "\xEF\xBC\x96\xEF\xBC\x95\xEF\xBC\x90\xEF\xBC\x89" "\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93" "\xE3\x83\xBC\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90" "\xEF\xBC\x90", RegionCode::SG(), &test_number)); EXPECT_EQ(us_number, test_number); PhoneNumber toll_free_number; toll_free_number.set_country_code(800); toll_free_number.set_national_number(uint64{12345678}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("011 800 1234 5678", RegionCode::US(), &test_number)); EXPECT_EQ(toll_free_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseWithLeadingZero) { PhoneNumber it_number; it_number.set_country_code(39); it_number.set_national_number(uint64{236618300}); it_number.set_italian_leading_zero(true); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+39 02-36618 300", RegionCode::NZ(), &test_number)); EXPECT_EQ(it_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("02-36618 300", RegionCode::IT(), &test_number)); EXPECT_EQ(it_number, test_number); it_number.Clear(); it_number.set_country_code(39); it_number.set_national_number(uint64{312345678}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("312 345 678", RegionCode::IT(), &test_number)); EXPECT_EQ(it_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseNationalNumberArgentina) { PhoneNumber ar_number; ar_number.set_country_code(54); ar_number.set_national_number(uint64{93435551212}); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+54 9 343 555 1212", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0343 15 555 1212", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); ar_number.set_national_number(uint64{93715654320}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+54 9 3715 65 4320", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03715 15 65 4320", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); ar_number.set_national_number(uint64{1137970000}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+54 11 3797 0000", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("011 3797 0000", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); ar_number.set_national_number(uint64{3715654321}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+54 3715 65 4321", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03715 65 4321", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); ar_number.set_national_number(uint64{2312340000}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+54 23 1234 0000", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("023 1234 0000", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseWithXInNumber) { PhoneNumber ar_number; ar_number.set_country_code(54); ar_number.set_national_number(uint64{123456789}); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0123456789", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(0) 123456789", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0 123456789", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(0xx) 123456789", RegionCode::AR(), &test_number)); EXPECT_EQ(ar_number, test_number); PhoneNumber ar_from_us; ar_from_us.set_country_code(54); ar_from_us.set_national_number(uint64{81429712}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("011xx5481429712", RegionCode::US(), &test_number)); EXPECT_EQ(ar_from_us, test_number); } TEST_F(PhoneNumberUtilTest, ParseNumbersMexico) { PhoneNumber mx_number; mx_number.set_country_code(52); mx_number.set_national_number(uint64{4499780001}); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+52 (449)978-0001", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("01 (449)978-0001", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(449)978-0001", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); mx_number.Clear(); mx_number.set_country_code(52); mx_number.set_national_number(uint64{13312345678}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+52 1 33 1234-5678", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("044 (33) 1234-5678", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("045 33 1234-5678", RegionCode::MX(), &test_number)); EXPECT_EQ(mx_number, test_number); } TEST_F(PhoneNumberUtilTest, FailedParseOnInvalidNumbers) { PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("This is not a phone number", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("1 Still not a number", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("1 MICROSOFT", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("12 MICROSOFT", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_LONG_NSN, phone_util_.Parse("01495 72553301873 810104", RegionCode::GB(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("+---", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("+***", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("+*******91", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_NSN, phone_util_.Parse("+49 0", RegionCode::DE(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse("+210 3456 56789", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse("+ 00 210 3 331 6005", RegionCode::NZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse("123 456 7890", RegionCode::GetUnknown(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse("123 456 7890", RegionCode::CS(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse("0044-----", RegionCode::GB(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse("0044", RegionCode::GB(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse("011", RegionCode::US(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::TOO_SHORT_AFTER_IDD, phone_util_.Parse("0119", RegionCode::US(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse("tel:555-1234;phone-context=www.google.com", RegionCode::ZZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("tel:555-1234;phone-context=1-331", RegionCode::ZZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse(";phone-context=", RegionCode::ZZ(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); } TEST_F(PhoneNumberUtilTest, ParseNumbersWithPlusWithNoRegion) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{33316005}); PhoneNumber result_proto; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+64 3 331 6005", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("\xEF\xBC\x8B" "64 3 331 6005", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(" +64 3 331 6005", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); PhoneNumber toll_free_number; toll_free_number.set_country_code(800); toll_free_number.set_national_number(uint64{12345678}); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+800 1234 5678", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(toll_free_number, result_proto); PhoneNumber universal_premium_rate; universal_premium_rate.set_country_code(979); universal_premium_rate.set_national_number(uint64{123456789}); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+979 123 456 789", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(universal_premium_rate, result_proto); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:03-331-6005;phone-context=+64", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse(" tel:03-331-6005;phone-context=+64", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:03-331-6005;isub=12345;phone-context=+64", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); nz_number.set_raw_input("+64 3 331 6005"); nz_number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); result_proto.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("+64 3 331 6005", RegionCode::GetUnknown(), &result_proto)); EXPECT_EQ(nz_number, result_proto); } TEST_F(PhoneNumberUtilTest, ParseNumberTooShortIfNationalPrefixStripped) { PhoneNumber test_number; PhoneNumber by_number; by_number.set_country_code(375); by_number.set_national_number(8123L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("8123", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); by_number.set_national_number(81234L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("81234", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); by_number.set_national_number(812345L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("812345", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); by_number.set_national_number(123456L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("8123456", RegionCode::BY(), &test_number)); EXPECT_EQ(by_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseExtensions) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(uint64{33316005}); nz_number.set_extension("3456"); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 331 6005 ext 3456", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 331 6005x3456", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03-331 6005 int.3456", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 331 6005 #3456", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); PhoneNumber non_extn_number; non_extn_number.set_country_code(1); non_extn_number.set_national_number(uint64{80074935247}); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("1800 six-flags", RegionCode::US(), &test_number)); EXPECT_EQ(non_extn_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("1800 SIX-FLAGS", RegionCode::US(), &test_number)); EXPECT_EQ(non_extn_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0~0 1800 7493 5247", RegionCode::PL(), &test_number)); EXPECT_EQ(non_extn_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(1800) 7493.5247", RegionCode::US(), &test_number)); EXPECT_EQ(non_extn_number, test_number); PhoneNumber extn_number; extn_number.set_country_code(1); extn_number.set_national_number(uint64{80074935247}); extn_number.set_extension("1234"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0~0 1800 7493 5247 ~1234", RegionCode::PL(), &test_number)); EXPECT_EQ(extn_number, test_number); PhoneNumber uk_number; uk_number.set_country_code(44); uk_number.set_national_number(uint64{2034567890}); uk_number.set_extension("456"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890x456", RegionCode::NZ(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890x456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890 x456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890 X456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890 X 456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890 X 456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890 x 456 ", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44 2034567890 X 456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44-2034567890;ext=456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:2034567890;ext=456;phone-context=+44", RegionCode::ZZ(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "+442034567890\xEF\xBD\x85\xEF\xBD\x98\xEF\xBD\x94\xEF\xBD\x8E" "456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "+44-2034567890\xEF\xBD\x98\xEF\xBD\x94\xEF\xBD\x8E""456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+44-2034567890\xEF\xBD\x98\xEF\xBD\x94""456", RegionCode::GB(), &test_number)); EXPECT_EQ(uk_number, test_number); PhoneNumber us_with_extension; us_with_extension.set_country_code(1); us_with_extension.set_national_number(uint64{8009013355}); us_with_extension.set_extension("7246433"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 x 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 , ext 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 ; 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355;7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 ,extension 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 ,extensi\xC3\xB3n 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 ,extensio\xCC\x81n 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 , 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(800) 901-3355 ext: 7246433", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); PhoneNumber ru_with_extension; ru_with_extension.set_country_code(7); ru_with_extension.set_national_number(4232022511L); ru_with_extension.set_extension("100"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "8 (423) 202-25-11, \xd0\xb4\xd0\xbe\xd0\xb1. 100", RegionCode::RU(), &test_number)); EXPECT_EQ(ru_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "8 (423) 202-25-11 \xd0\xb4\xd0\xbe\xd0\xb1. 100", RegionCode::RU(), &test_number)); EXPECT_EQ(ru_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "8 (423) 202-25-11, \xd0\xb4\xd0\xbe\xd0\xb1 100", RegionCode::RU(), &test_number)); EXPECT_EQ(ru_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "8 (423) 202-25-11 \xd0\xb4\xd0\xbe\xd0\xb1 100", RegionCode::RU(), &test_number)); EXPECT_EQ(ru_with_extension, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "8 (423) 202-25-11\xd0\xb4\xd0\xbe\xd0\xb1 100", RegionCode::RU(), &test_number)); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse( "8 (423) 202-25-11 \xd0\x94\xd0\x9e\xd0\x91 100", RegionCode::RU(), &test_number)); EXPECT_EQ(ru_with_extension, test_number); PhoneNumber us_with_two_extensions_number; us_with_two_extensions_number.set_country_code(1); us_with_two_extensions_number.set_national_number(uint64{2121231234}); us_with_two_extensions_number.set_extension("508"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(212)123-1234 x508/x1234", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_two_extensions_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(212)123-1234 x508/ x1234", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_two_extensions_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("(212)123-1234 x508\\x1234", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_two_extensions_number, test_number); us_with_extension.Clear(); us_with_extension.set_country_code(1); us_with_extension.set_national_number(uint64{6451231234}); us_with_extension.set_extension("910"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+1 (645) 123 1234-910#", RegionCode::US(), &test_number)); EXPECT_EQ(us_with_extension, test_number); } TEST_F(PhoneNumberUtilTest, TestParseHandlesLongExtensionsWithExplicitLabels) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); PhoneNumber test_number; nz_number.set_extension("0"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:+6433316005;ext=0", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); nz_number.set_extension("01234567890123456789"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:+6433316005;ext=01234567890123456789", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("tel:+6433316005;ext=012345678901234567890", RegionCode::NZ(), &test_number)); nz_number.set_extension("1"); EXPECT_EQ( PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005ext:1", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); nz_number.set_extension("12345678901234567890"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 xtn:12345678901234567890", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 extension\t12345678901234567890", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 xtensio:12345678901234567890", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 xtensión, 12345678901234567890#", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005extension.12345678901234567890", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 доб:12345678901234567890", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::TOO_LONG_NSN, phone_util_.Parse("03 3316005 extension 123456789012345678901", RegionCode::NZ(), &test_number)); } TEST_F(PhoneNumberUtilTest, TestParseHandlesLongExtensionsWithAutoDiallingLabels) { PhoneNumber us_number_user_input; us_number_user_input.set_country_code(1); us_number_user_input.set_national_number(2679000000ULL); PhoneNumber test_number; us_number_user_input.set_extension("123456789012345"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+12679000000,,123456789012345#", RegionCode::US(), &test_number)); EXPECT_EQ(us_number_user_input, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+12679000000;123456789012345#", RegionCode::US(), &test_number)); EXPECT_EQ(us_number_user_input, test_number); PhoneNumber uk_number_user_input; uk_number_user_input.set_country_code(44); uk_number_user_input.set_national_number(2034000000ULL); uk_number_user_input.set_extension("123456789"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+442034000000,,123456789#", RegionCode::GB(), &test_number)); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("+12679000000,,1234567890123456#", RegionCode::US(), &test_number)); } TEST_F(PhoneNumberUtilTest, TestParseHandlesShortExtensionsWithAmbiguousChar) { PhoneNumber nz_number; nz_number.set_country_code(64); nz_number.set_national_number(33316005ULL); PhoneNumber test_number; nz_number.set_extension("123456789"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 x 123456789", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 x. 123456789", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 #123456789#", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("03 3316005 ~ 123456789", RegionCode::NZ(), &test_number)); EXPECT_EQ(nz_number, test_number); EXPECT_EQ(PhoneNumberUtil::TOO_LONG_NSN, phone_util_.Parse("03 3316005 ~ 1234567890", RegionCode::NZ(), &test_number)); } TEST_F(PhoneNumberUtilTest, TestParseHandlesShortExtensionsWhenNotSureOfLabel) { PhoneNumber us_number; us_number.set_country_code(1); us_number.set_national_number(1234567890ULL); PhoneNumber test_number; us_number.set_extension("666666"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+1123-456-7890 666666#", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); us_number.set_extension("6"); EXPECT_EQ( PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("+11234567890-6#", RegionCode::US(), &test_number)); EXPECT_EQ(us_number, test_number); EXPECT_EQ(PhoneNumberUtil::NOT_A_NUMBER, phone_util_.Parse("+1123-456-7890 7777777#", RegionCode::US(), &test_number)); } TEST_F(PhoneNumberUtilTest, ParseAndKeepRaw) { PhoneNumber alpha_numeric_number; alpha_numeric_number.set_country_code(1); alpha_numeric_number.set_national_number(uint64{80074935247}); alpha_numeric_number.set_raw_input("800 six-flags"); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_DEFAULT_COUNTRY); PhoneNumber test_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("800 six-flags", RegionCode::US(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); alpha_numeric_number.set_national_number(uint64{8007493524}); alpha_numeric_number.set_raw_input("1800 six-flag"); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("1800 six-flag", RegionCode::US(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); alpha_numeric_number.set_raw_input("+1800 six-flag"); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("+1800 six-flag", RegionCode::CN(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); alpha_numeric_number.set_raw_input("001800 six-flag"); alpha_numeric_number.set_country_code_source( PhoneNumber::FROM_NUMBER_WITH_IDD); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("001800 six-flag", RegionCode::NZ(), &test_number)); EXPECT_EQ(alpha_numeric_number, test_number); test_number.Clear(); EXPECT_EQ(PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR, phone_util_.Parse("123 456 7890", RegionCode::CS(), &test_number)); EXPECT_EQ(PhoneNumber::default_instance(), test_number); PhoneNumber korean_number; korean_number.set_country_code(82); korean_number.set_national_number(22123456); korean_number.set_raw_input("08122123456"); korean_number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); korean_number.set_preferred_domestic_carrier_code("81"); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.ParseAndKeepRawInput("08122123456", RegionCode::KR(), &test_number)); EXPECT_EQ(korean_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseItalianLeadingZeros) { PhoneNumber zeros_number; zeros_number.set_country_code(61); PhoneNumber test_number; zeros_number.set_national_number(11L); zeros_number.set_italian_leading_zero(true); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("011", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); zeros_number.set_national_number(1L); zeros_number.set_italian_leading_zero(true); zeros_number.set_number_of_leading_zeros(2); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("001", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); zeros_number.set_national_number(0L); zeros_number.set_italian_leading_zero(true); zeros_number.set_number_of_leading_zeros(2); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("000", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); zeros_number.set_national_number(0L); zeros_number.set_italian_leading_zero(true); zeros_number.set_number_of_leading_zeros(3); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("0000", RegionCode::AU(), &test_number)); EXPECT_EQ(zeros_number, test_number); } TEST_F(PhoneNumberUtilTest, ParseWithPhoneContext) { PhoneNumber expected_number; expected_number.set_country_code(64); expected_number.set_national_number(33316005L); PhoneNumber actual_number; EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=+64", RegionCode::ZZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=+64;{this isn't " "part of phone-context anymore!}", RegionCode::ZZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); expected_number.set_national_number(3033316005L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=+64-3", RegionCode::ZZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); expected_number.set_country_code(55); expected_number.set_national_number(5033316005L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=+(555)", RegionCode::ZZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); expected_number.set_country_code(1); expected_number.set_national_number(23033316005L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=+-1-2.3()", RegionCode::ZZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); expected_number.set_country_code(64); expected_number.set_national_number(33316005L); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=abc.nz", RegionCode::NZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); EXPECT_EQ( PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=www.PHONE-numb3r.com", RegionCode::NZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=a", RegionCode::NZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=3phone.J.", RegionCode::NZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); actual_number.Clear(); EXPECT_EQ(PhoneNumberUtil::NO_PARSING_ERROR, phone_util_.Parse("tel:033316005;phone-context=a--z", RegionCode::NZ(), &actual_number)); EXPECT_EQ(expected_number, actual_number); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context="); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=+"); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=64"); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=++64"); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=+abc"); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=."); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=3phone"); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=a-.nz"); AssertThrowsForInvalidPhoneContext("tel:033316005;phone-context=a{b}c"); } TEST_F(PhoneNumberUtilTest, CanBeInternationallyDialled) { PhoneNumber test_number; test_number.set_country_code(1); test_number.set_national_number(uint64{8002530000}); EXPECT_FALSE(phone_util_.CanBeInternationallyDialled(test_number)); test_number.set_national_number(uint64{6502530000}); EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number)); test_number.set_national_number(uint64{2530000}); EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number)); test_number.set_country_code(64); test_number.set_national_number(uint64{33316005}); EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number)); test_number.set_country_code(800); test_number.set_national_number(uint64{12345678}); EXPECT_TRUE(phone_util_.CanBeInternationallyDialled(test_number)); } TEST_F(PhoneNumberUtilTest, IsAlphaNumber) { EXPECT_TRUE(phone_util_.IsAlphaNumber("1800 six-flags")); EXPECT_TRUE(phone_util_.IsAlphaNumber("1800 six-flags ext. 1234")); EXPECT_TRUE(phone_util_.IsAlphaNumber("+800 six-flags")); EXPECT_TRUE(phone_util_.IsAlphaNumber("180 six-flags")); EXPECT_FALSE(phone_util_.IsAlphaNumber("1800 123-1234")); EXPECT_FALSE(phone_util_.IsAlphaNumber("1 six-flags")); EXPECT_FALSE(phone_util_.IsAlphaNumber("18 six-flags")); EXPECT_FALSE(phone_util_.IsAlphaNumber("1800 123-1234 extension: 1234")); EXPECT_FALSE(phone_util_.IsAlphaNumber("+800 1234-1234")); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/phonenumberutil.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/phonenumberutil_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
d8c489fc-5b92-47f3-b9d8-612e250f0197
cpp
google/libphonenumber
asyoutypeformatter
cpp/src/phonenumbers/asyoutypeformatter.cc
cpp/test/phonenumbers/asyoutypeformatter_test.cc
#include "phonenumbers/asyoutypeformatter.h" #include <math.h> #include <cctype> #include <list> #include <string> #include <google/protobuf/message_lite.h> #include "phonenumbers/base/logging.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/regexp_factory.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/unicodestring.h" namespace i18n { namespace phonenumbers { using google::protobuf::RepeatedPtrField; namespace { const char kPlusSign = '+'; const size_t kMinLeadingDigitsLength = 3; const char kDigitPlaceholder[] = "\xE2\x80\x88"; const char kSeparatorBeforeNationalNumber = ' '; const char kNationalPrefixSeparatorsPattern[] = "[- ]"; void MatchAllGroups(const string& pattern, const string& input, const AbstractRegExpFactory& regexp_factory, RegExpCache* cache, string* group) { DCHECK(cache); DCHECK(group); string new_pattern(pattern); strrmm(&new_pattern, "()"); new_pattern = StrCat("(", new_pattern, ")"); const scoped_ptr<RegExpInput> consume_input( regexp_factory.CreateInput(input)); bool status = cache->GetRegExp(new_pattern).Consume(consume_input.get(), group); DCHECK(status); IGNORE_UNUSED(status); } PhoneMetadata CreateEmptyMetadata() { PhoneMetadata metadata; metadata.set_international_prefix("NA"); return metadata; } } AsYouTypeFormatter::AsYouTypeFormatter(const string& region_code) : regexp_factory_(new RegExpFactory()), regexp_cache_(*regexp_factory_.get(), 64), current_output_(), formatting_template_(), current_formatting_pattern_(), accrued_input_(), accrued_input_without_formatting_(), able_to_format_(true), input_has_formatting_(false), is_complete_number_(false), is_expecting_country_code_(false), phone_util_(*PhoneNumberUtil::GetInstance()), default_country_(region_code), empty_metadata_(CreateEmptyMetadata()), default_metadata_(GetMetadataForRegion(region_code)), current_metadata_(default_metadata_), last_match_position_(0), original_position_(0), position_to_remember_(0), prefix_before_national_number_(), should_add_space_after_national_prefix_(false), extracted_national_prefix_(), national_number_(), possible_formats_() { } const PhoneMetadata* AsYouTypeFormatter::GetMetadataForRegion( const string& region_code) const { int country_calling_code = phone_util_.GetCountryCodeForRegion(region_code); string main_country; phone_util_.GetRegionCodeForCountryCode(country_calling_code, &main_country); const PhoneMetadata* const metadata = phone_util_.GetMetadataForRegion(main_country); if (metadata) { return metadata; } return &empty_metadata_; } bool AsYouTypeFormatter::MaybeCreateNewTemplate() { for (list<const NumberFormat*>::const_iterator it = possible_formats_.begin(); it != possible_formats_.end(); ++it) { DCHECK(*it); const NumberFormat& number_format = **it; const string& pattern = number_format.pattern(); if (current_formatting_pattern_ == pattern) { return false; } if (CreateFormattingTemplate(number_format)) { current_formatting_pattern_ = pattern; SetShouldAddSpaceAfterNationalPrefix(number_format); last_match_position_ = 0; return true; } } able_to_format_ = false; return false; } void AsYouTypeFormatter::GetAvailableFormats(const string& leading_digits) { bool is_international_number = is_complete_number_ && extracted_national_prefix_.empty(); const RepeatedPtrField<NumberFormat>& format_list = (is_international_number && current_metadata_->intl_number_format().size() > 0) ? current_metadata_->intl_number_format() : current_metadata_->number_format(); for (RepeatedPtrField<NumberFormat>::const_iterator it = format_list.begin(); it != format_list.end(); ++it) { if (!extracted_national_prefix_.empty() && phone_util_.FormattingRuleHasFirstGroupOnly( it->national_prefix_formatting_rule()) && !it->national_prefix_optional_when_formatting() && !it->has_domestic_carrier_code_formatting_rule()) { continue; } else if (extracted_national_prefix_.empty() && !is_complete_number_ && !phone_util_.FormattingRuleHasFirstGroupOnly( it->national_prefix_formatting_rule()) && !it->national_prefix_optional_when_formatting()) { continue; } if (phone_util_.IsFormatEligibleForAsYouTypeFormatter(it->format())) { possible_formats_.push_back(&*it); } } NarrowDownPossibleFormats(leading_digits); } void AsYouTypeFormatter::NarrowDownPossibleFormats( const string& leading_digits) { const int index_of_leading_digits_pattern = static_cast<int>(leading_digits.length() - kMinLeadingDigitsLength); for (list<const NumberFormat*>::iterator it = possible_formats_.begin(); it != possible_formats_.end(); ) { DCHECK(*it); const NumberFormat& format = **it; if (format.leading_digits_pattern_size() == 0) { ++it; continue; } int last_leading_digits_pattern = format.leading_digits_pattern_size() - 1; if (last_leading_digits_pattern > index_of_leading_digits_pattern) last_leading_digits_pattern = index_of_leading_digits_pattern; const scoped_ptr<RegExpInput> input( regexp_factory_->CreateInput(leading_digits)); if (!regexp_cache_.GetRegExp(format.leading_digits_pattern().Get( last_leading_digits_pattern)).Consume(input.get())) { it = possible_formats_.erase(it); continue; } ++it; } } void AsYouTypeFormatter::SetShouldAddSpaceAfterNationalPrefix( const NumberFormat& format) { static const scoped_ptr<const RegExp> national_prefix_separators_pattern( regexp_factory_->CreateRegExp(kNationalPrefixSeparatorsPattern)); should_add_space_after_national_prefix_ = national_prefix_separators_pattern->PartialMatch( format.national_prefix_formatting_rule()); } bool AsYouTypeFormatter::CreateFormattingTemplate(const NumberFormat& format) { string number_pattern = format.pattern(); string number_format = format.format(); formatting_template_.remove(); UnicodeString temp_template; GetFormattingTemplate(number_pattern, number_format, &temp_template); if (temp_template.length() > 0) { formatting_template_.append(temp_template); return true; } return false; } void AsYouTypeFormatter::GetFormattingTemplate( const string& number_pattern, const string& number_format, UnicodeString* formatting_template) { DCHECK(formatting_template); static const char longest_phone_number[] = "999999999999999"; string a_phone_number; MatchAllGroups(number_pattern, longest_phone_number, *regexp_factory_, &regexp_cache_, &a_phone_number); if (a_phone_number.length() < national_number_.length()) { formatting_template->remove(); return; } regexp_cache_.GetRegExp(number_pattern).GlobalReplace( &a_phone_number, number_format); GlobalReplaceSubstring("9", kDigitPlaceholder, &a_phone_number); formatting_template->setTo(a_phone_number.c_str(), a_phone_number.size()); } void AsYouTypeFormatter::Clear() { current_output_.clear(); accrued_input_.remove(); accrued_input_without_formatting_.remove(); formatting_template_.remove(); last_match_position_ = 0; current_formatting_pattern_.clear(); prefix_before_national_number_.clear(); extracted_national_prefix_.clear(); national_number_.clear(); able_to_format_ = true; input_has_formatting_ = false; position_to_remember_ = 0; original_position_ = 0; is_complete_number_ = false; is_expecting_country_code_ = false; possible_formats_.clear(); should_add_space_after_national_prefix_ = false; if (current_metadata_ != default_metadata_) { current_metadata_ = GetMetadataForRegion(default_country_); } } const string& AsYouTypeFormatter::InputDigit(char32 next_char, string* result) { DCHECK(result); InputDigitWithOptionToRememberPosition(next_char, false, &current_output_); result->assign(current_output_); return *result; } const string& AsYouTypeFormatter::InputDigitAndRememberPosition( char32 next_char, string* result) { DCHECK(result); InputDigitWithOptionToRememberPosition(next_char, true, &current_output_); result->assign(current_output_); return *result; } void AsYouTypeFormatter::InputDigitWithOptionToRememberPosition( char32 next_char, bool remember_position, string* phone_number) { DCHECK(phone_number); accrued_input_.append(next_char); if (remember_position) { original_position_ = accrued_input_.length(); } string next_char_string; UnicodeString(next_char).toUTF8String(next_char_string); char normalized_next_char = '\0'; if (!(phone_util_.ContainsOnlyValidDigits(next_char_string) || (accrued_input_.length() == 1 && next_char == kPlusSign))) { able_to_format_ = false; input_has_formatting_ = true; } else { normalized_next_char = NormalizeAndAccrueDigitsAndPlusSign(next_char, remember_position); } if (!able_to_format_) { if (input_has_formatting_) { phone_number->clear(); accrued_input_.toUTF8String(*phone_number); } else if (AttemptToExtractIdd()) { if (AttemptToExtractCountryCode()) { AttemptToChoosePatternWithPrefixExtracted(phone_number); return; } } else if (AbleToExtractLongerNdd()) { prefix_before_national_number_.push_back(kSeparatorBeforeNationalNumber); AttemptToChoosePatternWithPrefixExtracted(phone_number); return; } phone_number->clear(); accrued_input_.toUTF8String(*phone_number); return; } switch (accrued_input_without_formatting_.length()) { case 0: case 1: case 2: phone_number->clear(); accrued_input_.toUTF8String(*phone_number); return; case 3: if (AttemptToExtractIdd()) { is_expecting_country_code_ = true; } else { RemoveNationalPrefixFromNationalNumber(&extracted_national_prefix_); AttemptToChooseFormattingPattern(phone_number); return; } default: if (is_expecting_country_code_) { if (AttemptToExtractCountryCode()) { is_expecting_country_code_ = false; } phone_number->assign(prefix_before_national_number_); phone_number->append(national_number_); return; } if (possible_formats_.size() > 0) { string temp_national_number; InputDigitHelper(normalized_next_char, &temp_national_number); string formatted_number; AttemptToFormatAccruedDigits(&formatted_number); if (formatted_number.length() > 0) { phone_number->assign(formatted_number); return; } NarrowDownPossibleFormats(national_number_); if (MaybeCreateNewTemplate()) { InputAccruedNationalNumber(phone_number); return; } if (able_to_format_) { AppendNationalNumber(temp_national_number, phone_number); } else { phone_number->clear(); accrued_input_.toUTF8String(*phone_number); } return; } else { AttemptToChooseFormattingPattern(phone_number); } } } void AsYouTypeFormatter::AttemptToChoosePatternWithPrefixExtracted( string* formatted_number) { able_to_format_ = true; is_expecting_country_code_ = false; possible_formats_.clear(); last_match_position_ = 0; formatting_template_.remove(); current_formatting_pattern_.clear(); AttemptToChooseFormattingPattern(formatted_number); } const string& AsYouTypeFormatter::GetExtractedNationalPrefix() const { return extracted_national_prefix_; } bool AsYouTypeFormatter::AbleToExtractLongerNdd() { if (extracted_national_prefix_.length() > 0) { national_number_.insert(0, extracted_national_prefix_); int index_of_previous_ndd = static_cast<int>( prefix_before_national_number_.find_last_of(extracted_national_prefix_)); prefix_before_national_number_.resize(index_of_previous_ndd); } string new_national_prefix; RemoveNationalPrefixFromNationalNumber(&new_national_prefix); return extracted_national_prefix_ != new_national_prefix; } void AsYouTypeFormatter::AttemptToFormatAccruedDigits( string* formatted_result) { DCHECK(formatted_result); for (list<const NumberFormat*>::const_iterator it = possible_formats_.begin(); it != possible_formats_.end(); ++it) { DCHECK(*it); const NumberFormat& number_format = **it; const string& pattern = number_format.pattern(); if (regexp_cache_.GetRegExp(pattern).FullMatch(national_number_)) { SetShouldAddSpaceAfterNationalPrefix(number_format); string formatted_number(national_number_); bool status = regexp_cache_.GetRegExp(pattern).GlobalReplace( &formatted_number, number_format.format()); DCHECK(status); IGNORE_UNUSED(status); string full_output(*formatted_result); AppendNationalNumber(formatted_number, &full_output); phone_util_.NormalizeDiallableCharsOnly(&full_output); string accrued_input_without_formatting_stdstring; accrued_input_without_formatting_.toUTF8String( accrued_input_without_formatting_stdstring); if (full_output == accrued_input_without_formatting_stdstring) { AppendNationalNumber(formatted_number, formatted_result); return; } } } } int AsYouTypeFormatter::GetRememberedPosition() const { UnicodeString current_output(current_output_.c_str()); if (!able_to_format_) { return ConvertUnicodeStringPosition(current_output, original_position_); } int accrued_input_index = 0; int current_output_index = 0; while (accrued_input_index < position_to_remember_ && current_output_index < current_output.length()) { if (accrued_input_without_formatting_[accrued_input_index] == current_output[current_output_index]) { ++accrued_input_index; } ++current_output_index; } return ConvertUnicodeStringPosition(current_output, current_output_index); } void AsYouTypeFormatter::AppendNationalNumber(const string& national_number, string* phone_number) const { int prefix_before_national_number_length = static_cast<int>(prefix_before_national_number_.size()); if (should_add_space_after_national_prefix_ && prefix_before_national_number_length > 0 && prefix_before_national_number_.at( prefix_before_national_number_length - 1) != kSeparatorBeforeNationalNumber) { phone_number->assign(prefix_before_national_number_); phone_number->push_back(kSeparatorBeforeNationalNumber); StrAppend(phone_number, national_number); } else { phone_number->assign( StrCat(prefix_before_national_number_, national_number)); } } void AsYouTypeFormatter::AttemptToChooseFormattingPattern( string* formatted_number) { DCHECK(formatted_number); if (national_number_.length() >= kMinLeadingDigitsLength) { GetAvailableFormats(national_number_); formatted_number->clear(); AttemptToFormatAccruedDigits(formatted_number); if (formatted_number->length() > 0) { return; } if (MaybeCreateNewTemplate()) { InputAccruedNationalNumber(formatted_number); } else { formatted_number->clear(); accrued_input_.toUTF8String(*formatted_number); } return; } else { AppendNationalNumber(national_number_, formatted_number); } } void AsYouTypeFormatter::InputAccruedNationalNumber(string* number) { DCHECK(number); int length_of_national_number = static_cast<int>(national_number_.length()); if (length_of_national_number > 0) { string temp_national_number; for (int i = 0; i < length_of_national_number; ++i) { temp_national_number.clear(); InputDigitHelper(national_number_[i], &temp_national_number); } if (able_to_format_) { AppendNationalNumber(temp_national_number, number); } else { number->clear(); accrued_input_.toUTF8String(*number); } return; } else { number->assign(prefix_before_national_number_); } } bool AsYouTypeFormatter::IsNanpaNumberWithNationalPrefix() const { return (current_metadata_->country_code() == 1) && (national_number_[0] == '1') && (national_number_[1] != '0') && (national_number_[1] != '1'); } void AsYouTypeFormatter::RemoveNationalPrefixFromNationalNumber( string* national_prefix) { int start_of_national_number = 0; if (IsNanpaNumberWithNationalPrefix()) { start_of_national_number = 1; prefix_before_national_number_.append("1"); prefix_before_national_number_.push_back(kSeparatorBeforeNationalNumber); is_complete_number_ = true; } else if (current_metadata_->has_national_prefix_for_parsing()) { const scoped_ptr<RegExpInput> consumed_input( regexp_factory_->CreateInput(national_number_)); const RegExp& pattern = regexp_cache_.GetRegExp( current_metadata_->national_prefix_for_parsing()); if (pattern.Consume(consumed_input.get())) { start_of_national_number = static_cast<int>( national_number_.length() - consumed_input->ToString().length()); if (start_of_national_number > 0) { is_complete_number_ = true; prefix_before_national_number_.append( national_number_.substr(0, start_of_national_number)); } } } national_prefix->assign(national_number_, 0, start_of_national_number); national_number_.erase(0, start_of_national_number); } bool AsYouTypeFormatter::AttemptToExtractIdd() { string accrued_input_without_formatting_stdstring; accrued_input_without_formatting_ .toUTF8String(accrued_input_without_formatting_stdstring); const scoped_ptr<RegExpInput> consumed_input( regexp_factory_->CreateInput(accrued_input_without_formatting_stdstring)); const RegExp& international_prefix = regexp_cache_.GetRegExp( StrCat("\\", string(&kPlusSign, 1), "|", current_metadata_->international_prefix())); if (international_prefix.Consume(consumed_input.get())) { is_complete_number_ = true; const int start_of_country_code = static_cast<int>( accrued_input_without_formatting_.length() - consumed_input->ToString().length()); national_number_.clear(); accrued_input_without_formatting_.tempSubString(start_of_country_code) .toUTF8String(national_number_); string before_country_code; accrued_input_without_formatting_.tempSubString(0, start_of_country_code) .toUTF8String(before_country_code); prefix_before_national_number_.clear(); prefix_before_national_number_.append(before_country_code); if (accrued_input_without_formatting_[0] != kPlusSign) { prefix_before_national_number_.push_back(kSeparatorBeforeNationalNumber); } return true; } return false; } bool AsYouTypeFormatter::AttemptToExtractCountryCode() { if (national_number_.length() == 0) { return false; } string number_without_country_code(national_number_); int country_code = phone_util_.ExtractCountryCode(&number_without_country_code); if (country_code == 0) { return false; } national_number_.assign(number_without_country_code); string new_region_code; phone_util_.GetRegionCodeForCountryCode(country_code, &new_region_code); if (PhoneNumberUtil::kRegionCodeForNonGeoEntity == new_region_code) { current_metadata_ = phone_util_.GetMetadataForNonGeographicalRegion(country_code); } else if (new_region_code != default_country_) { current_metadata_ = GetMetadataForRegion(new_region_code); } StrAppend(&prefix_before_national_number_, country_code); prefix_before_national_number_.push_back(kSeparatorBeforeNationalNumber); extracted_national_prefix_.clear(); return true; } char AsYouTypeFormatter::NormalizeAndAccrueDigitsAndPlusSign( char32 next_char, bool remember_position) { char normalized_char = next_char; if (next_char == kPlusSign) { accrued_input_without_formatting_.append(next_char); } else { string number; UnicodeString(next_char).toUTF8String(number); phone_util_.NormalizeDigitsOnly(&number); accrued_input_without_formatting_.append(next_char); national_number_.append(number); normalized_char = number[0]; } if (remember_position) { position_to_remember_ = accrued_input_without_formatting_.length(); } return normalized_char; } void AsYouTypeFormatter::InputDigitHelper(char next_char, string* number) { DCHECK(number); number->clear(); const char32 placeholder_codepoint = UnicodeString(kDigitPlaceholder)[0]; int placeholder_pos = formatting_template_ .tempSubString(last_match_position_).indexOf(placeholder_codepoint); if (placeholder_pos != -1) { UnicodeString temp_template = formatting_template_; placeholder_pos = temp_template.indexOf(placeholder_codepoint); temp_template.setCharAt(placeholder_pos, UnicodeString(next_char)[0]); last_match_position_ = placeholder_pos; formatting_template_.replace(0, temp_template.length(), temp_template); formatting_template_.tempSubString(0, last_match_position_ + 1) .toUTF8String(*number); } else { if (possible_formats_.size() == 1) { able_to_format_ = false; } current_formatting_pattern_.clear(); accrued_input_.toUTF8String(*number); } } int AsYouTypeFormatter::ConvertUnicodeStringPosition(const UnicodeString& s, int pos) { if (pos > s.length()) { return -1; } string substring; s.tempSubString(0, pos).toUTF8String(substring); return static_cast<int>(substring.length()); } } }
#include "phonenumbers/asyoutypeformatter.h" #include <gtest/gtest.h> #include "phonenumbers/base/logging.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { class PhoneMetadata; class AsYouTypeFormatterTest : public testing::Test { public: AsYouTypeFormatterTest(const AsYouTypeFormatterTest&) = delete; AsYouTypeFormatterTest& operator=(const AsYouTypeFormatterTest&) = delete; protected: AsYouTypeFormatterTest() : phone_util_(*PhoneNumberUtil::GetInstance()) { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } const PhoneMetadata* GetCurrentMetadata() const { return formatter_->current_metadata_; } const string& GetExtractedNationalPrefix() const { return formatter_->GetExtractedNationalPrefix(); } int ConvertUnicodeStringPosition(const UnicodeString& s, int pos) const { return AsYouTypeFormatter::ConvertUnicodeStringPosition(s, pos); } const PhoneNumberUtil& phone_util_; scoped_ptr<AsYouTypeFormatter> formatter_; string result_; }; TEST_F(AsYouTypeFormatterTest, ConvertUnicodeStringPosition) { EXPECT_EQ(-1, ConvertUnicodeStringPosition(UnicodeString("12345"), 10)); EXPECT_EQ(3, ConvertUnicodeStringPosition(UnicodeString("12345"), 3)); EXPECT_EQ(0, ConvertUnicodeStringPosition( UnicodeString("\xEF\xBC\x95" ), 0)); EXPECT_EQ(4, ConvertUnicodeStringPosition( UnicodeString("0\xEF\xBC\x95""3" ), 2)); EXPECT_EQ(5, ConvertUnicodeStringPosition( UnicodeString("0\xEF\xBC\x95""3" ), 3)); } TEST_F(AsYouTypeFormatterTest, Constructor) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_TRUE(GetCurrentMetadata() != NULL); } TEST_F(AsYouTypeFormatterTest, InvalidPlusSign) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GetUnknown())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+48 ", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+48 88 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+48 88 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48881231+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+48881231+2", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, TooLongNumberMatchingMultipleLeadingDigits) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GetUnknown())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+81 90", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+81 90 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 90 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 90 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+81 90 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+81 90 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+81 90 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+81 90 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+81 90 1234 5678", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 90 12 345 6789", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+81901234567890", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+819012345678901", formatter_->InputDigit('1', &result_)); } TEST_F(AsYouTypeFormatterTest, CountryWithSpaceInNationalPrefixFormattingRule) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::BY())); EXPECT_EQ("8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("881", formatter_->InputDigit('1', &result_)); EXPECT_EQ("8 819", formatter_->InputDigit('9', &result_)); EXPECT_EQ("8 8190", formatter_->InputDigit('0', &result_)); EXPECT_EQ("881 901", formatter_->InputDigit('1', &result_)); EXPECT_EQ("8 819 012", formatter_->InputDigit('2', &result_)); EXPECT_EQ("88190123", formatter_->InputDigit('3', &result_)); } TEST_F(AsYouTypeFormatterTest, CountryWithSpaceInNationalPrefixFormattingRuleAndLongNdd) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::BY())); EXPECT_EQ("9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("99", formatter_->InputDigit('9', &result_)); EXPECT_EQ("999", formatter_->InputDigit('9', &result_)); EXPECT_EQ("9999", formatter_->InputDigit('9', &result_)); EXPECT_EQ("99999 ", formatter_->InputDigit('9', &result_)); EXPECT_EQ("99999 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("99999 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("99999 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("99999 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("99999 12 345", formatter_->InputDigit('5', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_US) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("650 2532", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 253 2222", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("16", formatter_->InputDigit('6', &result_)); EXPECT_EQ("1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 2222", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 44 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 44 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("011 44 61", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 44 6 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 44 6 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 44 6 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 44 6 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 44 6 123 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 44 6 123 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 44 6 123 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 44 6 123 123 123", formatter_->InputDigit('3', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("011 54 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 54 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("011 54 91", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 54 9 11 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 54 9 11 231", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11 2312", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 54 9 11 2312 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 54 9 11 2312 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 54 9 11 2312 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 54 9 11 2312 1234", formatter_->InputDigit('4', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 24", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 244 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011 244 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 244 28", formatter_->InputDigit('8', &result_)); EXPECT_EQ("011 244 280", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000 0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000 00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 244 280 000 000", formatter_->InputDigit('0', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+48 ", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+48 88 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+48 88 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+48 88 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+48 88 123 12 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+48 88 123 12 12", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_USFullWidthCharacters) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("\xEF\xBC\x96" , formatter_->InputDigit(UnicodeString("\xEF\xBC\x96" )[0], &result_)); EXPECT_EQ("\xEF\xBC\x96\xEF\xBC\x95" , formatter_->InputDigit(UnicodeString("\xEF\xBC\x95" )[0], &result_)); EXPECT_EQ("650", formatter_->InputDigit(UnicodeString("\xEF\xBC\x90" )[0], &result_)); EXPECT_EQ("650 2", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 25", formatter_->InputDigit(UnicodeString("\xEF\xBC\x95" )[0], &result_)); EXPECT_EQ("650 253", formatter_->InputDigit(UnicodeString("\xEF\xBC\x93" )[0], &result_)); EXPECT_EQ("650 2532", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 253 22", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 253 222", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); EXPECT_EQ("650 253 2222", formatter_->InputDigit(UnicodeString("\xEF\xBC\x92" )[0], &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_USMobileShortCode) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("*", formatter_->InputDigit('*', &result_)); EXPECT_EQ("*1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("*12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("*121", formatter_->InputDigit('1', &result_)); EXPECT_EQ("*121#", formatter_->InputDigit('#', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_USVanityNumber) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("80", formatter_->InputDigit('0', &result_)); EXPECT_EQ("800", formatter_->InputDigit('0', &result_)); EXPECT_EQ("800 ", formatter_->InputDigit(' ', &result_)); EXPECT_EQ("800 M", formatter_->InputDigit('M', &result_)); EXPECT_EQ("800 MY", formatter_->InputDigit('Y', &result_)); EXPECT_EQ("800 MY ", formatter_->InputDigit(' ', &result_)); EXPECT_EQ("800 MY A", formatter_->InputDigit('A', &result_)); EXPECT_EQ("800 MY AP", formatter_->InputDigit('P', &result_)); EXPECT_EQ("800 MY APP", formatter_->InputDigit('P', &result_)); EXPECT_EQ("800 MY APPL", formatter_->InputDigit('L', &result_)); EXPECT_EQ("800 MY APPLE", formatter_->InputDigit('E', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTFAndRememberPositionUS) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("1", formatter_->InputDigitAndRememberPosition('1', &result_)); EXPECT_EQ(1, formatter_->GetRememberedPosition()); EXPECT_EQ("16", formatter_->InputDigit('6', &result_)); EXPECT_EQ("1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ(1, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650", formatter_->InputDigitAndRememberPosition('0', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253 222", formatter_->InputDigitAndRememberPosition('2', &result_)); EXPECT_EQ(13, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253 2222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(13, formatter_->GetRememberedPosition()); EXPECT_EQ("165025322222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(10, formatter_->GetRememberedPosition()); EXPECT_EQ("1650253222222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(10, formatter_->GetRememberedPosition()); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("16", formatter_->InputDigitAndRememberPosition('6', &result_)); EXPECT_EQ(2, formatter_->GetRememberedPosition()); EXPECT_EQ("1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); EXPECT_EQ("1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 650 253 2222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("165025322222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(2, formatter_->GetRememberedPosition()); EXPECT_EQ("1650253222222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(2, formatter_->GetRememberedPosition()); formatter_->Clear(); EXPECT_EQ("6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("650 2532", formatter_->InputDigitAndRememberPosition('2', &result_)); EXPECT_EQ(8, formatter_->GetRememberedPosition()); EXPECT_EQ("650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ(9, formatter_->GetRememberedPosition()); EXPECT_EQ("650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650253222;", formatter_->InputDigit(';', &result_)); EXPECT_EQ(7, formatter_->GetRememberedPosition()); EXPECT_EQ("650253222;2", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("650-", formatter_->InputDigit('-', &result_)); EXPECT_EQ("650-2", formatter_->InputDigitAndRememberPosition('2', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("650-25", formatter_->InputDigit('5', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("650-253", formatter_->InputDigit('3', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("650-253-", formatter_->InputDigit('-', &result_)); EXPECT_EQ("650-253-2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650-253-22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650-253-222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("650-253-2222", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 4", formatter_->InputDigitAndRememberPosition('4', &result_)); EXPECT_EQ("011 48 ", formatter_->InputDigit('8', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("011 48 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("011 48 88", formatter_->InputDigit('8', &result_)); EXPECT_EQ("011 48 88 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 48 88 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("011 48 88 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 48 88 123 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 48 88 123 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("011 48 88 123 12 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 48 88 123 12 12", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+1 6", formatter_->InputDigitAndRememberPosition('6', &result_)); EXPECT_EQ("+1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650 253", formatter_->InputDigitAndRememberPosition('3', &result_)); EXPECT_EQ("+1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ(10, formatter_->GetRememberedPosition()); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+1 6", formatter_->InputDigitAndRememberPosition('6', &result_)); EXPECT_EQ("+1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ(4, formatter_->GetRememberedPosition()); EXPECT_EQ("+1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+1650253222;", formatter_->InputDigit(';', &result_)); EXPECT_EQ(3, formatter_->GetRememberedPosition()); } TEST_F(AsYouTypeFormatterTest, AYTF_GBFixedLine) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GB())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02", formatter_->InputDigit('2', &result_)); EXPECT_EQ("020", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 7", formatter_->InputDigitAndRememberPosition('7', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("020 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ(5, formatter_->GetRememberedPosition()); EXPECT_EQ("020 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("020 7031 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("020 7031 30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 7031 300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("020 7031 3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_GBTollFree) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GB())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08", formatter_->InputDigit('8', &result_)); EXPECT_EQ("080", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("080 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ("080 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("080 7031 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("080 7031 30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 7031 300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 7031 3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_GBPremiumRate) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::GB())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("09", formatter_->InputDigit('9', &result_)); EXPECT_EQ("090", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("090 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ("090 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("090 7031 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("090 7031 30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 7031 300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("090 7031 3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_NZMobile) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::NZ())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02", formatter_->InputDigit('2', &result_)); EXPECT_EQ("021", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02-11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02-112", formatter_->InputDigit('2', &result_)); EXPECT_EQ("02-112 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("02-112 34", formatter_->InputDigit('4', &result_)); EXPECT_EQ("02-112 345", formatter_->InputDigit('5', &result_)); EXPECT_EQ("02-112 3456", formatter_->InputDigit('6', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_DE) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::DE())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("03", formatter_->InputDigit('3', &result_)); EXPECT_EQ("030", formatter_->InputDigit('0', &result_)); EXPECT_EQ("030/1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("030/12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("030/123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("030/1234", formatter_->InputDigit('4', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08", formatter_->InputDigit('8', &result_)); EXPECT_EQ("080", formatter_->InputDigit('0', &result_)); EXPECT_EQ("080 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("080 21", formatter_->InputDigit('1', &result_)); EXPECT_EQ("08021 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("08021 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("08021 234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("08021 2345", formatter_->InputDigit('5', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00 1 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("00 1 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("00 1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("00 1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00 1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("00 1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("00 1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00 1 650 253 2222", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_AR) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::AR())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("011 70", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 703", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 7031", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 7031-3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("011 7031-30", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 7031-300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("011 7031-3000", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_ARMobile) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::AR())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+54 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+54 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+54 91", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+54 9 11 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+54 9 11 231", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11 2312", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+54 9 11 2312 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+54 9 11 2312 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+54 9 11 2312 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+54 9 11 2312 1234", formatter_->InputDigit('4', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_KR) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::KR())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+82 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 51", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+82 51-2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 51-23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 51-234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+82 51-234-5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 51-234-56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 51-234-567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+82 51-234-5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+82 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-53", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 2-531", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+82 2-531-5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-531-56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-531-567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+82 2-531-5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+82 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 2-36", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-366", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-3665", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-3665-5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+82 2-3665-56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+82 2-3665-567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+82 2-3665-5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02", formatter_->InputDigit('2', &result_)); EXPECT_EQ("021", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02-11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02-114", formatter_->InputDigit('4', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02", formatter_->InputDigit('2', &result_)); EXPECT_EQ("021", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02-13", formatter_->InputDigit('3', &result_)); EXPECT_EQ("02-130", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02-1300", formatter_->InputDigit('0', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011-4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("011-45", formatter_->InputDigit('5', &result_)); EXPECT_EQ("011-456", formatter_->InputDigit('6', &result_)); EXPECT_EQ("011-456-7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("011-456-78", formatter_->InputDigit('8', &result_)); EXPECT_EQ("011-456-789", formatter_->InputDigit('9', &result_)); EXPECT_EQ("011-456-7890", formatter_->InputDigit('0', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011-9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("011-98", formatter_->InputDigit('8', &result_)); EXPECT_EQ("011-987", formatter_->InputDigit('7', &result_)); EXPECT_EQ("011-9876", formatter_->InputDigit('6', &result_)); EXPECT_EQ("011-9876-7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("011-9876-78", formatter_->InputDigit('8', &result_)); EXPECT_EQ("011-9876-789", formatter_->InputDigit('9', &result_)); EXPECT_EQ("011-9876-7890", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_MX) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::MX())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+52 80", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+52 800", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+52 800 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 800 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 800 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+52 800 123 4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+52 800 123 45", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 800 123 456", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+52 800 123 4567", formatter_->InputDigit('7', &result_)); formatter_->Clear(); EXPECT_EQ("9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("90", formatter_->InputDigit('0', &result_)); EXPECT_EQ("901", formatter_->InputDigit('1', &result_)); EXPECT_EQ("9011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("90112", formatter_->InputDigit('2', &result_)); EXPECT_EQ("901123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("9011234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("90112345", formatter_->InputDigit('5', &result_)); EXPECT_EQ("901123456", formatter_->InputDigit('6', &result_)); EXPECT_EQ("9011234567", formatter_->InputDigit('7', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 55", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 55 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 55 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 55 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+52 55 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+52 55 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 55 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+52 55 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+52 55 1234 5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 21", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 212", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 212 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+52 212 34", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+52 212 345", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 212 345 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+52 212 345 67", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+52 212 345 678", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+52 212 345 6789", formatter_->InputDigit('9', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 15", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 1 55", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 1 55 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 1 55 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 1 55 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+52 1 55 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+52 1 55 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 1 55 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+52 1 55 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+52 1 55 1234 5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 15", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 1 54", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+52 1 541", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 1 541 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 1 541 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+52 1 541 234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+52 1 541 234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 1 541 234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+52 1 541 234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+52 1 541 234 5678", formatter_->InputDigit('8', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_International_Toll_Free) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+80", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+800 ", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+800 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+800 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+800 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+800 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+800 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+800 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+800 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+800 1234 5678", formatter_->InputDigit('8', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_MultipleLeadingDigitPatterns) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::JP())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+81 50", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+81 50 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 50 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+81 50 234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+81 50 2345", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+81 50 2345 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+81 50 2345 67", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+81 50 2345 678", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 50 2345 6789", formatter_->InputDigit('9', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 22 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 22 21", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 2221 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 222 12 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+81 222 12 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+81 222 12 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+81 222 12 5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("01", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011 11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("011113", formatter_->InputDigit('3', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+81 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+81 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+81 33", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+81 33 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+81 3332", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 3332 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+81 3332 2 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+81 3332 2 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+81 3332 2 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+81 3332 2 5678", formatter_->InputDigit('8', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_LongIDD_AU) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::AU())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("001", formatter_->InputDigit('1', &result_)); EXPECT_EQ("0011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("0011 1 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("0011 1 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("0011 1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("0011 1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("0011 1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("0011 1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("0011 1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 1 650 253 2222", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("001", formatter_->InputDigit('1', &result_)); EXPECT_EQ("0011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("00118", formatter_->InputDigit('8', &result_)); EXPECT_EQ("0011 81 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("0011 81 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("0011 81 33", formatter_->InputDigit('3', &result_)); EXPECT_EQ("0011 81 33 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("0011 81 3332", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 81 3332 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 81 3332 2 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("0011 81 3332 2 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("0011 81 3332 2 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("0011 81 3332 2 5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("001", formatter_->InputDigit('1', &result_)); EXPECT_EQ("0011", formatter_->InputDigit('1', &result_)); EXPECT_EQ("00112", formatter_->InputDigit('2', &result_)); EXPECT_EQ("001124", formatter_->InputDigit('4', &result_)); EXPECT_EQ("0011 244 ", formatter_->InputDigit('4', &result_)); EXPECT_EQ("0011 244 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 244 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("0011 244 250", formatter_->InputDigit('0', &result_)); EXPECT_EQ("0011 244 250 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 244 250 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("0011 244 250 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("0011 244 250 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 244 250 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("0011 244 250 253 222", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_LongIDD_KR) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::KR())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("003", formatter_->InputDigit('3', &result_)); EXPECT_EQ("0030", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00300", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00300 1 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("00300 1 6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("00300 1 65", formatter_->InputDigit('5', &result_)); EXPECT_EQ("00300 1 650", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00300 1 650 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00300 1 650 25", formatter_->InputDigit('5', &result_)); EXPECT_EQ("00300 1 650 253", formatter_->InputDigit('3', &result_)); EXPECT_EQ("00300 1 650 253 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00300 1 650 253 22", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00300 1 650 253 222", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00300 1 650 253 2222", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_LongNDD_KR) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::KR())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08", formatter_->InputDigit('8', &result_)); EXPECT_EQ("088", formatter_->InputDigit('8', &result_)); EXPECT_EQ("0881", formatter_->InputDigit('1', &result_)); EXPECT_EQ("08811", formatter_->InputDigit('1', &result_)); EXPECT_EQ("08811-9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("08811-98", formatter_->InputDigit('8', &result_)); EXPECT_EQ("08811-987", formatter_->InputDigit('7', &result_)); EXPECT_EQ("08811-9876", formatter_->InputDigit('6', &result_)); EXPECT_EQ("08811-9876-7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("08811-9876-78", formatter_->InputDigit('8', &result_)); EXPECT_EQ("08811-9876-789", formatter_->InputDigit('9', &result_)); EXPECT_EQ("08811-9876-7890", formatter_->InputDigit('0', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08", formatter_->InputDigit('8', &result_)); EXPECT_EQ("085", formatter_->InputDigit('5', &result_)); EXPECT_EQ("0850", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08500 ", formatter_->InputDigit('0', &result_)); EXPECT_EQ("08500 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("08500 11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("08500 11-9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("08500 11-98", formatter_->InputDigit('8', &result_)); EXPECT_EQ("08500 11-987", formatter_->InputDigit('7', &result_)); EXPECT_EQ("08500 11-9876", formatter_->InputDigit('6', &result_)); EXPECT_EQ("08500 11-9876-7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("08500 11-9876-78", formatter_->InputDigit('8', &result_)); EXPECT_EQ("08500 11-9876-789", formatter_->InputDigit('9', &result_)); EXPECT_EQ("08500 11-9876-7890", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_LongNDD_SG) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::SG())); EXPECT_EQ("7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("77", formatter_->InputDigit('7', &result_)); EXPECT_EQ("777", formatter_->InputDigit('7', &result_)); EXPECT_EQ("7777", formatter_->InputDigit('7', &result_)); EXPECT_EQ("77777", formatter_->InputDigit('7', &result_)); EXPECT_EQ("777777 ", formatter_->InputDigit('7', &result_)); EXPECT_EQ("777777 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("777777 98", formatter_->InputDigit('8', &result_)); EXPECT_EQ("777777 987", formatter_->InputDigit('7', &result_)); EXPECT_EQ("777777 9876", formatter_->InputDigit('6', &result_)); EXPECT_EQ("777777 9876 7", formatter_->InputDigit('7', &result_)); EXPECT_EQ("777777 9876 78", formatter_->InputDigit('8', &result_)); EXPECT_EQ("777777 9876 789", formatter_->InputDigit('9', &result_)); EXPECT_EQ("777777 9876 7890", formatter_->InputDigit('0', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_ShortNumberFormattingFix_AU) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::AU())); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("1234 567 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("1234 567 89", formatter_->InputDigit('9', &result_)); EXPECT_EQ("1234 567 890", formatter_->InputDigit('0', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+61 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+61 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+61 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+61 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+61 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+61 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+61 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+61 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+61 1234 567 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+61 1234 567 89", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+61 1234 567 890", formatter_->InputDigit('0', &result_)); formatter_->Clear(); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("02", formatter_->InputDigit('2', &result_)); EXPECT_EQ("021", formatter_->InputDigit('1', &result_)); EXPECT_EQ("02 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("02 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("02 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("02 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("02 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("02 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("02 1234 5678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("21", formatter_->InputDigit('1', &result_)); EXPECT_EQ("212", formatter_->InputDigit('2', &result_)); EXPECT_EQ("2123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("21234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("212345", formatter_->InputDigit('5', &result_)); EXPECT_EQ("2123456", formatter_->InputDigit('6', &result_)); EXPECT_EQ("21234567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("212345678", formatter_->InputDigit('8', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+6", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+61 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+61 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+61 21", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+61 2 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+61 2 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+61 2 1234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+61 2 1234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+61 2 1234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+61 2 1234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("+61 2 1234 5678", formatter_->InputDigit('8', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_ShortNumberFormattingFix_KR) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::KR())); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("111", formatter_->InputDigit('1', &result_)); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("114", formatter_->InputDigit('4', &result_)); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("13", formatter_->InputDigit('3', &result_)); EXPECT_EQ("131", formatter_->InputDigit('1', &result_)); EXPECT_EQ("1312", formatter_->InputDigit('2', &result_)); EXPECT_EQ("13121", formatter_->InputDigit('1', &result_)); EXPECT_EQ("131212", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1312123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("13121234", formatter_->InputDigit('4', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+82 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+82 13", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 131", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+82 131-2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 131-2-1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+82 131-2-12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+82 131-2-123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+82 131-2-1234", formatter_->InputDigit('4', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_ShortNumberFormattingFix_MX) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::MX())); EXPECT_EQ("9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("91", formatter_->InputDigit('1', &result_)); EXPECT_EQ("911", formatter_->InputDigit('1', &result_)); formatter_->Clear(); EXPECT_EQ("8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("80", formatter_->InputDigit('0', &result_)); EXPECT_EQ("800", formatter_->InputDigit('0', &result_)); EXPECT_EQ("800 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("800 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("800 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("800 123 4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("800 123 45", formatter_->InputDigit('5', &result_)); EXPECT_EQ("800 123 456", formatter_->InputDigit('6', &result_)); EXPECT_EQ("800 123 4567", formatter_->InputDigit('7', &result_)); formatter_->Clear(); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 ", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+52 80", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+52 800", formatter_->InputDigit('0', &result_)); EXPECT_EQ("+52 800 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+52 800 12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+52 800 123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+52 800 123 4", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+52 800 123 45", formatter_->InputDigit('5', &result_)); EXPECT_EQ("+52 800 123 456", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+52 800 123 4567", formatter_->InputDigit('7', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_NoNationalPrefix) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::IT())); EXPECT_EQ("3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("33", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333 33", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333 333", formatter_->InputDigit('3', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_NoNationalPrefixFormattingRule) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::AO())); EXPECT_EQ("3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("33", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333 3", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333 33", formatter_->InputDigit('3', &result_)); EXPECT_EQ("333 333", formatter_->InputDigit('3', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_ShortNumberFormattingFix_US) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::US())); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("10", formatter_->InputDigit('0', &result_)); EXPECT_EQ("101", formatter_->InputDigit('1', &result_)); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("11", formatter_->InputDigit('1', &result_)); EXPECT_EQ("112", formatter_->InputDigit('2', &result_)); formatter_->Clear(); EXPECT_EQ("1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("12", formatter_->InputDigit('2', &result_)); EXPECT_EQ("1 22", formatter_->InputDigit('2', &result_)); } TEST_F(AsYouTypeFormatterTest, AYTF_ClearNDDAfterIDDExtraction) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::KR())); EXPECT_EQ("0", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00", formatter_->InputDigit('0', &result_)); EXPECT_EQ("007", formatter_->InputDigit('7', &result_)); EXPECT_EQ("0070", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00700", formatter_->InputDigit('0', &result_)); EXPECT_EQ("0", GetExtractedNationalPrefix()); EXPECT_EQ("00700 1 ", formatter_->InputDigit('1', &result_)); EXPECT_EQ("", GetExtractedNationalPrefix()); EXPECT_EQ("00700 1 2", formatter_->InputDigit('2', &result_)); EXPECT_EQ("00700 1 23", formatter_->InputDigit('3', &result_)); EXPECT_EQ("00700 1 234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("00700 1 234 5", formatter_->InputDigit('5', &result_)); EXPECT_EQ("00700 1 234 56", formatter_->InputDigit('6', &result_)); EXPECT_EQ("00700 1 234 567", formatter_->InputDigit('7', &result_)); EXPECT_EQ("00700 1 234 567 8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("00700 1 234 567 89", formatter_->InputDigit('9', &result_)); EXPECT_EQ("00700 1 234 567 890", formatter_->InputDigit('0', &result_)); EXPECT_EQ("00700 1 234 567 8901", formatter_->InputDigit('1', &result_)); EXPECT_EQ("00700123456789012", formatter_->InputDigit('2', &result_)); EXPECT_EQ("007001234567890123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("0070012345678901234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("00700123456789012345", formatter_->InputDigit('5', &result_)); EXPECT_EQ("007001234567890123456", formatter_->InputDigit('6', &result_)); EXPECT_EQ("0070012345678901234567", formatter_->InputDigit('7', &result_)); } TEST_F(AsYouTypeFormatterTest, NumberPatternsBecomingInvalidShouldNotResultInDigitLoss) { formatter_.reset(phone_util_.GetAsYouTypeFormatter(RegionCode::CN())); EXPECT_EQ("+", formatter_->InputDigit('+', &result_)); EXPECT_EQ("+8", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+86 ", formatter_->InputDigit('6', &result_)); EXPECT_EQ("+86 9", formatter_->InputDigit('9', &result_)); EXPECT_EQ("+86 98", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+86 988", formatter_->InputDigit('8', &result_)); EXPECT_EQ("+86 988 1", formatter_->InputDigit('1', &result_)); EXPECT_EQ("+8698812", formatter_->InputDigit('2', &result_)); EXPECT_EQ("+86988123", formatter_->InputDigit('3', &result_)); EXPECT_EQ("+869881234", formatter_->InputDigit('4', &result_)); EXPECT_EQ("+8698812345", formatter_->InputDigit('5', &result_)); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/asyoutypeformatter.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/asyoutypeformatter_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
ececb0ff-9d9f-410b-8980-048362fe68f2
cpp
google/libphonenumber
unicodestring
cpp/src/phonenumbers/unicodestring.cc
cpp/test/phonenumbers/unicodestring_test.cc
#include "phonenumbers/unicodestring.h" #include <algorithm> #include <cassert> #include <iterator> using std::advance; using std::equal; namespace i18n { namespace phonenumbers { UnicodeString& UnicodeString::operator=(const UnicodeString& src) { if (&src != this) { invalidateCachedIndex(); text_ = src.text_; } return *this; } bool UnicodeString::operator==(const UnicodeString& rhs) const { return equal(text_.begin(), text_.end(), rhs.text_.begin()); } void UnicodeString::append(const UnicodeString& unicode_string) { invalidateCachedIndex(); for (UnicodeString::const_iterator it = unicode_string.begin(); it != unicode_string.end(); ++it) { append(*it); } } int UnicodeString::indexOf(char32 codepoint) const { int pos = 0; for (UnicodeText::const_iterator it = text_.begin(); it != text_.end(); ++it, ++pos) { if (*it == codepoint) { return pos; } } return -1; } void UnicodeString::replace(int start, int length, const UnicodeString& src) { assert(length >= 0 && length <= this->length()); invalidateCachedIndex(); UnicodeText::const_iterator start_it = text_.begin(); advance(start_it, start); UnicodeText unicode_text; unicode_text.append(text_.begin(), start_it); unicode_text.append(src.text_); advance(start_it, length); unicode_text.append(start_it, text_.end()); text_ = unicode_text; } void UnicodeString::setCharAt(int pos, char32 c) { assert(pos < length()); invalidateCachedIndex(); UnicodeText::const_iterator pos_it = text_.begin(); advance(pos_it, pos); UnicodeText unicode_text; unicode_text.append(text_.begin(), pos_it); unicode_text.push_back(c); ++pos_it; unicode_text.append(pos_it, text_.end()); text_ = unicode_text; } UnicodeString UnicodeString::tempSubString(int start, int length) const { const int unicodestring_length = this->length(); if (length == std::numeric_limits<int>::max()) { length = unicodestring_length - start; } if (start > unicodestring_length || length > unicodestring_length) { return UnicodeString(""); } UnicodeText::const_iterator start_it = text_.begin(); advance(start_it, start); UnicodeText::const_iterator end_it = start_it; advance(end_it, length); UnicodeString substring; substring.text_.PointTo(start_it, end_it); return substring; } char32 UnicodeString::operator[](int index) const { assert(index < length()); if (cached_index_ == -1 || cached_index_ > index) { cached_it_ = text_.begin(); cached_index_ = 0; } for (; cached_index_ < index; ++cached_index_, ++cached_it_) {} return *cached_it_; } } }
#include <iostream> #include <gtest/gtest.h> #include "phonenumbers/unicodestring.h" using std::ostream; namespace i18n { namespace phonenumbers { ostream& operator<<(ostream& out, const UnicodeString& s) { string utf8; s.toUTF8String(utf8); out << utf8; return out; } TEST(UnicodeString, ToUTF8StringWithEmptyString) { UnicodeString s; string utf8; s.toUTF8String(utf8); EXPECT_EQ("", utf8); } TEST(UnicodeString, ToUTF8String) { UnicodeString s("hello"); string utf8; s.toUTF8String(utf8); EXPECT_EQ("hello", utf8); } TEST(UnicodeString, ToUTF8StringWithNonAscii) { UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" ); string utf8; s.toUTF8String(utf8); EXPECT_EQ("\xEF\xBC\x95\xEF\xBC\x93", utf8); } TEST(UnicodeString, AppendCodepoint) { UnicodeString s; s.append('h'); ASSERT_EQ(UnicodeString("h"), s); s.append('e'); EXPECT_EQ(UnicodeString("he"), s); } TEST(UnicodeString, AppendCodepointWithNonAscii) { UnicodeString s; s.append(0xFF15 ); ASSERT_EQ(UnicodeString("\xEF\xBC\x95" ), s); s.append(0xFF13 ); EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" ), s); } TEST(UnicodeString, AppendUnicodeString) { UnicodeString s; s.append(UnicodeString("he")); ASSERT_EQ(UnicodeString("he"), s); s.append(UnicodeString("llo")); EXPECT_EQ(UnicodeString("hello"), s); } TEST(UnicodeString, AppendUnicodeStringWithNonAscii) { UnicodeString s; s.append(UnicodeString("\xEF\xBC\x95" )); ASSERT_EQ(UnicodeString("\xEF\xBC\x95"), s); s.append(UnicodeString("\xEF\xBC\x93" )); EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" ), s); } TEST(UnicodeString, IndexOf) { UnicodeString s("hello"); EXPECT_EQ(0, s.indexOf('h')); EXPECT_EQ(2, s.indexOf('l')); EXPECT_EQ(4, s.indexOf('o')); } TEST(UnicodeString, IndexOfWithNonAscii) { UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" ); EXPECT_EQ(1, s.indexOf(0xFF13 )); } TEST(UnicodeString, ReplaceWithEmptyInputs) { UnicodeString s; s.replace(0, 0, UnicodeString("")); EXPECT_EQ(UnicodeString(""), s); } TEST(UnicodeString, ReplaceWithEmptyReplacement) { UnicodeString s("hello"); s.replace(0, 5, UnicodeString("")); EXPECT_EQ(UnicodeString(""), s); } TEST(UnicodeString, ReplaceBegining) { UnicodeString s("hello world"); s.replace(0, 5, UnicodeString("HELLO")); EXPECT_EQ(UnicodeString("HELLO world"), s); } TEST(UnicodeString, ReplaceMiddle) { UnicodeString s("hello world"); s.replace(5, 1, UnicodeString("AB")); EXPECT_EQ(UnicodeString("helloABworld"), s); } TEST(UnicodeString, ReplaceEnd) { UnicodeString s("hello world"); s.replace(10, 1, UnicodeString("AB")); EXPECT_EQ(UnicodeString("hello worlAB"), s); } TEST(UnicodeString, ReplaceWithNonAscii) { UnicodeString s("hello world"); s.replace(3, 2, UnicodeString("\xEF\xBC\x91\xEF\xBC\x90" )); EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90 world"), s); } TEST(UnicodeString, SetCharBegining) { UnicodeString s("hello"); s.setCharAt(0, 'H'); EXPECT_EQ(UnicodeString("Hello"), s); } TEST(UnicodeString, SetCharMiddle) { UnicodeString s("hello"); s.setCharAt(2, 'L'); EXPECT_EQ(UnicodeString("heLlo"), s); } TEST(UnicodeString, SetCharEnd) { UnicodeString s("hello"); s.setCharAt(4, 'O'); EXPECT_EQ(UnicodeString("hellO"), s); } TEST(UnicodeString, SetCharWithNonAscii) { UnicodeString s("hello"); s.setCharAt(4, 0xFF10 ); EXPECT_EQ(UnicodeString("hell\xEF\xBC\x90" ), s); } TEST(UnicodeString, TempSubStringWithEmptyString) { EXPECT_EQ(UnicodeString(""), UnicodeString().tempSubString(0, 0)); } TEST(UnicodeString, TempSubStringWithInvalidInputs) { UnicodeString s("hello"); EXPECT_EQ(UnicodeString(""), s.tempSubString(6)); EXPECT_EQ(UnicodeString(""), s.tempSubString(2, 6)); } TEST(UnicodeString, TempSubString) { UnicodeString s("hello"); EXPECT_EQ(UnicodeString(""), s.tempSubString(0, 0)); EXPECT_EQ(UnicodeString("h"), s.tempSubString(0, 1)); EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0, 5)); EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2, 3)); } TEST(UnicodeString, TempSubStringWithNoLength) { UnicodeString s("hello"); EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0)); EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2)); } TEST(UnicodeString, TempSubStringWithNonAscii) { UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" ); EXPECT_EQ(UnicodeString("\xEF\xBC\x91" ), s.tempSubString(3, 1)); } TEST(UnicodeString, OperatorEqual) { UnicodeString s("hello"); s = UnicodeString("Hello"); EXPECT_EQ(UnicodeString("Hello"), s); } TEST(UnicodeString, OperatorEqualWithNonAscii) { UnicodeString s("hello"); s = UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90" ); EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90"), s); } TEST(UnicodeString, OperatorBracket) { UnicodeString s("hello"); EXPECT_EQ('h', s[0]); EXPECT_EQ('e', s[1]); EXPECT_EQ('l', s[2]); EXPECT_EQ('l', s[3]); EXPECT_EQ('o', s[4]); } TEST(UnicodeString, OperatorBracketWithNonAscii) { UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" ); EXPECT_EQ('h', s[0]); EXPECT_EQ('e', s[1]); EXPECT_EQ('l', s[2]); EXPECT_EQ(0xFF11 , s[3]); EXPECT_EQ(0xFF10 , s[4]); } TEST(UnicodeString, OperatorBracketWithIteratorCacheInvalidation) { UnicodeString s("hello"); EXPECT_EQ('h', s[0]); EXPECT_EQ('e', s[1]); s.setCharAt(1, 'E'); EXPECT_EQ(UnicodeString("hEllo"), s); EXPECT_EQ('E', s[1]); EXPECT_EQ('h', s[0]); EXPECT_EQ('o', s[4]); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/unicodestring.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/unicodestring_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
bf51d14e-553a-4e21-83cb-2f920752ad17
cpp
google/libphonenumber
regexp_cache
cpp/src/phonenumbers/regexp_cache.cc
cpp/test/phonenumbers/regexp_cache_test.cc
#include "phonenumbers/regexp_cache.h" #include <cstddef> #include <string> #include <utility> #include "phonenumbers/base/synchronization/lock.h" #include "phonenumbers/regexp_adapter.h" using std::string; namespace i18n { namespace phonenumbers { RegExpCache::RegExpCache(const AbstractRegExpFactory& regexp_factory, size_t min_items) : regexp_factory_(regexp_factory), #ifdef I18N_PHONENUMBERS_USE_TR1_UNORDERED_MAP cache_impl_(new CacheImpl(min_items)) #else cache_impl_(new CacheImpl()) #endif {} RegExpCache::~RegExpCache() { AutoLock l(lock_); for (CacheImpl::const_iterator it = cache_impl_->begin(); it != cache_impl_->end(); ++it) { delete it->second; } } const RegExp& RegExpCache::GetRegExp(const string& pattern) { AutoLock l(lock_); CacheImpl::const_iterator it = cache_impl_->find(pattern); if (it != cache_impl_->end()) return *it->second; const RegExp* regexp = regexp_factory_.CreateRegExp(pattern); cache_impl_->insert(std::make_pair(pattern, regexp)); return *regexp; } } }
#include <cstddef> #include <string> #include <gtest/gtest.h> #include "phonenumbers/base/synchronization/lock.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/regexp_factory.h" namespace i18n { namespace phonenumbers { using std::string; class RegExpCacheTest : public testing::Test { protected: static constexpr size_t min_items_ = 2; RegExpCacheTest() : cache_(regexp_factory_, min_items_) {} virtual ~RegExpCacheTest() {} RegExpFactory regexp_factory_; RegExpCache cache_; }; TEST_F(RegExpCacheTest, CacheConstructor) { AutoLock l(cache_.lock_); ASSERT_TRUE(cache_.cache_impl_ != NULL); EXPECT_TRUE(cache_.cache_impl_->empty()); } TEST_F(RegExpCacheTest, GetRegExp) { static const string pattern1("foo"); static const string pattern2("foo"); const RegExp& regexp1 = cache_.GetRegExp(pattern1); const RegExp& regexp2 = cache_.GetRegExp(pattern2); EXPECT_TRUE(&regexp1 == &regexp2); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/regexp_cache.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/regexp_cache_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
c74a6817-3eb7-4344-996d-e523ce4fc6bf
cpp
google/libphonenumber
shortnumberinfo
cpp/src/phonenumbers/shortnumberinfo.cc
cpp/test/phonenumbers/shortnumberinfo_test.cc
#include "phonenumbers/shortnumberinfo.h" #include <algorithm> #include <string.h> #include <iterator> #include <map> #include "phonenumbers/default_logger.h" #include "phonenumbers/matcher_api.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/regex_based_matcher.h" #include "phonenumbers/region_code.h" #include "phonenumbers/short_metadata.h" namespace i18n { namespace phonenumbers { using google::protobuf::RepeatedField; using std::map; using std::string; bool LoadCompiledInMetadata(PhoneMetadataCollection* metadata) { if (!metadata->ParseFromArray(short_metadata_get(), short_metadata_size())) { LOG(ERROR) << "Could not parse binary data."; return false; } return true; } ShortNumberInfo::ShortNumberInfo() : phone_util_(*PhoneNumberUtil::GetInstance()), matcher_api_(new RegexBasedMatcher()), region_to_short_metadata_map_(new absl::flat_hash_map<string, PhoneMetadata>()), regions_where_emergency_numbers_must_be_exact_(new absl::flat_hash_set<string>()) { PhoneMetadataCollection metadata_collection; if (!LoadCompiledInMetadata(&metadata_collection)) { LOG(DFATAL) << "Could not parse compiled-in metadata."; return; } for (const auto& metadata : metadata_collection.metadata()) { const string& region_code = metadata.id(); region_to_short_metadata_map_->insert(std::make_pair(region_code, metadata)); } regions_where_emergency_numbers_must_be_exact_->insert("BR"); regions_where_emergency_numbers_must_be_exact_->insert("CL"); regions_where_emergency_numbers_must_be_exact_->insert("NI"); } ShortNumberInfo::~ShortNumberInfo() {} const PhoneMetadata* ShortNumberInfo::GetMetadataForRegion( const string& region_code) const { auto it = region_to_short_metadata_map_->find(region_code); if (it != region_to_short_metadata_map_->end()) { return &it->second; } return nullptr; } namespace { bool MatchesPossibleNumberAndNationalNumber( const MatcherApi& matcher_api, const string& number, const PhoneNumberDesc& desc) { const RepeatedField<int>& lengths = desc.possible_length(); if (desc.possible_length_size() > 0 && std::find(lengths.begin(), lengths.end(), number.length()) == lengths.end()) { return false; } return matcher_api.MatchNationalNumber(number, desc, false); } } bool ShortNumberInfo::RegionDialingFromMatchesNumber(const PhoneNumber& number, const string& region_dialing_from) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); return std::find(region_codes.begin(), region_codes.end(), region_dialing_from) != region_codes.end(); } bool ShortNumberInfo::IsPossibleShortNumberForRegion(const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); if (!phone_metadata) { return false; } string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); const RepeatedField<int>& lengths = phone_metadata->general_desc().possible_length(); return (std::find(lengths.begin(), lengths.end(), short_number.length()) != lengths.end()); } bool ShortNumberInfo::IsPossibleShortNumber(const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); for (const auto& region_code : region_codes) { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); if (!phone_metadata) { continue; } const RepeatedField<int>& lengths = phone_metadata->general_desc().possible_length(); if (std::find(lengths.begin(), lengths.end(), short_number.length()) != lengths.end()) { return true; } } return false; } bool ShortNumberInfo::IsValidShortNumberForRegion( const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); if (!phone_metadata) { return false; } string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); const PhoneNumberDesc& general_desc = phone_metadata->general_desc(); if (!MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, general_desc)) { return false; } const PhoneNumberDesc& short_number_desc = phone_metadata->short_code(); return MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, short_number_desc); } bool ShortNumberInfo::IsValidShortNumber(const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); string region_code; GetRegionCodeForShortNumberFromRegionList(number, region_codes, &region_code); if (region_codes.size() > 1 && region_code != RegionCode::GetUnknown()) { return true; } return IsValidShortNumberForRegion(number, region_code); } ShortNumberInfo::ShortNumberCost ShortNumberInfo::GetExpectedCostForRegion( const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return ShortNumberInfo::UNKNOWN_COST; } const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); if (!phone_metadata) { return ShortNumberInfo::UNKNOWN_COST; } string short_number; phone_util_.GetNationalSignificantNumber(number, &short_number); const RepeatedField<int>& lengths = phone_metadata->general_desc().possible_length(); if (std::find(lengths.begin(), lengths.end(), short_number.length()) == lengths.end()) { return ShortNumberInfo::UNKNOWN_COST; } if (MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, phone_metadata->premium_rate())) { return ShortNumberInfo::PREMIUM_RATE; } if (MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, phone_metadata->standard_rate())) { return ShortNumberInfo::STANDARD_RATE; } if (MatchesPossibleNumberAndNationalNumber(*matcher_api_, short_number, phone_metadata->toll_free())) { return ShortNumberInfo::TOLL_FREE; } if (IsEmergencyNumber(short_number, region_dialing_from)) { return ShortNumberInfo::TOLL_FREE; } return ShortNumberInfo::UNKNOWN_COST; } ShortNumberInfo::ShortNumberCost ShortNumberInfo::GetExpectedCost( const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); if (region_codes.size() == 0) { return ShortNumberInfo::UNKNOWN_COST; } if (region_codes.size() == 1) { return GetExpectedCostForRegion(number, region_codes.front()); } ShortNumberInfo::ShortNumberCost cost = ShortNumberInfo::TOLL_FREE; for (const auto& region_code : region_codes) { ShortNumberInfo::ShortNumberCost cost_for_region = GetExpectedCostForRegion(number, region_code); switch (cost_for_region) { case ShortNumberInfo::PREMIUM_RATE: return ShortNumberInfo::PREMIUM_RATE; case ShortNumberInfo::UNKNOWN_COST: return ShortNumberInfo::UNKNOWN_COST; case ShortNumberInfo::STANDARD_RATE: if (cost != ShortNumberInfo::UNKNOWN_COST) { cost = ShortNumberInfo::STANDARD_RATE; } break; case ShortNumberInfo::TOLL_FREE: break; default: LOG(ERROR) << "Unrecognised cost for region: " << static_cast<int>(cost_for_region); break; } } return cost; } void ShortNumberInfo::GetRegionCodeForShortNumberFromRegionList( const PhoneNumber& number, const list<string>& region_codes, string* region_code) const { if (region_codes.size() == 0) { region_code->assign(RegionCode::GetUnknown()); return; } else if (region_codes.size() == 1) { region_code->assign(region_codes.front()); return; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); for (const auto& region_code_it : region_codes) { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code_it); if (phone_metadata != nullptr && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->short_code())) { region_code->assign(region_code_it); return; } } region_code->assign(RegionCode::GetUnknown()); } string ShortNumberInfo::GetExampleShortNumber(const string& region_code) const { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); if (!phone_metadata) { return ""; } const PhoneNumberDesc& desc = phone_metadata->short_code(); if (desc.has_example_number()) { return desc.example_number(); } return ""; } string ShortNumberInfo::GetExampleShortNumberForCost(const string& region_code, ShortNumberInfo::ShortNumberCost cost) const { const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); if (!phone_metadata) { return ""; } const PhoneNumberDesc* desc = nullptr; switch (cost) { case TOLL_FREE: desc = &(phone_metadata->toll_free()); break; case STANDARD_RATE: desc = &(phone_metadata->standard_rate()); break; case PREMIUM_RATE: desc = &(phone_metadata->premium_rate()); break; default: break; } if (desc != nullptr && desc->has_example_number()) { return desc->example_number(); } return ""; } bool ShortNumberInfo::ConnectsToEmergencyNumber(const string& number, const string& region_code) const { return MatchesEmergencyNumberHelper(number, region_code, true ); } bool ShortNumberInfo::IsEmergencyNumber(const string& number, const string& region_code) const { return MatchesEmergencyNumberHelper(number, region_code, false ); } bool ShortNumberInfo::MatchesEmergencyNumberHelper(const string& number, const string& region_code, bool allow_prefix_match) const { string extracted_number; phone_util_.ExtractPossibleNumber(number, &extracted_number); if (phone_util_.StartsWithPlusCharsPattern(extracted_number)) { return false; } const PhoneMetadata* metadata = GetMetadataForRegion(region_code); if (!metadata || !metadata->has_emergency()) { return false; } phone_util_.NormalizeDigitsOnly(&extracted_number); bool allow_prefix_match_for_region = allow_prefix_match && regions_where_emergency_numbers_must_be_exact_->find(region_code) == regions_where_emergency_numbers_must_be_exact_->end(); return matcher_api_->MatchNationalNumber( extracted_number, metadata->emergency(), allow_prefix_match_for_region); } bool ShortNumberInfo::IsCarrierSpecific(const PhoneNumber& number) const { list<string> region_codes; phone_util_.GetRegionCodesForCountryCallingCode(number.country_code(), &region_codes); string region_code; GetRegionCodeForShortNumberFromRegionList(number, region_codes, &region_code); string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_code); return phone_metadata && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->carrier_specific()); } bool ShortNumberInfo::IsCarrierSpecificForRegion(const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); return phone_metadata && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->carrier_specific()); } bool ShortNumberInfo::IsSmsServiceForRegion(const PhoneNumber& number, const string& region_dialing_from) const { if (!RegionDialingFromMatchesNumber(number, region_dialing_from)) { return false; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); const PhoneMetadata* phone_metadata = GetMetadataForRegion(region_dialing_from); return phone_metadata && MatchesPossibleNumberAndNationalNumber(*matcher_api_, national_number, phone_metadata->sms_services()); } } }
#include "phonenumbers/shortnumberinfo.h" #include <gtest/gtest.h> #include "phonenumbers/base/logging.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { class ShortNumberInfoTest : public testing::Test { public: ShortNumberInfoTest(const ShortNumberInfoTest&) = delete; ShortNumberInfoTest& operator=(const ShortNumberInfoTest&) = delete; protected: PhoneNumber ParseNumberForTesting(const string& number, const string& region_code) { PhoneNumber phone_number; PhoneNumberUtil::ErrorType error_type = phone_util_.Parse( number, region_code, &phone_number); CHECK_EQ(error_type, PhoneNumberUtil::NO_PARSING_ERROR); IGNORE_UNUSED(error_type); return phone_number; } ShortNumberInfoTest() : short_info_() { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } const PhoneNumberUtil phone_util_; const ShortNumberInfo short_info_; }; TEST_F(ShortNumberInfoTest, IsPossibleShortNumber) { PhoneNumber possible_number; possible_number.set_country_code(33); possible_number.set_national_number(uint64{123456}); EXPECT_TRUE(short_info_.IsPossibleShortNumber(possible_number)); EXPECT_TRUE(short_info_.IsPossibleShortNumberForRegion( ParseNumberForTesting("123456", RegionCode::FR()), RegionCode::FR())); PhoneNumber impossible_number; impossible_number.set_country_code(33); impossible_number.set_national_number(uint64{9}); EXPECT_FALSE(short_info_.IsPossibleShortNumber(impossible_number)); PhoneNumber shared_number; shared_number.set_country_code(44); shared_number.set_national_number(uint64{11001}); EXPECT_TRUE(short_info_.IsPossibleShortNumber(shared_number)); } TEST_F(ShortNumberInfoTest, IsValidShortNumber) { PhoneNumber valid_number; valid_number.set_country_code(33); valid_number.set_national_number(uint64{1010}); EXPECT_TRUE(short_info_.IsValidShortNumber(valid_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("1010", RegionCode::FR()), RegionCode::FR())); PhoneNumber invalid_number; invalid_number.set_country_code(33); invalid_number.set_national_number(uint64{123456}); EXPECT_FALSE(short_info_.IsValidShortNumber(invalid_number)); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("123456", RegionCode::FR()), RegionCode::FR())); PhoneNumber shared_number; shared_number.set_country_code(44); shared_number.set_national_number(uint64{18001}); EXPECT_TRUE(short_info_.IsValidShortNumber(shared_number)); } TEST_F(ShortNumberInfoTest, IsCarrierSpecific) { PhoneNumber carrier_specific_number; carrier_specific_number.set_country_code(1); carrier_specific_number.set_national_number(uint64{33669}); EXPECT_TRUE(short_info_.IsCarrierSpecific(carrier_specific_number)); EXPECT_TRUE(short_info_.IsCarrierSpecificForRegion( ParseNumberForTesting("33669", RegionCode::US()), RegionCode::US())); PhoneNumber not_carrier_specific_number; not_carrier_specific_number.set_country_code(1); not_carrier_specific_number.set_national_number(uint64{911}); EXPECT_FALSE(short_info_.IsCarrierSpecific(not_carrier_specific_number)); EXPECT_FALSE(short_info_.IsCarrierSpecificForRegion( ParseNumberForTesting("911", RegionCode::US()), RegionCode::US())); PhoneNumber carrier_specific_number_for_some_region; carrier_specific_number_for_some_region.set_country_code(1); carrier_specific_number_for_some_region.set_national_number(uint64{211}); EXPECT_TRUE(short_info_.IsCarrierSpecific( carrier_specific_number_for_some_region)); EXPECT_TRUE(short_info_.IsCarrierSpecificForRegion( carrier_specific_number_for_some_region, RegionCode::US())); EXPECT_FALSE(short_info_.IsCarrierSpecificForRegion( carrier_specific_number_for_some_region, RegionCode::BB())); } TEST_F(ShortNumberInfoTest, IsSmsService) { PhoneNumber sms_service_number_for_some_region; sms_service_number_for_some_region.set_country_code(1); sms_service_number_for_some_region.set_national_number(uint64{21234}); EXPECT_TRUE(short_info_.IsSmsServiceForRegion( sms_service_number_for_some_region, RegionCode::US())); EXPECT_FALSE(short_info_.IsSmsServiceForRegion( sms_service_number_for_some_region, RegionCode::BB())); } TEST_F(ShortNumberInfoTest, GetExpectedCost) { uint64 national_number; const string& premium_rate_example = short_info_.GetExampleShortNumberForCost( RegionCode::FR(), ShortNumberInfo::PREMIUM_RATE); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(premium_rate_example, RegionCode::FR()), RegionCode::FR())); PhoneNumber premium_rate_number; premium_rate_number.set_country_code(33); safe_strtou64(premium_rate_example, &national_number); premium_rate_number.set_national_number(national_number); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCost(premium_rate_number)); const string& standard_rate_example = short_info_.GetExampleShortNumberForCost( RegionCode::FR(), ShortNumberInfo::STANDARD_RATE); EXPECT_EQ(ShortNumberInfo::STANDARD_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(standard_rate_example, RegionCode::FR()), RegionCode::FR())); PhoneNumber standard_rate_number; standard_rate_number.set_country_code(33); safe_strtou64(standard_rate_example, &national_number); standard_rate_number.set_national_number(national_number); EXPECT_EQ(ShortNumberInfo::STANDARD_RATE, short_info_.GetExpectedCost(standard_rate_number)); const string& toll_free_example = short_info_.GetExampleShortNumberForCost( RegionCode::FR(), ShortNumberInfo::TOLL_FREE); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(toll_free_example, RegionCode::FR()), RegionCode::FR())); PhoneNumber toll_free_number; toll_free_number.set_country_code(33); safe_strtou64(toll_free_example, &national_number); toll_free_number.set_national_number(national_number); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCost(toll_free_number)); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("12345", RegionCode::FR()), RegionCode::FR())); PhoneNumber unknown_cost_number; unknown_cost_number.set_country_code(33); unknown_cost_number.set_national_number(uint64{12345}); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(unknown_cost_number)); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("116123", RegionCode::FR()), RegionCode::FR())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("116123", RegionCode::FR()), RegionCode::FR())); PhoneNumber invalid_number; invalid_number.set_country_code(33); invalid_number.set_national_number(uint64{116123}); EXPECT_FALSE(short_info_.IsValidShortNumber(invalid_number)); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCost(invalid_number)); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("911", RegionCode::US()), RegionCode::ZZ())); unknown_cost_number.Clear(); unknown_cost_number.set_country_code(123); unknown_cost_number.set_national_number(uint64{911}); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(unknown_cost_number)); } TEST_F(ShortNumberInfoTest, GetExpectedCostForSharedCountryCallingCode) { string ambiguous_premium_rate_string("1234"); PhoneNumber ambiguous_premium_rate_number; ambiguous_premium_rate_number.set_country_code(61); ambiguous_premium_rate_number.set_national_number(uint64{1234}); string ambiguous_standard_rate_string("1194"); PhoneNumber ambiguous_standard_rate_number; ambiguous_standard_rate_number.set_country_code(61); ambiguous_standard_rate_number.set_national_number(uint64{1194}); string ambiguous_toll_free_string("733"); PhoneNumber ambiguous_toll_free_number; ambiguous_toll_free_number.set_country_code(61); ambiguous_toll_free_number.set_national_number(uint64{733}); EXPECT_TRUE(short_info_.IsValidShortNumber(ambiguous_premium_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumber(ambiguous_standard_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumber(ambiguous_toll_free_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_premium_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::PREMIUM_RATE, short_info_.GetExpectedCost(ambiguous_premium_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_EQ(ShortNumberInfo::STANDARD_RATE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::AU()), RegionCode::AU())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_standard_rate_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(ambiguous_standard_rate_number)); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::AU()), RegionCode::AU())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::AU()), RegionCode::AU())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting(ambiguous_toll_free_string, RegionCode::CX()), RegionCode::CX())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCost(ambiguous_toll_free_number)); } TEST_F(ShortNumberInfoTest, GetExampleShortNumber) { EXPECT_FALSE(short_info_.GetExampleShortNumber(RegionCode::AD()).empty()); EXPECT_FALSE(short_info_.GetExampleShortNumber(RegionCode::FR()).empty()); EXPECT_TRUE(short_info_.GetExampleShortNumber(RegionCode::UN001()).empty()); EXPECT_TRUE( short_info_.GetExampleShortNumber(RegionCode::GetUnknown()).empty()); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_US) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::US())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("112", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberLongNumber_US) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("9116666666", RegionCode::US())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("1126666666", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9996666666", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberWithFormatting_US) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("9-1-1", RegionCode::US())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("1-1-2", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9-9-9", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberWithPlusSign_US) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("+911", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("\xEF\xBC\x8B" "911", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber(" +911", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("+112", RegionCode::US())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("+999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_BR) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::BR())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("190", RegionCode::BR())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("999", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberLongNumber_BR) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9111", RegionCode::BR())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("1900", RegionCode::BR())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("9996", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_CL) { EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("131", RegionCode::CL())); EXPECT_TRUE(short_info_.ConnectsToEmergencyNumber("133", RegionCode::CL())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumberLongNumber_CL) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("1313", RegionCode::CL())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("1330", RegionCode::CL())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_AO) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::AO())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("222123456", RegionCode::AO())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("923123456", RegionCode::AO())); } TEST_F(ShortNumberInfoTest, ConnectsToEmergencyNumber_ZW) { EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("911", RegionCode::ZW())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("01312345", RegionCode::ZW())); EXPECT_FALSE(short_info_.ConnectsToEmergencyNumber("0711234567", RegionCode::ZW())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_US) { EXPECT_TRUE(short_info_.IsEmergencyNumber("911", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("112", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumberLongNumber_US) { EXPECT_FALSE(short_info_.IsEmergencyNumber("9116666666", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("1126666666", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("9996666666", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumberWithFormatting_US) { EXPECT_TRUE(short_info_.IsEmergencyNumber("9-1-1", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("*911", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("1-1-2", RegionCode::US())); EXPECT_TRUE(short_info_.IsEmergencyNumber("*112", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("9-9-9", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("*999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumberWithPlusSign_US) { EXPECT_FALSE(short_info_.IsEmergencyNumber("+911", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("\xEF\xBC\x8B" "911", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber(" +911", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("+112", RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("+999", RegionCode::US())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_BR) { EXPECT_TRUE(short_info_.IsEmergencyNumber("911", RegionCode::BR())); EXPECT_TRUE(short_info_.IsEmergencyNumber("190", RegionCode::BR())); EXPECT_FALSE(short_info_.IsEmergencyNumber("999", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, EmergencyNumberLongNumber_BR) { EXPECT_FALSE(short_info_.IsEmergencyNumber("9111", RegionCode::BR())); EXPECT_FALSE(short_info_.IsEmergencyNumber("1900", RegionCode::BR())); EXPECT_FALSE(short_info_.IsEmergencyNumber("9996", RegionCode::BR())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_AO) { EXPECT_FALSE(short_info_.IsEmergencyNumber("911", RegionCode::AO())); EXPECT_FALSE(short_info_.IsEmergencyNumber("222123456", RegionCode::AO())); EXPECT_FALSE(short_info_.IsEmergencyNumber("923123456", RegionCode::AO())); } TEST_F(ShortNumberInfoTest, IsEmergencyNumber_ZW) { EXPECT_FALSE(short_info_.IsEmergencyNumber("911", RegionCode::ZW())); EXPECT_FALSE(short_info_.IsEmergencyNumber("01312345", RegionCode::ZW())); EXPECT_FALSE(short_info_.IsEmergencyNumber("0711234567", RegionCode::ZW())); } TEST_F(ShortNumberInfoTest, EmergencyNumberForSharedCountryCallingCode) { EXPECT_TRUE(short_info_.IsEmergencyNumber("112", RegionCode::AU())); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("112", RegionCode::AU()), RegionCode::AU())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("112", RegionCode::AU()), RegionCode::AU())); EXPECT_TRUE(short_info_.IsEmergencyNumber("112", RegionCode::CX())); EXPECT_TRUE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("112", RegionCode::CX()), RegionCode::CX())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("112", RegionCode::CX()), RegionCode::CX())); PhoneNumber shared_emergency_number; shared_emergency_number.set_country_code(61); shared_emergency_number.set_national_number(uint64{112}); EXPECT_TRUE(short_info_.IsValidShortNumber(shared_emergency_number)); EXPECT_EQ(ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCost(shared_emergency_number)); } TEST_F(ShortNumberInfoTest, OverlappingNANPANumber) { EXPECT_TRUE(short_info_.IsEmergencyNumber("211", RegionCode::BB())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("211", RegionCode::BB()), RegionCode::BB())); EXPECT_FALSE(short_info_.IsEmergencyNumber("211", RegionCode::US())); EXPECT_EQ( ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("211", RegionCode::US()), RegionCode::US())); EXPECT_FALSE(short_info_.IsEmergencyNumber("211", RegionCode::CA())); EXPECT_EQ( ShortNumberInfo::TOLL_FREE, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("211", RegionCode::CA()), RegionCode::CA())); } TEST_F(ShortNumberInfoTest, CountryCallingCodeIsNotIgnored) { EXPECT_FALSE(short_info_.IsPossibleShortNumberForRegion( ParseNumberForTesting("+4640404", RegionCode::SE()), RegionCode::US())); EXPECT_FALSE(short_info_.IsValidShortNumberForRegion( ParseNumberForTesting("+4640404", RegionCode::SE()), RegionCode::US())); EXPECT_EQ(ShortNumberInfo::UNKNOWN_COST, short_info_.GetExpectedCostForRegion( ParseNumberForTesting("+4640404", RegionCode::SE()), RegionCode::US())); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/shortnumberinfo.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/shortnumberinfo_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
2bc2b96f-d502-4c20-9eae-a838f751e478
cpp
google/libphonenumber
logger
cpp/src/phonenumbers/logger.cc
cpp/test/phonenumbers/logger_test.cc
#include "phonenumbers/logger.h" #include <cstddef> namespace i18n { namespace phonenumbers { Logger* Logger::impl_ = NULL; } }
#include <string> #include <gtest/gtest.h> #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/logger.h" namespace i18n { namespace phonenumbers { class StringLogger : public Logger { public: virtual ~StringLogger() {} const string& message() const { return msg_; } virtual void WriteMessage(const string& msg) { msg_ += msg; } private: string msg_; }; class LoggerTest : public ::testing::Test { protected: virtual void SetUp() { test_logger_.reset(new StringLogger()); test_logger_->set_level(LOG_INFO); old_logger_ = Logger::mutable_logger_impl(); Logger::set_logger_impl(test_logger_.get()); } virtual void TearDown() { Logger::set_logger_impl(old_logger_); } scoped_ptr<StringLogger> test_logger_; Logger* old_logger_; }; TEST_F(LoggerTest, LoggerIgnoresHigherVerbosity) { LOG(LOG_DEBUG) << "Hello"; EXPECT_EQ("", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsNewline) { LOG(LOG_INFO) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerLogsEqualVerbosity) { LOG(LOG_INFO) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerLogsMoreSeriousMessages) { LOG(LOG_WARNING) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerConcatenatesMessages) { LOG(LOG_INFO) << "Hello"; ASSERT_EQ("Hello\n", test_logger_->message()); LOG(LOG_INFO) << " World"; EXPECT_EQ("Hello\n World\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerHandlesDifferentTypes) { LOG(LOG_INFO) << "Hello " << 42; EXPECT_EQ("Hello 42\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerIgnoresVerboseLogs) { VLOG(1) << "Hello"; EXPECT_EQ("", test_logger_->message()); VLOG(0) << "Hello"; EXPECT_EQ("", test_logger_->message()); test_logger_->set_level(LOG_DEBUG); VLOG(1) << "Hello"; EXPECT_EQ("", test_logger_->message()); VLOG(0) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerShowsDebugLogsAtDebugLevel) { test_logger_->set_level(LOG_DEBUG); LOG(LOG_DEBUG) << "Debug hello"; EXPECT_EQ("Debug hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsDebugLogsWhenVerbositySet) { int verbose_log_level = 2; test_logger_->set_verbosity_level(verbose_log_level); LOG(LOG_DEBUG) << "Debug hello"; EXPECT_EQ("Debug hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsErrorLogsWhenVerbositySet) { int verbose_log_level = 2; test_logger_->set_verbosity_level(verbose_log_level); LOG(ERROR) << "Error hello"; EXPECT_EQ("Error hello\n", test_logger_->message()); } TEST_F(LoggerTest, LoggerOutputsLogsAccordingToVerbosity) { int verbose_log_level = 2; test_logger_->set_verbosity_level(verbose_log_level); VLOG(verbose_log_level + 1) << "Hello 3"; EXPECT_EQ("", test_logger_->message()); VLOG(verbose_log_level - 1) << "Hello"; EXPECT_EQ("Hello\n", test_logger_->message()); VLOG(verbose_log_level) << "Hello 2"; EXPECT_EQ("Hello\nHello 2\n", test_logger_->message()); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/logger.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/logger_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
884a1873-2492-4e33-affb-1854f596ef62
cpp
google/libphonenumber
phonenumbermatcher
cpp/src/phonenumbers/phonenumbermatcher.cc
cpp/test/phonenumbers/phonenumbermatcher_test.cc
#include "phonenumbers/phonenumbermatcher.h" #ifndef I18N_PHONENUMBERS_USE_ICU_REGEXP #error phonenumbermatcher depends on ICU \ (i.e. I18N_PHONENUMBERS_USE_ICU_REGEXP must be set) #endif #include <ctype.h> #include <stddef.h> #include <limits> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include <unicode/uchar.h> #include "phonenumbers/alternate_format.h" #include "phonenumbers/base/logging.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/base/memory/singleton.h" #include "phonenumbers/callback.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/encoding_utils.h" #include "phonenumbers/normalize_utf8.h" #include "phonenumbers/phonemetadata.pb.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/phonenumbermatch.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/regexp_adapter.h" #include "phonenumbers/regexp_adapter_icu.h" #include "phonenumbers/regexp_cache.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/utf/unicodetext.h" #ifdef I18N_PHONENUMBERS_USE_RE2 #include "phonenumbers/regexp_adapter_re2.h" #endif using std::map; using std::numeric_limits; using std::string; namespace i18n { namespace phonenumbers { namespace { string Limit(int lower, int upper) { DCHECK_GE(lower, 0); DCHECK_GT(upper, 0); DCHECK_LT(lower, upper); return StrCat("{", lower, ",", upper, "}"); } bool IsInvalidPunctuationSymbol(char32 character) { return character == '%' || u_charType(character) == U_CURRENCY_SYMBOL; } bool ContainsOnlyValidXChars(const PhoneNumber& number, const string& candidate, const PhoneNumberUtil& util) { size_t found; found = candidate.find_first_of("xX"); while (found != string::npos && found < candidate.length() - 1) { char next_char = candidate[found + 1]; if (next_char == 'x' || next_char == 'X') { ++found; if (util.IsNumberMatchWithOneString( number, candidate.substr(found, candidate.length() - found)) != PhoneNumberUtil::NSN_MATCH) { return false; } } else { string normalized_extension(candidate.substr(found, candidate.length() - found)); util.NormalizeDigitsOnly(&normalized_extension); if (normalized_extension != number.extension()) { return false; } } found = candidate.find_first_of("xX", found + 1); } return true; } bool AllNumberGroupsRemainGrouped( const PhoneNumberUtil& util, const PhoneNumber& number, const string& normalized_candidate, const std::vector<string>& formatted_number_groups) { size_t from_index = 0; if (number.country_code_source() != PhoneNumber::FROM_DEFAULT_COUNTRY) { string country_code = SimpleItoa(number.country_code()); from_index = normalized_candidate.find(country_code) + country_code.size(); } for (size_t i = 0; i < formatted_number_groups.size(); ++i) { from_index = normalized_candidate.find(formatted_number_groups.at(i), from_index); if (from_index == string::npos) { return false; } from_index += formatted_number_groups.at(i).length(); if (i == 0 && from_index < normalized_candidate.length()) { string region; util.GetRegionCodeForCountryCode(number.country_code(), &region); string ndd_prefix; util.GetNddPrefixForRegion(region, true, &ndd_prefix); if (!ndd_prefix.empty() && isdigit(normalized_candidate.at(from_index))) { string national_significant_number; util.GetNationalSignificantNumber(number, &national_significant_number); return HasPrefixString(normalized_candidate.substr( from_index - formatted_number_groups.at(i).length()), national_significant_number); } } } return normalized_candidate.substr(from_index) .find(number.extension()) != string::npos; } bool LoadAlternateFormats(PhoneMetadataCollection* alternate_formats) { #if defined(I18N_PHONENUMBERS_USE_ALTERNATE_FORMATS) if (!alternate_formats->ParseFromArray(alternate_format_get(), alternate_format_size())) { LOG(ERROR) << "Could not parse binary data."; return false; } return true; #else return false; #endif } } class PhoneNumberMatcherRegExps : public Singleton<PhoneNumberMatcherRegExps> { private: friend class Singleton<PhoneNumberMatcherRegExps>; string opening_parens_; string closing_parens_; string non_parens_; string bracket_pair_limit_; string leading_maybe_matched_bracket_; string bracket_pairs_; string lead_limit_; string punctuation_limit_; int digit_block_limit_; string block_limit_; string punctuation_; string digit_sequence_; string lead_class_chars_; string lead_class_; public: scoped_ptr<const AbstractRegExpFactory> regexp_factory_for_pattern_; scoped_ptr<const AbstractRegExpFactory> regexp_factory_; mutable RegExpCache regexp_cache_; scoped_ptr<const RegExp> pub_pages_; scoped_ptr<const RegExp> slash_separated_dates_; scoped_ptr<const RegExp> time_stamps_; scoped_ptr<const RegExp> time_stamps_suffix_; scoped_ptr<const RegExp> matching_brackets_; scoped_ptr<std::vector<const RegExp*> > inner_matches_; scoped_ptr<const RegExp> capture_up_to_second_number_start_pattern_; scoped_ptr<const RegExp> capturing_ascii_digits_pattern_; scoped_ptr<const RegExp> lead_class_pattern_; scoped_ptr<const RegExp> pattern_; PhoneNumberMatcherRegExps() : opening_parens_("(\\[\xEF\xBC\x88\xEF\xBC\xBB" ), closing_parens_(")\\]\xEF\xBC\x89\xEF\xBC\xBD" ), non_parens_(StrCat("[^", opening_parens_, closing_parens_, "]")), bracket_pair_limit_(Limit(0, 3)), leading_maybe_matched_bracket_(StrCat( "(?:[", opening_parens_, "])?", "(?:", non_parens_, "+[", closing_parens_, "])?")), bracket_pairs_(StrCat( "(?:[", opening_parens_, "]", non_parens_, "+", "[", closing_parens_, "])", bracket_pair_limit_)), lead_limit_(Limit(0, 2)), punctuation_limit_(Limit(0, 4)), digit_block_limit_(PhoneNumberUtil::kMaxLengthForNsn + PhoneNumberUtil::kMaxLengthCountryCode), block_limit_(Limit(0, digit_block_limit_)), punctuation_(StrCat("[", PhoneNumberUtil::kValidPunctuation, "]", punctuation_limit_)), digit_sequence_(StrCat("\\p{Nd}", Limit(1, digit_block_limit_))), lead_class_chars_(StrCat(opening_parens_, PhoneNumberUtil::kPlusChars)), lead_class_(StrCat("[", lead_class_chars_, "]")), regexp_factory_for_pattern_(new ICURegExpFactory()), #ifdef I18N_PHONENUMBERS_USE_RE2 regexp_factory_(new RE2RegExpFactory()), #else regexp_factory_(new ICURegExpFactory()), #endif regexp_cache_(*regexp_factory_, 32), pub_pages_(regexp_factory_->CreateRegExp( "\\d{1,5}-+\\d{1,5}\\s{0,4}\\(\\d{1,4}")), slash_separated_dates_(regexp_factory_->CreateRegExp( "(?:(?:[0-3]?\\d/[01]?\\d)|" "(?:[01]?\\d/[0-3]?\\d))/(?:[12]\\d)?\\d{2}")), time_stamps_(regexp_factory_->CreateRegExp( "[12]\\d{3}[-/]?[01]\\d[-/]?[0-3]\\d +[0-2]\\d$")), time_stamps_suffix_(regexp_factory_->CreateRegExp(":[0-5]\\d")), matching_brackets_(regexp_factory_->CreateRegExp( StrCat(leading_maybe_matched_bracket_, non_parens_, "+", bracket_pairs_, non_parens_, "*"))), inner_matches_(new std::vector<const RegExp*>()), capture_up_to_second_number_start_pattern_( regexp_factory_->CreateRegExp( PhoneNumberUtil::kCaptureUpToSecondNumberStart)), capturing_ascii_digits_pattern_( regexp_factory_->CreateRegExp("(\\d+)")), lead_class_pattern_(regexp_factory_->CreateRegExp(lead_class_)), pattern_(regexp_factory_for_pattern_->CreateRegExp(StrCat( "((?:", lead_class_, punctuation_, ")", lead_limit_, digit_sequence_, "(?:", punctuation_, digit_sequence_, ")", block_limit_, "(?i)(?:", PhoneNumberUtil::GetInstance()->GetExtnPatternsForMatching(), ")?)"))) { inner_matches_->push_back( regexp_factory_->CreateRegExp("/+(.*)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("(\\([^(]*)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("(?:\\p{Z}-|-\\p{Z})\\p{Z}*(.+)")); inner_matches_->push_back( regexp_factory_->CreateRegExp( "[\xE2\x80\x92-\xE2\x80\x95\xEF\xBC\x8D]" "\\p{Z}*(.+)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("\\.+\\p{Z}*([^.]+)")); inner_matches_->push_back( regexp_factory_->CreateRegExp("\\p{Z}+(\\P{Z}+)")); } private: DISALLOW_COPY_AND_ASSIGN(PhoneNumberMatcherRegExps); }; class AlternateFormats : public Singleton<AlternateFormats> { public: PhoneMetadataCollection format_data_; map<int, const PhoneMetadata*> calling_code_to_alternate_formats_map_; AlternateFormats() : format_data_(), calling_code_to_alternate_formats_map_() { if (!LoadAlternateFormats(&format_data_)) { LOG(DFATAL) << "Could not parse compiled-in metadata."; return; } for (RepeatedPtrField<PhoneMetadata>::const_iterator it = format_data_.metadata().begin(); it != format_data_.metadata().end(); ++it) { calling_code_to_alternate_formats_map_.insert( std::make_pair(it->country_code(), &*it)); } } const PhoneMetadata* GetAlternateFormatsForCountry(int country_calling_code) const { map<int, const PhoneMetadata*>::const_iterator it = calling_code_to_alternate_formats_map_.find(country_calling_code); if (it != calling_code_to_alternate_formats_map_.end()) { return it->second; } return NULL; } private: DISALLOW_COPY_AND_ASSIGN(AlternateFormats); }; PhoneNumberMatcher::PhoneNumberMatcher(const PhoneNumberUtil& util, const string& text, const string& region_code, PhoneNumberMatcher::Leniency leniency, int max_tries) : reg_exps_(PhoneNumberMatcherRegExps::GetInstance()), alternate_formats_(AlternateFormats::GetInstance()), phone_util_(util), text_(text), preferred_region_(region_code), leniency_(leniency), max_tries_(max_tries), state_(NOT_READY), last_match_(NULL), search_index_(0), is_input_valid_utf8_(true) { is_input_valid_utf8_ = IsInputUtf8(); } PhoneNumberMatcher::PhoneNumberMatcher(const string& text, const string& region_code) : reg_exps_(PhoneNumberMatcherRegExps::GetInstance()), alternate_formats_(NULL), phone_util_(*PhoneNumberUtil::GetInstance()), text_(text), preferred_region_(region_code), leniency_(VALID), max_tries_(numeric_limits<int>::max()), state_(NOT_READY), last_match_(NULL), search_index_(0), is_input_valid_utf8_(true) { is_input_valid_utf8_ = IsInputUtf8(); } PhoneNumberMatcher::~PhoneNumberMatcher() { } bool PhoneNumberMatcher::IsInputUtf8() { UnicodeText number_as_unicode; number_as_unicode.PointToUTF8(text_.c_str(), text_.size()); return number_as_unicode.UTF8WasValid(); } bool PhoneNumberMatcher::IsLatinLetter(char32 letter) { if (!u_isalpha(letter) && (u_charType(letter) != U_NON_SPACING_MARK)) { return false; } UBlockCode block = ublock_getCode(letter); return ((block == UBLOCK_BASIC_LATIN) || (block == UBLOCK_LATIN_1_SUPPLEMENT) || (block == UBLOCK_LATIN_EXTENDED_A) || (block == UBLOCK_LATIN_EXTENDED_ADDITIONAL) || (block == UBLOCK_LATIN_EXTENDED_B) || (block == UBLOCK_COMBINING_DIACRITICAL_MARKS)); } bool PhoneNumberMatcher::ParseAndVerify(const string& candidate, int offset, PhoneNumberMatch* match) { DCHECK(match); if (!reg_exps_->matching_brackets_->FullMatch(candidate) || reg_exps_->pub_pages_->PartialMatch(candidate)) { return false; } if (leniency_ >= VALID) { scoped_ptr<RegExpInput> candidate_input( reg_exps_->regexp_factory_->CreateInput(candidate)); if (offset > 0 && !reg_exps_->lead_class_pattern_->Consume(candidate_input.get())) { char32 previous_char; const char* previous_char_ptr = EncodingUtils::BackUpOneUTF8Character(text_.c_str(), text_.c_str() + offset); EncodingUtils::DecodeUTF8Char(previous_char_ptr, &previous_char); if (IsInvalidPunctuationSymbol(previous_char) || IsLatinLetter(previous_char)) { return false; } } size_t lastCharIndex = offset + candidate.length(); if (lastCharIndex < text_.length()) { char32 next_char; const char* next_char_ptr = EncodingUtils::AdvanceOneUTF8Character( text_.c_str() + lastCharIndex - 1); EncodingUtils::DecodeUTF8Char(next_char_ptr, &next_char); if (IsInvalidPunctuationSymbol(next_char) || IsLatinLetter(next_char)) { return false; } } } PhoneNumber number; if (phone_util_.ParseAndKeepRawInput(candidate, preferred_region_, &number) != PhoneNumberUtil::NO_PARSING_ERROR) { return false; } if (VerifyAccordingToLeniency(leniency_, number, candidate)) { match->set_start(offset); match->set_raw_string(candidate); number.clear_country_code_source(); number.clear_preferred_domestic_carrier_code(); number.clear_raw_input(); match->set_number(number); return true; } return false; } bool PhoneNumberMatcher::VerifyAccordingToLeniency( Leniency leniency, const PhoneNumber& number, const string& candidate) const { switch (leniency) { case PhoneNumberMatcher::POSSIBLE: return phone_util_.IsPossibleNumber(number); case PhoneNumberMatcher::VALID: if (!phone_util_.IsValidNumber(number) || !ContainsOnlyValidXChars(number, candidate, phone_util_)) { return false; } return IsNationalPrefixPresentIfRequired(number); case PhoneNumberMatcher::STRICT_GROUPING: { if (!phone_util_.IsValidNumber(number) || !ContainsOnlyValidXChars(number, candidate, phone_util_) || ContainsMoreThanOneSlashInNationalNumber( number, candidate, phone_util_) || !IsNationalPrefixPresentIfRequired(number)) { return false; } ResultCallback4<bool, const PhoneNumberUtil&, const PhoneNumber&, const string&, const std::vector<string>&>* callback = NewPermanentCallback(&AllNumberGroupsRemainGrouped); bool is_valid = CheckNumberGroupingIsValid(number, candidate, callback); delete(callback); return is_valid; } case PhoneNumberMatcher::EXACT_GROUPING: { if (!phone_util_.IsValidNumber(number) || !ContainsOnlyValidXChars(number, candidate, phone_util_) || ContainsMoreThanOneSlashInNationalNumber( number, candidate, phone_util_) || !IsNationalPrefixPresentIfRequired(number)) { return false; } ResultCallback4<bool, const PhoneNumberUtil&, const PhoneNumber&, const string&, const std::vector<string>&>* callback = NewPermanentCallback( this, &PhoneNumberMatcher::AllNumberGroupsAreExactlyPresent); bool is_valid = CheckNumberGroupingIsValid(number, candidate, callback); delete(callback); return is_valid; } default: LOG(ERROR) << "No implementation defined for verification for leniency " << static_cast<int>(leniency); return false; } } bool PhoneNumberMatcher::ExtractInnerMatch(const string& candidate, int offset, PhoneNumberMatch* match) { DCHECK(match); for (std::vector<const RegExp*>::const_iterator regex = reg_exps_->inner_matches_->begin(); regex != reg_exps_->inner_matches_->end(); regex++) { scoped_ptr<RegExpInput> candidate_input( reg_exps_->regexp_factory_->CreateInput(candidate)); bool is_first_match = true; string group; while ((*regex)->FindAndConsume(candidate_input.get(), &group) && max_tries_ > 0) { int group_start_index = static_cast<int>(candidate.length() - candidate_input->ToString().length() - group.length()); if (is_first_match) { string first_group_only = candidate.substr(0, group_start_index); phone_util_.TrimUnwantedEndChars(&first_group_only); bool success = ParseAndVerify(first_group_only, offset, match); if (success) { return true; } --max_tries_; is_first_match = false; } phone_util_.TrimUnwantedEndChars(&group); bool success = ParseAndVerify(group, offset + group_start_index, match); if (success) { return true; } --max_tries_; } } return false; } bool PhoneNumberMatcher::ExtractMatch(const string& candidate, int offset, PhoneNumberMatch* match) { DCHECK(match); if (reg_exps_->slash_separated_dates_->PartialMatch(candidate)) { return false; } if (reg_exps_->time_stamps_->PartialMatch(candidate)) { scoped_ptr<RegExpInput> following_text( reg_exps_->regexp_factory_->CreateInput( text_.substr(offset + candidate.size()))); if (reg_exps_->time_stamps_suffix_->Consume(following_text.get())) { return false; } } if (ParseAndVerify(candidate, offset, match)) { return true; } return ExtractInnerMatch(candidate, offset, match); } bool PhoneNumberMatcher::HasNext() { if (!is_input_valid_utf8_) { state_ = DONE; return false; } if (state_ == NOT_READY) { PhoneNumberMatch temp_match; if (!Find(search_index_, &temp_match)) { state_ = DONE; } else { last_match_.reset(new PhoneNumberMatch(temp_match.start(), temp_match.raw_string(), temp_match.number())); search_index_ = last_match_->end(); state_ = READY; } } return state_ == READY; } bool PhoneNumberMatcher::Next(PhoneNumberMatch* match) { DCHECK(match); if (!HasNext()) { return false; } match->CopyFrom(*last_match_); state_ = NOT_READY; last_match_.reset(NULL); return true; } bool PhoneNumberMatcher::Find(int index, PhoneNumberMatch* match) { DCHECK(match); scoped_ptr<RegExpInput> text( reg_exps_->regexp_factory_for_pattern_->CreateInput(text_.substr(index))); string candidate; while ((max_tries_ > 0) && reg_exps_->pattern_->FindAndConsume(text.get(), &candidate)) { int start = static_cast<int>(text_.length() - text->ToString().length() - candidate.length()); reg_exps_->capture_up_to_second_number_start_pattern_-> PartialMatch(candidate, &candidate); if (ExtractMatch(candidate, start, match)) { return true; } index = static_cast<int>(start + candidate.length()); --max_tries_; } return false; } bool PhoneNumberMatcher::CheckNumberGroupingIsValid( const PhoneNumber& phone_number, const string& candidate, ResultCallback4<bool, const PhoneNumberUtil&, const PhoneNumber&, const string&, const std::vector<string>&>* checker) const { DCHECK(checker); string normalized_candidate = NormalizeUTF8::NormalizeDecimalDigits(candidate); std::vector<string> formatted_number_groups; GetNationalNumberGroups(phone_number, &formatted_number_groups); if (checker->Run(phone_util_, phone_number, normalized_candidate, formatted_number_groups)) { return true; } const PhoneMetadata* alternate_formats = alternate_formats_->GetAlternateFormatsForCountry( phone_number.country_code()); if (alternate_formats) { string national_significant_number; phone_util_.GetNationalSignificantNumber(phone_number, &national_significant_number); for (RepeatedPtrField<NumberFormat>::const_iterator it = alternate_formats->number_format().begin(); it != alternate_formats->number_format().end(); ++it) { if (it->leading_digits_pattern_size() > 0) { std::unique_ptr<RegExpInput> nsn_input( reg_exps_->regexp_factory_->CreateInput( national_significant_number)); if (!reg_exps_->regexp_cache_.GetRegExp( it->leading_digits_pattern(0)).Consume(nsn_input.get())) { continue; } } formatted_number_groups.clear(); GetNationalNumberGroupsForPattern(phone_number, &*it, &formatted_number_groups); if (checker->Run(phone_util_, phone_number, normalized_candidate, formatted_number_groups)) { return true; } } } return false; } void PhoneNumberMatcher::GetNationalNumberGroups( const PhoneNumber& number, std::vector<string>* digit_blocks) const { string rfc3966_format; phone_util_.Format(number, PhoneNumberUtil::RFC3966, &rfc3966_format); size_t end_index = rfc3966_format.find(';'); if (end_index == string::npos) { end_index = rfc3966_format.length(); } size_t start_index = rfc3966_format.find('-') + 1; SplitStringUsing(rfc3966_format.substr(start_index, end_index - start_index), '-', digit_blocks); } void PhoneNumberMatcher::GetNationalNumberGroupsForPattern( const PhoneNumber& number, const NumberFormat* formatting_pattern, std::vector<string>* digit_blocks) const { string rfc3966_format; string national_significant_number; phone_util_.GetNationalSignificantNumber(number, &national_significant_number); phone_util_.FormatNsnUsingPattern(national_significant_number, *formatting_pattern, PhoneNumberUtil::RFC3966, &rfc3966_format); SplitStringUsing(rfc3966_format, '-', digit_blocks); } bool PhoneNumberMatcher::IsNationalPrefixPresentIfRequired( const PhoneNumber& number) const { if (number.country_code_source() != PhoneNumber::FROM_DEFAULT_COUNTRY) { return true; } string phone_number_region; phone_util_.GetRegionCodeForCountryCode( number.country_code(), &phone_number_region); const PhoneMetadata* metadata = phone_util_.GetMetadataForRegion(phone_number_region); if (!metadata) { return true; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); const NumberFormat* format_rule = phone_util_.ChooseFormattingPatternForNumber(metadata->number_format(), national_number); if (format_rule && !format_rule->national_prefix_formatting_rule().empty()) { if (format_rule->national_prefix_optional_when_formatting()) { return true; } if (phone_util_.FormattingRuleHasFirstGroupOnly( format_rule->national_prefix_formatting_rule())) { return true; } string raw_input_copy(number.raw_input()); phone_util_.NormalizeDigitsOnly(&raw_input_copy); return phone_util_.MaybeStripNationalPrefixAndCarrierCode( *metadata, &raw_input_copy, NULL); } return true; } bool PhoneNumberMatcher::AllNumberGroupsAreExactlyPresent( const PhoneNumberUtil& util, const PhoneNumber& phone_number, const string& normalized_candidate, const std::vector<string>& formatted_number_groups) const { const scoped_ptr<RegExpInput> candidate_number( reg_exps_->regexp_factory_->CreateInput(normalized_candidate)); std::vector<string> candidate_groups; string digit_block; while (reg_exps_->capturing_ascii_digits_pattern_->FindAndConsume( candidate_number.get(), &digit_block)) { candidate_groups.push_back(digit_block); } int candidate_number_group_index = static_cast<int>( phone_number.has_extension() ? candidate_groups.size() - 2 : candidate_groups.size() - 1); string national_significant_number; util.GetNationalSignificantNumber(phone_number, &national_significant_number); if (candidate_groups.size() == 1 || candidate_groups.at(candidate_number_group_index).find( national_significant_number) != string::npos) { return true; } for (int formatted_number_group_index = static_cast<int>(formatted_number_groups.size() - 1); formatted_number_group_index > 0 && candidate_number_group_index >= 0; --formatted_number_group_index, --candidate_number_group_index) { if (candidate_groups.at(candidate_number_group_index) != formatted_number_groups.at(formatted_number_group_index)) { return false; } } return (candidate_number_group_index >= 0 && HasSuffixString(candidate_groups.at(candidate_number_group_index), formatted_number_groups.at(0))); } bool PhoneNumberMatcher::ContainsMoreThanOneSlashInNationalNumber( const PhoneNumber& number, const string& candidate, const PhoneNumberUtil& util) { size_t first_slash_in_body = candidate.find('/'); if (first_slash_in_body == string::npos) { return false; } size_t second_slash_in_body = candidate.find('/', first_slash_in_body + 1); if (second_slash_in_body == string::npos) { return false; } if (number.country_code_source() == PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN || number.country_code_source() == PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN) { string normalized_country_code = candidate.substr(0, first_slash_in_body); util.NormalizeDigitsOnly(&normalized_country_code); if (normalized_country_code == SimpleItoa(number.country_code())) { return candidate.find('/', second_slash_in_body + 1) != string::npos; } } return true; } } }
#include "phonenumbers/phonenumbermatcher.h" #include <string> #include <vector> #include <gtest/gtest.h> #include <unicode/unistr.h> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/base/memory/singleton.h" #include "phonenumbers/default_logger.h" #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/phonenumbermatch.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stringutil.h" #include "phonenumbers/test_util.h" namespace i18n { namespace phonenumbers { using std::string; using icu::UnicodeString; namespace { struct NumberContext { string leading_text_; string trailing_text_; NumberContext(const string& leading_text, const string& trailing_text) : leading_text_(leading_text), trailing_text_(trailing_text) { } }; struct NumberTest { string raw_string_; string region_; string ToString() const { return StrCat(raw_string_, " (", region_, ")"); } NumberTest(const string& raw_string, const string& region) : raw_string_(raw_string), region_(region) { } }; } class PhoneNumberMatcherTest : public testing::Test { protected: PhoneNumberMatcherTest() : phone_util_(*PhoneNumberUtil::GetInstance()), matcher_(phone_util_, "", RegionCode::US(), PhoneNumberMatcher::VALID, 5), offset_(0) { PhoneNumberUtil::GetInstance()->SetLogger(new StdoutLogger()); } bool IsLatinLetter(char32 letter) { return PhoneNumberMatcher::IsLatinLetter(letter); } bool ContainsMoreThanOneSlashInNationalNumber( const PhoneNumber& phone_number, const string& candidate) { return PhoneNumberMatcher::ContainsMoreThanOneSlashInNationalNumber( phone_number, candidate, phone_util_); } bool ExtractMatch(const string& text, PhoneNumberMatch* match) { return matcher_.ExtractMatch(text, offset_, match); } PhoneNumberMatcher* GetMatcherWithLeniency( const string& text, const string& region, PhoneNumberMatcher::Leniency leniency) const { return new PhoneNumberMatcher(phone_util_, text, region, leniency, 100 ); } void DoTestNumberMatchesForLeniency( const std::vector<NumberTest>& test_cases, PhoneNumberMatcher::Leniency leniency) const { scoped_ptr<PhoneNumberMatcher> matcher; for (std::vector<NumberTest>::const_iterator test = test_cases.begin(); test != test_cases.end(); ++test) { matcher.reset(GetMatcherWithLeniency( test->raw_string_, test->region_, leniency)); EXPECT_TRUE(matcher->HasNext()) << "No match found in " << test->ToString() << " for leniency: " << leniency; if (matcher->HasNext()) { PhoneNumberMatch match; matcher->Next(&match); EXPECT_EQ(test->raw_string_, match.raw_string()) << "Found wrong match in test " << test->ToString() << ". Found " << match.raw_string(); } } } void DoTestNumberNonMatchesForLeniency( const std::vector<NumberTest>& test_cases, PhoneNumberMatcher::Leniency leniency) const { scoped_ptr<PhoneNumberMatcher> matcher; for (std::vector<NumberTest>::const_iterator test = test_cases.begin(); test != test_cases.end(); ++test) { matcher.reset(GetMatcherWithLeniency( test->raw_string_, test->region_, leniency)); EXPECT_FALSE(matcher->HasNext()) << "Match found in " << test->ToString() << " for leniency: " << leniency; } } void AssertMatchProperties(const PhoneNumberMatch& match, const string& text, const string& number, const string& region_code) { PhoneNumber expected_result; phone_util_.Parse(number, region_code, &expected_result); EXPECT_EQ(expected_result, match.number()); EXPECT_EQ(number, match.raw_string()) << " Wrong number found in " << text; } void AssertEqualRange(const string& text, int index, int start, int end) { string sub = text.substr(index); PhoneNumberMatcher matcher(phone_util_, sub, RegionCode::NZ(), PhoneNumberMatcher::POSSIBLE, 1000000 ); PhoneNumberMatch match; ASSERT_TRUE(matcher.HasNext()); matcher.Next(&match); EXPECT_EQ(start - index, match.start()); EXPECT_EQ(end - index, match.end()); EXPECT_EQ(sub.substr(match.start(), match.length()), match.raw_string()); } void DoTestFindInContext(const string& number, const string& default_country) { FindPossibleInContext(number, default_country); PhoneNumber parsed; phone_util_.Parse(number, default_country, &parsed); if (phone_util_.IsValidNumber(parsed)) { FindValidInContext(number, default_country); } } void FindMatchesInContexts(const std::vector<NumberContext>& contexts, bool is_valid, bool is_possible, const string& region, const string& number) { if (is_valid) { DoTestInContext(number, region, contexts, PhoneNumberMatcher::VALID); } else { for (std::vector<NumberContext>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) { string text = StrCat(it->leading_text_, number, it->trailing_text_); PhoneNumberMatcher matcher(text, region); EXPECT_FALSE(matcher.HasNext()); } } if (is_possible) { DoTestInContext(number, region, contexts, PhoneNumberMatcher::POSSIBLE); } else { for (std::vector<NumberContext>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) { string text = StrCat(it->leading_text_, number, it->trailing_text_); PhoneNumberMatcher matcher(phone_util_, text, region, PhoneNumberMatcher::POSSIBLE, 10000); EXPECT_FALSE(matcher.HasNext()); } } } void FindMatchesInContexts(const std::vector<NumberContext>& contexts, bool is_valid, bool is_possible) { const string& region = RegionCode::US(); const string number("415-666-7777"); FindMatchesInContexts(contexts, is_valid, is_possible, region, number); } void FindPossibleInContext(const string& number, const string& default_country) { std::vector<NumberContext> context_pairs; context_pairs.push_back(NumberContext("", "")); context_pairs.push_back(NumberContext(" ", "\t")); context_pairs.push_back(NumberContext("Hello ", "")); context_pairs.push_back(NumberContext("", " to call me!")); context_pairs.push_back(NumberContext("Hi there, call ", " to reach me!")); context_pairs.push_back(NumberContext("Hi there, call ", ", or don't")); context_pairs.push_back(NumberContext("Hi call", "")); context_pairs.push_back(NumberContext("", "forme")); context_pairs.push_back(NumberContext("Hi call", "forme")); context_pairs.push_back(NumberContext("It's cheap! Call ", " before 6:30")); context_pairs.push_back(NumberContext("Call ", " or +1800-123-4567!")); context_pairs.push_back(NumberContext("Call me on June 2 at", "")); context_pairs.push_back(NumberContext( "As quoted by Alfonso 12-15 (2009), you may call me at ", "")); context_pairs.push_back(NumberContext( "As quoted by Alfonso et al. 12-15 (2009), you may call me at ", "")); context_pairs.push_back(NumberContext( "As I said on 03/10/2011, you may call me at ", "")); context_pairs.push_back(NumberContext("", ", 45 days a year")); context_pairs.push_back(NumberContext("", ";x 7246433")); context_pairs.push_back(NumberContext("Call ", "/x12 more")); DoTestInContext(number, default_country, context_pairs, PhoneNumberMatcher::POSSIBLE); } void FindValidInContext(const string& number, const string& default_country) { std::vector<NumberContext> context_pairs; context_pairs.push_back(NumberContext("It's only 9.99! Call ", " to buy")); context_pairs.push_back(NumberContext("Call me on 21.6.1984 at ", "")); context_pairs.push_back(NumberContext("Call me on 06/21 at ", "")); context_pairs.push_back(NumberContext("Call me on 21.6. at ", "")); context_pairs.push_back(NumberContext("Call me on 06/21/84 at ", "")); DoTestInContext(number, default_country, context_pairs, PhoneNumberMatcher::VALID); } void DoTestInContext(const string& number, const string& default_country, const std::vector<NumberContext>& context_pairs, PhoneNumberMatcher::Leniency leniency) { for (std::vector<NumberContext>::const_iterator it = context_pairs.begin(); it != context_pairs.end(); ++it) { string prefix = it->leading_text_; string text = StrCat(prefix, number, it->trailing_text_); int start = prefix.length(); int end = start + number.length(); PhoneNumberMatcher matcher(phone_util_, text, default_country, leniency, 1000000 ); PhoneNumberMatch match; ASSERT_TRUE(matcher.HasNext()) << "Did not find a number in '" << text << "'; expected '" << number << "'"; matcher.Next(&match); string extracted = text.substr(match.start(), match.length()); EXPECT_EQ(start, match.start()); EXPECT_EQ(end, match.end()); EXPECT_EQ(number, extracted); EXPECT_EQ(extracted, match.raw_string()) << "Unexpected phone region in '" << text << "'; extracted '" << extracted << "'"; EnsureTermination(text, default_country, leniency); } } void EnsureTermination(const string& text, const string& default_country, PhoneNumberMatcher::Leniency leniency) { for (size_t index = 0; index <= text.length(); ++index) { string sub = text.substr(index); PhoneNumberMatcher matcher(phone_util_, text, default_country, leniency, 1000000 ); string matches; PhoneNumberMatch match; int match_count = 0; while (matcher.HasNext()) { matcher.Next(&match); StrAppend(&matches, ",", match.ToString()); ++match_count; } ASSERT_LT(match_count, 10); } } const PhoneNumberUtil& phone_util_; private: PhoneNumberMatcher matcher_; int offset_; }; TEST_F(PhoneNumberMatcherTest, ContainsMoreThanOneSlashInNationalNumber) { PhoneNumber number; number.set_country_code(1); number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); string candidate = "1/05/2013"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(274); number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN); candidate = "27/4/2013"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(49); number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITH_PLUS_SIGN); candidate = "49/69/2013"; EXPECT_FALSE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(49); number.set_country_code_source(PhoneNumber::FROM_NUMBER_WITHOUT_PLUS_SIGN); candidate = "+49/69/2013"; EXPECT_FALSE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); candidate = "+ 49/69/2013"; EXPECT_FALSE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); candidate = "+ 49/69/20/13"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); number.Clear(); number.set_country_code(49); number.set_country_code_source(PhoneNumber::FROM_DEFAULT_COUNTRY); candidate = "49/69/2013"; EXPECT_TRUE(ContainsMoreThanOneSlashInNationalNumber(number, candidate)); } TEST_F(PhoneNumberMatcherTest, FindNationalNumber) { DoTestFindInContext("033316005", RegionCode::NZ()); DoTestFindInContext("03-331 6005", RegionCode::NZ()); DoTestFindInContext("03 331 6005", RegionCode::NZ()); DoTestFindInContext("0064 3 331 6005", RegionCode::NZ()); DoTestFindInContext("01164 3 331 6005", RegionCode::US()); DoTestFindInContext("+64 3 331 6005", RegionCode::US()); DoTestFindInContext("64(0)64123456", RegionCode::NZ()); DoTestFindInContext("0123/456789", RegionCode::PL()); DoTestFindInContext("123-456-7890", RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, FindWithInternationalPrefixes) { DoTestFindInContext("+1 (650) 333-6000", RegionCode::NZ()); DoTestFindInContext("1-650-333-6000", RegionCode::US()); DoTestFindInContext("0011-650-333-6000", RegionCode::SG()); DoTestFindInContext("0081-650-333-6000", RegionCode::SG()); DoTestFindInContext("0191-650-333-6000", RegionCode::SG()); DoTestFindInContext("0~01-650-333-6000", RegionCode::PL()); DoTestFindInContext("++1 (650) 333-6000", RegionCode::PL()); DoTestFindInContext( "\xEF\xBC\x8B""1 (650) 333-6000" , RegionCode::SG()); DoTestFindInContext( "\xEF\xBC\x8B\xEF\xBC\x91\xE3\x80\x80\xEF\xBC\x88\xEF\xBC\x96\xEF\xBC\x95" "\xEF\xBC\x90\xEF\xBC\x89\xE3\x80\x80\xEF\xBC\x93\xEF\xBC\x93\xEF\xBC\x93" "\xEF\xBC\x8D\xEF\xBC\x96\xEF\xBC\x90\xEF\xBC\x90\xEF\xBC\x90", RegionCode::SG()); } TEST_F(PhoneNumberMatcherTest, FindWithLeadingZero) { DoTestFindInContext("+39 02-36618 300", RegionCode::NZ()); DoTestFindInContext("02-36618 300", RegionCode::IT()); DoTestFindInContext("312 345 678", RegionCode::IT()); } TEST_F(PhoneNumberMatcherTest, FindNationalNumberArgentina) { DoTestFindInContext("+54 9 343 555 1212", RegionCode::AR()); DoTestFindInContext("0343 15 555 1212", RegionCode::AR()); DoTestFindInContext("+54 9 3715 65 4320", RegionCode::AR()); DoTestFindInContext("03715 15 65 4320", RegionCode::AR()); DoTestFindInContext("+54 11 3797 0000", RegionCode::AR()); DoTestFindInContext("011 3797 0000", RegionCode::AR()); DoTestFindInContext("+54 3715 65 4321", RegionCode::AR()); DoTestFindInContext("03715 65 4321", RegionCode::AR()); DoTestFindInContext("+54 23 1234 0000", RegionCode::AR()); DoTestFindInContext("023 1234 0000", RegionCode::AR()); } TEST_F(PhoneNumberMatcherTest, FindWithXInNumber) { DoTestFindInContext("(0xx) 123456789", RegionCode::AR()); DoTestFindInContext("(0xx) 123456789 x 1234", RegionCode::AR()); DoTestFindInContext("011xx5481429712", RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, FindNumbersMexico) { DoTestFindInContext("+52 (449)978-0001", RegionCode::MX()); DoTestFindInContext("01 (449)978-0001", RegionCode::MX()); DoTestFindInContext("(449)978-0001", RegionCode::MX()); DoTestFindInContext("+52 1 33 1234-5678", RegionCode::MX()); DoTestFindInContext("044 (33) 1234-5678", RegionCode::MX()); DoTestFindInContext("045 33 1234-5678", RegionCode::MX()); } TEST_F(PhoneNumberMatcherTest, FindNumbersWithPlusWithNoRegion) { DoTestFindInContext("+64 3 331 6005", RegionCode::ZZ()); } TEST_F(PhoneNumberMatcherTest, FindExtensions) { DoTestFindInContext("03 331 6005 ext 3456", RegionCode::NZ()); DoTestFindInContext("03-3316005x3456", RegionCode::NZ()); DoTestFindInContext("03-3316005 int.3456", RegionCode::NZ()); DoTestFindInContext("03 3316005 #3456", RegionCode::NZ()); DoTestFindInContext("0~0 1800 7493 524", RegionCode::PL()); DoTestFindInContext("(1800) 7493.524", RegionCode::US()); DoTestFindInContext("0~0 1800 7493 524 ~1234", RegionCode::PL()); DoTestFindInContext("+44 2034567890x456", RegionCode::NZ()); DoTestFindInContext("+44 2034567890x456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 x456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X 456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X 456", RegionCode::GB()); DoTestFindInContext("+44 2034567890 X 456", RegionCode::GB()); DoTestFindInContext("(800) 901-3355 x 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 , ext 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 ,extension 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 ,x 7246433", RegionCode::US()); DoTestFindInContext("(800) 901-3355 ext: 7246433", RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, FindInterspersedWithSpace) { DoTestFindInContext("0 3 3 3 1 6 0 0 5", RegionCode::NZ()); } TEST_F(PhoneNumberMatcherTest, IntermediateParsePositions) { string text = "Call 033316005 or 032316005!"; for (int i = 0; i <= 5; ++i) { AssertEqualRange(text, i, 5, 14); } AssertEqualRange(text, 6, 6, 14); AssertEqualRange(text, 7, 7, 14); for (int i = 8; i <= 19; ++i) { AssertEqualRange(text, i, 19, 28); } } TEST_F(PhoneNumberMatcherTest, FourMatchesInARow) { string number1 = "415-666-7777"; string number2 = "800-443-1223"; string number3 = "212-443-1223"; string number4 = "650-443-1223"; string text = StrCat(number1, " - ", number2, " - ", number3, " - ", number4); PhoneNumberMatcher matcher(text, RegionCode::US()); PhoneNumberMatch match; EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number1, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number2, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number3, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number4, RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, MatchesFoundWithMultipleSpaces) { string number1 = "415-666-7777"; string number2 = "800-443-1223"; string text = StrCat(number1, " ", number2); PhoneNumberMatcher matcher(text, RegionCode::US()); PhoneNumberMatch match; EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number1, RegionCode::US()); EXPECT_TRUE(matcher.HasNext()); EXPECT_TRUE(matcher.Next(&match)); AssertMatchProperties(match, text, number2, RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, MatchWithSurroundingZipcodes) { string number = "415-666-7777"; string zip_preceding = StrCat("My address is CA 34215 - ", number, " is my number."); PhoneNumber expected_result; phone_util_.Parse(number, RegionCode::US(), &expected_result); scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency(zip_preceding, RegionCode::US(), PhoneNumberMatcher::VALID)); PhoneNumberMatch match; EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->Next(&match)); AssertMatchProperties(match, zip_preceding, number, RegionCode::US()); number = "(415) 666 7777"; string zip_following = StrCat("My number is ", number, ". 34215 is my zip-code."); matcher.reset( GetMatcherWithLeniency(zip_following, RegionCode::US(), PhoneNumberMatcher::VALID)); PhoneNumberMatch match_with_spaces; EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->Next(&match_with_spaces)); AssertMatchProperties( match_with_spaces, zip_following, number, RegionCode::US()); } TEST_F(PhoneNumberMatcherTest, IsLatinLetter) { EXPECT_TRUE(IsLatinLetter('c')); EXPECT_TRUE(IsLatinLetter('C')); EXPECT_TRUE(IsLatinLetter(UnicodeString::fromUTF8("\xC3\x89" )[0])); EXPECT_TRUE(IsLatinLetter(UnicodeString::fromUTF8("\xCC\x81")[0])); EXPECT_FALSE(IsLatinLetter(':')); EXPECT_FALSE(IsLatinLetter('5')); EXPECT_FALSE(IsLatinLetter('-')); EXPECT_FALSE(IsLatinLetter('.')); EXPECT_FALSE(IsLatinLetter(' ')); EXPECT_FALSE( IsLatinLetter(UnicodeString::fromUTF8("\xE6\x88\x91" )[0])); EXPECT_FALSE(IsLatinLetter(UnicodeString::fromUTF8("\xE3\x81\xAE")[0])); EXPECT_FALSE(IsLatinLetter(UnicodeString::fromUTF8("\xE3\x81\xAE")[2])); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingLatinChars) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("abc", "def")); possible_only_contexts.push_back(NumberContext("abc", "")); possible_only_contexts.push_back(NumberContext("", "def")); possible_only_contexts.push_back(NumberContext("\xC3\x89" , "")); possible_only_contexts.push_back( NumberContext("\x20\x22\xCC\x81""e\xCC\x81" , "")); FindMatchesInContexts(possible_only_contexts, false, true); } TEST_F(PhoneNumberMatcherTest, MoneyNotSeenAsPhoneNumber) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("$", "")); possible_only_contexts.push_back(NumberContext("", "$")); possible_only_contexts.push_back(NumberContext("\xC2\xA3" , "")); possible_only_contexts.push_back(NumberContext("\xC2\xA5" , "")); FindMatchesInContexts(possible_only_contexts, false, true); } TEST_F(PhoneNumberMatcherTest, PercentageNotSeenAsPhoneNumber) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("", "%")); FindMatchesInContexts(possible_only_contexts, false, true); } TEST_F(PhoneNumberMatcherTest, PhoneNumberWithLeadingOrTrailingMoneyMatches) { std::vector<NumberContext> contexts; contexts.push_back(NumberContext("$20 ", "")); contexts.push_back(NumberContext("", " 100$")); FindMatchesInContexts(contexts, true, true); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingLatinCharsAndLeadingPunctuation) { std::vector<NumberContext> possible_only_contexts; possible_only_contexts.push_back(NumberContext("abc", "def")); possible_only_contexts.push_back(NumberContext("", "def")); possible_only_contexts.push_back(NumberContext("", "\xC3\x89" )); string number_with_plus = "+14156667777"; string number_with_brackets = "(415)6667777"; FindMatchesInContexts(possible_only_contexts, false, true, RegionCode::US(), number_with_plus); FindMatchesInContexts(possible_only_contexts, false, true, RegionCode::US(), number_with_brackets); std::vector<NumberContext> valid_contexts; valid_contexts.push_back(NumberContext("abc", "")); valid_contexts.push_back(NumberContext("\xC3\x89" , "")); valid_contexts.push_back( NumberContext("\xC3\x89" , ".")); valid_contexts.push_back(NumberContext("\xC3\x89" , " def")); FindMatchesInContexts(valid_contexts, true, true, RegionCode::US(), number_with_plus); FindMatchesInContexts(valid_contexts, true, true, RegionCode::US(), number_with_brackets); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingChineseChars) { std::vector<NumberContext> valid_contexts; valid_contexts.push_back(NumberContext( "\xE6\x88\x91\xE7\x9A\x84\xE7\x94\xB5\xE8\xAF\x9D\xE5\x8F\xB7\xE7\xA0\x81" "\xE6\x98\xAF", "")); valid_contexts.push_back(NumberContext( "", "\xE6\x98\xAF\xE6\x88\x91\xE7\x9A\x84\xE7\x94\xB5\xE8\xAF\x9D\xE5\x8F\xB7" "\xE7\xA0\x81")); valid_contexts.push_back(NumberContext( "\xE8\xAF\xB7\xE6\x8B\xA8\xE6\x89\x93" , "\xE6\x88\x91\xE5\x9C\xA8\xE6\x98\x8E\xE5\xA4\xA9" )); FindMatchesInContexts(valid_contexts, true, true); } TEST_F(PhoneNumberMatcherTest, MatchesWithSurroundingPunctuation) { std::vector<NumberContext> valid_contexts; valid_contexts.push_back(NumberContext("My number-", "")); valid_contexts.push_back(NumberContext("", ".Nice day.")); valid_contexts.push_back(NumberContext("Tel:", ".")); valid_contexts.push_back(NumberContext("Tel: ", " on Saturdays.")); FindMatchesInContexts(valid_contexts, true, true); } TEST_F(PhoneNumberMatcherTest, MatchesMultiplePhoneNumbersSeparatedByPhoneNumberPunctuation) { const string text = "Call 650-253-4561 -- 455-234-3451"; const string& region = RegionCode::US(); PhoneNumber number1; number1.set_country_code(phone_util_.GetCountryCodeForRegion(region)); number1.set_national_number(6502534561ULL); PhoneNumberMatch match1(5, "650-253-4561", number1); PhoneNumber number2; number2.set_country_code(phone_util_.GetCountryCodeForRegion(region)); number2.set_national_number(4552343451ULL); PhoneNumberMatch match2(21, "455-234-3451", number2); PhoneNumberMatcher matcher( phone_util_, text, region, PhoneNumberMatcher::VALID, 100); PhoneNumberMatch actual_match1; PhoneNumberMatch actual_match2; matcher.Next(&actual_match1); matcher.Next(&actual_match2); EXPECT_TRUE(match1.Equals(actual_match1)) << "Got: " << actual_match1.ToString(); EXPECT_TRUE(match2.Equals(actual_match2)) << "Got: " << actual_match2.ToString(); } TEST_F(PhoneNumberMatcherTest, DoesNotMatchMultiplePhoneNumbersSeparatedWithNoWhiteSpace) { const string text = "Call 650-253-4561--455-234-3451"; const string& region = RegionCode::US(); PhoneNumberMatcher matcher( phone_util_, text, region, PhoneNumberMatcher::VALID, 100); EXPECT_FALSE(matcher.HasNext()); } static const NumberTest kImpossibleCases[] = { NumberTest("12345", RegionCode::US()), NumberTest("23456789", RegionCode::US()), NumberTest("234567890112", RegionCode::US()), NumberTest("650+253+1234", RegionCode::US()), NumberTest("3/10/1984", RegionCode::CA()), NumberTest("03/27/2011", RegionCode::US()), NumberTest("31/8/2011", RegionCode::US()), NumberTest("1/12/2011", RegionCode::US()), NumberTest("10/12/82", RegionCode::DE()), NumberTest("650x2531234", RegionCode::US()), NumberTest("2012-01-02 08:00", RegionCode::US()), NumberTest("2012/01/02 08:00", RegionCode::US()), NumberTest("20120102 08:00", RegionCode::US()), NumberTest("2014-04-12 04:04 PM", RegionCode::US()), NumberTest("2014-04-12 &nbsp;04:04 PM", RegionCode::US()), NumberTest("2014-04-12 &nbsp;04:04 PM", RegionCode::US()), NumberTest("2014-04-12 04:04 PM", RegionCode::US()), }; static const NumberTest kPossibleOnlyCases[] = { NumberTest("7121115678", RegionCode::US()), NumberTest("1650 x 253 - 1234", RegionCode::US()), NumberTest("650 x 253 - 1234", RegionCode::US()), NumberTest("6502531x234", RegionCode::US()), NumberTest("(20) 3346 1234", RegionCode::GB()), }; static const NumberTest kValidCases[] = { NumberTest("65 02 53 00 00", RegionCode::US()), NumberTest("6502 538365", RegionCode::US()), NumberTest("650 NumberTest("650/253/1234", RegionCode::US()), NumberTest("9002309. 158", RegionCode::US()), NumberTest("12 7/8 - 14 12/34 - 5", RegionCode::US()), NumberTest("12.1 - 23.71 - 23.45", RegionCode::US()), NumberTest("800 234 1 111x1111", RegionCode::US()), NumberTest("1979-2011 100", RegionCode::US()), NumberTest("+494949-4-94", RegionCode::DE()), NumberTest( "\xEF\xBC\x94\xEF\xBC\x91\xEF\xBC\x95\xEF\xBC\x96\xEF\xBC\x96\xEF\xBC\x96" "\x2D\xEF\xBC\x97\xEF\xBC\x97\xEF\xBC\x97\xEF\xBC\x97", RegionCode::US()), NumberTest("2012-0102 08", RegionCode::US()), NumberTest("2012-01-02 08", RegionCode::US()), NumberTest("1800-1-0-10 22", RegionCode::AU()), NumberTest("030-3-2 23 12 34", RegionCode::DE()), NumberTest("03 0 -3 2 23 12 34", RegionCode::DE()), NumberTest("(0)3 0 -3 2 23 12 34", RegionCode::DE()), NumberTest("0 3 0 -3 2 23 12 34", RegionCode::DE()), #ifdef I18N_PHONENUMBERS_USE_ALTERNATE_FORMATS NumberTest("+52 332 123 23 23", RegionCode::MX()), #endif }; static const NumberTest kStrictGroupingCases[] = { NumberTest("(415) 6667777", RegionCode::US()), NumberTest("415-6667777", RegionCode::US()), NumberTest("0800-2491234", RegionCode::DE()), #ifdef I18N_PHONENUMBERS_USE_ALTERNATE_FORMATS NumberTest("0900-1 123123", RegionCode::DE()), NumberTest("(0)900-1 123123", RegionCode::DE()), NumberTest("0 900-1 123123", RegionCode::DE()), #endif NumberTest("+33 3 34 2312", RegionCode::FR()), }; static const NumberTest kExactGroupingCases[] = { NumberTest( "\xEF\xBC\x94\xEF\xBC\x91\xEF\xBC\x95\xEF\xBC\x96\xEF\xBC\x96\xEF\xBC\x96" "\xEF\xBC\x97\xEF\xBC\x97\xEF\xBC\x97\xEF\xBC\x97", RegionCode::US()), NumberTest( "\xEF\xBC\x94\xEF\xBC\x91\xEF\xBC\x95\xEF\xBC\x8D\xEF\xBC\x96\xEF\xBC\x96" "\xEF\xBC\x96\xEF\xBC\x8D\xEF\xBC\x97\xEF\xBC\x97\xEF\xBC\x97" "\xEF\xBC\x97", RegionCode::US()), NumberTest("4156667777", RegionCode::US()), NumberTest("4156667777 x 123", RegionCode::US()), NumberTest("415-666-7777", RegionCode::US()), NumberTest("415/666-7777", RegionCode::US()), NumberTest("415-666-7777 ext. 503", RegionCode::US()), NumberTest("1 415 666 7777 x 123", RegionCode::US()), NumberTest("+1 415-666-7777", RegionCode::US()), NumberTest("+494949 49", RegionCode::DE()), NumberTest("+49-49-34", RegionCode::DE()), NumberTest("+49-4931-49", RegionCode::DE()), NumberTest("04931-49", RegionCode::DE()), NumberTest("+49-494949", RegionCode::DE()), NumberTest("+49-494949 ext. 49", RegionCode::DE()), NumberTest("+49494949 ext. 49", RegionCode::DE()), NumberTest("0494949", RegionCode::DE()), NumberTest("0494949 ext. 49", RegionCode::DE()), NumberTest("01 (33) 3461 2234", RegionCode::MX()), NumberTest("(33) 3461 2234", RegionCode::MX()), #ifdef I18N_PHONENUMBERS_USE_ALTERNATE_FORMATS NumberTest("1800-10-10 22", RegionCode::AU()), NumberTest("0900-1 123 123", RegionCode::DE()), NumberTest("(0)900-1 123 123", RegionCode::DE()), NumberTest("0 900-1 123 123", RegionCode::DE()), #endif NumberTest("+33 3 34 23 12", RegionCode::FR()), }; TEST_F(PhoneNumberMatcherTest, MatchesWithPossibleLeniency) { std::vector<NumberTest> test_cases; test_cases.insert(test_cases.begin(), kPossibleOnlyCases, kPossibleOnlyCases + arraysize(kPossibleOnlyCases)); test_cases.insert(test_cases.begin(), kValidCases, kValidCases + arraysize(kValidCases)); test_cases.insert( test_cases.begin(), kStrictGroupingCases, kStrictGroupingCases + arraysize(kStrictGroupingCases)); test_cases.insert(test_cases.begin(), kExactGroupingCases, kExactGroupingCases + arraysize(kExactGroupingCases)); DoTestNumberMatchesForLeniency(test_cases, PhoneNumberMatcher::POSSIBLE); } TEST_F(PhoneNumberMatcherTest, NonMatchesWithPossibleLeniency) { std::vector<NumberTest> test_cases; test_cases.insert(test_cases.begin(), kImpossibleCases, kImpossibleCases + arraysize(kImpossibleCases)); DoTestNumberNonMatchesForLeniency(test_cases, PhoneNumberMatcher::POSSIBLE); } TEST_F(PhoneNumberMatcherTest, MatchesWithValidLeniency) { std::vector<NumberTest> test_cases; test_cases.insert(test_cases.begin(), kValidCases, kValidCases + arraysize(kValidCases)); test_cases.insert( test_cases.begin(), kStrictGroupingCases, kStrictGroupingCases + arraysize(kStrictGroupingCases)); test_cases.insert(test_cases.begin(), kExactGroupingCases, kExactGroupingCases + arraysize(kExactGroupingCases)); DoTestNumberMatchesForLeniency(test_cases, PhoneNumberMatcher::VALID); } TEST_F(PhoneNumberMatcherTest, NonMatchesWithValidLeniency) { std::vector<NumberTest> test_cases; test_cases.insert(test_cases.begin(), kImpossibleCases, kImpossibleCases + arraysize(kImpossibleCases)); test_cases.insert(test_cases.begin(), kPossibleOnlyCases, kPossibleOnlyCases + arraysize(kPossibleOnlyCases)); DoTestNumberNonMatchesForLeniency(test_cases, PhoneNumberMatcher::VALID); } TEST_F(PhoneNumberMatcherTest, MatchesWithStrictGroupingLeniency) { std::vector<NumberTest> test_cases; test_cases.insert( test_cases.begin(), kStrictGroupingCases, kStrictGroupingCases + arraysize(kStrictGroupingCases)); test_cases.insert(test_cases.begin(), kExactGroupingCases, kExactGroupingCases + arraysize(kExactGroupingCases)); DoTestNumberMatchesForLeniency(test_cases, PhoneNumberMatcher::STRICT_GROUPING); } TEST_F(PhoneNumberMatcherTest, NonMatchesWithStrictGroupingLeniency) { std::vector<NumberTest> test_cases; test_cases.insert(test_cases.begin(), kImpossibleCases, kImpossibleCases + arraysize(kImpossibleCases)); test_cases.insert(test_cases.begin(), kPossibleOnlyCases, kPossibleOnlyCases + arraysize(kPossibleOnlyCases)); test_cases.insert(test_cases.begin(), kValidCases, kValidCases + arraysize(kValidCases)); DoTestNumberNonMatchesForLeniency(test_cases, PhoneNumberMatcher::STRICT_GROUPING); } TEST_F(PhoneNumberMatcherTest, MatchesWithExactGroupingLeniency) { std::vector<NumberTest> test_cases; test_cases.insert(test_cases.begin(), kExactGroupingCases, kExactGroupingCases + arraysize(kExactGroupingCases)); DoTestNumberMatchesForLeniency(test_cases, PhoneNumberMatcher::EXACT_GROUPING); } TEST_F(PhoneNumberMatcherTest, NonMatchesWithExactGroupingLeniency) { std::vector<NumberTest> test_cases; test_cases.insert(test_cases.begin(), kImpossibleCases, kImpossibleCases + arraysize(kImpossibleCases)); test_cases.insert(test_cases.begin(), kPossibleOnlyCases, kPossibleOnlyCases + arraysize(kPossibleOnlyCases)); test_cases.insert(test_cases.begin(), kValidCases, kValidCases + arraysize(kValidCases)); test_cases.insert( test_cases.begin(), kStrictGroupingCases, kStrictGroupingCases + arraysize(kStrictGroupingCases)); DoTestNumberNonMatchesForLeniency(test_cases, PhoneNumberMatcher::EXACT_GROUPING); } TEST_F(PhoneNumberMatcherTest, ExtractMatchIgnoresAmericanDates) { PhoneNumberMatch match; string text = "As I said on 03/10/2011, you may call me at "; EXPECT_FALSE(ExtractMatch(text, &match)); text = "As I said on 03/27/2011, you may call me at "; EXPECT_FALSE(ExtractMatch(text, &match)); text = "As I said on 31/8/2011, you may call me at "; EXPECT_FALSE(ExtractMatch(text, &match)); text = "As I said on 1/12/2011, you may call me at "; EXPECT_FALSE(ExtractMatch(text, &match)); text = "I was born on 10/12/82. Please call me at "; EXPECT_FALSE(ExtractMatch(text, &match)); } TEST_F(PhoneNumberMatcherTest, NonMatchingBracketsAreInvalid) { scoped_ptr<PhoneNumberMatcher> matcher(GetMatcherWithLeniency( "80.585 [79.964, 81.191]", RegionCode::US(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); matcher.reset(GetMatcherWithLeniency( "80.585 [79.964]", RegionCode::US(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); matcher.reset(GetMatcherWithLeniency( "80.585 ((79.964)", RegionCode::US(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); matcher.reset(GetMatcherWithLeniency( "(80).(585) (79).(9)64", RegionCode::US(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, NoMatchIfRegionIsUnknown) { scoped_ptr<PhoneNumberMatcher> matcher(GetMatcherWithLeniency( "Random text body - number is 0331 6005, see you there", RegionCode::ZZ(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, NoMatchInEmptyString) { scoped_ptr<PhoneNumberMatcher> matcher(GetMatcherWithLeniency( "", RegionCode::US(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); matcher.reset(GetMatcherWithLeniency(" ", RegionCode::US(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, NoMatchIfNoNumber) { scoped_ptr<PhoneNumberMatcher> matcher(GetMatcherWithLeniency( "Random text body - number is foobar, see you there", RegionCode::US(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, NoErrorWithSpecialCharacters) { string stringWithSpecialCharacters = "Myfuzzvar1152: \"My info:%415-666-7777 123 fake street\"\nfuzzvar1155: " "47\nfuzzvar1158: %415-666-1234 " "i18n_phonenumbers_Pho\356eNumberMatcher_Leniency_VALID_1" "\nfuzzvar1159: 20316 info:%415-666-7777 123 fake str79ee\nt"; string Numbers; for (int i = 0; i < 100; ++i) Numbers.append(stringWithSpecialCharacters); scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency(Numbers, RegionCode::US(), PhoneNumberMatcher::POSSIBLE)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, Sequences) { const string text = "Call 033316005 or 032316005!"; const string& region = RegionCode::NZ(); PhoneNumber number1; number1.set_country_code(phone_util_.GetCountryCodeForRegion(region)); number1.set_national_number(33316005ULL); PhoneNumberMatch match1(5, "033316005", number1); PhoneNumber number2; number2.set_country_code(phone_util_.GetCountryCodeForRegion(region)); number2.set_national_number(32316005ULL); PhoneNumberMatch match2(19, "032316005", number2); PhoneNumberMatcher matcher( phone_util_, text, region, PhoneNumberMatcher::POSSIBLE, 100); PhoneNumberMatch actual_match1; PhoneNumberMatch actual_match2; matcher.Next(&actual_match1); matcher.Next(&actual_match2); EXPECT_TRUE(match1.Equals(actual_match1)); EXPECT_TRUE(match2.Equals(actual_match2)); } TEST_F(PhoneNumberMatcherTest, MaxMatches) { string numbers; for (int i = 0; i < 100; ++i) { numbers.append("My info: 415-666-7777,"); } PhoneNumber number; phone_util_.Parse("+14156667777", RegionCode::US(), &number); std::vector<PhoneNumber> expected(100, number); PhoneNumberMatcher matcher( phone_util_, numbers, RegionCode::US(), PhoneNumberMatcher::VALID, 10); std::vector<PhoneNumber> actual; PhoneNumberMatch match; while (matcher.HasNext()) { matcher.Next(&match); actual.push_back(match.number()); } EXPECT_EQ(expected, actual); } TEST_F(PhoneNumberMatcherTest, MaxMatchesInvalid) { string numbers; for (int i = 0; i < 10; ++i) { numbers.append("My address 949-8945-0"); } for (int i = 0; i < 100; ++i) { numbers.append("My info: 415-666-7777,"); } PhoneNumberMatcher matcher( phone_util_, numbers, RegionCode::US(), PhoneNumberMatcher::VALID, 10); EXPECT_FALSE(matcher.HasNext()); } TEST_F(PhoneNumberMatcherTest, MaxMatchesMixed) { string numbers; for (int i = 0; i < 100; ++i) { numbers.append("My info: 415-666-7777 123 fake street"); } PhoneNumber number; phone_util_.Parse("+14156667777", RegionCode::ZZ(), &number); std::vector<PhoneNumber> expected(10, number); PhoneNumberMatcher matcher( phone_util_, numbers, RegionCode::US(), PhoneNumberMatcher::VALID, 10); std::vector<PhoneNumber> actual; PhoneNumberMatch match; while (matcher.HasNext()) { matcher.Next(&match); actual.push_back(match.number()); } EXPECT_EQ(expected, actual); } TEST_F(PhoneNumberMatcherTest, NonPlusPrefixedNumbersNotFoundForInvalidRegion) { PhoneNumberMatch match; scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency("1 456 764 156", RegionCode::GetUnknown(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); EXPECT_FALSE(matcher->Next(&match)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, EmptyIteration) { PhoneNumberMatch match; scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency("", RegionCode::GetUnknown(), PhoneNumberMatcher::VALID)); EXPECT_FALSE(matcher->HasNext()); EXPECT_FALSE(matcher->HasNext()); EXPECT_FALSE(matcher->Next(&match)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, SingleIteration) { PhoneNumberMatch match; scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency("+14156667777", RegionCode::GetUnknown(), PhoneNumberMatcher::VALID)); EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->Next(&match)); EXPECT_FALSE(matcher->HasNext()); EXPECT_FALSE(matcher->Next(&match)); } TEST_F(PhoneNumberMatcherTest, SingleIteration_WithNextOnly) { PhoneNumberMatch match; scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency("+14156667777", RegionCode::GetUnknown(), PhoneNumberMatcher::VALID)); EXPECT_TRUE(matcher->Next(&match)); EXPECT_FALSE(matcher->Next(&match)); } TEST_F(PhoneNumberMatcherTest, DoubleIteration) { PhoneNumberMatch match; scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency("+14156667777 foobar +14156667777 ", RegionCode::GetUnknown(), PhoneNumberMatcher::VALID)); EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->Next(&match)); EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->HasNext()); EXPECT_TRUE(matcher->Next(&match)); EXPECT_FALSE(matcher->HasNext()); EXPECT_FALSE(matcher->Next(&match)); EXPECT_FALSE(matcher->HasNext()); } TEST_F(PhoneNumberMatcherTest, DoubleIteration_WithNextOnly) { PhoneNumberMatch match; scoped_ptr<PhoneNumberMatcher> matcher( GetMatcherWithLeniency("+14156667777 foobar +14156667777 ", RegionCode::GetUnknown(), PhoneNumberMatcher::VALID)); EXPECT_TRUE(matcher->Next(&match)); EXPECT_TRUE(matcher->Next(&match)); EXPECT_FALSE(matcher->Next(&match)); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/phonenumbermatcher.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/phonenumbermatcher_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
5b0e460d-7d88-4bf8-8b86-7f3ab7ca4561
cpp
google/libphonenumber
stringutil
cpp/src/phonenumbers/stringutil.cc
cpp/test/phonenumbers/stringutil_test.cc
#include <algorithm> #include <cassert> #include <cstring> #include <sstream> #include "phonenumbers/stringutil.h" #include "absl/strings/str_replace.h" #include "absl/strings/substitute.h" #include "absl/strings/match.h" namespace i18n { namespace phonenumbers { using std::equal; using std::stringstream; string operator+(const string& s, int n) { string result; absl::StrAppend(&result,s,n); return result; } string SimpleItoa(int n) { return absl::StrCat(n); } string SimpleItoa(uint64 n) { return absl::StrCat(n); } string SimpleItoa(int64 n) { return absl::StrCat(n); } bool HasPrefixString(const string& s, const string& prefix) { return absl::StartsWith(s, prefix); } size_t FindNth(const string& s, char c, int n) { size_t pos = string::npos; for (int i = 0; i < n; ++i) { pos = s.find_first_of(c, pos + 1); if (pos == string::npos) { break; } } return pos; } void SplitStringUsing(const string& s, char delimiter, vector<string>* result) { assert(result); for (absl::string_view split_piece : absl::StrSplit( s, absl::ByChar(delimiter), absl::SkipEmpty())) { result->push_back(std::string(split_piece)); } } bool TryStripPrefixString(const string& in, const string& prefix, string* out) { assert(out); const bool has_prefix = in.compare(0, prefix.length(), prefix) == 0; out->assign(has_prefix ? in.substr(prefix.length()) : in); return has_prefix; } bool HasSuffixString(const string& s, const string& suffix) { return absl::EndsWith(s, suffix); } template <typename T> void GenericAtoi(const string& s, T* out) { if (!absl::SimpleAtoi(s, out)) *out = 0; } void safe_strto32(const string& s, int32 *n) { GenericAtoi(s, n); } void safe_strtou64(const string& s, uint64 *n) { GenericAtoi(s, n); } void safe_strto64(const string& s, int64* n) { GenericAtoi(s, n); } void strrmm(string* s, const string& chars) { for (string::iterator it = s->begin(); it != s->end(); ) { const char current_char = *it; if (chars.find(current_char) != string::npos) { it = s->erase(it); } else { ++it; } } } int GlobalReplaceSubstring(const string& substring, const string& replacement, string* s) { return absl::StrReplaceAll({{substring, replacement}}, s);; } StringHolder::StringHolder(const string& s) : absl::AlphaNum(s) {} StringHolder::StringHolder(const char* cp) : absl::AlphaNum(cp) {} StringHolder::StringHolder(uint64 n) : absl::AlphaNum(n) {} StringHolder::StringHolder(absl::string_view sv) : absl::AlphaNum(sv) {} StringHolder::~StringHolder() {} string& operator+=(string& lhs, const StringHolder& rhs) { absl::string_view s = rhs.GetString();; if (s.size() != 0) { lhs += s.data(); } else { const char* const cs = rhs.GetCString(); if (cs) lhs.append(cs, rhs.Length()); } return lhs; } string StrCat(const StringHolder& s1, const StringHolder& s2) { return absl::StrCat(s1, s2); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3) { return absl::StrCat(s1, s2, s3); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4) { return absl::StrCat(s1, s2, s3, s4); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5) { return absl::StrCat(s1, s2, s3, s4, s5); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6) { return absl::StrCat(s1, s2, s3, s4, s5, s6); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8) { string result; result.reserve(s1.Length() + s2.Length() + s3.Length() + s4.Length() + s5.Length() + s6.Length() + s7.Length() + s8.Length() + 1); return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14, const StringHolder& s15) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15); } string StrCat(const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5, const StringHolder& s6, const StringHolder& s7, const StringHolder& s8, const StringHolder& s9, const StringHolder& s10, const StringHolder& s11, const StringHolder& s12, const StringHolder& s13, const StringHolder& s14, const StringHolder& s15, const StringHolder& s16) { return absl::StrCat(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16); } void StrAppend(string* dest, const StringHolder& s1) { absl::StrAppend(dest, s1); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2) { absl::StrAppend(dest, s1, s2); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3) { absl::StrAppend(dest, s1, s2, s3); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4) { absl::StrAppend(dest, s1, s2, s3, s4); } void StrAppend(string* dest, const StringHolder& s1, const StringHolder& s2, const StringHolder& s3, const StringHolder& s4, const StringHolder& s5) { absl::StrAppend(dest, s1, s2, s3, s4, s5); } } }
#include "phonenumbers/stringutil.h" #include <string> #include <vector> #include <gtest/gtest.h> using std::string; using std::vector; namespace i18n { namespace phonenumbers { TEST(StringUtilTest, OperatorPlus) { EXPECT_EQ("hello10", string("hello") + 10); } TEST(StringUtilTest, SimpleItoa) { EXPECT_EQ("10", SimpleItoa(10)); } TEST(StringUtilTest, HasPrefixString) { EXPECT_TRUE(HasPrefixString("hello world", "hello")); EXPECT_FALSE(HasPrefixString("hello world", "hellO")); } TEST(StringUtilTest, FindNthWithEmptyString) { EXPECT_EQ(string::npos, FindNth("", 'a', 1)); } TEST(StringUtilTest, FindNthWithNNegative) { EXPECT_EQ(string::npos, FindNth("hello world", 'o', -1)); } TEST(StringUtilTest, FindNthWithNTooHigh) { EXPECT_EQ(string::npos, FindNth("hello world", 'o', 3)); } TEST(StringUtilTest, FindNth) { EXPECT_EQ(7U, FindNth("hello world", 'o', 2)); } TEST(StringUtilTest, SplitStringUsingWithEmptyString) { vector<string> result; SplitStringUsing("", ':', &result); EXPECT_EQ(0U, result.size()); } TEST(StringUtilTest, SplitStringUsing) { vector<string> result; SplitStringUsing(":hello:world:", ':', &result); EXPECT_EQ(2U, result.size()); EXPECT_EQ("hello", result[0]); EXPECT_EQ("world", result[1]); } TEST(StringUtilTest, SplitStringUsingIgnoresEmptyToken) { vector<string> result; SplitStringUsing("hello::world", ':', &result); EXPECT_EQ(2U, result.size()); EXPECT_EQ("hello", result[0]); EXPECT_EQ("world", result[1]); } TEST(StringUtilTest, TryStripPrefixString) { string s; EXPECT_TRUE(TryStripPrefixString("hello world", "hello", &s)); EXPECT_EQ(" world", s); s.clear(); EXPECT_FALSE(TryStripPrefixString("hello world", "helloa", &s)); s.clear(); EXPECT_TRUE(TryStripPrefixString("hello world", "", &s)); EXPECT_EQ("hello world", s); s.clear(); EXPECT_FALSE(TryStripPrefixString("", "hello", &s)); s.clear(); } TEST(StringUtilTest, HasSuffixString) { EXPECT_TRUE(HasSuffixString("hello world", "hello world")); EXPECT_TRUE(HasSuffixString("hello world", "world")); EXPECT_FALSE(HasSuffixString("hello world", "world!")); EXPECT_TRUE(HasSuffixString("hello world", "")); EXPECT_FALSE(HasSuffixString("", "hello")); } TEST(StringUtilTest, safe_strto32) { int32 n; safe_strto32("0", &n); EXPECT_EQ(0, n); safe_strto32("16", &n); EXPECT_EQ(16, n); safe_strto32("2147483647", &n); EXPECT_EQ(2147483647, n); safe_strto32("-2147483648", &n); EXPECT_EQ(-2147483648LL, n); } TEST(StringUtilTest, safe_strtou64) { uint64 n; safe_strtou64("0", &n); EXPECT_EQ(0U, n); safe_strtou64("16", &n); EXPECT_EQ(16U, n); safe_strtou64("18446744073709551615", &n); EXPECT_EQ(18446744073709551615ULL, n); } TEST(StringUtilTest, strrmm) { string input("hello"); strrmm(&input, ""); EXPECT_EQ(input, input); string empty; strrmm(&empty, ""); EXPECT_EQ("", empty); strrmm(&empty, "aa"); EXPECT_EQ("", empty); strrmm(&input, "h"); EXPECT_EQ("ello", input); strrmm(&input, "el"); EXPECT_EQ("o", input); } TEST(StringUtilTest, GlobalReplaceSubstring) { string input("hello"); EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(0, GlobalReplaceSubstring("", "aaa", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(0, GlobalReplaceSubstring("", "", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(0, GlobalReplaceSubstring("aaa", "bbb", &input)); EXPECT_EQ("hello", input); EXPECT_EQ(1, GlobalReplaceSubstring("o", "o world", &input)); ASSERT_EQ("hello world", input); EXPECT_EQ(2, GlobalReplaceSubstring("o", "O", &input)); EXPECT_EQ("hellO wOrld", input); } TEST(StringUtilTest, StringHolder) { static const char cstring[] = "aaa"; StringHolder sh1(cstring); EXPECT_EQ(cstring, sh1.GetCString()); string s = "aaa"; StringHolder sh2(s); EXPECT_EQ(cstring, sh2.GetString()); string s2 = "hello"; StringHolder sh3(s2); EXPECT_EQ(5U, sh3.Length()); StringHolder sh4(42); static const char cstring2[] = "42";; EXPECT_EQ(cstring2, sh4.GetString()); } TEST(StringUtilTest, OperatorPlusEquals) { string s = "h"; static const char append1[] = "ello"; s += StringHolder(append1); EXPECT_EQ("hello", s); s = "h"; string append2 = "ello"; s += StringHolder(append2); EXPECT_EQ("hello", s); } TEST(StringUtilTest, StrCat) { string s; s = StrCat("a", "b"); EXPECT_EQ("ab", s); s = StrCat("a", "b", "c"); EXPECT_EQ("abc", s); s = StrCat("a", "b", "c", "d"); EXPECT_EQ("abcd", s); s = StrCat("a", "b", "c", "d", "e"); EXPECT_EQ("abcde", s); s = StrCat("a", "b", "c", "d", "e", "f"); EXPECT_EQ("abcdef", s); s = StrCat("a", "b", "c", "d", "e", "f", "g"); EXPECT_EQ("abcdefg", s); s = StrCat("a", "b", "c", "d", "e", "f", "g", "h"); EXPECT_EQ("abcdefgh", s); s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i"); EXPECT_EQ("abcdefghi", s); s = StrCat("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"); EXPECT_EQ("abcdefghijk", s); } TEST(StringUtilTest, StrAppend) { string s; StrAppend(&s, "a"); ASSERT_EQ("a", s); StrAppend(&s, "b", "c"); ASSERT_EQ("abc", s); StrAppend(&s, "d", "e", "f"); ASSERT_EQ("abcdef", s); StrAppend(&s, "g", "h", "i", "j"); ASSERT_EQ("abcdefghij", s); StrAppend(&s, "k", "l", "m", "n", "o"); ASSERT_EQ("abcdefghijklmno", s); StrAppend(&s, 42); ASSERT_EQ("abcdefghijklmno42", s); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/stringutil.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/stringutil_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
3ec29614-5909-4ff3-94b0-a536b979a79e
cpp
google/libphonenumber
unicodetext
cpp/src/phonenumbers/utf/unicodetext.cc
cpp/test/phonenumbers/utf/unicodetext_test.cc
#include <algorithm> #include <sstream> #include <cassert> #include <cstdio> #include "phonenumbers/default_logger.h" #include "phonenumbers/utf/unicodetext.h" #include "phonenumbers/utf/stringpiece.h" #include "phonenumbers/utf/utf.h" #include "phonenumbers/utf/unilib.h" namespace i18n { namespace phonenumbers { using std::string; using std::stringstream; using std::max; using std::hex; using std::dec; static int CodepointDistance(const char* start, const char* end) { int n = 0; for (const char* p = start; p < end; ++p) { n += (*reinterpret_cast<const signed char*>(p) >= -0x40); } return n; } static int CodepointCount(const char* utf8, int len) { return CodepointDistance(utf8, utf8 + len); } UnicodeText::const_iterator::difference_type distance(const UnicodeText::const_iterator& first, const UnicodeText::const_iterator& last) { return CodepointDistance(first.it_, last.it_); } static int ConvertToInterchangeValid(char* start, int len) { char* const in = start; char* out = start; char* const end = start + len; while (start < end) { int good = UniLib::SpanInterchangeValid(start, static_cast<int>(end - start)); if (good > 0) { if (out != start) { memmove(out, start, good); } out += good; start += good; if (start == end) { break; } } Rune rune; int n; if (isvalidcharntorune(start, static_cast<int>(end - start), &rune, &n)) { start += n; } else { start += 1; } *out++ = ' '; } return static_cast<int>(out - in); } void UnicodeText::Repr::reserve(int new_capacity) { if (capacity_ >= new_capacity && ours_) return; capacity_ = max(new_capacity, (3 * capacity_) / 2 + 20); char* new_data = new char[capacity_]; if (data_) { memcpy(new_data, data_, size_); if (ours_) delete[] data_; } data_ = new_data; ours_ = true; } void UnicodeText::Repr::resize(int new_size) { if (new_size == 0) { clear(); } else { if (!ours_ || new_size > capacity_) reserve(new_size); if (size_ < new_size) memset(data_ + size_, 0, new_size - size_); size_ = new_size; ours_ = true; } } void UnicodeText::Repr::clear() { if (ours_) delete[] data_; data_ = NULL; size_ = capacity_ = 0; ours_ = true; } void UnicodeText::Repr::Copy(const char* data, int size) { resize(size); memcpy(data_, data, size); } void UnicodeText::Repr::TakeOwnershipOf(char* data, int size, int capacity) { if (data == data_) return; if (ours_ && data_) delete[] data_; data_ = data; size_ = size; capacity_ = capacity; ours_ = true; } void UnicodeText::Repr::PointTo(const char* data, int size) { if (ours_ && data_) delete[] data_; data_ = const_cast<char*>(data); size_ = size; capacity_ = size; ours_ = false; } void UnicodeText::Repr::append(const char* bytes, int byte_length) { reserve(size_ + byte_length); memcpy(data_ + size_, bytes, byte_length); size_ += byte_length; } string UnicodeText::Repr::DebugString() const { stringstream ss; ss << "{Repr " << hex << this << " data=" << data_ << " size=" << dec << size_ << " capacity=" << capacity_ << " " << (ours_ ? "Owned" : "Alias") << "}"; string result; ss >> result; return result; } UnicodeText::UnicodeText() { } UnicodeText::UnicodeText(const UnicodeText& src) { Copy(src); } UnicodeText::UnicodeText(const UnicodeText::const_iterator& first, const UnicodeText::const_iterator& last) { assert(first <= last && "Incompatible iterators"); repr_.append(first.it_, static_cast<int>(last.it_ - first.it_)); } string UnicodeText::UTF8Substring(const const_iterator& first, const const_iterator& last) { assert(first <= last && "Incompatible iterators"); return string(first.it_, last.it_ - first.it_); } UnicodeText& UnicodeText::operator=(const UnicodeText& src) { if (this != &src) { Copy(src); } return *this; } UnicodeText& UnicodeText::Copy(const UnicodeText& src) { repr_.Copy(src.repr_.data_, src.repr_.size_); return *this; } UnicodeText& UnicodeText::CopyUTF8(const char* buffer, int byte_length) { repr_.Copy(buffer, byte_length); repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length); if (!repr_.utf8_was_valid_) { LOG(WARNING) << "UTF-8 buffer is not interchange-valid."; repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length); } return *this; } UnicodeText& UnicodeText::UnsafeCopyUTF8(const char* buffer, int byte_length) { repr_.Copy(buffer, byte_length); return *this; } UnicodeText& UnicodeText::TakeOwnershipOfUTF8(char* buffer, int byte_length, int byte_capacity) { repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity); repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length); if (!repr_.utf8_was_valid_) { LOG(WARNING) << "UTF-8 buffer is not interchange-valid."; repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length); } return *this; } UnicodeText& UnicodeText::UnsafeTakeOwnershipOfUTF8(char* buffer, int byte_length, int byte_capacity) { repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity); return *this; } UnicodeText& UnicodeText::PointToUTF8(const char* buffer, int byte_length) { repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length); if (repr_.utf8_was_valid_) { repr_.PointTo(buffer, byte_length); } else { LOG(WARNING) << "UTF-8 buffer is not interchange-valid."; repr_.Copy(buffer, byte_length); repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length); } return *this; } UnicodeText& UnicodeText::UnsafePointToUTF8(const char* buffer, int byte_length) { repr_.PointTo(buffer, byte_length); return *this; } UnicodeText& UnicodeText::PointTo(const UnicodeText& src) { repr_.PointTo(src.repr_.data_, src.repr_.size_); return *this; } UnicodeText& UnicodeText::PointTo(const const_iterator &first, const const_iterator &last) { assert(first <= last && " Incompatible iterators"); repr_.PointTo(first.utf8_data(), static_cast<int>(last.utf8_data() - first.utf8_data())); return *this; } UnicodeText& UnicodeText::append(const UnicodeText& u) { repr_.append(u.repr_.data_, u.repr_.size_); return *this; } UnicodeText& UnicodeText::append(const const_iterator& first, const const_iterator& last) { assert(first <= last && "Incompatible iterators"); repr_.append(first.it_, static_cast<int>(last.it_ - first.it_)); return *this; } UnicodeText& UnicodeText::UnsafeAppendUTF8(const char* utf8, int len) { repr_.append(utf8, len); return *this; } UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look, const_iterator start_pos) const { assert(start_pos.utf8_data() >= utf8_data()); assert(start_pos.utf8_data() <= utf8_data() + utf8_length()); return UnsafeFind(look, start_pos); } UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look) const { return UnsafeFind(look, begin()); } UnicodeText::const_iterator UnicodeText::UnsafeFind( const UnicodeText& look, const_iterator start_pos) const { StringPiece searching(utf8_data(), utf8_length()); StringPiece look_piece(look.utf8_data(), look.utf8_length()); StringPiece::size_type found = searching.find(look_piece, start_pos.utf8_data() - utf8_data()); if (found == StringPiece::npos) return end(); return const_iterator(utf8_data() + found); } bool UnicodeText::HasReplacementChar() const { StringPiece searching(utf8_data(), utf8_length()); StringPiece looking_for("\xEF\xBF\xBD", 3); return searching.find(looking_for) != StringPiece::npos; } void UnicodeText::clear() { repr_.clear(); } UnicodeText::~UnicodeText() {} void UnicodeText::push_back(char32 c) { if (UniLib::IsValidCodepoint(c)) { char buf[UTFmax]; Rune rune = c; int len = runetochar(buf, &rune); if (UniLib::IsInterchangeValid(buf, len)) { repr_.append(buf, len); } else { fprintf(stderr, "Unicode value 0x%x is not valid for interchange\n", c); repr_.append(" ", 1); } } else { fprintf(stderr, "Illegal Unicode value: 0x%x\n", c); repr_.append(" ", 1); } } int UnicodeText::size() const { return CodepointCount(repr_.data_, repr_.size_); } bool operator==(const UnicodeText& lhs, const UnicodeText& rhs) { if (&lhs == &rhs) return true; if (lhs.repr_.size_ != rhs.repr_.size_) return false; return memcmp(lhs.repr_.data_, rhs.repr_.data_, lhs.repr_.size_) == 0; } string UnicodeText::DebugString() const { stringstream ss; ss << "{UnicodeText " << hex << this << dec << " chars=" << size() << " repr=" << repr_.DebugString() << "}"; #if 0 return StringPrintf("{UnicodeText %p chars=%d repr=%s}", this, size(), repr_.DebugString().c_str()); #endif string result; ss >> result; return result; } UnicodeText::const_iterator::const_iterator() : it_(0) {} UnicodeText::const_iterator::const_iterator(const const_iterator& other) : it_(other.it_) { } UnicodeText::const_iterator& UnicodeText::const_iterator::operator=(const const_iterator& other) { if (&other != this) it_ = other.it_; return *this; } UnicodeText::const_iterator UnicodeText::begin() const { return const_iterator(repr_.data_); } UnicodeText::const_iterator UnicodeText::end() const { return const_iterator(repr_.data_ + repr_.size_); } bool operator<(const UnicodeText::const_iterator& lhs, const UnicodeText::const_iterator& rhs) { return lhs.it_ < rhs.it_; } char32 UnicodeText::const_iterator::operator*() const { uint8 byte1 = static_cast<uint8>(it_[0]); if (byte1 < 0x80) return byte1; uint8 byte2 = static_cast<uint8>(it_[1]); if (byte1 < 0xE0) return ((byte1 & 0x1F) << 6) | (byte2 & 0x3F); uint8 byte3 = static_cast<uint8>(it_[2]); if (byte1 < 0xF0) return ((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F); uint8 byte4 = static_cast<uint8>(it_[3]); return ((byte1 & 0x07) << 18) | ((byte2 & 0x3F) << 12) | ((byte3 & 0x3F) << 6) | (byte4 & 0x3F); } UnicodeText::const_iterator& UnicodeText::const_iterator::operator++() { it_ += UniLib::OneCharLen(it_); return *this; } UnicodeText::const_iterator& UnicodeText::const_iterator::operator--() { while (UniLib::IsTrailByte(*--it_)) { } return *this; } int UnicodeText::const_iterator::get_utf8(char* utf8_output) const { utf8_output[0] = it_[0]; if (static_cast<unsigned char>(it_[0]) < 0x80) return 1; utf8_output[1] = it_[1]; if (static_cast<unsigned char>(it_[0]) < 0xE0) return 2; utf8_output[2] = it_[2]; if (static_cast<unsigned char>(it_[0]) < 0xF0) return 3; utf8_output[3] = it_[3]; return 4; } UnicodeText::const_iterator UnicodeText::MakeIterator(const char* p) const { #ifndef NDEBUG assert(p != NULL); const char* start = utf8_data(); int len = utf8_length(); const char* end = start + len; assert(p >= start); assert(p <= end); assert(p == end || !UniLib::IsTrailByte(*p)); #endif return const_iterator(p); } string UnicodeText::const_iterator::DebugString() const { stringstream ss; ss << "{iter " << hex << it_ << "}"; string result; ss >> result; return result; } } }
#include <gtest/gtest.h> #include "phonenumbers/utf/unicodetext.h" namespace i18n { namespace phonenumbers { TEST(UnicodeTextTest, Iterator) { struct value { const char* utf8; char32 code_point; } values[] = { { "\x31", 0x31 }, { "\xC2\xBD", 0x00BD }, { "\xEF\xBC\x91", 0xFF11 }, { "\xF0\x9F\x80\x80", 0x1F000 }, }; for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) { string number(values[i].utf8); UnicodeText number_as_unicode; number_as_unicode.PointToUTF8(number.data(), number.size()); EXPECT_TRUE(number_as_unicode.UTF8WasValid()); UnicodeText::const_iterator it = number_as_unicode.begin(); EXPECT_EQ(values[i].code_point, *it); } } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/utf/unicodetext.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/utf/unicodetext_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
53829aa9-260b-47ea-86e1-9a547c472f1e
cpp
google/libphonenumber
mapping_file_provider
cpp/src/phonenumbers/geocoding/mapping_file_provider.cc
cpp/test/phonenumbers/geocoding/mapping_file_provider_test.cc
#include "phonenumbers/geocoding/mapping_file_provider.h" #include <algorithm> #include <cstddef> #include <cstring> #include <sstream> #include <string> #include "phonenumbers/geocoding/geocoding_data.h" namespace i18n { namespace phonenumbers { using std::string; namespace { struct NormalizedLocale { const char* locale; const char* normalized_locale; }; const NormalizedLocale kNormalizedLocales[] = { {"zh_TW", "zh_Hant"}, {"zh_HK", "zh_Hant"}, {"zh_MO", "zh_Hant"}, }; const char* GetNormalizedLocale(const string& full_locale) { const int size = sizeof(kNormalizedLocales) / sizeof(*kNormalizedLocales); for (int i = 0; i != size; ++i) { if (full_locale.compare(kNormalizedLocales[i].locale) == 0) { return kNormalizedLocales[i].normalized_locale; } } return NULL; } void AppendLocalePart(const string& part, string* full_locale) { if (!part.empty()) { full_locale->append("_"); full_locale->append(part); } } void ConstructFullLocale(const string& language, const string& script, const string& region, string* full_locale) { full_locale->assign(language); AppendLocalePart(script, full_locale); AppendLocalePart(region, full_locale); } bool IsLowerThan(const char* s1, const char* s2) { return strcmp(s1, s2) < 0; } bool HasLanguage(const CountryLanguages* languages, const string& language) { const char** const start = languages->available_languages; const char** const end = start + languages->available_languages_size; const char** const it = std::lower_bound(start, end, language.c_str(), IsLowerThan); return it != end && strcmp(language.c_str(), *it) == 0; } } MappingFileProvider::MappingFileProvider( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages) : country_calling_codes_(country_calling_codes), country_calling_codes_size_(country_calling_codes_size), get_country_languages_(get_country_languages) { } const string& MappingFileProvider::GetFileName(int country_calling_code, const string& language, const string& script, const string& region, string* filename) const { filename->clear(); if (language.empty()) { return *filename; } const int* const country_calling_codes_end = country_calling_codes_ + country_calling_codes_size_; const int* const it = std::lower_bound(country_calling_codes_, country_calling_codes_end, country_calling_code); if (it == country_calling_codes_end || *it != country_calling_code) { return *filename; } const CountryLanguages* const langs = get_country_languages_(it - country_calling_codes_); if (langs->available_languages_size > 0) { string language_code; FindBestMatchingLanguageCode(langs, language, script, region, &language_code); if (!language_code.empty()) { std::stringstream filename_buf; filename_buf << country_calling_code << "_" << language_code; *filename = filename_buf.str(); } } return *filename; } void MappingFileProvider::FindBestMatchingLanguageCode( const CountryLanguages* languages, const string& language, const string& script, const string& region, string* best_match) const { string full_locale; ConstructFullLocale(language, script, region, &full_locale); const char* const normalized_locale = GetNormalizedLocale(full_locale); if (normalized_locale != NULL) { string normalized_locale_str(normalized_locale); if (HasLanguage(languages, normalized_locale_str)) { best_match->swap(normalized_locale_str); return; } } if (HasLanguage(languages, full_locale)) { best_match->swap(full_locale); return; } if (script.empty() != region.empty()) { if (HasLanguage(languages, language)) { *best_match = language; return; } } else if (!script.empty() && !region.empty()) { string lang_with_script(language); lang_with_script.append("_"); lang_with_script.append(script); if (HasLanguage(languages, lang_with_script)) { best_match->swap(lang_with_script); return; } } string lang_with_region(language); lang_with_region.append("_"); lang_with_region.append(region); if (HasLanguage(languages, lang_with_region)) { best_match->swap(lang_with_region); return; } if (HasLanguage(languages, language)) { *best_match = language; return; } best_match->clear(); } } }
#include "phonenumbers/geocoding/mapping_file_provider.h" #include <gtest/gtest.h> #include "phonenumbers/geocoding/geocoding_data.h" namespace i18n { namespace phonenumbers { using std::string; namespace { #define COUNTRY_LANGUAGES(code, languagelist) \ const char* country_languages_##code[] = languagelist; \ const CountryLanguages country_##code = { \ country_languages_##code, \ sizeof(country_languages_##code) / sizeof(*country_languages_##code), \ }; #define ARRAY_WRAPPER(...) __VA_ARGS__ const int country_calling_codes[] = {1, 41, 65, 86}; const int country_calling_codes_size = sizeof(country_calling_codes) / sizeof(*country_calling_codes); COUNTRY_LANGUAGES(1, ARRAY_WRAPPER({"en"})); COUNTRY_LANGUAGES(41, ARRAY_WRAPPER({"de", "fr", "it", "rm"})); COUNTRY_LANGUAGES(65, ARRAY_WRAPPER({"en", "ms", "ta", "zh_Hans"})); COUNTRY_LANGUAGES(86, ARRAY_WRAPPER({"en", "zh", "zh_Hant"})); const CountryLanguages* country_languages[] = { &country_1, &country_41, &country_65, &country_86, }; const CountryLanguages* test_get_country_languages(int index) { return country_languages[index]; } } TEST(MappingFileProviderTest, TestGetFileName) { MappingFileProvider provider(country_calling_codes, country_calling_codes_size, test_get_country_languages); string filename; EXPECT_EQ("1_en", provider.GetFileName(1, "en", "", "", &filename)); EXPECT_EQ("1_en", provider.GetFileName(1, "en", "", "US", &filename)); EXPECT_EQ("1_en", provider.GetFileName(1, "en", "", "GB", &filename)); EXPECT_EQ("41_de", provider.GetFileName(41, "de", "", "CH", &filename)); EXPECT_EQ("", provider.GetFileName(44, "en", "", "GB", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "", "", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "Hans", "", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "", "CN", &filename)); EXPECT_EQ("", provider.GetFileName(86, "", "", "CN", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "Hans", "CN", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "Hans", "SG", &filename)); EXPECT_EQ("86_zh", provider.GetFileName(86, "zh", "", "SG", &filename)); EXPECT_EQ("86_zh_Hant", provider.GetFileName(86, "zh", "", "TW", &filename)); EXPECT_EQ("86_zh_Hant", provider.GetFileName(86, "zh", "", "HK", &filename)); EXPECT_EQ("86_zh_Hant", provider.GetFileName(86, "zh", "Hant", "TW", &filename)); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/geocoding/mapping_file_provider.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/geocoding/mapping_file_provider_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
90e26224-4975-4dca-8430-82008ab8aee2
cpp
google/libphonenumber
area_code_map
cpp/src/phonenumbers/geocoding/area_code_map.cc
cpp/test/phonenumbers/geocoding/area_code_map_test.cc
#include "phonenumbers/geocoding/area_code_map.h" #include <cstddef> #include "phonenumbers/geocoding/default_map_storage.h" #include "phonenumbers/phonenumber.pb.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stringutil.h" namespace i18n { namespace phonenumbers { AreaCodeMap::AreaCodeMap() : phone_util_(*PhoneNumberUtil::GetInstance()) { } AreaCodeMap::~AreaCodeMap() { } void AreaCodeMap::ReadAreaCodeMap(const PrefixDescriptions* descriptions) { DefaultMapStorage* storage = new DefaultMapStorage(); storage->ReadFromMap(descriptions); storage_.reset(storage); } const char* AreaCodeMap::Lookup(const PhoneNumber& number) const { const int entries = storage_->GetNumOfEntries(); if (!entries) { return NULL; } string national_number; phone_util_.GetNationalSignificantNumber(number, &national_number); int64 phone_prefix; safe_strto64(SimpleItoa(number.country_code()) + national_number, &phone_prefix); const int* const lengths = storage_->GetPossibleLengths(); const int lengths_size = storage_->GetPossibleLengthsSize(); int current_index = entries - 1; for (int lengths_index = lengths_size - 1; lengths_index >= 0; --lengths_index) { const int possible_length = lengths[lengths_index]; string phone_prefix_str = SimpleItoa(phone_prefix); if (static_cast<int>(phone_prefix_str.length()) > possible_length) { safe_strto64(phone_prefix_str.substr(0, possible_length), &phone_prefix); } current_index = BinarySearch(0, current_index, phone_prefix); if (current_index < 0) { return NULL; } const int32 current_prefix = storage_->GetPrefix(current_index); if (phone_prefix == current_prefix) { return storage_->GetDescription(current_index); } } return NULL; } int AreaCodeMap::BinarySearch(int start, int end, int64 value) const { int current = 0; while (start <= end) { current = (start + end) / 2; int32 current_value = storage_->GetPrefix(current); if (current_value == value) { return current; } else if (current_value > value) { --current; end = current; } else { start = current + 1; } } return current; } } }
#include "phonenumbers/geocoding/area_code_map.h" #include <cstddef> #include <vector> #include <gtest/gtest.h> #include "phonenumbers/geocoding/geocoding_data.h" #include "phonenumbers/phonenumber.pb.h" namespace i18n { namespace phonenumbers { namespace { void MakeCodeMap(const PrefixDescriptions* descriptions, scoped_ptr<AreaCodeMap>* code_map) { scoped_ptr<AreaCodeMap> cm(new AreaCodeMap()); cm->ReadAreaCodeMap(descriptions); code_map->swap(cm); } const int32 prefix_1_us_prefixes[] = { 1212, 1480, 1650, 1907, 1201664, 1480893, 1501372, 1626308, 1650345, 1867993, 1972480, }; const char* prefix_1_us_descriptions[] = { "New York", "Arizona", "California", "Alaska", "Westwood, NJ", "Phoenix, AZ", "Little Rock, AR", "Alhambra, CA", "San Mateo, CA", "Dawson, YT", "Richardson, TX", }; const int32 prefix_1_us_lengths[] = { 4, 7, }; const PrefixDescriptions prefix_1_us = { prefix_1_us_prefixes, sizeof(prefix_1_us_prefixes) / sizeof(*prefix_1_us_prefixes), prefix_1_us_descriptions, prefix_1_us_lengths, sizeof(prefix_1_us_lengths) / sizeof(*prefix_1_us_lengths), }; const int32 prefix_39_it_prefixes[] = { 3902, 3906, 39010, 390131, 390321, 390975, }; const char* prefix_39_it_descriptions[] = { "Milan", "Rome", "Genoa", "Alessandria", "Novara", "Potenza", }; const int32 prefix_39_it_lengths[] = { 4, 5, 6, }; const PrefixDescriptions prefix_39_it = { prefix_39_it_prefixes, sizeof(prefix_39_it_prefixes) / sizeof(*prefix_39_it_prefixes), prefix_39_it_descriptions, prefix_39_it_lengths, sizeof(prefix_39_it_lengths) / sizeof(*prefix_1_us_lengths), }; void MakeCodeMapUS(scoped_ptr<AreaCodeMap>* code_map) { MakeCodeMap(&prefix_1_us, code_map); } void MakeCodeMapIT(scoped_ptr<AreaCodeMap>* code_map) { MakeCodeMap(&prefix_39_it, code_map); } PhoneNumber MakePhoneNumber(int32 country_code, uint64 national_number) { PhoneNumber number; number.set_country_code(country_code); number.set_national_number(national_number); return number; } } class AreaCodeMapTest : public testing::Test { protected: virtual void SetUp() { MakeCodeMapUS(&map_US_); MakeCodeMapIT(&map_IT_); } scoped_ptr<AreaCodeMap> map_US_; scoped_ptr<AreaCodeMap> map_IT_; }; TEST_F(AreaCodeMapTest, TestLookupInvalidNumberUS) { EXPECT_STREQ("New York", map_US_->Lookup(MakePhoneNumber(1, 2121234567L))); } TEST_F(AreaCodeMapTest, TestLookupNumberNJ) { EXPECT_STREQ("Westwood, NJ", map_US_->Lookup(MakePhoneNumber(1, 2016641234L))); } TEST_F(AreaCodeMapTest, TestLookupNumberNY) { EXPECT_STREQ("New York", map_US_->Lookup(MakePhoneNumber(1, 2126641234L))); } TEST_F(AreaCodeMapTest, TestLookupNumberCA1) { EXPECT_STREQ("San Mateo, CA", map_US_->Lookup(MakePhoneNumber(1, 6503451234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberCA2) { EXPECT_STREQ("California", map_US_->Lookup(MakePhoneNumber(1, 6502531234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberTX) { EXPECT_STREQ("Richardson, TX", map_US_->Lookup(MakePhoneNumber(1, 9724801234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberNotFoundTX) { EXPECT_STREQ(NULL, map_US_->Lookup(MakePhoneNumber(1, 9724811234LL))); } TEST_F(AreaCodeMapTest, TestLookupNumberCH) { EXPECT_STREQ(NULL, map_US_->Lookup(MakePhoneNumber(41, 446681300L))); } TEST_F(AreaCodeMapTest, TestLookupNumberIT) { PhoneNumber number = MakePhoneNumber(39, 212345678L); number.set_italian_leading_zero(true); EXPECT_STREQ("Milan", map_IT_->Lookup(number)); number.set_national_number(612345678L); EXPECT_STREQ("Rome", map_IT_->Lookup(number)); number.set_national_number(3211234L); EXPECT_STREQ("Novara", map_IT_->Lookup(number)); number.set_national_number(321123456L); number.set_italian_leading_zero(false); EXPECT_STREQ(NULL, map_IT_->Lookup(number)); number.set_national_number(321123L); number.set_italian_leading_zero(true); EXPECT_STREQ("Novara", map_IT_->Lookup(number)); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/geocoding/area_code_map.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/geocoding/area_code_map_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
aa95446b-57f9-41a9-b640-95014161ac37
cpp
google/libphonenumber
phonenumber_offline_geocoder
cpp/src/phonenumbers/geocoding/phonenumber_offline_geocoder.cc
cpp/test/phonenumbers/geocoding/phonenumber_offline_geocoder_test.cc
#include "phonenumbers/geocoding/phonenumber_offline_geocoder.h" #include <algorithm> #include <string> #include <unicode/unistr.h> #include "phonenumbers/geocoding/area_code_map.h" #include "phonenumbers/geocoding/geocoding_data.h" #include "phonenumbers/geocoding/mapping_file_provider.h" #include "phonenumbers/phonenumberutil.h" #include "phonenumbers/stl_util.h" #include "absl/synchronization/mutex.h" namespace i18n { namespace phonenumbers { using icu::UnicodeString; using std::string; namespace { bool IsLowerThan(const char* s1, const char* s2) { return strcmp(s1, s2) < 0; } } PhoneNumberOfflineGeocoder::PhoneNumberOfflineGeocoder() { Init(get_country_calling_codes(), get_country_calling_codes_size(), get_country_languages, get_prefix_language_code_pairs(), get_prefix_language_code_pairs_size(), get_prefix_descriptions); } PhoneNumberOfflineGeocoder::PhoneNumberOfflineGeocoder( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions) { Init(country_calling_codes, country_calling_codes_size, get_country_languages, prefix_language_code_pairs, prefix_language_code_pairs_size, get_prefix_descriptions); } void PhoneNumberOfflineGeocoder::Init( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages, const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions) { phone_util_ = PhoneNumberUtil::GetInstance(); provider_.reset(new MappingFileProvider(country_calling_codes, country_calling_codes_size, get_country_languages)); prefix_language_code_pairs_ = prefix_language_code_pairs; prefix_language_code_pairs_size_ = prefix_language_code_pairs_size; get_prefix_descriptions_ = get_prefix_descriptions; } PhoneNumberOfflineGeocoder::~PhoneNumberOfflineGeocoder() { absl::MutexLock l(&mu_); gtl::STLDeleteContainerPairSecondPointers( available_maps_.begin(), available_maps_.end()); } const AreaCodeMap* PhoneNumberOfflineGeocoder::GetPhonePrefixDescriptions( int prefix, const string& language, const string& script, const string& region) const { string filename; provider_->GetFileName(prefix, language, script, region, &filename); if (filename.empty()) { return NULL; } AreaCodeMaps::const_iterator it = available_maps_.find(filename); if (it == available_maps_.end()) { return LoadAreaCodeMapFromFile(filename); } return it->second; } const AreaCodeMap* PhoneNumberOfflineGeocoder::LoadAreaCodeMapFromFile( const string& filename) const { const char** const prefix_language_code_pairs_end = prefix_language_code_pairs_ + prefix_language_code_pairs_size_; const char** const prefix_language_code_pair = std::lower_bound(prefix_language_code_pairs_, prefix_language_code_pairs_end, filename.c_str(), IsLowerThan); if (prefix_language_code_pair != prefix_language_code_pairs_end && filename.compare(*prefix_language_code_pair) == 0) { AreaCodeMap* const m = new AreaCodeMap(); m->ReadAreaCodeMap(get_prefix_descriptions_( prefix_language_code_pair - prefix_language_code_pairs_)); return available_maps_.insert(AreaCodeMaps::value_type(filename, m)) .first->second; } return NULL; } string PhoneNumberOfflineGeocoder::GetCountryNameForNumber( const PhoneNumber& number, const Locale& language) const { string region_code; phone_util_->GetRegionCodeForNumber(number, &region_code); return GetRegionDisplayName(&region_code, language); } string PhoneNumberOfflineGeocoder::GetRegionDisplayName( const string* region_code, const Locale& language) const { if (region_code == NULL || region_code->compare("ZZ") == 0 || region_code->compare( PhoneNumberUtil::kRegionCodeForNonGeoEntity) == 0) { return ""; } UnicodeString udisplay_country; icu::Locale("", region_code->c_str()).getDisplayCountry( language, udisplay_country); string display_country; udisplay_country.toUTF8String(display_country); return display_country; } string PhoneNumberOfflineGeocoder::GetDescriptionForValidNumber( const PhoneNumber& number, const Locale& language) const { const char* const description = GetAreaDescription( number, language.getLanguage(), "", language.getCountry()); return *description != '\0' ? description : GetCountryNameForNumber(number, language); } string PhoneNumberOfflineGeocoder::GetDescriptionForValidNumber( const PhoneNumber& number, const Locale& language, const string& user_region) const { string region_code; phone_util_->GetRegionCodeForNumber(number, &region_code); if (user_region.compare(region_code) == 0) { return GetDescriptionForValidNumber(number, language); } return GetRegionDisplayName(&region_code, language); } string PhoneNumberOfflineGeocoder::GetDescriptionForNumber( const PhoneNumber& number, const Locale& locale) const { PhoneNumberUtil::PhoneNumberType number_type = phone_util_->GetNumberType(number); if (number_type == PhoneNumberUtil::UNKNOWN) { return ""; } else if (!phone_util_->IsNumberGeographical(number_type, number.country_code())) { return GetCountryNameForNumber(number, locale); } return GetDescriptionForValidNumber(number, locale); } string PhoneNumberOfflineGeocoder::GetDescriptionForNumber( const PhoneNumber& number, const Locale& language, const string& user_region) const { PhoneNumberUtil::PhoneNumberType number_type = phone_util_->GetNumberType(number); if (number_type == PhoneNumberUtil::UNKNOWN) { return ""; } else if (!phone_util_->IsNumberGeographical(number_type, number.country_code())) { return GetCountryNameForNumber(number, language); } return GetDescriptionForValidNumber(number, language, user_region); } const char* PhoneNumberOfflineGeocoder::GetAreaDescription( const PhoneNumber& number, const string& lang, const string& script, const string& region) const { const int country_calling_code = number.country_code(); const int phone_prefix = country_calling_code; absl::MutexLock l(&mu_); const AreaCodeMap* const descriptions = GetPhonePrefixDescriptions( phone_prefix, lang, script, region); const char* description = descriptions ? descriptions->Lookup(number) : NULL; if ((!description || *description == '\0') && MayFallBackToEnglish(lang)) { const AreaCodeMap* default_descriptions = GetPhonePrefixDescriptions( phone_prefix, "en", "", ""); if (!default_descriptions) { return ""; } description = default_descriptions->Lookup(number); } return description ? description : ""; } bool PhoneNumberOfflineGeocoder::MayFallBackToEnglish( const string& lang) const { return lang.compare("zh") && lang.compare("ja") && lang.compare("ko"); } } }
#include "phonenumbers/geocoding/phonenumber_offline_geocoder.h" #include <gtest/gtest.h> #include <unicode/locid.h> #include "phonenumbers/geocoding/geocoding_test_data.h" #include "phonenumbers/phonenumber.h" #include "phonenumbers/phonenumber.pb.h" namespace i18n { namespace phonenumbers { using icu::Locale; namespace { PhoneNumber MakeNumber(int32 country_code, uint64 national_number) { PhoneNumber n; n.set_country_code(country_code); n.set_national_number(national_number); return n; } const Locale kEnglishLocale = Locale("en", "GB"); const Locale kFrenchLocale = Locale("fr", "FR"); const Locale kGermanLocale = Locale("de", "DE"); const Locale kItalianLocale = Locale("it", "IT"); const Locale kKoreanLocale = Locale("ko", "KR"); const Locale kSimplifiedChineseLocale = Locale("zh", "CN"); } class PhoneNumberOfflineGeocoderTest : public testing::Test { protected: PhoneNumberOfflineGeocoderTest() : KO_NUMBER1(MakeNumber(82, 22123456UL)), KO_NUMBER2(MakeNumber(82, 322123456UL)), KO_NUMBER3(MakeNumber(82, uint64{6421234567})), KO_INVALID_NUMBER(MakeNumber(82, 1234UL)), KO_MOBILE(MakeNumber(82, uint64{101234567})), US_NUMBER1(MakeNumber(1, uint64{6502530000})), US_NUMBER2(MakeNumber(1, uint64{6509600000})), US_NUMBER3(MakeNumber(1, 2128120000UL)), US_NUMBER4(MakeNumber(1, uint64{6174240000})), US_INVALID_NUMBER(MakeNumber(1, 123456789UL)), BS_NUMBER1(MakeNumber(1, 2423651234UL)), AU_NUMBER(MakeNumber(61, 236618300UL)), NUMBER_WITH_INVALID_COUNTRY_CODE(MakeNumber(999, 2423651234UL)), INTERNATIONAL_TOLL_FREE(MakeNumber(800, 12345678UL)) { } virtual void SetUp() { geocoder_.reset( new PhoneNumberOfflineGeocoder( get_test_country_calling_codes(), get_test_country_calling_codes_size(), get_test_country_languages, get_test_prefix_language_code_pairs(), get_test_prefix_language_code_pairs_size(), get_test_prefix_descriptions)); } protected: scoped_ptr<PhoneNumberOfflineGeocoder> geocoder_; const PhoneNumber KO_NUMBER1; const PhoneNumber KO_NUMBER2; const PhoneNumber KO_NUMBER3; const PhoneNumber KO_INVALID_NUMBER; const PhoneNumber KO_MOBILE; const PhoneNumber US_NUMBER1; const PhoneNumber US_NUMBER2; const PhoneNumber US_NUMBER3; const PhoneNumber US_NUMBER4; const PhoneNumber US_INVALID_NUMBER; const PhoneNumber BS_NUMBER1; const PhoneNumber AU_NUMBER; const PhoneNumber NUMBER_WITH_INVALID_COUNTRY_CODE; const PhoneNumber INTERNATIONAL_TOLL_FREE; }; TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumberWithNoDataFile) { EXPECT_EQ("\xe7""\xbe""\x8e""\xe5""\x9b""\xbd", geocoder_->GetDescriptionForNumber(US_NUMBER1, kSimplifiedChineseLocale)); EXPECT_EQ("Bahamas", geocoder_->GetDescriptionForNumber(BS_NUMBER1, Locale("en", "US"))); EXPECT_EQ("Australia", geocoder_->GetDescriptionForNumber(AU_NUMBER, Locale("en", "US"))); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(NUMBER_WITH_INVALID_COUNTRY_CODE, Locale("en", "US"))); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(INTERNATIONAL_TOLL_FREE, Locale("en", "US"))); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumberWithMissingPrefix) { EXPECT_EQ("United States", geocoder_->GetDescriptionForNumber(US_NUMBER4, Locale("en", "US"))); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumber_en_US) { EXPECT_EQ("CA", geocoder_->GetDescriptionForNumber(US_NUMBER1, Locale("en", "US"))); EXPECT_EQ("Mountain View, CA", geocoder_->GetDescriptionForNumber(US_NUMBER2, Locale("en", "US"))); EXPECT_EQ("New York, NY", geocoder_->GetDescriptionForNumber(US_NUMBER3, Locale("en", "US"))); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForKoreanNumber) { EXPECT_EQ("Seoul", geocoder_->GetDescriptionForNumber(KO_NUMBER1, kEnglishLocale)); EXPECT_EQ("Incheon", geocoder_->GetDescriptionForNumber(KO_NUMBER2, kEnglishLocale)); EXPECT_EQ("Jeju", geocoder_->GetDescriptionForNumber(KO_NUMBER3, kEnglishLocale)); EXPECT_EQ("\xec""\x84""\x9c""\xec""\x9a""\xb8", geocoder_->GetDescriptionForNumber(KO_NUMBER1, kKoreanLocale)); EXPECT_EQ("\xec""\x9d""\xb8""\xec""\xb2""\x9c", geocoder_->GetDescriptionForNumber(KO_NUMBER2, kKoreanLocale)); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForFallBack) { EXPECT_EQ("Kalifornien", geocoder_->GetDescriptionForNumber(US_NUMBER1, kGermanLocale)); EXPECT_EQ("New York, NY", geocoder_->GetDescriptionForNumber(US_NUMBER3, kGermanLocale)); EXPECT_EQ("CA", geocoder_->GetDescriptionForNumber(US_NUMBER1, kItalianLocale)); EXPECT_EQ("\xeb""\x8c""\x80""\xed""\x95""\x9c""\xeb""\xaf""\xbc""\xea""\xb5" "\xad", geocoder_->GetDescriptionForNumber(KO_NUMBER3, kKoreanLocale)); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNumberWithUserRegion) { EXPECT_EQ("Estados Unidos", geocoder_->GetDescriptionForNumber(US_NUMBER1, Locale("es", "ES"), "IT")); EXPECT_EQ("Estados Unidos", geocoder_->GetDescriptionForNumber(US_NUMBER1, Locale("es", "ES"), "ZZ")); EXPECT_EQ("Kalifornien", geocoder_->GetDescriptionForNumber(US_NUMBER1, kGermanLocale, "US")); EXPECT_EQ("CA", geocoder_->GetDescriptionForNumber(US_NUMBER1, kFrenchLocale, "US")); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(US_INVALID_NUMBER, kEnglishLocale, "US")); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForInvalidNumber) { EXPECT_EQ("", geocoder_->GetDescriptionForNumber(KO_INVALID_NUMBER, kEnglishLocale)); EXPECT_EQ("", geocoder_->GetDescriptionForNumber(US_INVALID_NUMBER, kEnglishLocale)); } TEST_F(PhoneNumberOfflineGeocoderTest, TestGetDescriptionForNonGeographicalNumberWithGeocodingPrefix) { EXPECT_EQ("South Korea", geocoder_->GetDescriptionForNumber(KO_MOBILE, kEnglishLocale)); } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/geocoding/phonenumber_offline_geocoder.cc
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/geocoding/phonenumber_offline_geocoder_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
829c19fc-b072-493f-add4-3d8563d80635
cpp
google/libphonenumber
regexp_adapter
cpp/src/phonenumbers/regexp_adapter.h
cpp/test/phonenumbers/regexp_adapter_test.cc
#ifndef I18N_PHONENUMBERS_REGEXP_ADAPTER_H_ #define I18N_PHONENUMBERS_REGEXP_ADAPTER_H_ #include <cstddef> #include <string> namespace i18n { namespace phonenumbers { using std::string; class RegExpInput { public: virtual ~RegExpInput() {} virtual string ToString() const = 0; }; class RegExp { public: virtual ~RegExp() {} virtual bool Consume(RegExpInput* input_string, bool anchor_at_start, string* matched_string1, string* matched_string2, string* matched_string3, string* matched_string4, string* matched_string5, string* matched_string6) const = 0; inline bool Consume(RegExpInput* input_string, string* matched_string1, string* matched_string2, string* matched_string3, string* matched_string4, string* matched_string5, string* matched_string6) const { return Consume(input_string, true, matched_string1, matched_string2, matched_string3, matched_string4, matched_string5, matched_string6); } inline bool Consume(RegExpInput* input_string, string* matched_string1, string* matched_string2, string* matched_string3, string* matched_string4, string* matched_string5) const { return Consume(input_string, true, matched_string1, matched_string2, matched_string3, matched_string4, matched_string5, NULL); } inline bool Consume(RegExpInput* input_string, string* matched_string1, string* matched_string2, string* matched_string3, string* matched_string4) const { return Consume(input_string, true, matched_string1, matched_string2, matched_string3, matched_string4, NULL, NULL); } inline bool Consume(RegExpInput* input_string, string* matched_string1, string* matched_string2, string* matched_string3) const { return Consume(input_string, true, matched_string1, matched_string2, matched_string3, NULL, NULL, NULL); } inline bool Consume(RegExpInput* input_string, string* matched_string1, string* matched_string2) const { return Consume(input_string, true, matched_string1, matched_string2, NULL, NULL, NULL, NULL); } inline bool Consume(RegExpInput* input_string, string* matched_string) const { return Consume(input_string, true, matched_string, NULL, NULL, NULL, NULL, NULL); } inline bool Consume(RegExpInput* input_string) const { return Consume(input_string, true, NULL, NULL, NULL, NULL, NULL, NULL); } inline bool FindAndConsume(RegExpInput* input_string, string* matched_string) const { return Consume(input_string, false, matched_string, NULL, NULL, NULL, NULL, NULL); } virtual bool Match(const string& input_string, bool full_match, string* matched_string) const = 0; inline bool PartialMatch(const string& input_string, string* matched_string) const { return Match(input_string, false, matched_string); } inline bool PartialMatch(const string& input_string) const { return Match(input_string, false, NULL); } inline bool FullMatch(const string& input_string, string* matched_string) const { return Match(input_string, true, matched_string); } inline bool FullMatch(const string& input_string) const { return Match(input_string, true, NULL); } virtual bool Replace(string* string_to_process, bool global, const string& replacement_string) const = 0; inline bool Replace(string* string_to_process, const string& replacement_string) const { return Replace(string_to_process, false, replacement_string); } inline bool GlobalReplace(string* string_to_process, const string& replacement_string) const { return Replace(string_to_process, true, replacement_string); } }; class AbstractRegExpFactory { public: virtual ~AbstractRegExpFactory() {} virtual RegExpInput* CreateInput(const string& utf8_input) const = 0; virtual RegExp* CreateRegExp(const string& utf8_regexp) const = 0; }; } } #endif
#include "phonenumbers/regexp_adapter.h" #include <string> #include <vector> #include <gtest/gtest.h> #include "phonenumbers/base/memory/scoped_ptr.h" #include "phonenumbers/stl_util.h" #include "phonenumbers/stringutil.h" #ifdef I18N_PHONENUMBERS_USE_RE2 #include "phonenumbers/regexp_adapter_re2.h" #else #include "phonenumbers/regexp_adapter_icu.h" #endif namespace i18n { namespace phonenumbers { using std::vector; struct RegExpTestContext { explicit RegExpTestContext(const string& name, const AbstractRegExpFactory* factory) : name(name), factory(factory), digits(factory->CreateRegExp("\\d+")), parentheses_digits(factory->CreateRegExp("\\((\\d+)\\)")), single_digit(factory->CreateRegExp("\\d")), two_digit_groups(factory->CreateRegExp("(\\d+)-(\\d+)")), six_digit_groups(factory->CreateRegExp( "(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)-(\\d+)")) {} const string name; const scoped_ptr<const AbstractRegExpFactory> factory; const scoped_ptr<const RegExp> digits; const scoped_ptr<const RegExp> parentheses_digits; const scoped_ptr<const RegExp> single_digit; const scoped_ptr<const RegExp> two_digit_groups; const scoped_ptr<const RegExp> six_digit_groups; }; class RegExpAdapterTest : public testing::Test { protected: RegExpAdapterTest() { #ifdef I18N_PHONENUMBERS_USE_RE2 contexts_.push_back( new RegExpTestContext("RE2", new RE2RegExpFactory())); #else contexts_.push_back( new RegExpTestContext("ICU Regex", new ICURegExpFactory())); #endif } ~RegExpAdapterTest() { gtl::STLDeleteElements(&contexts_); } static string ErrorMessage(const RegExpTestContext& context) { return StrCat("Test failed with ", context.name, " implementation."); } typedef vector<const RegExpTestContext*>::const_iterator TestContextIterator; vector<const RegExpTestContext*> contexts_; }; TEST_F(RegExpAdapterTest, TestConsumeNoMatch) { for (vector<const RegExpTestContext*>::const_iterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; const scoped_ptr<RegExpInput> input( context.factory->CreateInput("+1-123-456-789")); ASSERT_FALSE(context.digits->Consume( input.get(), true, NULL, NULL, NULL, NULL, NULL, NULL)) << ErrorMessage(context); ASSERT_EQ("+1-123-456-789", input->ToString()) << ErrorMessage(context); string res1; ASSERT_FALSE(context.parentheses_digits->Consume( input.get(), true, &res1, NULL, NULL, NULL, NULL, NULL)) << ErrorMessage(context); ASSERT_EQ("+1-123-456-789", input->ToString()) << ErrorMessage(context); ASSERT_EQ("", res1) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestConsumeWithNull) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; const AbstractRegExpFactory& factory = *context.factory; const scoped_ptr<RegExpInput> input(factory.CreateInput("+123")); const scoped_ptr<const RegExp> plus_sign(factory.CreateRegExp("(\\+)")); ASSERT_TRUE(plus_sign->Consume(input.get(), true, NULL, NULL, NULL, NULL, NULL, NULL)) << ErrorMessage(context); ASSERT_EQ("123", input->ToString()) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestConsumeRetainsMatches) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; const scoped_ptr<RegExpInput> input( context.factory->CreateInput("1-123-456-789")); string res1, res2; ASSERT_TRUE(context.two_digit_groups->Consume( input.get(), true, &res1, &res2, NULL, NULL, NULL, NULL)) << ErrorMessage(context); ASSERT_EQ("-456-789", input->ToString()) << ErrorMessage(context); ASSERT_EQ("1", res1) << ErrorMessage(context); ASSERT_EQ("123", res2) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestFindAndConsume) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; const scoped_ptr<RegExpInput> input( context.factory->CreateInput("+1-123-456-789")); const scoped_ptr<RegExpInput> input_with_six_digit_groups( context.factory->CreateInput("111-222-333-444-555-666")); ASSERT_TRUE(context.digits->Consume(input.get(), false, NULL, NULL, NULL, NULL, NULL, NULL)) << ErrorMessage(context); ASSERT_EQ("-123-456-789", input->ToString()) << ErrorMessage(context); ASSERT_TRUE(context.digits->Consume(input.get(), false, NULL, NULL, NULL, NULL, NULL, NULL)) << ErrorMessage(context); ASSERT_EQ("-456-789", input->ToString()) << ErrorMessage(context); ASSERT_FALSE(context.parentheses_digits->Consume( input.get(), false, NULL, NULL, NULL, NULL, NULL, NULL)) << ErrorMessage(context); ASSERT_EQ("-456-789", input->ToString()) << ErrorMessage(context); string res1, res2; ASSERT_TRUE(context.two_digit_groups->Consume( input.get(), false, &res1, &res2, NULL, NULL, NULL, NULL)) << ErrorMessage(context); printf("previous input: %s", input.get()->ToString().c_str()); ASSERT_EQ("", input->ToString()) << ErrorMessage(context); ASSERT_EQ("456", res1) << ErrorMessage(context); ASSERT_EQ("789", res2) << ErrorMessage(context); string mat1, mat2, res3, res4, res5, res6; ASSERT_TRUE(context.six_digit_groups->Consume( input_with_six_digit_groups.get(), false, &mat1, &mat2, &res3, &res4, &res5, &res6)) << ErrorMessage(context); printf("Present input: %s", input_with_six_digit_groups.get()->ToString().c_str()); ASSERT_EQ("", input_with_six_digit_groups->ToString()) << ErrorMessage(context); ASSERT_EQ("111", mat1) << ErrorMessage(context); ASSERT_EQ("222", mat2) << ErrorMessage(context); ASSERT_EQ("333", res3) << ErrorMessage(context); ASSERT_EQ("444", res4) << ErrorMessage(context); ASSERT_EQ("555", res5) << ErrorMessage(context); ASSERT_EQ("666", res6) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestPartialMatch) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; const AbstractRegExpFactory& factory = *context.factory; const scoped_ptr<const RegExp> reg_exp(factory.CreateRegExp("([\\da-z]+)")); string matched; EXPECT_TRUE(reg_exp->PartialMatch("12345af", &matched)) << ErrorMessage(context); EXPECT_EQ("12345af", matched) << ErrorMessage(context); EXPECT_TRUE(reg_exp->PartialMatch("12345af", NULL)) << ErrorMessage(context); EXPECT_TRUE(reg_exp->PartialMatch("[12]", &matched)) << ErrorMessage(context); EXPECT_EQ("12", matched) << ErrorMessage(context); matched.clear(); EXPECT_FALSE(reg_exp->PartialMatch("[]", &matched)) << ErrorMessage(context); EXPECT_EQ("", matched) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestFullMatch) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; const AbstractRegExpFactory& factory = *context.factory; const scoped_ptr<const RegExp> reg_exp(factory.CreateRegExp("([\\da-z]+)")); string matched; EXPECT_TRUE(reg_exp->FullMatch("12345af", &matched)) << ErrorMessage(context); EXPECT_EQ("12345af", matched) << ErrorMessage(context); EXPECT_TRUE(reg_exp->FullMatch("12345af", NULL)) << ErrorMessage(context); matched.clear(); EXPECT_FALSE(reg_exp->FullMatch("[12]", &matched)) << ErrorMessage(context); EXPECT_EQ("", matched) << ErrorMessage(context); matched.clear(); EXPECT_FALSE(reg_exp->FullMatch("[]", &matched)) << ErrorMessage(context); EXPECT_EQ("", matched) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestReplace) { for (vector<const RegExpTestContext*>::const_iterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; string input("123-4567 "); ASSERT_TRUE(context.single_digit->Replace(&input, "+")) << ErrorMessage(context); ASSERT_EQ("+23-4567 ", input) << ErrorMessage(context); ASSERT_TRUE(context.single_digit->Replace(&input, "+")) << ErrorMessage(context); ASSERT_EQ("++3-4567 ", input) << ErrorMessage(context); const scoped_ptr<const RegExp> single_letter( context.factory->CreateRegExp("[a-z]")); ASSERT_FALSE(single_letter->Replace(&input, "+")) << ErrorMessage(context); ASSERT_EQ("++3-4567 ", input) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestReplaceWithGroup) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; string input = "123-4567 abc"; ASSERT_TRUE(context.two_digit_groups->Replace(&input, "$2")) << ErrorMessage(context); ASSERT_EQ("4567 abc", input) << ErrorMessage(context); input = "123-4567"; ASSERT_TRUE(context.two_digit_groups->Replace(&input, "$1")) << ErrorMessage(context); ASSERT_EQ("123", input) << ErrorMessage(context); input = "123-4567"; ASSERT_TRUE(context.two_digit_groups->Replace(&input, "$2")) << ErrorMessage(context); ASSERT_EQ("4567", input) << ErrorMessage(context); input = "123-4567"; ASSERT_TRUE(context.two_digit_groups->Replace(&input, "$1 $2")) << ErrorMessage(context); ASSERT_EQ("123 4567", input) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestReplaceWithDollarSign) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; string input = "123-4567"; ASSERT_TRUE(context.two_digit_groups->Replace(&input, "\\$1 \\$2")) << ErrorMessage(context); ASSERT_EQ("$1 $2", input) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestGlobalReplace) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; string input("123-4567 "); ASSERT_TRUE(context.single_digit->GlobalReplace(&input, "*")) << ErrorMessage(context); ASSERT_EQ("***-**** ", input) << ErrorMessage(context); ASSERT_FALSE(context.single_digit->GlobalReplace(&input, "*")) << ErrorMessage(context); ASSERT_EQ("***-**** ", input) << ErrorMessage(context); } } TEST_F(RegExpAdapterTest, TestUtf8) { for (TestContextIterator it = contexts_.begin(); it != contexts_.end(); ++it) { const RegExpTestContext& context = **it; const AbstractRegExpFactory& factory = *context.factory; const scoped_ptr<const RegExp> reg_exp(factory.CreateRegExp( "\xE2\x84\xA1\xE2\x8A\x8F([\xCE\xB1-\xCF\x89]*)\xE2\x8A\x90" )); string matched; EXPECT_FALSE(reg_exp->Match( "\xE2\x84\xA1\xE2\x8A\x8F" "123\xE2\x8A\x90" , true, &matched)) << ErrorMessage(context); EXPECT_TRUE(reg_exp->Match( "\xE2\x84\xA1\xE2\x8A\x8F\xCE\xB1\xCE\xB2\xE2\x8A\x90" , true, &matched)) << ErrorMessage(context); EXPECT_EQ("\xCE\xB1\xCE\xB2" , matched) << ErrorMessage(context); } } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/regexp_adapter.h
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/regexp_adapter_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
20c2a41d-cae1-4ee1-b9da-0a950d5bb1dc
cpp
google/libphonenumber
geocoding_data
cpp/src/phonenumbers/geocoding/geocoding_data.h
cpp/test/phonenumbers/geocoding/geocoding_data_test.cc
#ifndef I18N_PHONENUMBERS_GEOCODING_DATA #define I18N_PHONENUMBERS_GEOCODING_DATA #include <cstdint> namespace i18n { namespace phonenumbers { struct CountryLanguages { const char** available_languages; const int available_languages_size; }; struct PrefixDescriptions { const int32_t* prefixes; const int prefixes_size; const char** descriptions; const int32_t* possible_lengths; const int possible_lengths_size; }; const int* get_country_calling_codes(); int get_country_calling_codes_size(); const CountryLanguages* get_country_languages(int index); const char** get_prefix_language_code_pairs(); int get_prefix_language_code_pairs_size(); const PrefixDescriptions* get_prefix_descriptions(int index); } } #endif
#include <cmath> #include <set> #include <string> #include <gtest/gtest.h> #include "phonenumbers/base/basictypes.h" #include "phonenumbers/geocoding/geocoding_data.h" #include "phonenumbers/geocoding/geocoding_test_data.h" #include "absl/container/btree_set.h" namespace i18n { namespace phonenumbers { using std::set; using std::string; namespace { typedef const CountryLanguages* (*country_languages_getter)(int index); typedef const PrefixDescriptions* (*prefix_descriptions_getter)(int index); void TestCountryLanguages(const CountryLanguages* languages) { EXPECT_GT(languages->available_languages_size, 0); for (int i = 0; i < languages->available_languages_size; ++i) { string language(languages->available_languages[i]); EXPECT_GT(language.size(), 0); if (i > 0) { EXPECT_LT(string(languages->available_languages[i - 1]), language); } } } void TestCountryCallingCodeLanguages( const int* country_calling_codes, int country_calling_codes_size, country_languages_getter get_country_languages) { EXPECT_GT(country_calling_codes_size, 0); for (int i = 0; i < country_calling_codes_size; ++i) { int code = country_calling_codes[i]; EXPECT_GT(code, 0); if (i > 0) { EXPECT_LT(country_calling_codes[i-1], code); } TestCountryLanguages(get_country_languages(i)); } } void TestPrefixDescriptions(const PrefixDescriptions* descriptions) { EXPECT_GT(descriptions->prefixes_size, 0); absl::btree_set<int> possible_lengths; for (int i = 0; i < descriptions->prefixes_size; ++i) { int prefix = descriptions->prefixes[i]; EXPECT_GT(prefix, 0); if (i > 0) { EXPECT_LT(descriptions->prefixes[i - 1], prefix); } possible_lengths.insert(log10(prefix) + 1); } EXPECT_GT(descriptions->possible_lengths_size, 0); for (int i = 0; i < descriptions->possible_lengths_size; ++i) { int possible_length = descriptions->possible_lengths[i]; EXPECT_GT(possible_length, 0); if (i > 0) { EXPECT_LT(descriptions->possible_lengths[i - 1], possible_length); } EXPECT_TRUE( possible_lengths.find(possible_length) != possible_lengths.end()); } } void TestAllPrefixDescriptions( const char** prefix_language_code_pairs, int prefix_language_code_pairs_size, prefix_descriptions_getter get_prefix_descriptions) { EXPECT_GT(prefix_language_code_pairs_size, 0); for (int i = 0; i < prefix_language_code_pairs_size; ++i) { string language_code_pair(prefix_language_code_pairs[i]); EXPECT_GT(language_code_pair.size(), 0); if (i > 0) { EXPECT_LT(string(prefix_language_code_pairs[i - 1]), language_code_pair); } TestPrefixDescriptions(get_prefix_descriptions(i)); } } } TEST(GeocodingDataTest, TestCountryCallingCodeLanguages) { TestCountryCallingCodeLanguages(get_country_calling_codes(), get_country_calling_codes_size(), get_country_languages); } TEST(GeocodingDataTest, TestTestCountryCallingCodeLanguages) { TestCountryCallingCodeLanguages(get_test_country_calling_codes(), get_test_country_calling_codes_size(), get_test_country_languages); } TEST(GeocodingDataTest, TestPrefixDescriptions) { TestAllPrefixDescriptions(get_prefix_language_code_pairs(), get_prefix_language_code_pairs_size(), get_prefix_descriptions); } TEST(GeocodingDataTest, TestTestPrefixDescriptions) { TestAllPrefixDescriptions(get_test_prefix_language_code_pairs(), get_test_prefix_language_code_pairs_size(), get_test_prefix_descriptions); } TEST(GeocodingDataTest, TestTestGeocodingData) { ASSERT_EQ(3, get_test_country_calling_codes_size()); const int* country_calling_codes = get_test_country_calling_codes(); const int expected_calling_codes[] = {1, 54, 82}; for (int i = 0; i < get_test_country_calling_codes_size(); ++i) { EXPECT_EQ(expected_calling_codes[i], country_calling_codes[i]); } const CountryLanguages* langs_1 = get_test_country_languages(0); ASSERT_EQ(2, langs_1->available_languages_size); const char* expected_languages[] = {"de", "en"}; for (int i = 0; i < langs_1->available_languages_size; ++i) { EXPECT_STREQ(expected_languages[i], langs_1->available_languages[i]); } ASSERT_EQ(5, get_test_prefix_language_code_pairs_size()); const char** language_code_pairs = get_test_prefix_language_code_pairs(); const char* expected_language_code_pairs[] = { "1_de", "1_en", "54_en", "82_en", "82_ko", }; for (int i = 0; i < get_test_prefix_language_code_pairs_size(); ++i) { EXPECT_STREQ(expected_language_code_pairs[i], language_code_pairs[i]); } const PrefixDescriptions* desc_1_de = get_test_prefix_descriptions(0); ASSERT_EQ(2, desc_1_de->prefixes_size); const int32 expected_prefixes[] = {1201, 1650}; const char* expected_descriptions[] = { "New Jersey", "Kalifornien", }; for (int i = 0; i < desc_1_de->prefixes_size; ++i) { EXPECT_EQ(expected_prefixes[i], desc_1_de->prefixes[i]); EXPECT_STREQ(expected_descriptions[i], desc_1_de->descriptions[i]); } ASSERT_EQ(1, desc_1_de->possible_lengths_size); const int expected_lengths[] = {4}; for (int i = 0; i < desc_1_de->possible_lengths_size; ++i) { EXPECT_EQ(expected_lengths[i], desc_1_de->possible_lengths[i]); } } } }
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/src/phonenumbers/geocoding/geocoding_data.h
https://github.com/google/libphonenumber/blob/9aa9aaa39ad8098aef56071d2df4f6f8d251c98b/cpp/test/phonenumbers/geocoding/geocoding_data_test.cc
9aa9aaa39ad8098aef56071d2df4f6f8d251c98b
e162909f-8720-485d-a783-1593f03d6009
cpp
google/langsvr
buffer_writer
src/buffer_writer.cc
src/buffer_writer_test.cc
#include "langsvr/buffer_writer.h" namespace langsvr { BufferWriter::BufferWriter() = default; Result<SuccessType> BufferWriter::Write(const std::byte* in, size_t count) { size_t at = buffer.size(); buffer.resize(at + count); memcpy(&buffer[at], in, count); return Success; } std::string_view BufferWriter::BufferString() const { if (buffer.empty()) { return ""; } auto* data = reinterpret_cast<const char*>(&buffer[0]); static_assert(sizeof(std::byte) == sizeof(char), "length needs calculation"); return std::string_view(data, buffer.size()); } }
#include "langsvr/buffer_writer.h" #include "gmock/gmock.h" namespace langsvr { namespace { template <typename T, typename U> std::vector<T> Cast(const std::vector<U>& in) { std::vector<T> out; out.resize(in.size()); for (size_t i = 0, n = in.size(); i < n; i++) { out[i] = static_cast<T>(in[i]); } return out; } TEST(BufferWriterTest, String) { BufferWriter writer; EXPECT_EQ(writer.String("hello world"), Success); EXPECT_THAT(Cast<int>(writer.buffer), testing::ElementsAre(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100)); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/buffer_writer.cc
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/buffer_writer_test.cc
303c526231a90049a3e384549720f3fbd453cf66
4a4ecea8-5f00-46ff-b387-1843c5c83db4
cpp
google/langsvr
buffer_reader
src/buffer_reader.cc
src/buffer_reader_test.cc
#include "langsvr/buffer_reader.h" #include <cstring> namespace langsvr { BufferReader::~BufferReader() = default; size_t BufferReader::Read(std::byte* out, size_t count) { size_t n = std::min(count, bytes_remaining_); memcpy(out, data_, n); data_ += n; bytes_remaining_ -= n; return n; } }
#include "langsvr/buffer_reader.h" #include "gtest/gtest.h" namespace langsvr { namespace { template <typename... ARGS> auto Data(ARGS&&... args) { return std::vector{std::byte{static_cast<uint8_t>(args)}...}; } TEST(BufferReaderTest, String) { BufferReader reader{"hello world"}; auto first = reader.String(5); ASSERT_EQ(first, Success); EXPECT_EQ(first.Get(), "hello"); auto second = reader.String(6); ASSERT_EQ(second, Success); EXPECT_EQ(second.Get(), " world"); auto third = reader.String(1); EXPECT_NE(third, Success); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/buffer_reader.cc
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/buffer_reader_test.cc
303c526231a90049a3e384549720f3fbd453cf66
b0c69f73-dc57-4fc8-8147-50f1158eaf32
cpp
google/langsvr
session
src/session.cc
src/session_test.cc
#include "langsvr/session.h" #include <string> #include "langsvr/json/builder.h" namespace langsvr { Result<SuccessType> Session::Receive(std::string_view json) { auto json_builder = json::Builder::Create(); auto object = json_builder->Parse(json); if (object != Success) { return object.Failure(); } auto method = object.Get()->Get<json::String>("method"); if (method != Success) { auto id = object.Get()->Get<json::I64>("id"); if (id != Success) { return id.Failure(); } auto handler_it = response_handlers_.find(id.Get()); if (handler_it == response_handlers_.end()) { return Failure{"received response for unknown request with ID " + std::to_string(id.Get())}; } auto handler = std::move(handler_it->second); response_handlers_.erase(handler_it); return handler(*object.Get()); } if (object.Get()->Has("id")) { auto id = object.Get()->Get<json::I64>("id"); if (id != Success) { return id.Failure(); } auto it = request_handlers_.find(method.Get()); if (it == request_handlers_.end()) { return Failure{"no handler registered for request method '" + method.Get() + "'"}; } auto& request_handler = it->second; auto result = request_handler.function(*object.Get(), *json_builder.get()); if (result != Success) { return result.Failure(); } std::array response_members{ json::Builder::Member{"id", json_builder->I64(id.Get())}, result.Get(), }; auto* response = json_builder->Object(response_members); if (auto res = SendJson(response->Json()); res != Success) { return res.Failure(); } if (request_handler.post_send) { request_handler.post_send(); } } else { auto it = notification_handlers_.find(method.Get()); if (it == notification_handlers_.end()) { return Failure{"no handler registered for request method '" + method.Get() + "'"}; } auto& notification_handler = it->second; return notification_handler.function(*object.Get()); } return Success; } Result<SuccessType> Session::SendJson(std::string_view msg) { if (!sender_) [[unlikely]] { return Failure{"no sender set"}; } return sender_(msg); } }
#include "langsvr/lsp/lsp.h" #include "langsvr/session.h" #include <gtest/gtest.h> #include "langsvr/json/builder.h" #include "langsvr/lsp/decode.h" #include "gmock/gmock.h" #include "langsvr/result.h" namespace langsvr { namespace { Result<lsp::InitializeRequest> GetInitializeRequest() { static constexpr std::string_view kJSON = R"({"processId":71875,"clientInfo":{"name":"My Awesome Editor","version":"1.2.3"},"locale":"en-gb","rootPath":"/home/bob/src/langsvr","rootUri":"file: auto b = json::Builder::Create(); auto msg = b->Parse(kJSON); if (msg != Success) { return msg.Failure(); } lsp::InitializeRequest request; if (auto res = lsp::Decode(*msg.Get(), request); res != Success) { return res.Failure(); } return request; } TEST(Session, InitializeRequest_ResultOrFailure) { auto request = GetInitializeRequest(); ASSERT_EQ(request, Success); Session server_session; Session client_session; client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); }); server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); }); bool handler_called = false; server_session.Register([&](const lsp::InitializeRequest& init) -> Result<lsp::InitializeResult, lsp::InitializeError> { handler_called = true; EXPECT_EQ(request, init); lsp::InitializeResult res; res.capabilities.hover_provider = true; return res; }); auto response_future = client_session.Send(request.Get()); ASSERT_EQ(response_future, Success); EXPECT_TRUE(handler_called); auto response = response_future.Get().get(); ASSERT_EQ(response, Success); lsp::InitializeResult expected; expected.capabilities.hover_provider = true; EXPECT_EQ(response.Get(), expected); } TEST(Session, InitializeRequest_ResultOnly) { auto request = GetInitializeRequest(); ASSERT_EQ(request, Success); Session server_session; Session client_session; client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); }); server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); }); bool handler_called = false; server_session.Register([&](const lsp::InitializeRequest& init) { handler_called = true; EXPECT_EQ(request, init); lsp::InitializeResult res; res.capabilities.hover_provider = true; return res; }); auto response_future = client_session.Send(request.Get()); ASSERT_EQ(response_future, Success); EXPECT_TRUE(handler_called); auto response = response_future.Get().get(); ASSERT_EQ(response, Success); lsp::InitializeResult expected; expected.capabilities.hover_provider = true; EXPECT_EQ(response.Get(), expected); } TEST(Session, InitializeRequest_FailureOnly) { auto request = GetInitializeRequest(); ASSERT_EQ(request, Success); Session server_session; Session client_session; client_session.SetSender([&](std::string_view msg) { return server_session.Receive(msg); }); server_session.SetSender([&](std::string_view msg) { return client_session.Receive(msg); }); bool handler_called = false; server_session.Register([&](const lsp::InitializeRequest& init) { handler_called = true; EXPECT_EQ(request, init); lsp::InitializeError err; err.retry = true; return err; }); auto response_future = client_session.Send(request.Get()); ASSERT_EQ(response_future, Success); EXPECT_TRUE(handler_called); auto response = response_future.Get().get(); ASSERT_NE(response, Success); lsp::InitializeError expected; expected.retry = true; EXPECT_EQ(response.Failure(), expected); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/session.cc
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/session_test.cc
303c526231a90049a3e384549720f3fbd453cf66
f529b4b2-96b8-494a-bfea-07202301e8d3
cpp
google/langsvr
content_stream
src/content_stream.cc
src/content_stream_test.cc
#include "langsvr/content_stream.h" #include <sstream> #include <string> #include "langsvr/reader.h" #include "langsvr/writer.h" #include "src/utils/replace_all.h" namespace langsvr { namespace { static constexpr std::string_view kContentLength = "Content-Length: "; Result<SuccessType> Match(Reader& reader, std::string_view str) { auto got = reader.String(str.size()); if (got != Success) { return got.Failure(); } if (got.Get() != str) { std::stringstream err; err << "expected '" << str << "' got '" << got.Get() << "'"; return Failure{err.str()}; } return Success; } } Result<std::string> ReadContent(Reader& reader) { if (auto match = Match(reader, kContentLength); match != Success) { return match.Failure(); } uint64_t len = 0; while (true) { char c = 0; if (auto read = reader.Read(reinterpret_cast<std::byte*>(&c), sizeof(c)); read != sizeof(c)) { return Failure{"end of stream while parsing content length"}; } if (c >= '0' && c <= '9') { len = len * 10 + static_cast<uint64_t>(c - '0'); continue; } if (c == '\r') { break; } return Failure{"invalid content length value"}; } auto got = reader.String(3); if (got != Success) { return got.Failure(); } if (got.Get() != "\n\r\n") { auto fmt = [](std::string s) { s = ReplaceAll(s, "\n", "␊"); s = ReplaceAll(s, "\r", "␍"); return s; }; std::stringstream err; err << "expected '␍␊␍␊' got '␍" << fmt(got.Get()) << "'"; return Failure{err.str()}; } return reader.String(len); } Result<SuccessType> WriteContent(Writer& writer, std::string_view content) { std::stringstream ss; ss << kContentLength << content.length() << "\r\n\r\n" << content; return writer.String(ss.str()); } }
#include "langsvr/content_stream.h" #include "gtest/gtest.h" #include "langsvr/buffer_reader.h" #include "langsvr/buffer_writer.h" namespace langsvr { namespace { TEST(ReadContent, Empty) { BufferReader reader(""); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "EOF"); } TEST(ReadContent, InvalidContentLength) { BufferReader reader("Content-Length: apples"); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "invalid content length value"); } TEST(ReadContent, MissingFirstCR) { BufferReader reader("Content-Length: 10\r "); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "expected '␍␊␍␊' got '␍ '"); } TEST(ReadContent, MissingSecondLF) { BufferReader reader("Content-Length: 10\r\n "); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "expected '␍␊␍␊' got '␍␊ '"); } TEST(ReadContent, MissingSecondCR) { BufferReader reader("Content-Length: 10\r\n\r "); auto got = ReadContent(reader); EXPECT_NE(got, Success); EXPECT_EQ(got.Failure().reason, "expected '␍␊␍␊' got '␍␊␍ '"); } TEST(ReadContent, ValidMessage) { BufferReader reader("Content-Length: 11\r\n\r\nhello world"); auto got = ReadContent(reader); EXPECT_EQ(got, Success); EXPECT_EQ(got.Get(), "hello world"); } TEST(ReadContent, BufferTooShort) { BufferReader reader("Content-Length: 99\r\n\r\nhello world"); auto got = ReadContent(reader); EXPECT_NE(got, Success); } TEST(ReadContent, ValidMessages) { BufferReader reader("Content-Length: 5\r\n\r\nhelloContent-Length: 5\r\n\r\nworld"); { auto got = ReadContent(reader); EXPECT_EQ(got, "hello"); } { auto got = ReadContent(reader); EXPECT_EQ(got, "world"); } } TEST(WriteContent, Single) { BufferWriter writer; auto got = WriteContent(writer, "hello world"); EXPECT_EQ(got, Success); EXPECT_EQ(writer.BufferString(), "Content-Length: 11\r\n\r\nhello world"); } TEST(WriteContent, Multiple) { BufferWriter writer; { auto got = WriteContent(writer, "hello"); EXPECT_EQ(got, Success); EXPECT_EQ(writer.BufferString(), "Content-Length: 5\r\n\r\nhello"); } { auto got = WriteContent(writer, "world"); EXPECT_EQ(got, Success); EXPECT_EQ(writer.BufferString(), "Content-Length: 5\r\n\r\nhelloContent-Length: 5\r\n\r\nworld"); } } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/content_stream.cc
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/content_stream_test.cc
303c526231a90049a3e384549720f3fbd453cf66
3a0f99c2-f130-42c7-848e-16e5e583a8ca
cpp
google/langsvr
decode
src/lsp/decode.cc
src/lsp/decode_test.cc
#include "langsvr/lsp/decode.h" namespace langsvr::lsp { Result<SuccessType> Decode(const json::Value& v, Null&) { return v.Null(); } Result<SuccessType> Decode(const json::Value& v, Boolean& out) { auto res = v.Bool(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, Integer& out) { auto res = v.I64(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, Uinteger& out) { auto res = v.U64(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, Decimal& out) { auto res = v.F64(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } Result<SuccessType> Decode(const json::Value& v, String& out) { auto res = v.String(); if (res == Success) [[likely]] { out = res.Get(); return Success; } return res.Failure(); } }
#include "langsvr/json/builder.h" #include "langsvr/lsp/lsp.h" #include "langsvr/lsp/printer.h" #include "gmock/gmock.h" namespace langsvr::lsp { namespace { TEST(DecodeTest, ShowDocumentParams) { auto b = json::Builder::Create(); auto parse_res = b->Parse( R"({"selection":{"end":{"character":4,"line":3},"start":{"character":2,"line":1}},"uri":"file.txt"})"); EXPECT_EQ(parse_res, Success); ShowDocumentParams got; auto decode_res = Decode(*parse_res.Get(), got); EXPECT_EQ(decode_res, Success); ShowDocumentParams expected; expected.uri = "file.txt"; expected.selection = Range{{1, 2}, {3, 4}}; EXPECT_EQ(got, expected); } TEST(DecodeTest, ErrNullStruct) { auto b = json::Builder::Create(); auto parse_res = b->Parse("null"); EXPECT_EQ(parse_res, Success); SemanticTokensFullDelta got; auto decode_res = Decode(*parse_res.Get(), got); EXPECT_NE(decode_res, Success); } TEST(DecodeTest, ErrNumberStruct) { auto b = json::Builder::Create(); auto parse_res = b->Parse("42"); EXPECT_EQ(parse_res, Success); SemanticTokensFullDelta got; auto decode_res = Decode(*parse_res.Get(), got); EXPECT_NE(decode_res, Success); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/lsp/decode.cc
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/lsp/decode_test.cc
303c526231a90049a3e384549720f3fbd453cf66
6f7ffe16-c5ff-47d3-844e-a0bf0bc88a11
cpp
google/langsvr
encode
src/lsp/encode.cc
src/lsp/encode_test.cc
#include "langsvr/lsp/encode.h" namespace langsvr::lsp { Result<const json::Value*> Encode(Null, json::Builder& b) { return b.Null(); } Result<const json::Value*> Encode(Boolean in, json::Builder& b) { return b.Bool(in); } Result<const json::Value*> Encode(Integer in, json::Builder& b) { return b.I64(in); } Result<const json::Value*> Encode(Uinteger in, json::Builder& b) { return b.U64(in); } Result<const json::Value*> Encode(Decimal in, json::Builder& b) { return b.F64(in); } Result<const json::Value*> Encode(const String& in, json::Builder& b) { return b.String(in); } }
#include "langsvr/json/builder.h" #include "langsvr/lsp/lsp.h" #include "gmock/gmock.h" namespace langsvr::lsp { namespace { TEST(EncodeTest, ShowDocumentParams) { ShowDocumentParams params; params.uri = "file.txt"; params.selection = Range{{1, 2}, {3, 4}}; auto b = json::Builder::Create(); auto res = Encode(params, *b); EXPECT_EQ(res, Success); EXPECT_EQ( res.Get()->Json(), R"({"selection":{"end":{"character":4,"line":3},"start":{"character":2,"line":1}},"uri":"file.txt"})"); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/lsp/encode.cc
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/lsp/encode_test.cc
303c526231a90049a3e384549720f3fbd453cf66
7019c30e-0cbb-4217-afdf-ec0d4e20abb2
cpp
google/langsvr
traits
include/langsvr/traits.h
src/traits_test.cc
#ifndef LANGSVR_TRAITS_H_ #define LANGSVR_TRAITS_H_ #include <string> #include <tuple> namespace langsvr { template <typename SUCCESS_TYPE, typename FAILURE_TYPE> struct Result; } namespace langsvr::detail { template <int N, typename... Types> using NthTypeOf = typename std::tuple_element<N, std::tuple<Types...>>::type; template <typename RETURN, typename... PARAMETERS> struct Signature { using ret = RETURN; using parameters = std::tuple<PARAMETERS...>; template <std::size_t N> using parameter = NthTypeOf<N, PARAMETERS...>; static constexpr std::size_t parameter_count = sizeof...(PARAMETERS); }; template <typename F> struct SignatureOf { using type = typename SignatureOf<decltype(&F::operator())>::type; }; template <typename R, typename... ARGS> struct SignatureOf<R (*)(ARGS...)> { using type = Signature<typename std::decay<R>::type, typename std::decay<ARGS>::type...>; }; template <typename R, typename C, typename... ARGS> struct SignatureOf<R (C::*)(ARGS...)> { using type = Signature<typename std::decay<R>::type, typename std::decay<ARGS>::type...>; }; template <typename R, typename C, typename... ARGS> struct SignatureOf<R (C::*)(ARGS...) const> { using type = Signature<typename std::decay<R>::type, typename std::decay<ARGS>::type...>; }; template <typename T, typename... TYPES> struct TypeIndexHelper; template <typename T> struct TypeIndexHelper<T> { static const size_t value = 0; }; template <typename T, typename FIRST, typename... OTHERS> struct TypeIndexHelper<T, FIRST, OTHERS...> { static const size_t value = std::is_same_v<T, FIRST> ? 0 : 1 + TypeIndexHelper<T, OTHERS...>::value; }; template <typename T, typename... TYPES> struct TypeIndex { static const size_t value = TypeIndexHelper<T, TYPES...>::value; static_assert(value < sizeof...(TYPES), "type not found"); }; template <typename LHS, typename RHS, typename = void> struct HasOperatorShiftLeft : std::false_type {}; template <typename LHS, typename RHS> struct HasOperatorShiftLeft<LHS, RHS, std::void_t<decltype((std::declval<LHS>() << std::declval<RHS>()))>> : std::true_type {}; template <typename T, typename = void> struct IsResult : std::false_type {}; template <typename SUCCESS, typename FAILURE> struct IsResult<Result<SUCCESS, FAILURE>> : std::true_type {}; } namespace langsvr { template <typename F> using SignatureOf = typename detail::SignatureOf<std::decay_t<F>>::type; template <typename F, std::size_t N> using ParameterType = typename SignatureOf<std::decay_t<F>>::template parameter<N>; template <typename F> using ReturnType = typename SignatureOf<std::decay_t<F>>::ret; template <typename T, typename... TYPES> static constexpr size_t TypeIndex = detail::TypeIndex<T, TYPES...>::value; template <typename T, typename... TYPES> static constexpr bool TypeIsIn = (std::is_same_v<T, TYPES> || ...); template <typename LHS, typename RHS> static constexpr bool HasOperatorShiftLeft = detail::HasOperatorShiftLeft<LHS, RHS>::value; template <typename T> static constexpr bool IsStringLike = std::is_same_v<std::decay_t<T>, std::string> || std::is_same_v<std::decay_t<T>, std::string_view> || std::is_same_v<std::decay_t<T>, const char*> || std::is_same_v<std::decay_t<T>, char*>; template <typename T> static constexpr bool IsResult = detail::IsResult<T>::value; } #endif
#include "langsvr/traits.h" #include <functional> namespace langsvr { namespace { static_assert(TypeIndex<int, int, bool, float> == 0); static_assert(TypeIndex<bool, int, bool, float> == 1); static_assert(TypeIndex<float, int, bool, float> == 2); struct S {}; void F1(S) {} void F3(int, S, float) {} struct StaticTests { [[maybe_unused]] void Function() { F1({}); F3(0, {}, 0); static_assert(std::is_same_v<ParameterType<decltype(&F1), 0>, S>); static_assert(std::is_same_v<ParameterType<decltype(&F3), 0>, int>); static_assert(std::is_same_v<ParameterType<decltype(&F3), 1>, S>); static_assert(std::is_same_v<ParameterType<decltype(&F3), 2>, float>); static_assert(std::is_same_v<ReturnType<decltype(&F1)>, void>); static_assert(std::is_same_v<ReturnType<decltype(&F3)>, void>); static_assert(SignatureOf<decltype(&F1)>::parameter_count == 1); static_assert(SignatureOf<decltype(&F3)>::parameter_count == 3); } [[maybe_unused]] void Method() { class C { public: void F1(S) {} void F3(int, S, float) {} }; C().F1({}); C().F3(0, {}, 0); static_assert(std::is_same_v<ParameterType<decltype(&C::F1), 0>, S>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 0>, int>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 1>, S>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 2>, float>); static_assert(std::is_same_v<ReturnType<decltype(&C::F1)>, void>); static_assert(std::is_same_v<ReturnType<decltype(&C::F3)>, void>); static_assert(SignatureOf<decltype(&C::F1)>::parameter_count == 1); static_assert(SignatureOf<decltype(&C::F3)>::parameter_count == 3); } [[maybe_unused]] void ConstMethod() { class C { public: void F1(S) const {} void F3(int, S, float) const {} }; C().F1({}); C().F3(0, {}, 0); static_assert(std::is_same_v<ParameterType<decltype(&C::F1), 0>, S>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 0>, int>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 1>, S>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 2>, float>); static_assert(std::is_same_v<ReturnType<decltype(&C::F1)>, void>); static_assert(std::is_same_v<ReturnType<decltype(&C::F3)>, void>); static_assert(SignatureOf<decltype(&C::F1)>::parameter_count == 1); static_assert(SignatureOf<decltype(&C::F3)>::parameter_count == 3); } [[maybe_unused]] void StaticMethod() { class C { public: static void F1(S) {} static void F3(int, S, float) {} }; C::F1({}); C::F3(0, {}, 0); static_assert(std::is_same_v<ParameterType<decltype(&C::F1), 0>, S>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 0>, int>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 1>, S>); static_assert(std::is_same_v<ParameterType<decltype(&C::F3), 2>, float>); static_assert(std::is_same_v<ReturnType<decltype(&C::F1)>, void>); static_assert(std::is_same_v<ReturnType<decltype(&C::F3)>, void>); static_assert(SignatureOf<decltype(&C::F1)>::parameter_count == 1); static_assert(SignatureOf<decltype(&C::F3)>::parameter_count == 3); } [[maybe_unused]] void FunctionLike() { using F1 = std::function<void(S)>; using F3 = std::function<void(int, S, float)>; static_assert(std::is_same_v<ParameterType<F1, 0>, S>); static_assert(std::is_same_v<ParameterType<F3, 0>, int>); static_assert(std::is_same_v<ParameterType<F3, 1>, S>); static_assert(std::is_same_v<ParameterType<F3, 2>, float>); static_assert(std::is_same_v<ReturnType<F1>, void>); static_assert(std::is_same_v<ReturnType<F3>, void>); static_assert(SignatureOf<F1>::parameter_count == 1); static_assert(SignatureOf<F3>::parameter_count == 3); } [[maybe_unused]] void Lambda() { auto l1 = [](S) {}; auto l3 = [](int, S, float) {}; static_assert(std::is_same_v<ParameterType<decltype(l1), 0>, S>); static_assert(std::is_same_v<ParameterType<decltype(l3), 0>, int>); static_assert(std::is_same_v<ParameterType<decltype(l3), 1>, S>); static_assert(std::is_same_v<ParameterType<decltype(l3), 2>, float>); static_assert(std::is_same_v<ReturnType<decltype(l1)>, void>); static_assert(std::is_same_v<ReturnType<decltype(l3)>, void>); static_assert(SignatureOf<decltype(l1)>::parameter_count == 1); static_assert(SignatureOf<decltype(l3)>::parameter_count == 3); } }; } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/include/langsvr/traits.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/traits_test.cc
303c526231a90049a3e384549720f3fbd453cf66
243c6b17-25a6-4704-95ee-94c556bbfcf9
cpp
google/langsvr
result
include/langsvr/result.h
src/result_test.cc
#ifndef LANGSVR_UTILS_RESULT_RESULT_H_ #define LANGSVR_UTILS_RESULT_RESULT_H_ #include <cassert> #include <ostream> #include <string> #include <utility> #include <variant> #include "langsvr/traits.h" namespace langsvr { struct SuccessType {}; static constexpr const SuccessType Success; struct Failure { std::string reason; }; static inline std::ostream& operator<<(std::ostream& out, const Failure& failure) { return out << failure.reason; } template <typename SUCCESS_TYPE, typename FAILURE_TYPE = Failure> struct [[nodiscard]] Result { using ResultSuccess = SUCCESS_TYPE; using ResultFailure = FAILURE_TYPE; static_assert(!std::is_same_v<SUCCESS_TYPE, FAILURE_TYPE>, "Result must not have the same type for SUCCESS_TYPE and FAILURE_TYPE"); Result() : value(std::monostate{}) {} Result(const SUCCESS_TYPE& success) : value{success} {} Result(SUCCESS_TYPE&& success) : value(std::move(SUCCESS_TYPE(std::move(success)))) {} Result(const FAILURE_TYPE& failure) : value{failure} {} Result(FAILURE_TYPE&& failure) : value{std::move(failure)} {} template <typename S, typename F, typename = std::void_t<decltype(SUCCESS_TYPE{std::declval<S>()}), decltype(FAILURE_TYPE{std::declval<F>()})>> Result(const Result<S, F>& other) { if (other == Success) { value = SUCCESS_TYPE{other.Get()}; } else { value = FAILURE_TYPE{other.Failure()}; } } const SUCCESS_TYPE* operator->() const { Validate(); return &(Get()); } SUCCESS_TYPE* operator->() { Validate(); return &(Get()); } const SUCCESS_TYPE& Get() const { Validate(); return std::get<SUCCESS_TYPE>(value); } SUCCESS_TYPE& Get() { Validate(); return std::get<SUCCESS_TYPE>(value); } SUCCESS_TYPE&& Move() { Validate(); return std::get<SUCCESS_TYPE>(std::move(value)); } const FAILURE_TYPE& Failure() const { Validate(); return std::get<FAILURE_TYPE>(value); } template <typename T> bool operator==(const Result& other) const { return value == other.value; } template <typename T> bool operator==(const T& val) const { Validate(); using D = std::decay_t<T>; static constexpr bool is_success = std::is_same_v<D, SuccessType>; static constexpr bool is_success_ty = std::is_same_v<D, SUCCESS_TYPE> || (IsStringLike<SUCCESS_TYPE> && IsStringLike<D>); static constexpr bool is_failure_ty = std::is_same_v<D, FAILURE_TYPE> || (IsStringLike<FAILURE_TYPE> && IsStringLike<D>); static_assert(is_success || is_success_ty || is_failure_ty, "unsupported type for Result equality operator"); static_assert(!(is_success_ty && is_failure_ty), "ambiguous success / failure type for Result equality operator"); if constexpr (is_success) { return std::holds_alternative<SUCCESS_TYPE>(value); } else if constexpr (is_success_ty) { if (auto* v = std::get_if<SUCCESS_TYPE>(&value)) { return *v == val; } return false; } else if constexpr (is_failure_ty) { if (auto* v = std::get_if<FAILURE_TYPE>(&value)) { return *v == val; } return false; } } template <typename T> bool operator!=(const T& val) const { return !(*this == val); } private: void Validate() const { assert(!std::holds_alternative<std::monostate>(value)); } std::variant<std::monostate, SUCCESS_TYPE, FAILURE_TYPE> value; }; template <typename SUCCESS, typename FAILURE> static inline std::ostream& operator<<(std::ostream& out, const Result<SUCCESS, FAILURE>& res) { if (res == Success) { if constexpr (HasOperatorShiftLeft<std::ostream&, SUCCESS>) { return out << "success: " << res.Get(); } else { return out << "success"; } } else { if constexpr (HasOperatorShiftLeft<std::ostream&, FAILURE>) { return out << "failure: " << res.Failure(); } else { return out << "failure"; } } } } #endif
#include "langsvr/result.h" #include <string> #include "gmock/gmock.h" namespace langsvr { namespace { struct S { int value; }; static inline bool operator==(const S& a, const S& b) { return a.value == b.value; } TEST(ResultTest, SuccessInt) { auto r = Result<int>(123); ASSERT_EQ(r, Success); EXPECT_EQ(r.Get(), 123); } TEST(ResultTest, SuccessStruct) { auto r = Result<S>({123}); ASSERT_EQ(r, Success); EXPECT_EQ(r->value, 123); EXPECT_EQ(r, S{123}); } TEST(ResultTest, Failure) { auto r = Result<int>(Failure{}); EXPECT_NE(r, Success); } TEST(ResultTest, CustomFailure) { auto r = Result<int, std::string>("oh noes!"); EXPECT_NE(r, Success); EXPECT_EQ(r.Failure(), "oh noes!"); } TEST(ResultTest, ValueCast) { struct X {}; struct Y : X {}; Y* y = nullptr; auto r_y = Result<Y*>{y}; auto r_x = Result<X*>{r_y}; (void)r_x; (void)r_y; } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/include/langsvr/result.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/result_test.cc
303c526231a90049a3e384549720f3fbd453cf66
b428a4e6-f411-4fe5-b691-f4f37449cc1c
cpp
google/langsvr
optional
include/langsvr/optional.h
src/optional_test.cc
#ifndef LANGSVR_OPTIONAL_H_ #define LANGSVR_OPTIONAL_H_ #include <cassert> #include <type_traits> #include <utility> namespace langsvr { template <typename T> struct Optional { Optional() = default; ~Optional() { Reset(); } Optional(const Optional& other) { *this = other; } Optional(Optional&& other) { *this = std::move(other); } Optional(const T& other) { *this = other; } Optional(T&& other) { *this = std::move(other); } void Reset() { if (ptr) { delete ptr; ptr = nullptr; } } Optional& operator=(const Optional& other) { Reset(); if (other.ptr) { ptr = new T(*other); } return *this; } Optional& operator=(Optional&& other) { Reset(); ptr = other.ptr; other.ptr = nullptr; return *this; } Optional& operator=(const T& value) { Reset(); if (!ptr) { ptr = new T(value); } return *this; } Optional& operator=(T&& value) { Reset(); if (!ptr) { ptr = new T(std::move(value)); } return *this; } operator bool() const { return ptr != nullptr; } bool operator!() const { return ptr == nullptr; } T* operator->() { return &Get(); } const T* operator->() const { return &Get(); } T& operator*() { return Get(); } const T& operator*() const { return Get(); } template <typename V> bool operator==(V&& value) const { if constexpr (std::is_same_v<Optional, std::decay_t<V>>) { return (!*this && !value) || (*this && value && (Get() == value.Get())); } else { if (!ptr) { return false; } return Get() == std::forward<V>(value); } } template <typename V> bool operator!=(V&& value) const { return !(*this == std::forward<V>(value)); } private: T& Get() { assert(ptr); return *ptr; } const T& Get() const { assert(ptr); return *ptr; } T* ptr = nullptr; }; } #endif
#include "langsvr/optional.h" #include "gmock/gmock.h" namespace langsvr { namespace { TEST(OptionalTest, CtorNoArgs) { Optional<std::string> opt; EXPECT_FALSE(opt); EXPECT_TRUE(!opt); EXPECT_NE(opt, "hello"); } TEST(OptionalTest, CopyCtorWithValue) { std::string val{"hello"}; Optional<std::string> opt{val}; EXPECT_TRUE(opt); EXPECT_FALSE(!opt); EXPECT_EQ(opt, "hello"); EXPECT_NE(opt, "world"); EXPECT_EQ(*opt, "hello"); } TEST(OptionalTest, MoveCtorWithValue) { std::string val{"hello"}; Optional<std::string> opt{std::move(val)}; EXPECT_TRUE(opt); EXPECT_FALSE(!opt); EXPECT_EQ(opt, "hello"); EXPECT_NE(opt, "world"); EXPECT_EQ(*opt, "hello"); } TEST(OptionalTest, CopyCtorWithOptional) { Optional<std::string> other{"hello"}; Optional<std::string> opt{other}; EXPECT_TRUE(opt); EXPECT_FALSE(!opt); EXPECT_EQ(opt, "hello"); EXPECT_NE(opt, "world"); EXPECT_EQ(*opt, "hello"); } TEST(OptionalTest, MoveCtorWithOptional) { Optional<std::string> other{"hello"}; Optional<std::string> opt{std::move(other)}; EXPECT_TRUE(opt); EXPECT_FALSE(!opt); EXPECT_EQ(opt, "hello"); EXPECT_NE(opt, "world"); EXPECT_EQ(*opt, "hello"); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/include/langsvr/optional.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/optional_test.cc
303c526231a90049a3e384549720f3fbd453cf66
a3ced6ed-efb3-49e4-9e6d-da590ac7fa65
cpp
google/langsvr
one_of
include/langsvr/one_of.h
src/one_of_test.cc
#ifndef LANGSVR_ONE_OF_H_ #define LANGSVR_ONE_OF_H_ #include <memory> #include <type_traits> #include <utility> #include "langsvr/traits.h" namespace langsvr { template <typename... TYPES> struct OneOf { template <typename T> static constexpr bool IsValidType = TypeIsIn<std::decay_t<T>, TYPES...>; OneOf() = default; ~OneOf() { Reset(); } template <typename T, typename = std::enable_if_t<IsValidType<T>>> OneOf(T&& value) { Set(std::forward<T>(value)); } OneOf(const OneOf& other) { *this = other; } OneOf(OneOf&& other) { ptr = other.ptr; kind = other.kind; other.ptr = nullptr; } OneOf& operator=(const OneOf& other) { Reset(); auto copy = [this](auto* p) { if (p) { this->ptr = new std::decay_t<decltype(*p)>(*p); return true; } return false; }; (copy(other.Get<TYPES>()) || ...); kind = other.kind; return *this; } template <typename T, typename = std::enable_if_t<IsValidType<T>>> OneOf& operator=(T&& value) { Set(std::forward<T>(value)); return *this; } bool operator==(const OneOf& other) const { return Visit([&](const auto& value) { using T = std::decay_t<decltype(value)>; if (auto* other_value = other.Get<T>()) { return value == *other_value; } return false; }); } bool operator!=(const OneOf& other) const { return !(*this == other); } void Reset() { (delete Get<TYPES>(), ...); ptr = nullptr; kind = kNoKind; } template <typename T, typename = std::enable_if_t<IsValidType<T>>> void Set(T&& value) { using D = std::decay_t<T>; Reset(); kind = static_cast<uint8_t>(TypeIndex<D, TYPES...>); ptr = new D(std::forward<T>(value)); } template <typename T> bool Is() const { return kind == TypeIndex<T, TYPES...>; } template <typename T> T* Get() { return this->Is<T>() ? static_cast<T*>(ptr) : nullptr; } template <typename T> const T* Get() const { return this->Is<T>() ? static_cast<const T*>(ptr) : nullptr; } template <typename F> auto Visit(F&& cb) const { using FIRST = typename std::tuple_element<0, std::tuple<TYPES...>>::type; using RET = decltype(cb(std::declval<FIRST&>())); if constexpr (std::is_void_v<RET>) { auto call = [&](auto* p) { if (p) { cb(*p); } }; (call(Get<TYPES>()), ...); } else { RET ret{}; auto call = [&](auto* p) { if (p) { ret = cb(*p); } }; (call(Get<TYPES>()), ...); return ret; } } private: static_assert(sizeof...(TYPES) < 255); static constexpr uint8_t kNoKind = 0xff; void* ptr = nullptr; uint8_t kind = 0xff; }; } #endif
#include "langsvr/one_of.h" #include "gmock/gmock.h" namespace langsvr { namespace { TEST(OneOfTest, CtorNoArgs) { OneOf<int, std::string, float> oneof; EXPECT_FALSE(oneof.Is<int>()); EXPECT_FALSE(oneof.Is<std::string>()); EXPECT_FALSE(oneof.Is<float>()); oneof.Visit([&](auto&) { FAIL() << "should not be called"; }); } TEST(OneOfTest, CopyCtorWithValue) { std::string val{"hello"}; OneOf<int, std::string, float> oneof{val}; ASSERT_TRUE(oneof.Is<std::string>()); EXPECT_FALSE(oneof.Is<int>()); EXPECT_FALSE(oneof.Is<float>()); EXPECT_EQ(*oneof.Get<std::string>(), std::string("hello")); std::variant<int, std::string, float> visit_val; auto res = oneof.Visit([&](auto& v) { visit_val = v; return 42; }); EXPECT_EQ(res, 42); ASSERT_TRUE(std::holds_alternative<std::string>(visit_val)); EXPECT_EQ(std::get<std::string>(visit_val), std::string("hello")); } TEST(OneOfTest, MoveCtorWithValue) { std::string val{"hello"}; OneOf<int, std::string, float> oneof{std::move(val)}; ASSERT_TRUE(oneof.Is<std::string>()); EXPECT_FALSE(oneof.Is<int>()); EXPECT_FALSE(oneof.Is<float>()); EXPECT_EQ(*oneof.Get<std::string>(), std::string("hello")); std::variant<int, std::string, float> visit_val; auto res = oneof.Visit([&](auto& v) { visit_val = v; return 42; }); EXPECT_EQ(res, 42); ASSERT_TRUE(std::holds_alternative<std::string>(visit_val)); EXPECT_EQ(std::get<std::string>(visit_val), std::string("hello")); } TEST(OneOfTest, CopyCtorWithOneOf) { OneOf<int, std::string, float> other{std::string("hello")}; OneOf<int, std::string, float> oneof{other}; ASSERT_TRUE(oneof.Is<std::string>()); EXPECT_FALSE(oneof.Is<int>()); EXPECT_FALSE(oneof.Is<float>()); EXPECT_EQ(*oneof.Get<std::string>(), std::string("hello")); std::variant<int, std::string, float> visit_val; auto res = oneof.Visit([&](auto& v) { visit_val = v; return 42; }); EXPECT_EQ(res, 42); ASSERT_TRUE(std::holds_alternative<std::string>(visit_val)); EXPECT_EQ(std::get<std::string>(visit_val), std::string("hello")); } TEST(OneOfTest, MoveCtorWithOneOf) { OneOf<int, std::string, float> other{std::string("hello")}; OneOf<int, std::string, float> oneof{std::move(other)}; ASSERT_TRUE(oneof.Is<std::string>()); EXPECT_FALSE(oneof.Is<int>()); EXPECT_FALSE(oneof.Is<float>()); EXPECT_EQ(*oneof.Get<std::string>(), std::string("hello")); std::variant<int, std::string, float> visit_val; auto res = oneof.Visit([&](auto& v) { visit_val = v; return 42; }); EXPECT_EQ(res, 42); ASSERT_TRUE(std::holds_alternative<std::string>(visit_val)); EXPECT_EQ(std::get<std::string>(visit_val), std::string("hello")); } TEST(OneOfTest, Reset) { OneOf<int, std::string, float> oneof{std::string("hello")}; oneof.Reset(); EXPECT_FALSE(oneof.Is<std::string>()); EXPECT_FALSE(oneof.Is<int>()); EXPECT_FALSE(oneof.Is<float>()); oneof.Visit([&](auto&) { FAIL() << "should not be called"; }); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/include/langsvr/one_of.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/one_of_test.cc
303c526231a90049a3e384549720f3fbd453cf66
44f531c3-4137-4b29-8a03-3fd609e926f9
cpp
google/langsvr
span
include/langsvr/span.h
src/span_test.cc
#ifndef LANGSVR_SPAN_H_ #define LANGSVR_SPAN_H_ #include <array> #include <cstddef> #include <vector> namespace langsvr { template <typename T> class Span { public: Span(T* first, size_t count) : elements_(first), count_(count) {} Span(const std::vector<T>& vec) : elements_(vec.data()), count_(vec.size()) {} template <size_t N> Span(const std::array<T, N>& arr) : elements_(arr.data()), count_(arr.size()) {} const T& front() const { return elements_[0]; } const T& back() const { return elements_[count_ - 1]; } const T& operator[](size_t i) const { return elements_[i]; } const T* begin() const { return &elements_[0]; } const T* end() const { return &elements_[count_]; } size_t size() const { return count_; } private: const T* const elements_; const size_t count_; }; } #endif
#include "langsvr/span.h" #include <vector> #include "gmock/gmock.h" namespace langsvr { namespace { TEST(SpanTest, CtorPtrCount) { int data[]{0, 1, 2, 3}; Span<int> span{&data[0], 4}; EXPECT_EQ(span[0], 0); EXPECT_EQ(span[1], 1); EXPECT_EQ(span[2], 2); EXPECT_EQ(span[3], 3); EXPECT_EQ(span.front(), 0); EXPECT_EQ(span.back(), 3); EXPECT_EQ(span.begin(), &data[0]); EXPECT_EQ(span.end(), &data[3] + 1); } TEST(SpanTest, CtorVector) { std::vector<int> data{0, 1, 2, 3}; Span<int> span{&data[0], 4}; EXPECT_EQ(span[0], 0); EXPECT_EQ(span[1], 1); EXPECT_EQ(span[2], 2); EXPECT_EQ(span[3], 3); EXPECT_EQ(span.front(), 0); EXPECT_EQ(span.back(), 3); EXPECT_EQ(span.begin(), &data[0]); EXPECT_EQ(span.end(), &data[3] + 1); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/include/langsvr/span.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/span_test.cc
303c526231a90049a3e384549720f3fbd453cf66
7c4f1970-d8d3-4a57-b484-7690362ef1d8
cpp
google/langsvr
comparators
include/langsvr/lsp/comparators.h
src/lsp/comparators_test.cc
#ifndef LANGSVR_LSP_COMPARATORS_H_ #define LANGSVR_LSP_COMPARATORS_H_ #include "langsvr/lsp/lsp.h" namespace langsvr::lsp { inline int Compare(Position a, Position b) { if (a.line < b.line) { return -1; } if (a.line > b.line) { return 1; } if (a.character < b.character) { return -1; } if (a.character > b.character) { return 1; } return 0; } inline bool operator<(Position a, Position b) { return Compare(a, b) < 0; } inline bool operator<=(Position a, Position b) { return Compare(a, b) <= 0; } inline bool operator>(Position a, Position b) { return Compare(a, b) > 0; } inline bool operator>=(Position a, Position b) { return Compare(a, b) >= 0; } inline bool ContainsExclusive(Range r, Position p) { return p >= r.start && p < r.end; } inline bool ContainsInclusive(Range r, Position p) { return p >= r.start && p <= r.end; } } #endif
#include "include/langsvr/lsp/comparators.h" #include "langsvr/lsp/lsp.h" #include "langsvr/lsp/printer.h" #include "gmock/gmock.h" namespace langsvr::lsp { namespace { TEST(ComparatorsTest, Position) { const Position pos_1_1{1, 1}; const Position pos_1_2{1, 2}; const Position pos_2_1{2, 1}; const Position pos_2_2{2, 2}; EXPECT_EQ(Compare(pos_1_1, pos_1_1), 0); EXPECT_EQ(Compare(pos_1_1, pos_1_2), -1); EXPECT_EQ(Compare(pos_1_2, pos_1_1), 1); EXPECT_TRUE(pos_1_1 == pos_1_1); EXPECT_FALSE(pos_1_1 != pos_1_1); EXPECT_FALSE(pos_1_1 < pos_1_1); EXPECT_FALSE(pos_1_1 > pos_1_1); EXPECT_TRUE(pos_1_1 <= pos_1_1); EXPECT_TRUE(pos_1_1 >= pos_1_1); EXPECT_FALSE(pos_1_1 == pos_1_2); EXPECT_TRUE(pos_1_1 != pos_1_2); EXPECT_TRUE(pos_1_1 < pos_1_2); EXPECT_FALSE(pos_1_1 > pos_1_2); EXPECT_TRUE(pos_1_1 <= pos_1_2); EXPECT_FALSE(pos_1_1 >= pos_1_2); EXPECT_FALSE(pos_1_2 == pos_1_1); EXPECT_TRUE(pos_1_2 != pos_1_1); EXPECT_FALSE(pos_1_2 < pos_1_1); EXPECT_TRUE(pos_1_2 > pos_1_1); EXPECT_FALSE(pos_1_2 <= pos_1_1); EXPECT_TRUE(pos_1_2 >= pos_1_1); EXPECT_FALSE(pos_1_1 == pos_2_1); EXPECT_TRUE(pos_1_1 != pos_2_1); EXPECT_TRUE(pos_1_1 < pos_2_1); EXPECT_FALSE(pos_1_1 > pos_2_1); EXPECT_TRUE(pos_1_1 <= pos_2_1); EXPECT_FALSE(pos_1_1 >= pos_2_1); EXPECT_FALSE(pos_2_1 == pos_1_1); EXPECT_TRUE(pos_2_1 != pos_1_1); EXPECT_FALSE(pos_2_1 < pos_1_1); EXPECT_TRUE(pos_2_1 > pos_1_1); EXPECT_FALSE(pos_2_1 <= pos_1_1); EXPECT_TRUE(pos_2_1 >= pos_1_1); std::array positions = { pos_2_1, pos_1_2, pos_1_1, pos_2_2, }; std::sort(positions.begin(), positions.end()); std::array positions_sorted = { pos_1_1, pos_1_2, pos_2_1, pos_2_2, }; EXPECT_EQ(positions, positions_sorted); } TEST(ComparatorsTest, ContainsExclusive) { const Position pos_1_1{1, 1}; const Position pos_1_2{1, 2}; const Position pos_2_1{2, 1}; const Position pos_2_2{2, 2}; EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_1_1}, pos_1_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_1_1}, pos_1_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_1_1}, pos_2_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_1_1}, pos_2_2)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_1, pos_1_2}, pos_1_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_1_2}, pos_1_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_1_2}, pos_2_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_1_2}, pos_2_2)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_1, pos_2_1}, pos_1_1)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_1, pos_2_1}, pos_1_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_2_1}, pos_2_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_2_1}, pos_2_2)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_1, pos_2_2}, pos_1_1)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_1, pos_2_2}, pos_1_2)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_1, pos_2_2}, pos_2_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_1, pos_2_2}, pos_2_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_1_2}, pos_1_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_1_2}, pos_1_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_1_2}, pos_2_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_1_2}, pos_2_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_2_1}, pos_1_1)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_2, pos_2_1}, pos_1_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_2_1}, pos_2_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_2_1}, pos_2_2)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_2_2}, pos_1_1)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_2, pos_2_2}, pos_1_2)); EXPECT_TRUE(ContainsExclusive(Range{pos_1_2, pos_2_2}, pos_2_1)); EXPECT_FALSE(ContainsExclusive(Range{pos_1_2, pos_2_2}, pos_2_2)); } TEST(ComparatorsTest, ContainsInclusive) { const Position pos_1_1{1, 1}; const Position pos_1_2{1, 2}; const Position pos_2_1{2, 1}; const Position pos_2_2{2, 2}; EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_1_1}, pos_1_1)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_1, pos_1_1}, pos_1_2)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_1, pos_1_1}, pos_2_1)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_1, pos_1_1}, pos_2_2)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_1_2}, pos_1_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_1_2}, pos_1_2)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_1, pos_1_2}, pos_2_1)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_1, pos_1_2}, pos_2_2)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_2_1}, pos_1_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_2_1}, pos_1_2)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_2_1}, pos_2_1)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_1, pos_2_1}, pos_2_2)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_2_2}, pos_1_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_2_2}, pos_1_2)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_2_2}, pos_2_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_1, pos_2_2}, pos_2_2)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_2, pos_1_2}, pos_1_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_2, pos_1_2}, pos_1_2)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_2, pos_1_2}, pos_2_1)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_2, pos_1_2}, pos_2_2)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_2, pos_2_1}, pos_1_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_2, pos_2_1}, pos_1_2)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_2, pos_2_1}, pos_2_1)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_2, pos_2_1}, pos_2_2)); EXPECT_FALSE(ContainsInclusive(Range{pos_1_2, pos_2_2}, pos_1_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_2, pos_2_2}, pos_1_2)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_2, pos_2_2}, pos_2_1)); EXPECT_TRUE(ContainsInclusive(Range{pos_1_2, pos_2_2}, pos_2_2)); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/include/langsvr/lsp/comparators.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/lsp/comparators_test.cc
303c526231a90049a3e384549720f3fbd453cf66
c4f6349c-d229-4b92-b60f-2e85745f5542
cpp
google/langsvr
builder
include/langsvr/json/builder.h
src/json/builder_test.cc
#ifndef LANGSVR_JSON_BUILDER_ #define LANGSVR_JSON_BUILDER_ #include <memory> #include <type_traits> #include "langsvr/json/value.h" #include "langsvr/span.h" #include "langsvr/traits.h" namespace langsvr::json { class Value; } namespace langsvr::json { class Builder { public: virtual ~Builder(); static std::unique_ptr<Builder> Create(); virtual Result<const Value*> Parse(std::string_view json) = 0; virtual const Value* Null() = 0; virtual const Value* Bool(json::Bool value) = 0; virtual const Value* I64(json::I64 value) = 0; virtual const Value* U64(json::U64 value) = 0; virtual const Value* F64(json::F64 value) = 0; virtual const Value* String(json::String value) = 0; const Value* String(std::string_view value) { return String(json::String(value)); } const Value* String(const char* value) { return String(json::String(value)); } virtual const Value* Array(Span<const Value*> elements) = 0; struct Member { json::String name; const Value* value; }; virtual const Value* Object(Span<Member> members) = 0; template <typename T> auto Create(T&& value) { static constexpr bool is_bool = std::is_same_v<T, json::Bool>; static constexpr bool is_i64 = std::is_integral_v<T> && std::is_signed_v<T>; static constexpr bool is_u64 = std::is_integral_v<T> && std::is_unsigned_v<T>; static constexpr bool is_f64 = std::is_floating_point_v<T>; static constexpr bool is_string = IsStringLike<T>; static_assert(is_bool || is_i64 || is_u64 || is_f64 || is_string); if constexpr (is_bool) { return Bool(std::forward<T>(value)); } else if constexpr (is_i64) { return I64(static_cast<json::I64>(std::forward<T>(value))); } else if constexpr (is_u64) { return U64(static_cast<json::U64>(std::forward<T>(value))); } else if constexpr (is_f64) { return F64(static_cast<json::F64>(std::forward<T>(value))); } else if constexpr (is_string) { return String(std::forward<T>(value)); } } }; } #endif
#include "langsvr/json/builder.h" #include "gtest/gtest.h" #include "src/utils/replace_all.h" namespace langsvr::json { namespace { TEST(JsonBuilder, ParseNull) { auto b = Builder::Create(); auto null_res = b->Parse("null"); ASSERT_EQ(null_res, Success); auto& null = null_res.Get(); EXPECT_EQ(null->Kind(), json::Kind::kNull); EXPECT_EQ(null->Json(), "null"); } TEST(JsonBuilder, ParseBool) { auto b = Builder::Create(); auto true_res = b->Parse("true"); ASSERT_EQ(true_res, Success); auto& true_ = true_res.Get(); EXPECT_EQ(true_->Bool(), true); EXPECT_EQ(true_->Kind(), json::Kind::kBool); EXPECT_EQ(true_->Json(), "true"); } TEST(JsonBuilder, ParseI64) { auto b = Builder::Create(); auto i64_res = b->Parse("9223372036854775807"); ASSERT_EQ(i64_res, Success); auto& i64 = i64_res.Get(); EXPECT_EQ(i64->I64(), static_cast<json::I64>(9223372036854775807)); EXPECT_EQ(i64->Kind(), json::Kind::kI64); EXPECT_EQ(i64->Json(), "9223372036854775807"); } TEST(JsonBuilder, ParseU64) { auto b = Builder::Create(); auto u64_res = b->Parse("9223372036854775808"); ASSERT_EQ(u64_res, Success); auto& u64 = u64_res.Get(); EXPECT_EQ(u64->U64(), static_cast<json::U64>(9223372036854775808u)); EXPECT_EQ(u64->Kind(), json::Kind::kU64); EXPECT_EQ(u64->Json(), "9223372036854775808"); } TEST(JsonBuilder, ParseF64) { auto b = Builder::Create(); auto f64_res = b->Parse("42.0"); ASSERT_EQ(f64_res, Success); auto& f64 = f64_res.Get(); EXPECT_EQ(f64->F64().Get(), 42.0); EXPECT_EQ(f64->Kind(), json::Kind::kF64); EXPECT_EQ(f64->Json(), "42.0"); } TEST(JsonBuilder, ParseString) { auto b = Builder::Create(); auto string_res = b->Parse("\"hello world\""); ASSERT_EQ(string_res, Success); auto& string_ = string_res.Get(); EXPECT_EQ(string_->String(), "hello world"); EXPECT_EQ(string_->Kind(), json::Kind::kString); EXPECT_EQ(string_->Json(), "\"hello world\""); } TEST(JsonBuilder, ParseArray) { auto b = Builder::Create(); auto arr_res = b->Parse("[10, false, \"fish\" ]"); ASSERT_EQ(arr_res, Success); auto& arr = arr_res.Get(); EXPECT_EQ(arr->Kind(), json::Kind::kArray); EXPECT_EQ(ReplaceAll(arr->Json(), " ", ""), "[10,false,\"fish\"]"); EXPECT_EQ(arr->Count(), 3u); EXPECT_EQ(arr->Get<json::I64>(0u), static_cast<json::I64>(10)); EXPECT_EQ(arr->Get<json::Bool>(1u), false); EXPECT_EQ(arr->Get<json::String>(2u), "fish"); auto oob = arr->Get(3); EXPECT_NE(oob, Success); } TEST(JsonBuilder, ParseObject) { auto b = Builder::Create(); auto root_res = b->Parse(R"({"cat": "meow", "ten": 10, "yes": true})"); ASSERT_EQ(root_res, Success); auto& root = root_res.Get(); EXPECT_EQ(root->Kind(), json::Kind::kObject); EXPECT_EQ(ReplaceAll(root->Json(), " ", ""), R"({"cat":"meow","ten":10,"yes":true})"); EXPECT_EQ(root->Count(), 3u); EXPECT_EQ(root->Get<json::String>("cat"), "meow"); EXPECT_EQ(root->Get<json::I64>("ten"), static_cast<json::I64>(10)); EXPECT_EQ(root->Get<json::Bool>("yes"), true); auto missing = root->Get("missing"); EXPECT_NE(missing, Success); } TEST(JsonBuilder, CreateNull) { auto b = Builder::Create(); auto v = b->Null(); EXPECT_EQ(v->Kind(), json::Kind::kNull); EXPECT_EQ(v->Json(), "null"); } TEST(JsonBuilder, CreateBool) { auto b = Builder::Create(); auto v = b->Bool(true); EXPECT_EQ(v->Kind(), json::Kind::kBool); EXPECT_EQ(v->Json(), "true"); } TEST(JsonBuilder, CreateI64) { auto b = Builder::Create(); auto v = b->I64(static_cast<json::I64>(9223372036854775807)); EXPECT_EQ(v->Kind(), json::Kind::kI64); EXPECT_EQ(v->Json(), "9223372036854775807"); } TEST(JsonBuilder, CreateU64) { auto b = Builder::Create(); auto v = b->U64(static_cast<json::U64>(9223372036854775808ul)); EXPECT_EQ(v->Kind(), json::Kind::kU64); EXPECT_EQ(v->Json(), "9223372036854775808"); } TEST(JsonBuilder, CreateF64) { auto b = Builder::Create(); auto v = b->F64(static_cast<json::F64>(42.0)); EXPECT_EQ(v->Kind(), json::Kind::kF64); EXPECT_EQ(v->Json(), "42.0"); } TEST(JsonBuilder, CreateString) { auto b = Builder::Create(); auto v = b->String("hello world"); EXPECT_EQ(v->Kind(), json::Kind::kString); EXPECT_EQ(v->Json(), "\"hello world\""); } TEST(JsonBuilder, CreateArray) { auto b = Builder::Create(); std::vector elements{ b->I64(10), b->Bool(false), b->String("fish"), }; auto v = b->Array(elements); EXPECT_EQ(v->Kind(), json::Kind::kArray); EXPECT_EQ(ReplaceAll(v->Json(), " ", ""), R"([10,false,"fish"])"); } TEST(JsonBuilder, CreateObject) { auto b = Builder::Create(); std::vector members{ Builder::Member{"cat", b->String("meow")}, Builder::Member{"ten", b->I64(10)}, Builder::Member{"yes", b->Bool(true)}, }; auto v = b->Object(members); EXPECT_EQ(v->Kind(), json::Kind::kObject); EXPECT_EQ(ReplaceAll(v->Json(), " ", ""), R"({"cat":"meow","ten":10,"yes":true})"); } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/include/langsvr/json/builder.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/json/builder_test.cc
303c526231a90049a3e384549720f3fbd453cf66
88c2c198-269a-40f5-b83c-69515f289132
cpp
google/langsvr
block_allocator
src/utils/block_allocator.h
src/utils/block_allocator_test.cc
#ifndef SRC_LANGSVR_UTILS_BLOCK_ALLOCATOR_H_ #define SRC_LANGSVR_UTILS_BLOCK_ALLOCATOR_H_ #include <stdint.h> #include <array> #include <cstring> #include <utility> namespace langsvr { template <typename T> inline constexpr T RoundUp(T alignment, T value) { return ((value + alignment - 1) / alignment) * alignment; } template <typename TO, typename FROM> inline TO Bitcast(FROM&& from) { static_assert(sizeof(FROM) == sizeof(TO)); static_assert(std::is_trivially_copyable_v<std::decay_t<FROM>>); static_assert(std::is_trivially_copyable_v<std::decay_t<TO>>); TO to; memcpy(reinterpret_cast<std::byte*>(&to), reinterpret_cast<const std::byte*>(&from), sizeof(TO)); return to; } template <typename T, size_t BLOCK_SIZE = 64 * 1024, size_t BLOCK_ALIGNMENT = 16> class BlockAllocator { struct Pointers { static constexpr size_t kMax = 32; std::array<T*, kMax> ptrs; Pointers* next; Pointers* prev; size_t count; }; struct alignas(BLOCK_ALIGNMENT) Block { uint8_t data[BLOCK_SIZE]; Block* next = nullptr; }; template <bool IS_CONST> class TView; template <bool IS_CONST> class TIterator { using PointerTy = std::conditional_t<IS_CONST, const T*, T*>; public: bool operator==(const TIterator& other) const { return ptrs == other.ptrs && idx == other.idx; } bool operator!=(const TIterator& other) const { return !(*this == other); } TIterator& operator++() { if (ptrs != nullptr) { ++idx; if (idx >= ptrs->count) { idx = 0; ptrs = ptrs->next; } } return *this; } TIterator& operator--() { if (ptrs != nullptr) { if (idx == 0) { ptrs = ptrs->prev; idx = ptrs->count - 1; } --idx; } return *this; } PointerTy operator*() const { return ptrs->ptrs[idx]; } private: friend TView<IS_CONST>; explicit TIterator(const Pointers* p, size_t i) : ptrs(p), idx(i) {} const Pointers* ptrs = nullptr; size_t idx = 0; }; template <bool IS_CONST> class TView { public: TIterator<IS_CONST> begin() const { return TIterator<IS_CONST>{allocator_->data.pointers.root, 0}; } TIterator<IS_CONST> end() const { return TIterator<IS_CONST>{nullptr, 0}; } private: friend BlockAllocator; explicit TView(BlockAllocator const* allocator) : allocator_(allocator) {} BlockAllocator const* const allocator_; }; public: using Iterator = TIterator< false>; using ConstIterator = TIterator< true>; using View = TView<false>; using ConstView = TView<true>; BlockAllocator() = default; BlockAllocator(BlockAllocator&& rhs) { std::swap(data, rhs.data); } BlockAllocator& operator=(BlockAllocator&& rhs) { if (this != &rhs) { Reset(); std::swap(data, rhs.data); } return *this; } ~BlockAllocator() { Reset(); } View Objects() { return View(this); } ConstView Objects() const { return ConstView(this); } template <typename TYPE = T, typename... ARGS> TYPE* Create(ARGS&&... args) { static_assert(std::is_same<T, TYPE>::value || std::is_base_of<T, TYPE>::value, "TYPE does not derive from T"); static_assert(std::is_same<T, TYPE>::value || std::has_virtual_destructor<T>::value, "TYPE requires a virtual destructor when calling Create() for a type " "that is not T"); auto* ptr = Allocate<TYPE>(); new (ptr) TYPE(std::forward<ARGS>(args)...); AddObjectPointer(ptr); data.count++; return ptr; } void Reset() { for (auto ptr : Objects()) { ptr->~T(); } auto* block = data.block.root; while (block != nullptr) { auto* next = block->next; delete block; block = next; } data = {}; } size_t Count() const { return data.count; } private: BlockAllocator(const BlockAllocator&) = delete; BlockAllocator& operator=(const BlockAllocator&) = delete; template <typename TYPE> TYPE* Allocate() { static_assert(sizeof(TYPE) <= BLOCK_SIZE, "Cannot construct TYPE with size greater than BLOCK_SIZE"); static_assert(alignof(TYPE) <= BLOCK_ALIGNMENT, "alignof(TYPE) is greater than ALIGNMENT"); auto& block = data.block; block.current_offset = RoundUp(alignof(TYPE), block.current_offset); if (block.current_offset + sizeof(TYPE) > BLOCK_SIZE) { auto* prev_block = block.current; block.current = new Block; if (!block.current) { return nullptr; } block.current->next = nullptr; block.current_offset = 0; if (prev_block) { prev_block->next = block.current; } else { block.root = block.current; } } auto* base = &block.current->data[0]; auto* ptr = Bitcast<TYPE*>(base + block.current_offset); block.current_offset += sizeof(TYPE); return ptr; } void AddObjectPointer(T* ptr) { auto& pointers = data.pointers; if (!pointers.current || pointers.current->count == Pointers::kMax) { auto* prev_pointers = pointers.current; pointers.current = Allocate<Pointers>(); if (!pointers.current) { return; } pointers.current->next = nullptr; pointers.current->prev = prev_pointers; pointers.current->count = 0; if (prev_pointers) { prev_pointers->next = pointers.current; } else { pointers.root = pointers.current; } } pointers.current->ptrs[pointers.current->count++] = ptr; } struct { struct { Block* root = nullptr; Block* current = nullptr; size_t current_offset = BLOCK_SIZE; } block; struct { Pointers* root = nullptr; Pointers* current = nullptr; } pointers; size_t count = 0; } data; }; } #endif
#include "src/utils/block_allocator.h" #include <vector> #include "gtest/gtest.h" namespace langsvr { namespace { struct LifetimeCounter { explicit LifetimeCounter(size_t* count) : count_(count) { (*count)++; } ~LifetimeCounter() { (*count_)--; } size_t* const count_; }; using BlockAllocatorTest = testing::Test; TEST_F(BlockAllocatorTest, Empty) { using Allocator = BlockAllocator<int>; Allocator allocator; EXPECT_EQ(allocator.Count(), 0u); for (int* i : allocator.Objects()) { (void)i; if ((true)) { FAIL() << "BlockAllocator should be empty"; } } for (const int* i : static_cast<const Allocator&>(allocator).Objects()) { (void)i; if ((true)) { FAIL() << "BlockAllocator should be empty"; } } } TEST_F(BlockAllocatorTest, Count) { using Allocator = BlockAllocator<int>; for (size_t n : {0u, 1u, 10u, 16u, 20u, 32u, 50u, 64u, 100u, 256u, 300u, 512u, 500u, 512u}) { Allocator allocator; EXPECT_EQ(allocator.Count(), 0u); for (size_t i = 0; i < n; i++) { allocator.Create(123); } EXPECT_EQ(allocator.Count(), n); } } TEST_F(BlockAllocatorTest, ObjectLifetime) { using Allocator = BlockAllocator<LifetimeCounter>; size_t count = 0; { Allocator allocator; EXPECT_EQ(count, 0u); allocator.Create(&count); EXPECT_EQ(count, 1u); allocator.Create(&count); EXPECT_EQ(count, 2u); allocator.Create(&count); EXPECT_EQ(count, 3u); } EXPECT_EQ(count, 0u); } TEST_F(BlockAllocatorTest, MoveConstruct) { using Allocator = BlockAllocator<LifetimeCounter>; for (size_t n : {0u, 1u, 10u, 16u, 20u, 32u, 50u, 64u, 100u, 256u, 300u, 512u, 500u, 512u}) { size_t count = 0; { Allocator allocator_a; for (size_t i = 0; i < n; i++) { allocator_a.Create(&count); } EXPECT_EQ(count, n); EXPECT_EQ(allocator_a.Count(), n); Allocator allocator_b{std::move(allocator_a)}; EXPECT_EQ(count, n); EXPECT_EQ(allocator_b.Count(), n); } EXPECT_EQ(count, 0u); } } TEST_F(BlockAllocatorTest, MoveAssign) { using Allocator = BlockAllocator<LifetimeCounter>; for (size_t n : {0u, 1u, 10u, 16u, 20u, 32u, 50u, 64u, 100u, 256u, 300u, 512u, 500u, 512u}) { size_t count_a = 0; size_t count_b = 0; { Allocator allocator_a; for (size_t i = 0; i < n; i++) { allocator_a.Create(&count_a); } EXPECT_EQ(count_a, n); EXPECT_EQ(allocator_a.Count(), n); Allocator allocator_b; for (size_t i = 0; i < n; i++) { allocator_b.Create(&count_b); } EXPECT_EQ(count_b, n); EXPECT_EQ(allocator_b.Count(), n); allocator_b = std::move(allocator_a); EXPECT_EQ(count_a, n); EXPECT_EQ(count_b, 0u); EXPECT_EQ(allocator_b.Count(), n); } EXPECT_EQ(count_a, 0u); EXPECT_EQ(count_b, 0u); } } TEST_F(BlockAllocatorTest, ObjectOrder) { using Allocator = BlockAllocator<int>; Allocator allocator; constexpr int N = 10000; for (int i = 0; i < N; i++) { allocator.Create(i); } { int i = 0; for (int* p : allocator.Objects()) { EXPECT_EQ(*p, i); i++; } EXPECT_EQ(i, N); } { int i = 0; for (const int* p : static_cast<const Allocator&>(allocator).Objects()) { EXPECT_EQ(*p, i); i++; } EXPECT_EQ(i, N); } } TEST_F(BlockAllocatorTest, AddWhileIterating) { using Allocator = BlockAllocator<size_t>; Allocator allocator; for (int i = 0; i < 20; i++) { allocator.Create(allocator.Count()); std::vector<size_t*> seen; for (auto* j : allocator.Objects()) { if (*j % 3 == 0) { allocator.Create(allocator.Count()); } seen.push_back(j); } size_t n = 0; for (auto* obj : allocator.Objects()) { ASSERT_TRUE(n < seen.size()); EXPECT_EQ(seen[n++], obj); } } } } }
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/utils/block_allocator.h
https://github.com/google/langsvr/blob/303c526231a90049a3e384549720f3fbd453cf66/src/utils/block_allocator_test.cc
303c526231a90049a3e384549720f3fbd453cf66
04744e90-f803-47c0-9f89-9e06a981cff5
cpp
google/tensorstore
dim_expression
python/tensorstore/dim_expression.cc
tensorstore/index_space/dim_expression_test.cc
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "python/tensorstore/dim_expression.h" #include <memory> #include <string> #include <string_view> #include <utility> #include <variant> #include <vector> #include "absl/base/optimization.h" #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/strings/escaping.h" #include "python/tensorstore/index.h" #include "python/tensorstore/numpy_indexing_spec.h" #include "python/tensorstore/sequence_parameter.h" #include "python/tensorstore/serialization.h" #include "python/tensorstore/subscript_method.h" #include "python/tensorstore/tensorstore_module_components.h" #include "tensorstore/index.h" #include "tensorstore/index_space/dim_expression.h" #include "tensorstore/index_space/dimension_identifier.h" #include "tensorstore/index_space/dimension_index_buffer.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/internal/numpy_indexing_spec.h" #include "tensorstore/internal/global_initializer.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/serialization/std_optional.h" #include "tensorstore/serialization/std_variant.h" #include "tensorstore/serialization/std_vector.h" #include "tensorstore/util/result.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace internal_python { namespace py = ::pybind11; void AppendDimensionSelectionRepr(std::string* out, span<const DynamicDimSpec> dims) { if (dims.empty()) { tensorstore::StrAppend(out, "()"); } for (size_t i = 0; i < dims.size(); ++i) { const auto& d = dims[i]; if (auto* index = std::get_if<DimensionIndex>(&d)) { tensorstore::StrAppend(out, (i == 0 ? "" : ","), *index); } else if (auto* label = std::get_if<std::string>(&d)) { tensorstore::StrAppend(out, (i == 0 ? "" : ","), "'", absl::CHexEscape(*label), "'"); } else { const auto& slice = std::get<DimRangeSpec>(d); tensorstore::StrAppend(out, (i == 0 ? "" : ","), slice); } } } std::string PythonDimExpressionChainTail::repr() const { std::string out = "d["; AppendDimensionSelectionRepr(&out, dims); tensorstore::StrAppend(&out, "]"); return out; } std::string PythonTranslateOp::repr() const { constexpr auto op_suffix = [](TranslateOpKind kind) { switch (kind) { case TranslateOpKind::kTranslateTo: return "to"; case TranslateOpKind::kTranslateBy: return "by"; case TranslateOpKind::kTranslateBackwardBy: return "backward_by"; } ABSL_UNREACHABLE(); }; return tensorstore::StrCat( ".translate_", op_suffix(translate_kind), "[", IndexVectorRepr(indices, true, true), "]"); } Result<IndexTransform<>> PythonTranslateOp::Apply(IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { return internal_index_space::ApplyTranslate( std::move(transform), buffer, indices, translate_kind, domain_only); } std::string PythonStrideOp::repr() const { return tensorstore::StrCat( ".stride[", IndexVectorRepr(strides, true, true), "]"); } Result<IndexTransform<>> PythonStrideOp::Apply(IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { return internal_index_space::ApplyStrideOp(std::move(transform), buffer, strides, domain_only); } std::string PythonLabelOp::repr() const { std::string r = ".label["; for (size_t i = 0; i < labels.size(); ++i) { tensorstore::StrAppend(&r, i == 0 ? "" : ",", "'", absl::CHexEscape(labels[i]), "'"); } tensorstore::StrAppend(&r, "]"); return r; } Result<IndexTransform<>> PythonLabelOp::Apply(IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { return internal_index_space::ApplyLabel(std::move(transform), buffer, span(labels), domain_only); } std::string PythonDiagonalOp::repr() const { return ".diagonal"; } Result<IndexTransform<>> PythonDiagonalOp::Apply(IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { return internal_index_space::ApplyDiagonal(std::move(transform), buffer, domain_only); } std::string PythonTransposeOp::repr() const { std::string out = ".transpose["; AppendDimensionSelectionRepr(&out, target_dim_specs); tensorstore::StrAppend(&out, "]"); return out; } Result<IndexTransform<>> PythonTransposeOp::Apply(IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { return internal_index_space::ApplyTransposeToDynamic( std::move(transform), buffer, target_dim_specs, domain_only); } std::string PythonChangeImplicitStateOp::repr() const { std::string out = ".mark_bounds_implicit["; constexpr auto format_bound = [](std::optional<bool> value) -> std::string_view { if (!value.has_value()) return ""; return *value ? "True" : "False"; }; if (lower_implicit == upper_implicit && lower_implicit) { tensorstore::StrAppend(&out, format_bound(lower_implicit)); } else { tensorstore::StrAppend(&out, format_bound(lower_implicit), ":", format_bound(upper_implicit)); } out += ']'; return out; } Result<IndexTransform<>> PythonChangeImplicitStateOp::Apply( IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { const auto do_apply = [&](bool implicit) { if (lower_implicit == implicit || upper_implicit == implicit) { TENSORSTORE_ASSIGN_OR_RETURN( transform, internal_index_space::ApplyChangeImplicitState( std::move(transform), buffer, implicit, lower_implicit == implicit, upper_implicit == implicit, domain_only)); } return absl::OkStatus(); }; TENSORSTORE_RETURN_IF_ERROR(do_apply(false)); TENSORSTORE_RETURN_IF_ERROR(do_apply(true)); return transform; } std::string PythonIndexOp::repr() const { return tensorstore::StrCat(GetIndexingModePrefix(spec.mode), "[", IndexingSpecRepr(spec), "]"); } Result<IndexTransform<>> PythonIndexOp::Apply(IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { TENSORSTORE_ASSIGN_OR_RETURN( auto new_transform, ToIndexTransform(spec, transform.domain(), buffer)); return internal_index_space::ComposeTransforms( std::move(transform), std::move(new_transform), domain_only); } Result<IndexTransform<>> PythonIndexOp::ApplyInitial( span<const DynamicDimSpec> dim_selection, IndexTransform<> transform, DimensionIndexBuffer* buffer, bool domain_only) const { TENSORSTORE_ASSIGN_OR_RETURN( auto new_transform, ToIndexTransform(spec, transform.domain(), dim_selection, buffer)); return internal_index_space::ComposeTransforms( transform, std::move(new_transform), domain_only); } namespace { auto GetOps(const PythonDimExpressionChain& ops) { absl::InlinedVector<const PythonDimExpressionChain*, 4> op_vec; for (auto* op = &ops; op; op = op->parent.get()) { op_vec.push_back(op); } return op_vec; } } std::string PythonDimExpression::repr() const { std::string out; auto op_vec = GetOps(*ops); for (size_t i = op_vec.size(); i--;) { out += op_vec[i]->repr(); } return out; } Result<IndexTransform<>> PythonDimExpressionChainTail::Apply( IndexTransform<> transform, DimensionIndexBuffer* dimensions, bool domain_only) const { TENSORSTORE_RETURN_IF_ERROR(internal_index_space::GetDimensions( transform.input_labels(), dims, dimensions)); return transform; } Result<IndexTransform<>> PythonDimExpression::Apply( IndexTransform<> transform, DimensionIndexBuffer* dimensions, bool domain_only) const { auto op_vec = GetOps(*ops); if (op_vec.size() < 2) { return absl::InvalidArgumentError( "Must specify at least one operation in dimension expression"); } auto op_it = op_vec.rbegin(); if (auto first_op_it = std::next(op_it); (*first_op_it)->kind() == DimExpressionOpKind::kIndex) { op_it = std::next(first_op_it); auto* dim_selection_op = static_cast<const PythonDimExpressionChainTail*>(op_vec.back()); TENSORSTORE_ASSIGN_OR_RETURN( transform, (static_cast<const PythonDimExpressionChainOp<PythonIndexOp>*>( *first_op_it)) ->op.ApplyInitial(dim_selection_op->dims, std::move(transform), dimensions, domain_only)); } for (; op_it != op_vec.rend(); ++op_it) { TENSORSTORE_ASSIGN_OR_RETURN( transform, (*op_it)->Apply(std::move(transform), dimensions, domain_only)); } return transform; } [[nodiscard]] bool PythonDimExpression::Encode( serialization::EncodeSink& sink) const { for (auto* op = ops.get(); op; op = op->parent.get()) { if (!serialization::Encode(sink, op->kind()) || !op->Encode(sink)) { return false; } } return true; } namespace { template <typename... T> PythonDimExpressionChain::Ptr MakeChainOp(DimExpressionOpKind kind) { PythonDimExpressionChain::Ptr ptr; [[maybe_unused]] const bool matched = ((kind == T::kind ? ((ptr = internal::MakeIntrusivePtr< PythonDimExpressionChainOp<T>>()), true) : false) || ...); return ptr; } } [[nodiscard]] bool PythonDimExpression::Decode( serialization::DecodeSource& source) { PythonDimExpressionChain::Ptr* next_op = &ops; while (true) { DimExpressionOpKind kind; if (!serialization::Decode(source, kind)) return false; if (kind == DimExpressionOpKind::kDimSelection) { *next_op = internal::MakeIntrusivePtr<PythonDimExpressionChainTail>(); } else { *next_op = MakeChainOp<PythonTranslateOp, PythonStrideOp, PythonLabelOp, PythonDiagonalOp, PythonTransposeOp, PythonChangeImplicitStateOp, PythonIndexOp>(kind); if (!*next_op) { source.Fail(absl::DataLossError("Invalid DimExpression op")); return false; } } if (!const_cast<PythonDimExpressionChain&>(**next_op).Decode(source)) { return false; } if (kind == DimExpressionOpKind::kDimSelection) break; next_op = &const_cast<PythonDimExpressionChain&>(**next_op).parent; } return true; } bool PythonDimExpressionChainTail::Equal( const PythonDimExpressionChain& other) const { return dims == static_cast<const PythonDimExpressionChainTail&>(other).dims; } bool operator==(const PythonDimExpression& a, const PythonDimExpression& b) { const PythonDimExpressionChain* a_op = a.ops.get(); const PythonDimExpressionChain* b_op = b.ops.get(); while (true) { if (!a_op && !b_op) return true; if (!a_op || !b_op) return false; if (a_op->kind() != b_op->kind()) return false; if (!a_op->Equal(*b_op)) return false; a_op = a_op->parent.get(); b_op = b_op->parent.get(); } } namespace { using ClsDimExpression = py::class_<PythonDimExpression, std::shared_ptr<PythonDimExpression>>; using ClsDimensionSelection = py::class_<DimensionSelection, PythonDimExpression, std::shared_ptr<DimensionSelection>>; ClsDimExpression MakeDimExpressionClass(py::module m) { return ClsDimExpression(m, "DimExpression", R"( Specifies an advanced indexing operation. :ref:`Dimension expressions<python-dim-expressions>` permit indexing using :ref:`dimension labels<dimension-labels>`, and also support additional operations that cannot be performed with plain :ref:`python-numpy-style-indexing`. Group: Indexing Operations ========== )"); } void DefineDimExpressionAttributes(ClsDimExpression& cls) { using Self = PythonDimExpression; DefineNumpyIndexingMethods( &cls, { { R"( Applies a :ref:`NumPy-style indexing operation<python-dim-expression-numpy-indexing>` with default index array semantics. When using NumPy-style indexing with a dimension expression, all selected dimensions must be consumed by a term of the indexing spec; there is no implicit addition of an `Ellipsis` term to consume any remaining dimensions. Returns: Dimension expression with the indexing operation added. Group: Operations Examples ======== :ref:`Integer indexing<python-indexing-integer>` ------------------------------------------------ >>> transform = ts.IndexTransform(input_labels=['x', 'y', 'z']) >>> transform[ts.d['x'][5]] Rank 2 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) "y" 1: (-inf*, +inf*) "z" Output index maps: out[0] = 5 out[1] = 0 + 1 * in[0] out[2] = 0 + 1 * in[1] >>> transform[ts.d['x', 'z'][5, 6]] Rank 1 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) "y" Output index maps: out[0] = 5 out[1] = 0 + 1 * in[0] out[2] = 6 A single scalar index term applies to all selected dimensions: >>> transform[ts.d['x', 'y'][5]] Rank 1 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) "z" Output index maps: out[0] = 5 out[1] = 5 out[2] = 0 + 1 * in[0] .. seealso:: :ref:`python-indexing-integer` :ref:`Interval indexing<python-indexing-interval>` -------------------------------------------------- >>> transform = ts.IndexTransform(input_labels=['x', 'y', 'z']) >>> transform[ts.d['x'][5:10]] Rank 3 -> 3 index space transform: Input domain: 0: [5, 10) "x" 1: (-inf*, +inf*) "y" 2: (-inf*, +inf*) "z" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'z'][5:10, 20:30]] Rank 3 -> 3 index space transform: Input domain: 0: [5, 10) "x" 1: (-inf*, +inf*) "y" 2: [20, 30) "z" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] As an extension, TensorStore allows the ``start``, ``stop``, and ``step`` :py:obj:`python:slice` terms to be vectors rather than scalars: >>> transform[ts.d['x', 'z'][[5, 20]:[10, 30]]] Rank 3 -> 3 index space transform: Input domain: 0: [5, 10) "x" 1: (-inf*, +inf*) "y" 2: [20, 30) "z" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'z'][[5, 20]:30]] Rank 3 -> 3 index space transform: Input domain: 0: [5, 30) "x" 1: (-inf*, +inf*) "y" 2: [20, 30) "z" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] As with integer indexing, a single scalar slice applies to all selected dimensions: >>> transform[ts.d['x', 'z'][5:30]] Rank 3 -> 3 index space transform: Input domain: 0: [5, 30) "x" 1: (-inf*, +inf*) "y" 2: [5, 30) "z" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] .. seealso:: :ref:`python-indexing-interval` :ref:`Adding singleton dimensions<python-indexing-newaxis>` ----------------------------------------------------------- Specifying a value of :py:obj:`.newaxis` (equal to `None`) adds a new inert/singleton dimension with :ref:`implicit bounds<implicit-bounds>` :math:`[0, 1)`: >>> transform = ts.IndexTransform(input_labels=['x', 'y']) >>> transform[ts.d[1][ts.newaxis]] Rank 3 -> 2 index space transform: Input domain: 0: (-inf*, +inf*) "x" 1: [0*, 1*) 2: (-inf*, +inf*) "y" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[2] >>> transform[ts.d[0, -1][ts.newaxis, ts.newaxis]] Rank 4 -> 2 index space transform: Input domain: 0: [0*, 1*) 1: (-inf*, +inf*) "x" 2: (-inf*, +inf*) "y" 3: [0*, 1*) Output index maps: out[0] = 0 + 1 * in[1] out[1] = 0 + 1 * in[2] As with integer indexing, if only a single :python:`ts.newaxis` term is specified, it applies to all selected dimensions: >>> transform[ts.d[0, -1][ts.newaxis]] Rank 4 -> 2 index space transform: Input domain: 0: [0*, 1*) 1: (-inf*, +inf*) "x" 2: (-inf*, +inf*) "y" 3: [0*, 1*) Output index maps: out[0] = 0 + 1 * in[1] out[1] = 0 + 1 * in[2] :py:obj:`.newaxis` terms are only permitted in the first operation of a dimension expression, since in subsequent operations all dimensions of the dimension selection necessarily refer to existing dimensions: .. admonition:: Error :class: failure >>> transform[ts.d[0, 1].translate_by[5][ts.newaxis]] Traceback (most recent call last): ... IndexError: tensorstore.newaxis (`None`) not valid in chained indexing operations It is also an error to use :py:obj:`.newaxis` with dimensions specified by label: .. admonition:: Error :class: failure >>> transform[ts.d['x'][ts.newaxis]] Traceback (most recent call last): ... IndexError: New dimensions cannot be specified by label... .. seealso:: :ref:`python-indexing-newaxis` :ref:`Ellipsis<python-indexing-ellipsis>` ----------------------------------------- Specifying the special `Ellipsis` value (:python:`...`) is equivalent to specifying as many full slices :python:`:` as needed to consume the remaining selected dimensions not consumed by other indexing terms: >>> transform = ts.IndexTransform(input_rank=4) >>> transform[ts.d[:][1, ..., 5].translate_by[3]] Rank 2 -> 4 index space transform: Input domain: 0: (-inf*, +inf*) 1: (-inf*, +inf*) Output index maps: out[0] = 1 out[1] = -3 + 1 * in[0] out[2] = -3 + 1 * in[1] out[3] = 5 An indexing spec consisting solely of an `Ellipsis` term has no effect: >>> transform[ts.d[:][...]] Rank 4 -> 4 index space transform: Input domain: 0: (-inf*, +inf*) 1: (-inf*, +inf*) 2: (-inf*, +inf*) 3: (-inf*, +inf*) Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] out[3] = 0 + 1 * in[3] .. seealso:: :ref:`python-indexing-ellipsis` :ref:`Integer array indexing<python-indexing-integer-array>` ------------------------------------------------------------ Specifying an `~numpy.typing.ArrayLike` *index array* of integer values selects the coordinates given by the elements of the array of the selected dimension: >>> x = ts.array([[1, 2, 3], [4, 5, 6]], dtype=ts.int32) >>> x = x[ts.d[:].label['x', 'y']] >>> x[ts.d['y'][[1, 1, 0]]] TensorStore({ 'array': [[2, 2, 1], [5, 5, 4]], 'context': {'data_copy_concurrency': {}}, 'driver': 'array', 'dtype': 'int32', 'transform': { 'input_exclusive_max': [2, 3], 'input_inclusive_min': [0, 0], 'input_labels': ['x', ''], }, }) As in the example above, if only a single index array term is specified, the dimensions of the index array are added to the result domain in place of the selected dimension, consistent with :ref:`direct NumPy-style indexing<python-indexing-integer-array>` in the default index array mode. However, when using NumPy-style indexing with a dimension expression, if more than one index array term is specified, the broadcast dimensions of the index arrays are always added to the beginning of the result domain, i.e. exactly the behavior of :py:obj:`DimExpression.vindex`. Unlike with direct NumPy-style indexing (not with a dimension expression), the behavior does not depend on whether the index array terms apply to consecutive dimensions, since consecutive dimensions are not well-defined for dimension expressions: >>> x = ts.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=ts.int32) >>> x = x[ts.d[:].label['x', 'y', 'z']] >>> x[ts.d['z', 'y'][[1, 0], [1, 1]]] TensorStore({ 'array': [[4, 3], [8, 7]], 'context': {'data_copy_concurrency': {}}, 'driver': 'array', 'dtype': 'int32', 'transform': { 'input_exclusive_max': [2, 2], 'input_inclusive_min': [0, 0], 'input_labels': ['x', ''], }, }) .. seealso:: :ref:`python-indexing-integer-array` :ref:`Boolean array indexing<python-indexing-boolean-array>` ------------------------------------------------------------ Specifying an `~numpy.typing.ArrayLike` of `bool` values is equivalent to specifying a sequence of integer index arrays containing the coordinates of `True` values (in C order), e.g. as obtained from `numpy.nonzero`: Specifying a 1-d `bool` array is equivalent to a single index array of the non-zero coordinates: >>> x = ts.array([[1, 2, 3], [4, 5, 6]], dtype=ts.int32) >>> x = x[ts.d[:].label['x', 'y']] >>> x[ts.d['y'][[False, True, True]]] TensorStore({ 'array': [[2, 3], [5, 6]], 'context': {'data_copy_concurrency': {}}, 'driver': 'array', 'dtype': 'int32', 'transform': { 'input_exclusive_max': [2, 2], 'input_inclusive_min': [0, 0], 'input_labels': ['x', ''], }, }) Equivalently, using an index array: >>> x[ts.d['y'][[1, 2]]] TensorStore({ 'array': [[2, 3], [5, 6]], 'context': {'data_copy_concurrency': {}}, 'driver': 'array', 'dtype': 'int32', 'transform': { 'input_exclusive_max': [2, 2], 'input_inclusive_min': [0, 0], 'input_labels': ['x', ''], }, }) More generally, specifying an ``n``-dimensional `bool` array is equivalent to specifying ``n`` 1-dimensional index arrays, where the ``i``\ th index array specifies the ``i``\ th coordinate of the `True` values: >>> x = ts.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], ... dtype=ts.int32) >>> x = x[ts.d[:].label['x', 'y', 'z']] >>> x[ts.d['x', 'z'][[[True, False, False], [True, True, False]]]] TensorStore({ 'array': [[1, 4], [7, 10], [8, 11]], 'context': {'data_copy_concurrency': {}}, 'driver': 'array', 'dtype': 'int32', 'transform': { 'input_exclusive_max': [3, 2], 'input_inclusive_min': [0, 0], 'input_labels': ['', 'y'], }, }) Equivalently, using an index array: >>> x[ts.d['x', 'z'][[0, 1, 1], [0, 0, 1]]] TensorStore({ 'array': [[1, 4], [7, 10], [8, 11]], 'context': {'data_copy_concurrency': {}}, 'driver': 'array', 'dtype': 'int32', 'transform': { 'input_exclusive_max': [3, 2], 'input_inclusive_min': [0, 0], 'input_labels': ['', 'y'], }, }) Note that as with integer array indexing, when using NumPy-styling indexing with a dimension expression, if boolean arrays are applied to more than one selected dimension, the added dimension corresponding to the `True` values is always added to the beginning of the result domain, i.e. exactly the behavior of :py:obj:`DimExpression.vindex`. .. seealso:: :ref:`python-indexing-boolean-array` )"}, {R"( Applies a :ref:`NumPy-style indexing operation<python-dim-expression-numpy-indexing>` with :ref:`outer indexing semantics<python-oindex-indexing>`. This is similar to :py:obj:`DimExpression.__getitem__`, but differs in that any integer or boolean array indexing terms are applied orthogonally: Examples: >>> transform = ts.IndexTransform(input_labels=['x', 'y', 'z']) >>> transform[ts.d['x', 'z'].oindex[[1, 2, 3], [4, 5, 6]]] Rank 3 -> 3 index space transform: Input domain: 0: [0, 3) 1: (-inf*, +inf*) "y" 2: [0, 3) Output index maps: out[0] = 0 + 1 * bounded((-inf, +inf), array(in)), where array = {{{1}}, {{2}}, {{3}}} out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * bounded((-inf, +inf), array(in)), where array = {{{4, 5, 6}}} Returns: Dimension expression with the indexing operation added. See also: - :ref:`python-oindex-indexing` Group: Operations )"}, {R"( Applies a :ref:`NumPy-style indexing operation<python-dim-expression-numpy-indexing>` with :ref:`vectorized indexing semantics<python-vindex-indexing>`. This is similar to :py:obj:`DimExpression.__getitem__`, but differs in that if :python:`indices` specifies any array indexing terms, the broadcasted array dimensions are unconditionally added as the first dimensions of the result domain: Examples: >>> transform = ts.IndexTransform(input_labels=['x', 'y', 'z']) >>> transform[ts.d['y', 'z'].vindex[[1, 2, 3], [4, 5, 6]]] Rank 2 -> 3 index space transform: Input domain: 0: [0, 3) 1: (-inf*, +inf*) "x" Output index maps: out[0] = 0 + 1 * in[1] out[1] = 0 + 1 * bounded((-inf, +inf), array(in)), where array = {{1}, {2}, {3}} out[2] = 0 + 1 * bounded((-inf, +inf), array(in)), where array = {{4}, {5}, {6}} Returns: Dimension expression with the indexing operation added. See also: - :ref:`python-vindex-indexing` Group: Operations )"}, }, [](const Self& self, NumpyIndexingSpecPlaceholder spec) { return self.Extend(PythonIndexOp{ spec.Parse(self.ops->kind() == DimExpressionOpKind::kDimSelection ? NumpyIndexingSpec::Usage::kDimSelectionInitial : NumpyIndexingSpec::Usage::kDimSelectionChained)}); }); constexpr auto apply_op = [](const Self& self, auto&& op) { return self.Extend(std::forward<decltype(op)>(op)); }; DefineTranslateToOp<Self>(cls, apply_op, R"( Translates the domains of the selected input dimensions to the specified origins without affecting the output range. Examples: >>> transform = ts.IndexTransform(input_shape=[4, 5, 6], ... input_labels=['x', 'y', 'z']) >>> transform[ts.d['x', 'y'].translate_to[10, 20]] Rank 3 -> 3 index space transform: Input domain: 0: [10, 14) "x" 1: [20, 25) "y" 2: [0, 6) "z" Output index maps: out[0] = -10 + 1 * in[0] out[1] = -20 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'y'].translate_to[10, None]] Rank 3 -> 3 index space transform: Input domain: 0: [10, 14) "x" 1: [0, 5) "y" 2: [0, 6) "z" Output index maps: out[0] = -10 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'y'].translate_to[10]] Rank 3 -> 3 index space transform: Input domain: 0: [10, 14) "x" 1: [10, 15) "y" 2: [0, 6) "z" Output index maps: out[0] = -10 + 1 * in[0] out[1] = -10 + 1 * in[1] out[2] = 0 + 1 * in[2] The new dimension selection is the same as the prior dimension selection. Args: origins: The new origins for each of the selected dimensions. May also be a scalar, e.g. :python:`5`, in which case the same origin is used for all selected dimensions. If :python:`None` is specified for a given dimension, the origin of that dimension remains unchanged. Returns: Dimension expression with the translation operation added. Raises: IndexError: If the number origins does not match the number of selected dimensions. IndexError: If any of the selected dimensions has a lower bound of :python:`-inf`. Group: Operations )"); DefineTranslateByOp<Self>(cls, apply_op, R"( Translates (shifts) the domains of the selected input dimensions by the specified offsets, without affecting the output range. Examples: >>> transform = ts.IndexTransform(input_inclusive_min=[2, 3, 4], ... input_shape=[4, 5, 6], ... input_labels=['x', 'y', 'z']) >>> transform[ts.d['x', 'y'].translate_by[10, 20]] Rank 3 -> 3 index space transform: Input domain: 0: [12, 16) "x" 1: [23, 28) "y" 2: [4, 10) "z" Output index maps: out[0] = -10 + 1 * in[0] out[1] = -20 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'y'].translate_by[10, None]] Rank 3 -> 3 index space transform: Input domain: 0: [12, 16) "x" 1: [3, 8) "y" 2: [4, 10) "z" Output index maps: out[0] = -10 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'y'].translate_by[10]] Rank 3 -> 3 index space transform: Input domain: 0: [12, 16) "x" 1: [13, 18) "y" 2: [4, 10) "z" Output index maps: out[0] = -10 + 1 * in[0] out[1] = -10 + 1 * in[1] out[2] = 0 + 1 * in[2] The new dimension selection is the same as the prior dimension selection. Args: offsets: The offsets for each of the selected dimensions. May also be a scalar, e.g. :python:`5`, in which case the same offset is used for all selected dimensions. Specifying :python:`None` for a given dimension (equivalent to specifying an offset of :python:`0`) leaves the origin of that dimension unchanged. Returns: Dimension expression with the translation operation added. Raises: IndexError: If the number origins does not match the number of selected dimensions. Group: Operations )"); DefineTranslateBackwardByOp<Self>(cls, apply_op, R"( Translates (shifts) the domains of the selected input dimensions backward by the specified offsets, without affecting the output range. Examples: >>> transform = ts.IndexTransform(input_inclusive_min=[2, 3, 4], ... input_shape=[4, 5, 6], ... input_labels=['x', 'y', 'z']) >>> transform[ts.d['x', 'y'].translate_backward_by[10, 20]] Rank 3 -> 3 index space transform: Input domain: 0: [-8, -4) "x" 1: [-17, -12) "y" 2: [4, 10) "z" Output index maps: out[0] = 10 + 1 * in[0] out[1] = 20 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'y'].translate_backward_by[10, None]] Rank 3 -> 3 index space transform: Input domain: 0: [-8, -4) "x" 1: [3, 8) "y" 2: [4, 10) "z" Output index maps: out[0] = 10 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> transform[ts.d['x', 'y'].translate_backward_by[10]] Rank 3 -> 3 index space transform: Input domain: 0: [-8, -4) "x" 1: [-7, -2) "y" 2: [4, 10) "z" Output index maps: out[0] = 10 + 1 * in[0] out[1] = 10 + 1 * in[1] out[2] = 0 + 1 * in[2] The new dimension selection is the same as the prior dimension selection. Args: offsets: The offsets for each of the selected dimensions. May also be a scalar, e.g. :python:`5`, in which case the same offset is used for all selected dimensions. Specifying :python:`None` for a given dimension (equivalent to specifying an offset of :python:`0`) leaves the origin of that dimension unchanged. Returns: Dimension expression with the translation operation added. Raises: IndexError: If the number origins does not match the number of selected dimensions. Group: Operations )"); DefineSubscriptMethod<Self, struct StrideTag>(&cls, "stride", "_Stride") .def( "__getitem__", +[](const Self& self, OptionallyImplicitIndexVectorOrScalarContainer strides) { return self.Extend( PythonStrideOp{ToIndexVectorOrScalarContainer(strides)}); }, R"( Strides the domains of the selected input dimensions by the specified amounts. For each selected dimension ``i``, the new domain is the set of indices ``x`` such that :python:`x * strides[i]` is contained in the original domain. Examples: >>> transform = ts.IndexTransform(input_inclusive_min=[0, 2, 1], ... input_inclusive_max=[6, 5, 8], ... input_labels=["x", "y", "z"]) >>> transform[ts.d["x", "z"].stride[-2, 3]] Rank 3 -> 3 index space transform: Input domain: 0: [-3, 1) "x" 1: [2, 6) "y" 2: [1, 3) "z" Output index maps: out[0] = 0 + -2 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 3 * in[2] >>> transform[ts.d["x", "z"].stride[3]] Rank 3 -> 3 index space transform: Input domain: 0: [0, 3) "x" 1: [2, 6) "y" 2: [1, 3) "z" Output index maps: out[0] = 0 + 3 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 3 * in[2] Note: :python:`expr.stride[strides]` is similar to the :ref:`NumPy-style slicing<python-indexing-interval>` operation :python:`expr[::strides]` except that the striding is always done with respect to an origin of 0, irrespective of the existing dimension lower bounds. The new dimension selection is the same as the prior dimension selection. Args: strides: Strides for each selected dimension. May also be a scalar, e.g. :python:`2`, in which case the same stride value is used for all selected dimensions. Specifying :python:`None` for a given dimension (equivalent to specifying a stride of :python:`1`) leaves that dimension unchanged. Specify a stride of :python:`0` is not valid. Returns: Dimension expression with the striding operation added. Raises: IndexError: If the number strides does not match the number of selected dimensions. Group: Operations )", py::arg("strides")); DefineSubscriptMethod<Self, struct TransposeTag>(&cls, "transpose", "_Transpose") .def( "__getitem__", +[](const Self& self, DimensionSelectionLike dim_specs) { return self.Extend(PythonTransposeOp{dim_specs.value.dims()}); }, R"( Transposes the selected dimensions to the specified target indices. A dimension range may be specified to reverse the order of all dimensions: >>> transform = ts.IndexTransform(input_shape=[2, 3, 4], ... input_labels=["x", "y", "z"]) >>> transform[ts.d[:].transpose[::-1]] Rank 3 -> 3 index space transform: Input domain: 0: [0, 4) "z" 1: [0, 3) "y" 2: [0, 2) "x" Output index maps: out[0] = 0 + 1 * in[2] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[0] Dimensions not in the selection retain their relative order and fill in the dimension indices not in :python:`target`: >>> transform = ts.IndexTransform(input_shape=[2, 3, 4], ... input_labels=["x", "y", "z"]) >>> transform[ts.d['x', 'z'].transpose[0, 1]] Rank 3 -> 3 index space transform: Input domain: 0: [0, 2) "x" 1: [0, 4) "z" 2: [0, 3) "y" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[2] out[2] = 0 + 1 * in[1] A single non-negative :python:`target` index may be specified to reorder all of the selected dimensions to start at the specified index: >>> transform = ts.IndexTransform(input_shape=[2, 3, 4, 5], ... input_labels=["a", "b", "c", "d"]) >>> transform[ts.d['a', 'd'].transpose[1]] Rank 4 -> 4 index space transform: Input domain: 0: [0, 3) "b" 1: [0, 2) "a" 2: [0, 5) "d" 3: [0, 4) "c" Output index maps: out[0] = 0 + 1 * in[1] out[1] = 0 + 1 * in[0] out[2] = 0 + 1 * in[3] out[3] = 0 + 1 * in[2] A single negative :python:`target` index may be specified to order all of the selected dimensions to end at the specified index from end: >>> transform = ts.IndexTransform(input_shape=[2, 3, 4, 5], ... input_labels=["a", "b", "c", "d"]) >>> transform[ts.d['a', 'd'].transpose[-1]] Rank 4 -> 4 index space transform: Input domain: 0: [0, 3) "b" 1: [0, 4) "c" 2: [0, 2) "a" 3: [0, 5) "d" Output index maps: out[0] = 0 + 1 * in[2] out[1] = 0 + 1 * in[0] out[2] = 0 + 1 * in[1] out[3] = 0 + 1 * in[3] Args: target: Target dimension indices for the selected dimensions. All dimensions must be specified by index. Labels are not permitted. If the dimension selection has :python:`k > 1` dimensions, a single non-negative index :python:`i` is equivalent to :python:`i:i+k`; a single negative index :python:`-i` is equivalent to :python:`-i-k:-i`. Returns: Dimension expression with the transpose operation added. Group: Operations )", py::arg("target")); DefineLabelOp<Self>(cls, apply_op, R"( Sets (or changes) the :ref:`labels<dimension-labels>` of the selected dimensions. Examples: >>> ts.IndexTransform(3)[ts.d[0].label['x']] Rank 3 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) "x" 1: (-inf*, +inf*) 2: (-inf*, +inf*) Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> ts.IndexTransform(3)[ts.d[0, 2].label['x', 'z']] Rank 3 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) "x" 1: (-inf*, +inf*) 2: (-inf*, +inf*) "z" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> ts.IndexTransform(3)[ts.d[:].label['x', 'y', 'z']] Rank 3 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) "x" 1: (-inf*, +inf*) "y" 2: (-inf*, +inf*) "z" Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> ts.IndexTransform(3)[ts.d[0, 1].label['x', 'y'].translate_by[2]] Rank 3 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) "x" 1: (-inf*, +inf*) "y" 2: (-inf*, +inf*) Output index maps: out[0] = -2 + 1 * in[0] out[1] = -2 + 1 * in[1] out[2] = 0 + 1 * in[2] The new dimension selection is the same as the prior dimension selection. Args: labels: Dimension labels for each selected dimension. Returns: Dimension expression with the label operation added. Raises: IndexError: If the number of labels does not match the number of selected dimensions, or if the resultant domain would have duplicate labels. Group: Operations )"); cls.def_property_readonly( "diagonal", [](const Self& self) { return self.Extend(PythonDiagonalOp{}); }, R"( Extracts the diagonal of the selected dimensions. The selection dimensions are removed from the resultant index space, and a new dimension corresponding to the diagonal is added as the first dimension, with an input domain equal to the intersection of the input domains of the selection dimensions. The new dimension selection is equal to :python:`ts.d[0]`, corresponding to the newly added diagonal dimension. The lower and upper bounds of the new diagonal dimension are :ref:`implicit<implicit-bounds>` if, and only if, the lower or upper bounds, respectively, of every selected dimension are implicit. Examples: >>> transform = ts.IndexTransform(input_shape=[2, 3], ... input_labels=["x", "y"]) >>> transform[ts.d['x', 'y'].diagonal] Rank 1 -> 2 index space transform: Input domain: 0: [0, 2) Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[0] >>> transform = ts.IndexTransform(3) >>> transform[ts.d[0, 2].diagonal] Rank 2 -> 3 index space transform: Input domain: 0: (-inf*, +inf*) 1: (-inf*, +inf*) Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[0] Note: If zero dimensions are selected, :py:obj:`.diagonal` simply results in a new singleton dimension as the first dimension, equivalent to :python:`[ts.newaxis]`: >>> transform = ts.IndexTransform(1) >>> transform[ts.d[()].diagonal] Rank 2 -> 1 index space transform: Input domain: 0: (-inf*, +inf*) 1: (-inf*, +inf*) Output index maps: out[0] = 0 + 1 * in[1] If only one dimension is selected, :py:obj:`.diagonal` is equivalent to :python:`.label[''].transpose[0]`: >>> transform = ts.IndexTransform(input_labels=['x', 'y']) >>> transform[ts.d[1].diagonal] Rank 2 -> 2 index space transform: Input domain: 0: (-inf*, +inf*) 1: (-inf*, +inf*) "x" Output index maps: out[0] = 0 + 1 * in[1] out[1] = 0 + 1 * in[0] Group: Operations )"); DefineMarkBoundsImplicitOp<Self>(cls, apply_op, R"( Marks the lower/upper bounds of the selected dimensions as :ref:`implicit/explicit<implicit-bounds>`. For a `TensorStore`, implicit bounds indicate resizeable dimensions. Marking a bound as explicit fixes it to its current value such that it won't be adjusted by subsequent `TensorStore.resolve` calls if the stored bounds change. Because implicit bounds do not constrain subsequent indexing/slicing operations, a bound may be marked implicit in order to expand the domain. .. warning:: Be careful when marking bounds as implicit, since this may bypass intended constraints on the domain. Examples: >>> s = await ts.open({ ... 'driver': 'zarr', ... 'kvstore': 'memory: ... }, ... shape=[100, 200], ... dtype=ts.uint32, ... create=True) >>> s.domain { [0, 100*), [0, 200*) } >>> await s.resize(exclusive_max=[200, 300]) >>> (await s.resolve()).domain { [0, 200*), [0, 300*) } >>> (await s[ts.d[0].mark_bounds_implicit[False]].resolve()).domain { [0, 100), [0, 300*) } >>> s_subregion = s[20:30, 40:50] >>> s_subregion.domain { [20, 30), [40, 50) } >>> (await ... s_subregion[ts.d[0].mark_bounds_implicit[:True]].resolve()).domain { [20, 200*), [40, 50) } >>> t = ts.IndexTransform(input_rank=3) >>> t = t[ts.d[0, 2].mark_bounds_implicit[False]] >>> t Rank 3 -> 3 index space transform: Input domain: 0: (-inf, +inf) 1: (-inf*, +inf*) 2: (-inf, +inf) Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> t = t[ts.d[0, 1].mark_bounds_implicit[:True]] >>> t Rank 3 -> 3 index space transform: Input domain: 0: (-inf, +inf*) 1: (-inf*, +inf*) 2: (-inf, +inf) Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] >>> t = t[ts.d[1, 2].mark_bounds_implicit[True:False]] >>> t Rank 3 -> 3 index space transform: Input domain: 0: (-inf, +inf*) 1: (-inf*, +inf) 2: (-inf*, +inf) Output index maps: out[0] = 0 + 1 * in[0] out[1] = 0 + 1 * in[1] out[2] = 0 + 1 * in[2] The new dimension selection is the same as the prior dimension selection. Args: implicit: Indicates the new implicit value for the lower and upper bounds. Must be one of: - `None` to indicate no change; - `True` to change both lower and upper bounds to implicit; - `False` to change both lower and upper bounds to explicit. - a `slice`, where :python:`start` and :python:`stop` specify the new implicit value for the lower and upper bounds, respectively, and each must be one of `None`, `True`, or `False`. Returns: Dimension expression with bounds marked as implicit/explicit. Raises: IndexError: If the resultant domain would have an input dimension referenced by an index array marked as implicit. Group: Operations )"); cls.def("__repr__", &PythonDimExpression::repr); cls.def("__eq__", [](const Self& a, const Self& b) { return a == b; }); cls.attr("__iter__") = py::none(); EnablePicklingFromSerialization(cls); } ClsDimensionSelection MakeDimensionSelectionClass(py::module m) { return ClsDimensionSelection(m, "d", R"( Specifies a dimension selection, for starting a :ref:`dimension expression<python-dim-expressions>`. A dimension selection specifies a sequence of dimensions, either by index or :ref:`label<dimension-labels>`. :ref:`python-dim-selections` may be used as part of a :ref:`dimension expression<python-dim-expression-construction>` to specify the dimensions to which an indexing operation applies. Group: Indexing Constructors ============ Operations ========== )"); } void DefineDimensionSelectionAttributes(ClsDimensionSelection& cls) { cls.def_static( "__class_getitem__", [](DimensionSelectionLike selection) { return selection.value; }, R"( Constructs from a sequence of dimension indices, ranges, and/or labels. Examples: >>> ts.d[0, 1, 2] d[0,1,2] >>> ts.d[0:1, 2, "x"] d[0:1,2,'x'] >>> ts.d[[0, 1], [2]] d[0,1,2] >>> ts.d[[0, 1], ts.d[2, 3]] d[0,1,2,3] )", py::arg("selection")); cls.def( "__eq__", [](const DimensionSelection& a, const DimensionSelection& b) { return a.dims() == b.dims(); }, py::arg("other")); EnablePicklingFromSerialization(cls); } void RegisterDimExpressionBindings(pybind11::module m, Executor defer) { defer([cls = MakeDimExpressionClass(m)]() mutable { DefineDimExpressionAttributes(cls); }); defer([cls = MakeDimensionSelectionClass(m)]() mutable { DefineDimensionSelectionAttributes(cls); }); m.attr("newaxis") = py::none(); } TENSORSTORE_GLOBAL_INITIALIZER { RegisterPythonComponent(RegisterDimExpressionBindings, -850); } } bool CastToDimensionSelection(py::handle src, std::vector<DynamicDimSpec>& out) { if (PyUnicode_Check(src.ptr())) { out.emplace_back(py::cast<std::string>(src)); } else if (PyIndex_Check(src.ptr())) { out.emplace_back(DimensionIndex(py::cast<PythonDimensionIndex>(src))); } else if (PySlice_Check(src.ptr())) { out.emplace_back(py::cast<DimRangeSpec>(src)); } else if (py::isinstance<DimensionSelection>(src)) { auto existing = py::cast<DimensionSelection>(src); out.insert(out.end(), existing.dims().begin(), existing.dims().end()); } else { py::object seq = py::reinterpret_steal<py::object>(PySequence_Fast(src.ptr(), "")); if (!seq) { PyErr_Clear(); return false; } std::vector<py::object> seq_objs; Py_ssize_t seq_size = PySequence_Fast_GET_SIZE(seq.ptr()); seq_objs.reserve(seq_size); PyObject** elems = PySequence_Fast_ITEMS(seq.ptr()); for (Py_ssize_t i = 0; i < seq_size; ++i) { seq_objs.push_back(py::reinterpret_borrow<py::object>(elems[i])); } for (const auto& obj : seq_objs) { if (!CastToDimensionSelection(obj, out)) return false; } } return true; } PythonDimExpressionChain::~PythonDimExpressionChain() = default; bool PythonDimExpressionChainTail::Encode( serialization::EncodeSink& sink) const { return serialization::Encode(sink, dims); } bool PythonDimExpressionChainTail::Decode(serialization::DecodeSource& source) { return serialization::Decode(source, dims); } } namespace serialization { [[nodiscard]] bool Serializer<internal_python::PythonDimExpression>::Encode( EncodeSink& sink, const internal_python::PythonDimExpression& value) { return value.Encode(sink); } [[nodiscard]] bool Serializer<internal_python::PythonDimExpression>::Decode( DecodeSource& source, internal_python::PythonDimExpression& value) { return value.Decode(source); } [[nodiscard]] bool Serializer<internal_python::DimensionSelection>::Encode( EncodeSink& sink, const internal_python::DimensionSelection& value) { return serialization::Encode(sink, value.dims()); } [[nodiscard]] bool Serializer<internal_python::DimensionSelection>::Decode( DecodeSource& source, internal_python::DimensionSelection& value) { auto ops = internal::MakeIntrusivePtr< internal_python::PythonDimExpressionChainTail>(); if (!serialization::Decode(source, ops->dims)) return false; value.ops = std::move(ops); return true; } } } namespace pybind11 { namespace detail { bool type_caster<tensorstore::internal_python::DimensionSelectionLike>::load( handle src, bool convert) { if (pybind11::isinstance<tensorstore::internal_python::DimensionSelection>( src)) { value.value = pybind11::cast<tensorstore::internal_python::DimensionSelection>(src); return true; } if (!convert) return false; auto ops = tensorstore::internal::MakeIntrusivePtr< tensorstore::internal_python::PythonDimExpressionChainTail>(); auto& dims = ops->dims; if (tensorstore::internal_python::CastToDimensionSelection(src, dims)) { value.value.ops = std::move(ops); return true; } return false; } handle type_caster<tensorstore::internal_python::DimensionSelectionLike>::cast( tensorstore::internal_python::DimensionSelectionLike value, return_value_policy policy, handle parent) { return pybind11::cast(std::move(value.value)); } bool type_caster<tensorstore::DimRangeSpec>::load(handle src, bool convert) { if (!PySlice_Check(src.ptr())) return false; Py_ssize_t start, stop, step; if (PySlice_Unpack(src.ptr(), &start, &stop, &step) != 0) { return false; } auto* slice_obj = reinterpret_cast<PySliceObject*>(src.ptr()); if (slice_obj->start != Py_None) value.inclusive_start = start; if (slice_obj->stop != Py_None) value.exclusive_stop = stop; value.step = step; return true; } handle type_caster<tensorstore::DimRangeSpec>::cast( const tensorstore::DimRangeSpec& x, return_value_policy , handle ) { handle h(PySlice_New(pybind11::cast(x.inclusive_start).ptr(), pybind11::cast(x.exclusive_stop).ptr(), x.step == 1 ? nullptr : pybind11::cast(x.step).ptr())); if (!h.ptr()) throw error_already_set(); return h; } } }
#include "tensorstore/index_space/dim_expression.h" #include <string_view> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorstore/array.h" #include "tensorstore/box.h" #include "tensorstore/index.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/transformed_array.h" #include "tensorstore/rank.h" #include "tensorstore/util/result.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status_testutil.h" namespace { using ::tensorstore::AllDims; using ::tensorstore::BoxView; using ::tensorstore::DimRange; using ::tensorstore::Dims; using ::tensorstore::Index; using ::tensorstore::MakeArray; using ::tensorstore::MakeOffsetArrayView; using ::tensorstore::Materialize; static const Index default_origin[3] = {0, 0, 0}; auto TestArray(tensorstore::span<const Index, 3> origin = default_origin) { static const int test_array[4][4][8] = { { {111, 112, 113, 114, 115, 116, 117, 118}, {121, 122, 123, 124, 125, 126, 127, 128}, {131, 132, 133, 134, 135, 136, 137, 138}, {141, 142, 143, 144, 145, 146, 147, 148}, }, { {211, 212, 213, 214, 215, 216, 217, 218}, {221, 222, 223, 224, 225, 226, 227, 228}, {231, 232, 233, 234, 235, 236, 237, 238}, {241, 242, 243, 244, 245, 246, 247, 248}, }, { {311, 312, 313, 314, 315, 316, 317, 318}, {321, 322, 323, 324, 325, 326, 327, 328}, {331, 332, 333, 334, 335, 336, 337, 338}, {341, 342, 343, 344, 345, 346, 347, 348}, }, { {411, 412, 413, 414, 415, 416, 417, 418}, {421, 422, 423, 424, 425, 426, 427, 428}, {431, 432, 433, 434, 435, 436, 437, 438}, {441, 442, 443, 444, 445, 446, 447, 448}, }}; return MakeOffsetArrayView(origin, test_array); } TEST(DimExpressionTest, TranslateBy) { auto view = TestArray() | Dims(0, 2).TranslateBy({10, 20}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(344, ((*view)({12, 3, 23}))); } TEST(DimExpressionTest, TranslateBySingle) { auto view = TestArray() | Dims(0, 2).TranslateBy(10); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, TranslateTo) { const Index origin[3] = {1, 2, 3}; auto view = TestArray(origin) | Dims(0, 2).TranslateTo({10, 20}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(344 - 123, ((*view)({11, 3, 20}))); } TEST(DimExpressionTest, TranslateToSingle) { auto view = TestArray() | AllDims().TranslateTo(0); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, IndexSlice) { auto view = TestArray() | Dims(0, 2).IndexSlice({2, 4}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(345, ((*view)({3}))); } TEST(DimExpressionTest, IndexSliceSingle) { auto view = TestArray() | Dims(0, 2).IndexSlice(1); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, BoxSlice) { auto view = TestArray() | Dims(0, 2).BoxSlice(BoxView({1, 4}, {3, 4})) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(245, ((*view)({1, 3, 4}))); } TEST(DimExpressionTest, TranslateBoxSlice) { const Index origin[3] = {0, 2, 0}; auto view = TestArray(origin) | Dims(0, 2).TranslateBoxSlice(BoxView({1, 4}, {3, 4})) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(245 - 20, ((*view)({0, 3, 0}))); } TEST(DimExpressionTest, ClosedInterval) { auto view = TestArray() | Dims(0, 2).ClosedInterval({1, 6}, {3, 0}, {1, -2}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(347, ((*view)({2, 3, -3}))); } TEST(DimExpressionTest, ClosedInterval1) { auto view = TestArray() | Dims(0, 2).ClosedInterval(1, 1); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, HalfOpenInterval) { auto view = TestArray() | Dims(0, 2).HalfOpenInterval({1, 6}, {3, 0}, {1, -2}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(347, ((*view)({2, 3, -3}))); } TEST(DimExpressionTest, HalfOpenInterval1) { auto view = TestArray() | Dims(0, 2).HalfOpenInterval(1, 2); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, SizedInterval) { auto view = TestArray() | Dims(0, 2).SizedInterval({1, 6}, {3, 2}, {1, -2}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(347, ((*view)({2, 3, -3}))); } TEST(DimExpressionTest, SizedInterval1) { auto view = TestArray() | Dims(0, 2).SizedInterval(1, 2); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, TranslateClosedInterval) { auto view = TestArray() | Dims(0, 2).TranslateClosedInterval({0, 1}, {1, 1}); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, TranslateClosedInterval1) { auto view = TestArray() | Dims(0, 2).TranslateClosedInterval(1, 1); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, TranslateHalfOpenInterval) { auto view = TestArray() | Dims(0, 2).TranslateHalfOpenInterval({0, 1}, {1, 1}); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, TranslateHalfOpenInterval1) { auto view = TestArray() | Dims(0, 2).TranslateHalfOpenInterval(1, 2); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, TranslateSizedInterval) { auto view = TestArray() | Dims(0, 2).TranslateSizedInterval({0, 1}, {1, 1}); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, TranslateSizedInterval1) { auto view = TestArray() | Dims(0, 2).TranslateSizedInterval(1, 2); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, IndexArraySlice) { auto view = TestArray() | Dims(0, 2).IndexArraySlice( MakeArray<Index>({{1, 2, 3}, {3, 2, 1}}), MakeArray<Index>({{7, 6, 5}, {1, 2, 4}})) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(248, ((*view)({0, 0, 3}))); } TEST(DimExpressionTest, IndexVectorArraySlice) { auto view = TestArray() | Dims(0, 2).IndexVectorArraySlice( MakeArray<Index>( {{{1, 7}, {2, 6}, {3, 5}}, {{3, 1}, {2, 2}, {1, 4}}}), -1) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(248, ((*view)({0, 0, 3}))); } TEST(DimExpressionTest, OuterIndexArraySlice) { auto view = TestArray() | Dims(2, 0).OuterIndexArraySlice( MakeArray<Index>({{4, 5}, {6, 7}}), MakeArray<Index>({3, 2})) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(438, ((*view)({0, 2, 1, 1}))); } TEST(DimExpressionTest, Label) { auto view = TestArray() | Dims(0, 2).Label({"a", "b"}); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, LabelB) { auto view = TestArray() | Dims(0, 2).Label("a", "b"); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, MoveTo) { auto view = TestArray() | Dims(2, 0).MoveTo(1) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(345, ((*view)({3, 4, 2}))); } TEST(DimExpressionTest, MoveToFront) { auto view = TestArray() | Dims(0, 2).MoveToFront(); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, MoveToBack) { auto view = TestArray() | Dims(0, 2).MoveToFront(); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, Diagonal) { auto view = TestArray() | Dims(0, 2).Diagonal() | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(343, ((*view)({2, 3}))); } TEST(DimExpressionTest, AddNew) { auto view = TestArray() | Dims(0, -1).AddNew() | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(333, ((*view)({0, 2, 2, 2, 0}))); } TEST(DimExpressionTest, Transpose) { auto view = TestArray() | Dims(2, 0, 1).Transpose() | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(234, ((*view)({3, 1, 2}))); } TEST(DimExpressionTest, TransposeB) { auto view = TestArray() | Dims(2, 0).Transpose({1, 2}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(345, ((*view)({3, 4, 2}))); } TEST(DimExpressionTest, MarkBoundsExplicit) { auto view = TestArray() | Dims(2, 0).MarkBoundsExplicit(); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, UnsafeMarkBoundsImplicit) { auto view = TestArray() | Dims(2, 0).UnsafeMarkBoundsImplicit(); TENSORSTORE_EXPECT_OK(view); } TEST(DimExpressionTest, Stride) { auto view = TestArray() | Dims(0, 2).Stride({-2, 3}) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(344, ((*view)({-1, 3, 1}))); } TEST(DimExpressionTest, AllDims) { auto view = TestArray() | AllDims().IndexSlice(1) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(222, ((*view)())); } TEST(DimExpressionTest, DimRange) { auto view = TestArray() | tensorstore::DimRange(1).IndexSlice(1) | Materialize(); TENSORSTORE_EXPECT_OK(view); EXPECT_EQ(322, ((*view)(2))); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/python/tensorstore/dim_expression.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/index_space/dim_expression_test.cc
4f887a6430414cd6088e1743555015b10f116d50
697358e5-9e87-487b-a7f6-e0a7ac0f0008
cpp
google/tensorstore
future
tensorstore/util/future.cc
tensorstore/util/future_test.cc
#include "tensorstore/util/future.h" #include <stddef.h> #include <stdint.h> #include <atomic> #include <cassert> #include <thread> #include <utility> #include "absl/base/attributes.h" #include "absl/base/const_init.h" #include "absl/base/no_destructor.h" #include "absl/base/optimization.h" #include "absl/hash/hash.h" #include "absl/status/status.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "tensorstore/internal/container/intrusive_linked_list.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/metrics/counter.h" #include "tensorstore/internal/metrics/gauge.h" #include "tensorstore/internal/metrics/metadata.h" #include "tensorstore/util/future_impl.h" #include "tensorstore/util/result.h" #include "tensorstore/util/span.h" using ::tensorstore::internal_metrics::MetricMetadata; namespace tensorstore { namespace internal_future { namespace { auto& live_futures = internal_metrics::Gauge<int64_t>::New( "/tensorstore/futures/live", MetricMetadata("Live futures")); auto& future_ready_callbacks = internal_metrics::Counter<int64_t>::New( "/tensorstore/futures/ready_callbacks", MetricMetadata("Ready callbacks")); auto& future_not_needed_callbacks = internal_metrics::Counter<int64_t>::New( "/tensorstore/futures/not_needed_callbacks", MetricMetadata("Not needed callbacks")); auto& future_force_callbacks = internal_metrics::Counter<int64_t>::New( "/tensorstore/futures/force_callbacks", MetricMetadata("Force callbacks")); } static CallbackListNode unregister_requested; struct ABSL_CACHELINE_ALIGNED CacheLineAlignedMutex { absl::Mutex mutex{absl::kConstInit}; }; constexpr size_t kNumMutexes = 64; absl::Mutex* GetMutex(FutureStateBase* ptr) { ABSL_CONST_INIT static CacheLineAlignedMutex mutexes[kNumMutexes]; return &mutexes[absl::HashOf(ptr) % kNumMutexes].mutex; } using CallbackListAccessor = internal::intrusive_linked_list::MemberAccessor<CallbackListNode>; namespace { CallbackPointer MakeUnregisteredCallbackPointer(CallbackBase* callback) { assert(callback->reference_count_.load(std::memory_order_relaxed) >= 2); callback->next = callback->prev = callback; callback->reference_count_.fetch_sub(1, std::memory_order_relaxed); return CallbackPointer(callback, internal::adopt_object_ref); } } CallbackPointer FutureStateBase::RegisterReadyCallback( ReadyCallbackBase* callback) { assert(callback->reference_count_.load(std::memory_order_relaxed) >= 2); { absl::MutexLock lock(GetMutex(this)); future_ready_callbacks.Increment(); if (!this->ready()) { InsertBefore(CallbackListAccessor{}, &ready_callbacks_, callback); return CallbackPointer(callback, internal::adopt_object_ref); } } callback->OnReady(); return MakeUnregisteredCallbackPointer(callback); } CallbackPointer FutureStateBase::RegisterNotNeededCallback( ResultNotNeededCallbackBase* callback) { assert(callback->reference_count_.load(std::memory_order_relaxed) >= 2); { absl::MutexLock lock(GetMutex(this)); future_not_needed_callbacks.Increment(); if (result_needed()) { InsertBefore(CallbackListAccessor{}, &promise_callbacks_, callback); return CallbackPointer(callback, internal::adopt_object_ref); } } callback->OnResultNotNeeded(); return MakeUnregisteredCallbackPointer(callback); } CallbackPointer FutureStateBase::RegisterForceCallback( ForceCallbackBase* callback) { assert(callback->reference_count_.load(std::memory_order_relaxed) >= 2); auto* mutex = GetMutex(this); { absl::MutexLock lock(mutex); future_force_callbacks.Increment(); const auto state = state_.load(std::memory_order_acquire); if ((state & kResultLocked) != 0 || !has_future()) { goto destroy_callback; } if (state & kForcing) { goto already_forced; } InsertBefore(CallbackListAccessor{}, &promise_callbacks_, callback); return CallbackPointer(callback, internal::adopt_object_ref); } already_forced: callback->OnForced(); if (callback->callback_type() == CallbackBase::kLinkCallback) { absl::MutexLock lock(mutex); if (result_needed()) { InsertBefore(CallbackListAccessor{}, &promise_callbacks_, callback); return CallbackPointer(callback, internal::adopt_object_ref); } } else { return MakeUnregisteredCallbackPointer(callback); } destroy_callback: callback->OnUnregistered(); return MakeUnregisteredCallbackPointer(callback); } CallbackBase::~CallbackBase() {} void CallbackBase::Unregister(bool block) noexcept { auto* shared_state = this->shared_state(); auto* mutex = GetMutex(shared_state); { absl::MutexLock lock(mutex); if (next == this) { return; } if (next == nullptr || next == &unregister_requested) { next = &unregister_requested; if (!block || running_callback_thread == std::this_thread::get_id()) { return; } const auto is_done = [&] { return this->next != &unregister_requested; }; mutex->Await(absl::Condition(&is_done)); return; } Remove(CallbackListAccessor{}, this); next = this; } this->OnUnregistered(); CallbackPointerTraits::decrement(this); } FutureStateBase::FutureStateBase() : state_(kInitial), combined_reference_count_(2), promise_reference_count_(1), future_reference_count_(1) { Initialize(CallbackListAccessor{}, &ready_callbacks_); Initialize(CallbackListAccessor{}, &promise_callbacks_); live_futures.Increment(); } namespace { void NoMorePromiseReferences(FutureStateBase* shared_state) { if (shared_state->LockResult()) { shared_state->MarkResultWrittenAndCommitResult(); } else { shared_state->CommitResult(); } shared_state->ReleaseCombinedReference(); } template <typename BeforeUnregisterFunc, typename AfterUnregisterFunc> inline void RunAndReleaseCallbacks(FutureStateBase* shared_state, CallbackListNode* head, BeforeUnregisterFunc before_func, AfterUnregisterFunc after_func) { const auto thread_id = std::this_thread::get_id(); auto* mutex = GetMutex(shared_state); CallbackPointer prev_node; while (true) { CallbackListNode* next_node; { absl::MutexLock lock(mutex); if (prev_node != nullptr) { using Id = std::thread::id; prev_node->running_callback_thread.~Id(); prev_node->next = prev_node.get(); } next_node = head->next; if (next_node == head) { break; } Remove(CallbackListAccessor{}, next_node); next_node->next = nullptr; new (&next_node->running_callback_thread) std::thread::id(thread_id); } if (prev_node) after_func(prev_node.get()); prev_node.reset(static_cast<CallbackBase*>(next_node), internal::adopt_object_ref); before_func(prev_node.get()); } if (prev_node) after_func(prev_node.get()); } void RunReadyCallbacks(FutureStateBase* shared_state) { RunAndReleaseCallbacks( shared_state, &shared_state->ready_callbacks_, [](CallbackBase* callback) { static_cast<ReadyCallbackBase*>(callback)->OnReady(); }, [](CallbackBase* callback) {}); } void DestroyPromiseCallbacks(FutureStateBase* shared_state) { RunAndReleaseCallbacks( shared_state, &shared_state->promise_callbacks_, [](CallbackBase* callback) { if (callback->callback_type() == CallbackBase::kResultNotNeededCallback) { static_cast<ResultNotNeededCallbackBase*>(callback) ->OnResultNotNeeded(); } }, [](CallbackBase* callback) { if (callback->callback_type() != CallbackBase::kResultNotNeededCallback) { callback->OnUnregistered(); } }); } void RunForceCallbacks(FutureStateBase* shared_state) { const auto thread_id = std::this_thread::get_id(); auto* mutex = GetMutex(shared_state); CallbackPointer prev_node; CallbackListNode temp_head; CallbackListNode* const head = &shared_state->promise_callbacks_; while (true) { CallbackListNode* next_node; { absl::MutexLock lock(mutex); if (prev_node) { using Id = std::thread::id; if (prev_node->callback_type() == CallbackBase::kLinkCallback) { if (prev_node->next == &unregister_requested) { prev_node->next = prev_node.get(); mutex->Unlock(); static_cast<CallbackBase*>(prev_node.get())->OnUnregistered(); mutex->Lock(); } else { prev_node->running_callback_thread.~Id(); InsertBefore(CallbackListAccessor{}, head, prev_node.release()); } } else { assert(prev_node->callback_type() == CallbackBase::kForceCallback); prev_node->next = prev_node.get(); } } else { temp_head.next = head->next; temp_head.next->prev = &temp_head; temp_head.prev = head->prev; temp_head.prev->next = &temp_head; head->next = head->prev = head; shared_state->state_.fetch_or(FutureStateBase::kForcing); } while (true) { next_node = temp_head.next; if (next_node == &temp_head) return; Remove(CallbackListAccessor{}, next_node); if (static_cast<CallbackBase*>(next_node)->callback_type() == CallbackBase::kResultNotNeededCallback) { InsertBefore(CallbackListAccessor{}, head, next_node); continue; } next_node->next = nullptr; new (&next_node->running_callback_thread) std::thread::id(thread_id); break; } } prev_node.reset(static_cast<CallbackBase*>(next_node), internal::adopt_object_ref); static_cast<ForceCallbackBase*>(prev_node.get())->OnForced(); } } void NoMoreFutureReferences(FutureStateBase* shared_state) { DestroyPromiseCallbacks(shared_state); shared_state->ReleaseCombinedReference(); } } void FutureStateBase::Force() noexcept { StateValue prior_state = kInitial; if (!state_.compare_exchange_strong(prior_state, kPreparingToForce)) { return; } RunForceCallbacks(this); prior_state = state_.fetch_or(kForced); if (prior_state & kResultLocked) { DestroyPromiseCallbacks(this); } } void FutureStateBase::ReleaseFutureReference() { if (--future_reference_count_ == 0) { NoMoreFutureReferences(this); } } void FutureStateBase::ReleasePromiseReference() { if (--promise_reference_count_ == 0) { NoMorePromiseReferences(this); } } void FutureStateBase::ReleaseCombinedReference() { if (--combined_reference_count_ == 0) { delete this; } } bool FutureStateBase::AcquireFutureReference() noexcept { auto existing = future_reference_count_.load(std::memory_order_relaxed); while (true) { if (existing == 0) { if ((state_.load(std::memory_order_acquire) & kResultLocked) == 0) { return false; } if (future_reference_count_.fetch_add(1, std::memory_order_acq_rel) == 0) { combined_reference_count_.fetch_add(1, std::memory_order_relaxed); } return true; } if (future_reference_count_.compare_exchange_weak( existing, existing + 1, std::memory_order_acq_rel)) { return true; } } } bool FutureStateBase::LockResult() noexcept { const StateValue prior_state = state_.fetch_or(kResultLocked); if (prior_state & kResultLocked) return false; if ((prior_state & kForced) != 0 || (prior_state & kPreparingToForce) == 0) { DestroyPromiseCallbacks(this); } else { } return true; } void FutureStateBase::MarkResultWritten() noexcept { const StateValue prior_state = state_.fetch_or(kResultWritten); assert(prior_state & kResultLocked); assert((prior_state & kResultWritten) == 0); if (prior_state & kReady) { RunReadyCallbacks(this); } } bool FutureStateBase::CommitResult() noexcept { const StateValue prior_state = state_.fetch_or(kReady); if (prior_state & kReady) return false; if (prior_state & kResultWritten) { RunReadyCallbacks(this); } return true; } void FutureStateBase::MarkResultWrittenAndCommitResult() noexcept { [[maybe_unused]] const StateValue prior_state = state_.fetch_or(kResultWrittenAndReady); assert(prior_state & kResultLocked); assert((prior_state & kResultWritten) == 0); RunReadyCallbacks(this); } bool FutureStateBase::WaitFor(absl::Duration duration) noexcept { if (ready()) return true; Force(); absl::Mutex* mutex = GetMutex(this); bool is_ready = mutex->LockWhenWithTimeout( absl::Condition(this, &FutureStateBase::ready), duration); mutex->Unlock(); return is_ready; } bool FutureStateBase::WaitUntil(absl::Time deadline) noexcept { if (ready()) return true; Force(); absl::Mutex* mutex = GetMutex(this); bool is_ready = mutex->LockWhenWithDeadline( absl::Condition(this, &FutureStateBase::ready), deadline); mutex->Unlock(); return is_ready; } void FutureStateBase::Wait() noexcept { if (ready()) return; Force(); absl::Mutex* mutex = GetMutex(this); mutex->LockWhen(absl::Condition(this, &FutureStateBase::ready)); mutex->Unlock(); } FutureStateBase::~FutureStateBase() { assert(promise_callbacks_.next == &promise_callbacks_); assert(ready_callbacks_.next == &ready_callbacks_); live_futures.Decrement(); } } ReadyFuture<const void> MakeReadyFuture() { static absl::NoDestructor<ReadyFuture<const void>> future{ MakeReadyFuture<void>(MakeResult())}; return *future; } Future<void> WaitAllFuture(tensorstore::span<const AnyFuture> futures) { auto& f = futures; switch (f.size()) { case 0: return MakeReadyFuture<void>(absl::OkStatus()); case 1: return PromiseFuturePair<void>::LinkError(absl::OkStatus(), f[0]).future; case 2: return PromiseFuturePair<void>::LinkError(absl::OkStatus(), f[0], f[1]) .future; case 3: return PromiseFuturePair<void>::LinkError(absl::OkStatus(), f[0], f[1], f[2]) .future; case 4: return PromiseFuturePair<void>::LinkError(absl::OkStatus(), f[0], f[1], f[2], f[3]) .future; case 5: return PromiseFuturePair<void>::LinkError(absl::OkStatus(), f[0], f[1], f[2], f[3], f[4]) .future; case 6: return PromiseFuturePair<void>::LinkError(absl::OkStatus(), f[0], f[1], f[2], f[3], f[4], f[5]) .future; case 7: return PromiseFuturePair<void>::LinkError(absl::OkStatus(), f[0], f[1], f[2], f[3], f[4], f[5], f[6]) .future; default: break; } auto [promise, result] = PromiseFuturePair<void>::LinkError( absl::OkStatus(), f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]); f = f.subspan(8); while (f.size() > 8) { LinkError(promise, f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]); f = f.subspan(8); } switch (f.size()) { case 0: return std::move(result); case 1: LinkError(std::move(promise), f[0]); return std::move(result); case 2: LinkError(std::move(promise), f[0], f[1]); return std::move(result); case 3: LinkError(std::move(promise), f[0], f[1], f[2]); return std::move(result); case 4: LinkError(std::move(promise), f[0], f[1], f[2], f[3]); return std::move(result); case 5: LinkError(std::move(promise), f[0], f[1], f[2], f[3], f[4]); return std::move(result); case 6: LinkError(std::move(promise), f[0], f[1], f[2], f[3], f[4], f[5]); return std::move(result); case 7: LinkError(std::move(promise), f[0], f[1], f[2], f[3], f[4], f[5], f[6]); return std::move(result); case 8: LinkError(std::move(promise), f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]); return std::move(result); } ABSL_UNREACHABLE(); } }
#include "tensorstore/util/future.h" #include <stddef.h> #include <atomic> #include <chrono> #include <functional> #include <memory> #include <thread> #include <type_traits> #include <utility> #include <benchmark/benchmark.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tensorstore/internal/metrics/registry.h" #include "tensorstore/internal/testing/concurrent.h" #include "tensorstore/util/executor.h" #include "tensorstore/util/future_impl.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" #include "tensorstore/util/str_cat.h" namespace { using ::tensorstore::AnyFuture; using ::tensorstore::Future; using ::tensorstore::FutureCallbackRegistration; using ::tensorstore::InlineExecutor; using ::tensorstore::IsFutureConvertible; using ::tensorstore::MakeReadyFuture; using ::tensorstore::MakeResult; using ::tensorstore::MatchesStatus; using ::tensorstore::Promise; using ::tensorstore::PromiseFuturePair; using ::tensorstore::ReadyFuture; using ::tensorstore::Result; using ::tensorstore::internal_future::FutureAccess; using ::tensorstore::internal_testing::TestConcurrent; static_assert(IsFutureConvertible<int, const int>); static_assert(!IsFutureConvertible<const int, int>); static_assert( std::is_same_v< decltype(FutureAccess::rep_pointer(std::declval<Future<void>&>())), tensorstore::internal_future::FutureStatePointer&>); static_assert( std::is_same_v<decltype(FutureAccess::rep_pointer( std::declval<const Future<void>&>())), const tensorstore::internal_future::FutureStatePointer&>); static_assert( std::is_same_v< decltype(FutureAccess::rep_pointer(std::declval<Future<void>&&>())), tensorstore::internal_future::FutureStatePointer&&>); static_assert( std::is_same_v< decltype(FutureAccess::rep_pointer(std::declval<Promise<void>&>())), tensorstore::internal_future::PromiseStatePointer&>); static_assert( std::is_same_v<decltype(FutureAccess::rep_pointer( std::declval<const Promise<void>&>())), const tensorstore::internal_future::PromiseStatePointer&>); static_assert( std::is_same_v< decltype(FutureAccess::rep_pointer(std::declval<Promise<void>&&>())), tensorstore::internal_future::PromiseStatePointer&&>); static_assert(!std::is_constructible_v<Result<int>, Result<Future<int>>>); static_assert(!std::is_convertible_v<Result<int>, Result<Future<int>>>); static_assert(!std::is_assignable_v<Result<int>, Result<Future<int>>>); static_assert(std::is_same_v< Result<Future<void>>, tensorstore::FlatResult<std::invoke_result_t<Future<void>()>>>); TEST(FutureTest, Valid) { EXPECT_TRUE(Future<int>().null()); EXPECT_TRUE(Promise<int>().null()); auto pair = PromiseFuturePair<int>::Make(); EXPECT_FALSE(pair.future.null()); EXPECT_FALSE(pair.promise.null()); auto future2 = pair.promise.future(); EXPECT_FALSE(future2.null()); } TEST(FutureTest, MakeReadyFuture) { Future<int> future = MakeReadyFuture<int>(3); EXPECT_EQ(true, future.ready()); EXPECT_EQ(3, future.result().value()); Result<int> result{tensorstore::in_place}; bool got_result = false; future.ExecuteWhenReady([&](ReadyFuture<int> r) { got_result = true; result = r.result(); }); EXPECT_TRUE(got_result); EXPECT_EQ(result, future.result()); } TEST(FutureTest, MakeInPlace) { auto pair = PromiseFuturePair<int>::Make(tensorstore::in_place, 4); pair.promise.reset(); EXPECT_EQ(4, pair.future.value()); } TEST(FutureTest, ConstructFromValue) { Future<int> x = 3; EXPECT_EQ(3, x.value()); } TEST(FutureTest, ConstructFromValueConst) { Future<const int> x = 3; EXPECT_EQ(3, x.value()); } TEST(FutureTest, FlattenResultError) { Future<int> x = MakeResult<Future<int>>(absl::UnknownError("Error")); EXPECT_THAT(x.result(), MatchesStatus(absl::StatusCode::kUnknown, "Error")); } TEST(FutureTest, FlattenResultErrorConst) { Future<const int> x = MakeResult<Future<int>>(absl::UnknownError("Error")); EXPECT_THAT(x.result(), MatchesStatus(absl::StatusCode::kUnknown, "Error")); } TEST(FutureTest, FlattenResultSuccess) { auto pair = PromiseFuturePair<int>::Make(); Future<int> x = MakeResult(pair.future); EXPECT_TRUE(HaveSameSharedState(pair.future, x)); } TEST(FutureTest, FlattenResultSuccessConstConvert) { auto pair = PromiseFuturePair<int>::Make(); Future<const int> x = MakeResult(pair.future); EXPECT_TRUE(HaveSameSharedState(pair.future, x)); } TEST(FutureTest, FlattenResultLvalue) { Result<Future<int>> f1 = absl::UnknownError(""); Future<int> f2 = f1; EXPECT_EQ(absl::UnknownError(""), GetStatus(f2.result())); } TEST(FutureTest, SetResult) { { auto pair = PromiseFuturePair<int>::Make(); EXPECT_FALSE(pair.promise.ready()); EXPECT_TRUE(pair.promise.result_needed()); EXPECT_FALSE(pair.future.ready()); Result<int> result{tensorstore::in_place}; bool got_result = false; pair.future.ExecuteWhenReady([&](ReadyFuture<int> r) { got_result = true; result = r.result(); }); EXPECT_FALSE(got_result); EXPECT_TRUE(pair.promise.SetResult(5)); EXPECT_FALSE(pair.promise.result_needed()); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_EQ(result, 5); } { auto pair = PromiseFuturePair<int>::Make(); pair.promise.SetResult(std::in_place, 6); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_TRUE(pair.future.result().ok()); } { auto pair = PromiseFuturePair<int>::Make(); pair.promise.SetResult(MakeResult(7)); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_TRUE(pair.future.result().ok()); } { auto pair = PromiseFuturePair<int>::Make(); pair.promise.SetResult(absl::InternalError("error")); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_FALSE(pair.future.result().ok()); } { auto pair = PromiseFuturePair<int>::Make(); pair.promise.SetResult(MakeResult<int>(absl::InternalError("error"))); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_FALSE(pair.future.result().ok()); } } TEST(FutureTest, SetResultVoid) { { auto pair = PromiseFuturePair<void>::Make(); EXPECT_FALSE(pair.promise.ready()); EXPECT_TRUE(pair.promise.result_needed()); EXPECT_FALSE(pair.future.ready()); EXPECT_TRUE(pair.promise.SetResult(absl::OkStatus())); EXPECT_FALSE(pair.promise.result_needed()); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_TRUE(pair.future.result().ok()); } { auto pair = PromiseFuturePair<void>::Make(); pair.promise.SetResult(std::in_place); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_TRUE(pair.future.result().ok()); } { auto pair = PromiseFuturePair<void>::Make(); pair.promise.SetResult(MakeResult<void>(absl::OkStatus())); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_TRUE(pair.future.result().ok()); } { auto pair = PromiseFuturePair<void>::Make(); pair.promise.SetResult(absl::InternalError("error")); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_FALSE(pair.future.result().ok()); } { auto pair = PromiseFuturePair<void>::Make(); pair.promise.SetResult(MakeResult<void>(absl::InternalError("error"))); EXPECT_TRUE(pair.future.ready()); EXPECT_TRUE(pair.promise.ready()); EXPECT_FALSE(pair.future.result().ok()); } } TEST(FutureTest, Wait) { auto pair = PromiseFuturePair<int>::Make(); std::thread thread( [](Promise<int> promise) { absl::SleepFor(absl::Milliseconds(20)); EXPECT_TRUE(promise.SetResult(5)); }, std::move(pair.promise)); pair.future.Wait(); EXPECT_EQ(5, pair.future.result()); thread.join(); } TEST(FutureTest, WaitForFailure) { for (size_t i = 0; i < 100; ++i) { auto pair = PromiseFuturePair<int>::Make(); EXPECT_FALSE(pair.future.WaitFor(absl::Milliseconds(10))); std::thread thread( [](Promise<int> promise) { absl::SleepFor(absl::Milliseconds(20)); EXPECT_TRUE(promise.SetResult(5)); }, pair.promise); const bool ready = pair.future.WaitFor(absl::Milliseconds(5)); thread.join(); if (!ready) { return; } } FAIL(); } TEST(FutureTest, WaitForSuccess) { for (size_t i = 0; i < 100; ++i) { auto pair = PromiseFuturePair<int>::Make(); std::thread thread( [](Promise<int> promise) { absl::SleepFor(absl::Milliseconds(5)); EXPECT_TRUE(promise.SetResult(5)); }, pair.promise); const bool ready1 = pair.future.WaitFor(absl::Milliseconds(20)); const bool ready2 = pair.future.WaitFor(absl::Milliseconds(10)); thread.join(); if (ready1 && ready2) { return; } } FAIL(); } TEST(FutureTest, WaitUntilFailure) { for (size_t i = 0; i < 100; ++i) { auto pair = PromiseFuturePair<int>::Make(); EXPECT_FALSE(pair.future.WaitUntil(absl::Now() - absl::Milliseconds(10))); EXPECT_FALSE(pair.future.WaitUntil(absl::Now() + absl::Milliseconds(10))); std::thread thread( [](Promise<int> promise) { absl::SleepFor(absl::Milliseconds(20)); EXPECT_TRUE(promise.SetResult(5)); }, pair.promise); const bool ready = pair.future.WaitUntil(absl::Now() + absl::Milliseconds(5)); thread.join(); if (!ready) { return; } } FAIL(); } TEST(FutureTest, WaitUntilSuccess) { for (size_t i = 0; i < 100; ++i) { auto pair = PromiseFuturePair<int>::Make(); std::thread thread( [](Promise<int> promise) { absl::SleepFor(absl::Milliseconds(5)); EXPECT_TRUE(promise.SetResult(5)); }, pair.promise); const bool ready1 = pair.future.WaitUntil(absl::Now() + absl::Milliseconds(20)); const bool ready2 = pair.future.WaitUntil(absl::Now() + absl::Milliseconds(10)); thread.join(); if (ready1 && ready2) { return; } } FAIL(); } TEST(FutureTest, SetResultTwice) { auto pair = PromiseFuturePair<int>::Make(); EXPECT_TRUE(pair.promise.SetResult(3)); EXPECT_EQ(3, pair.future.result()); EXPECT_EQ(false, pair.promise.SetResult(5)); EXPECT_EQ(3, pair.future.result()); } TEST(FutureTest, ExecuteWhenNotNeeded) { auto pair = PromiseFuturePair<int>::Make(); bool no_future = false; pair.promise.ExecuteWhenNotNeeded([&] { no_future = true; }); EXPECT_FALSE(no_future); pair.future.reset(); EXPECT_FALSE(pair.promise.result_needed()); EXPECT_TRUE(no_future); } TEST(FutureTest, ExecuteWhenNotNeededBeforeForced) { auto pair = PromiseFuturePair<int>::Make(); bool no_future = false; pair.promise.ExecuteWhenNotNeeded([&] { no_future = true; }); EXPECT_FALSE(no_future); pair.future.reset(); EXPECT_FALSE(pair.promise.result_needed()); EXPECT_TRUE(no_future); } TEST(FutureTest, ExecuteWhenNotNeededUnregister) { auto pair = PromiseFuturePair<int>::Make(); bool no_future = false; auto registration = pair.promise.ExecuteWhenNotNeeded([&] { no_future = true; }); EXPECT_FALSE(no_future); registration.Unregister(); pair.future.reset(); EXPECT_FALSE(no_future); } TEST(FutureTest, ExecuteWhenNotNeededImmediate) { auto pair = PromiseFuturePair<int>::Make(); bool no_future = false; pair.future.reset(); auto registration = pair.promise.ExecuteWhenNotNeeded([&] { no_future = true; }); EXPECT_TRUE(no_future); registration.Unregister(); } TEST(FutureTest, ExecuteWhenReadyUnregisterTwice) { auto pair = PromiseFuturePair<int>::Make(); bool invoked = false; auto registration = pair.future.ExecuteWhenReady([&](ReadyFuture<int>) { invoked = true; }); EXPECT_FALSE(invoked); auto registration2 = registration; registration.Unregister(); registration2.Unregister(); pair.promise.SetResult(3); EXPECT_FALSE(invoked); } TEST(FutureTest, ExecuteWhenNotNeededThenForce) { auto pair = PromiseFuturePair<int>::Make(); bool no_future = false; auto registration = pair.promise.ExecuteWhenNotNeeded([&] { no_future = true; }); pair.future.Force(); pair.future.reset(); EXPECT_TRUE(no_future); registration.Unregister(); } TEST(FutureTest, ExecuteWhenReadyUnregisterSelf) { auto pair = PromiseFuturePair<int>::Make(); bool invoked = false; FutureCallbackRegistration registration; registration = pair.future.ExecuteWhenReady([&](ReadyFuture<int>) { invoked = true; registration(); }); pair.promise.SetResult(3); EXPECT_TRUE(invoked); } TEST(FutureTest, ExecuteWhenReadyUnregisterSelfTwice) { auto pair = PromiseFuturePair<int>::Make(); bool invoked = false; FutureCallbackRegistration registration; registration = pair.future.ExecuteWhenReady([&](ReadyFuture<int>) { invoked = true; auto registration_copy = registration; registration(); registration_copy(); }); pair.promise.SetResult(3); EXPECT_TRUE(invoked); } TEST(FutureTest, Destructor) { auto pair = PromiseFuturePair<int>::Make(); static_cast<void>(pair); } TEST(FutureTest, DestructorExecuteWhenReady) { auto pair = PromiseFuturePair<int>::Make(); pair.future.ExecuteWhenReady([&](ReadyFuture<int>) {}); } TEST(FutureTest, ExecuteWhenReadyUnregisterOther) { auto pair = PromiseFuturePair<int>::Make(); bool invoked = false; FutureCallbackRegistration registration; pair.future.ExecuteWhenReady([&](ReadyFuture<int>) { registration(); }); registration = pair.future.ExecuteWhenReady([&](ReadyFuture<int>) { invoked = true; }); pair.promise.SetResult(3); EXPECT_FALSE(invoked); } TEST(FutureTest, ExecuteWhenReadyUnregisterConcurrent) { PromiseFuturePair<int> pair; std::atomic<bool> unregistered; FutureCallbackRegistration registration; TestConcurrent( 1000, [&] { unregistered = false; pair = PromiseFuturePair<int>::Make(); registration = pair.future.ExecuteWhenReady([&](ReadyFuture<int>) { for (int i = 0; i < 100; ++i) { EXPECT_FALSE(unregistered.load()); } }); }, [&] { EXPECT_TRUE(unregistered.load()); }, [&] { pair.promise.SetResult(3); }, [&] { registration.Unregister(); unregistered = true; }); } TEST(FutureTest, ExecuteWhenReadyUnregisterNonBlockingConcurrent) { PromiseFuturePair<int> pair; std::atomic<bool> callback_started, unregister_returned, callback_finished; FutureCallbackRegistration registration; TestConcurrent( 1, [&] { callback_started = false; callback_finished = false; unregister_returned = false; pair = PromiseFuturePair<int>::Make(); registration = pair.future.ExecuteWhenReady([&](ReadyFuture<int>) { callback_started = true; while (unregister_returned == false) { } callback_finished = true; }); }, [&] { EXPECT_TRUE(callback_started); EXPECT_TRUE(unregister_returned); EXPECT_TRUE(callback_finished); }, [&] { pair.promise.SetResult(3); }, [&] { while (!callback_started) { } EXPECT_FALSE(callback_finished); registration.UnregisterNonBlocking(); unregister_returned = true; }); } TEST(FutureTest, ExecuteWhenNotNeededUnregisterConcurrent) { PromiseFuturePair<int> pair; std::atomic<bool> unregistered; FutureCallbackRegistration registration; TestConcurrent( 1000, [&] { unregistered = false; pair = PromiseFuturePair<int>::Make(); registration = pair.promise.ExecuteWhenNotNeeded([&] { for (int i = 0; i < 100; ++i) { EXPECT_FALSE(unregistered.load()); } }); }, [&] { EXPECT_TRUE(unregistered.load()); }, [&] { pair.promise.SetResult(3); }, [&] { registration.Unregister(); unregistered = true; }); } TEST(FutureTest, ExecuteWhenForcedUnregisterConcurrent) { PromiseFuturePair<int> pair; std::atomic<bool> unregistered; FutureCallbackRegistration registration; TestConcurrent( 1000, [&] { unregistered = false; pair = PromiseFuturePair<int>::Make(); registration = pair.promise.ExecuteWhenForced([&](Promise<int>) { for (int i = 0; i < 100; ++i) { EXPECT_FALSE(unregistered.load()); } }); }, [&] { EXPECT_TRUE(unregistered.load()); }, [&] { pair.future.Force(); }, [&] { registration.Unregister(); unregistered = true; }); } TEST(FutureTest, SetResultInForceCallback) { auto pair = PromiseFuturePair<int>::Make(); pair.promise.ExecuteWhenForced([](Promise<int> p) { p.SetResult(5); }); EXPECT_FALSE(pair.future.ready()); pair.future.Force(); EXPECT_EQ(true, pair.future.ready()); EXPECT_EQ(5, pair.future.result()); } TEST(FutureTest, ForceCallbackAddedAfterForced) { auto pair = PromiseFuturePair<int>::Make(); auto sentinel = std::make_shared<int>(); pair.future.Force(); bool callback_ran = false; pair.promise.ExecuteWhenForced( [sentinel, &callback_ran](Promise<int> p) { callback_ran = true; }); EXPECT_TRUE(callback_ran); EXPECT_EQ(1, sentinel.use_count()); EXPECT_FALSE(pair.future.ready()); } TEST(FutureTest, ForceCallbackAddedAfterForcedWithNoFuturesRemaining) { auto pair = PromiseFuturePair<int>::Make(); auto sentinel = std::make_shared<int>(); pair.future.Force(); pair.future.reset(); bool callback_ran = false; pair.promise.ExecuteWhenForced( [sentinel, &callback_ran](Promise<int> p) { callback_ran = true; }); EXPECT_FALSE(callback_ran); EXPECT_EQ(1, sentinel.use_count()); EXPECT_FALSE(pair.promise.result_needed()); } TEST(FutureTest, ForceCallbackDestroyedAfterForce) { auto pair = PromiseFuturePair<int>::Make(); auto sentinel = std::make_shared<int>(); pair.promise.ExecuteWhenForced( [sentinel](Promise<int> p) { p.SetResult(5); }); EXPECT_EQ(2, sentinel.use_count()); EXPECT_FALSE(pair.future.ready()); pair.future.Force(); EXPECT_EQ(1, sentinel.use_count()); EXPECT_EQ(true, pair.future.ready()); EXPECT_EQ(5, pair.future.result()); } TEST(FutureTest, ForceAfterReady) { auto pair = PromiseFuturePair<int>::Make(); bool forced = false; auto sentinel = std::make_shared<int>(); pair.promise.ExecuteWhenForced( [&forced, sentinel](Promise<int> p) { forced = true; }); EXPECT_EQ(2, sentinel.use_count()); pair.promise.SetResult(3); EXPECT_FALSE(forced); EXPECT_EQ(1, sentinel.use_count()); pair.future.Force(); EXPECT_FALSE(forced); } TEST(FutureTest, ForceCallbacksDestroyedWhenNoFuturesRemain) { auto pair = PromiseFuturePair<int>::Make(); bool forced = false; auto sentinel = std::make_shared<int>(); pair.promise.ExecuteWhenForced( [&forced, sentinel](Promise<int> p) { forced = true; }); EXPECT_EQ(2, sentinel.use_count()); pair.future.reset(); EXPECT_EQ(1, sentinel.use_count()); EXPECT_FALSE(forced); } struct CallOnCopy { CallOnCopy(const CallOnCopy& x) : call_when_copied(x.call_when_copied), call_when_invoked(x.call_when_invoked) { call_when_copied(); } CallOnCopy(std::function<void()> call_when_copied, std::function<void()> call_when_invoked) : call_when_copied(call_when_copied), call_when_invoked(call_when_invoked) {} template <typename... Arg> void operator()(Arg&&...) { call_when_invoked(); } std::function<void()> call_when_copied, call_when_invoked; }; TEST(FutureTest, SetReadyCalledConcurrentlyWithExecuteWhenReady) { bool was_called = false; auto pair = PromiseFuturePair<int>::Make(); pair.future.ExecuteWhenReady(CallOnCopy{[&] { pair.promise.SetResult(5); }, [&] { was_called = true; }}); EXPECT_TRUE(was_called); EXPECT_EQ(5, pair.future.result().value()); } TEST(FutureTest, ForceCalledConcurrentlyWithExecuteWhenForced) { bool was_called = false; auto sentinel = std::make_shared<int>(); auto pair = PromiseFuturePair<int>::Make(); pair.promise.ExecuteWhenForced(CallOnCopy{ [&] { pair.future.Force(); }, [&, sentinel] { was_called = true; }}); EXPECT_TRUE(was_called); EXPECT_EQ(1, sentinel.use_count()); } TEST(FutureTest, ForceAndThenSetResultCalledConcurrentlyWithExecuteWhenForced) { bool was_called = false; auto sentinel = std::make_shared<int>(); auto pair = PromiseFuturePair<int>::Make(); pair.promise.ExecuteWhenForced(CallOnCopy{[&] { pair.future.Force(); }, [&, sentinel] { was_called = true; pair.promise.SetResult(5); }}); EXPECT_TRUE(was_called); EXPECT_EQ(1, sentinel.use_count()); EXPECT_EQ(5, pair.future.result().value()); } TEST(FutureTest, LastFutureReleasedConcurrentlyWithExecuteWhenNotNeeded) { bool was_called = false; auto sentinel = std::make_shared<int>(); auto pair = PromiseFuturePair<int>::Make(); pair.promise.ExecuteWhenNotNeeded(CallOnCopy{ [&] { pair.future.reset(); }, [&, sentinel] { was_called = true; }}); EXPECT_TRUE(was_called); EXPECT_EQ(1, sentinel.use_count()); } TEST(FutureTest, LastFutureReleasedConcurrentlyWithExecuteWhenForced) { bool was_called = false; auto sentinel = std::make_shared<int>(); auto pair = PromiseFuturePair<int>::Make(); pair.promise.ExecuteWhenForced(CallOnCopy{ [&] { pair.future.reset(); }, [&, sentinel] { was_called = true; }}); EXPECT_FALSE(was_called); EXPECT_EQ(1, sentinel.use_count()); } TEST(FutureTest, SetResultCalledConcurrentlyWithExecuteWhenForced) { bool was_called = false; auto sentinel = std::make_shared<int>(); auto pair = PromiseFuturePair<int>::Make(); pair.promise.ExecuteWhenForced( CallOnCopy{[&] { pair.promise.SetResult(5); }, [&, sentinel] { was_called = true; }}); EXPECT_FALSE(was_called); EXPECT_EQ(1, sentinel.use_count()); EXPECT_EQ(5, pair.future.result().value()); } TEST(FutureTest, PromiseBroken) { auto pair = PromiseFuturePair<int>::Make(); pair.promise = {}; EXPECT_TRUE(pair.future.ready()); EXPECT_FALSE(pair.future.result().has_value()); EXPECT_EQ(absl::UnknownError(""), pair.future.result().status()); } TEST(FutureTest, ConvertInt) { auto pair = PromiseFuturePair<int>::Make(); Future<const int> f = pair.future; Promise<const int> p = pair.promise; } TEST(FutureTest, ConvertVoid) { auto pair = PromiseFuturePair<void>::Make(); Future<const void> f = pair.future; Promise<const void> p = pair.promise; pair.promise.SetResult(tensorstore::MakeResult()); f.value(); } TEST(FutureTest, ConvertVoid2) { Future<const void> f; Promise<const void> p; auto pair = PromiseFuturePair<void>::Make(); f = pair.future; p = pair.promise; pair.promise.SetResult(std::in_place); f.value(); } struct NonMovable { NonMovable(int value) : value(value) {} NonMovable(NonMovable const&) = delete; NonMovable(NonMovable&&) = delete; int value; }; TEST(FutureTest, NonMovableTypeInitialize) { auto pair = PromiseFuturePair<NonMovable>::Make(3); pair.promise.SetReady(); EXPECT_EQ(3, pair.future.value().value); } TEST(FutureTest, NonMovableTypeSetReady) { auto pair = PromiseFuturePair<NonMovable>::Make(); pair.promise.raw_result().emplace(5); pair.promise.SetReady(); EXPECT_EQ(5, pair.future.value().value); } TEST(HaveSameSharedStateTest, Invalid) { Future<int> fa, fb; Future<const int> cf; Promise<int> pa, pb; Promise<int> cp; EXPECT_TRUE(HaveSameSharedState(fa, fb)); EXPECT_TRUE(HaveSameSharedState(fa, cf)); EXPECT_TRUE(HaveSameSharedState(pa, pb)); EXPECT_TRUE(HaveSameSharedState(pa, fa)); EXPECT_TRUE(HaveSameSharedState(fa, pb)); EXPECT_TRUE(HaveSameSharedState(pa, cf)); } TEST(HaveSameSharedStateTest, Valid) { auto pair1 = PromiseFuturePair<void>::Make(); auto pair2 = PromiseFuturePair<void>::Make(); EXPECT_TRUE(HaveSameSharedState(pair1.future, pair1.future)); EXPECT_TRUE(HaveSameSharedState(pair1.future, pair1.promise)); EXPECT_TRUE(HaveSameSharedState(pair1.promise, pair1.future)); EXPECT_TRUE(HaveSameSharedState(pair1.promise, pair1.promise)); EXPECT_FALSE(HaveSameSharedState(pair1.promise, pair2.promise)); EXPECT_FALSE(HaveSameSharedState(pair1.promise, pair2.future)); EXPECT_FALSE(HaveSameSharedState(pair1.future, pair2.future)); EXPECT_FALSE(HaveSameSharedState(pair1.future, pair2.promise)); } TEST(AcquireFutureReferenceTest, ExistingFutureNotReady) { auto pair = PromiseFuturePair<void>::Make(); auto future2 = pair.promise.future(); EXPECT_TRUE(HaveSameSharedState(future2, pair.future)); } TEST(AcquireFutureReferenceTest, ExistingFutureReady) { auto pair = PromiseFuturePair<void>::Make(); pair.promise.SetReady(); auto future2 = pair.promise.future(); EXPECT_TRUE(HaveSameSharedState(future2, pair.future)); } TEST(AcquireFutureReferenceTest, NoExistingFutureNotReady) { auto pair = PromiseFuturePair<void>::Make(); pair.future.reset(); auto future2 = pair.promise.future(); EXPECT_FALSE(!future2.null()); } TEST(AcquireFutureReferenceTest, NoExistingFutureReady) { auto pair = PromiseFuturePair<void>::Make(); pair.future.reset(); pair.promise.SetReady(); auto future2 = pair.promise.future(); EXPECT_TRUE(HaveSameSharedState(future2, pair.promise)); } TEST(LinkTest, MultipleSimple) { auto a_pair = PromiseFuturePair<int>::Make(); auto b_pair = PromiseFuturePair<int>::Make(); auto c_pair = PromiseFuturePair<int>::Make(); EXPECT_FALSE(a_pair.future.ready()); EXPECT_FALSE(b_pair.future.ready()); EXPECT_FALSE(c_pair.future.ready()); Link( [](Promise<int> c, ReadyFuture<int> a, ReadyFuture<int> b) { c.SetResult(a.result().value() + b.result().value()); }, c_pair.promise, a_pair.future, b_pair.future); a_pair.promise.SetResult(5); EXPECT_FALSE(b_pair.future.ready()); EXPECT_FALSE(c_pair.future.ready()); b_pair.promise.SetResult(3); ASSERT_TRUE(c_pair.future.ready()); EXPECT_EQ(8, c_pair.future.result().value()); } TEST(LinkTest, EmptyCallback) { auto a_pair = PromiseFuturePair<int>::Make(); auto b_pair = PromiseFuturePair<int>::Make(); struct Callback { void operator()(Promise<int> b, ReadyFuture<int> a) const { b.SetResult(a.result().value()); } }; Link(Callback{}, b_pair.promise, a_pair.future); EXPECT_FALSE(a_pair.future.ready()); EXPECT_FALSE(b_pair.future.ready()); a_pair.promise.SetResult(5); ASSERT_TRUE(b_pair.future.ready()); EXPECT_EQ(5, b_pair.future.result().value()); } TEST(LinkValueTest, MultipleSuccessError) { auto a_pair = PromiseFuturePair<int>::Make(); auto b_pair = PromiseFuturePair<int>::Make(); auto c_pair = PromiseFuturePair<int>::Make(); LinkValue( [](Promise<int> c, ReadyFuture<int> a, ReadyFuture<int> b) { c.SetResult(a.result().value() + b.result().value()); }, c_pair.promise, a_pair.future, b_pair.future); a_pair.promise.SetResult(5); EXPECT_FALSE(c_pair.future.ready()); b_pair.promise.SetResult(absl::InvalidArgumentError("Test error")); ASSERT_TRUE(c_pair.future.ready()); EXPECT_THAT(c_pair.future.result().status(), MatchesStatus(absl::StatusCode::kInvalidArgument, "Test error")); } TEST(LinkValueTest, MultipleErrorSuccess) { auto a_pair = PromiseFuturePair<int>::Make(); auto b_pair = PromiseFuturePair<int>::Make(); auto c_pair = PromiseFuturePair<int>::Make(); LinkValue( [](Promise<int> c, ReadyFuture<int> a, ReadyFuture<int> b) { c.SetResult(a.result().value() + b.result().value()); }, c_pair.promise, a_pair.future, b_pair.future); b_pair.promise.SetResult(absl::InvalidArgumentError("Test error")); ASSERT_TRUE(c_pair.future.ready()); EXPECT_THAT(c_pair.future.result().status(), MatchesStatus(absl::StatusCode::kInvalidArgument, "Test error")); } TEST(LinkErrorTest, ImmediateSuccess) { auto pair = PromiseFuturePair<int>::Make(3); LinkError(pair.promise, MakeReadyFuture<int>(1)); EXPECT_FALSE(pair.future.ready()); pair.promise.reset(); ASSERT_TRUE(pair.future.ready()); EXPECT_EQ(3, pair.future.value()); } TEST(LinkErrorTest, ImmediateFailure) { auto pair = PromiseFuturePair<int>::Make(3); LinkError(pair.promise, MakeReadyFuture<int>(absl::UnknownError("Msg"))); pair.promise.reset(); EXPECT_EQ(absl::UnknownError("Msg"), pair.future.result().status()); } TEST(LinkErrorTest, DelayedSuccess) { auto pair1 = PromiseFuturePair<int>::Make(3); auto pair2 = PromiseFuturePair<void>::Make(); LinkError(pair1.promise, pair2.future); pair1.promise.reset(); EXPECT_FALSE(pair1.future.ready()); pair2.promise.SetResult(tensorstore::MakeResult()); ASSERT_TRUE(pair1.future.ready()); EXPECT_EQ(3, pair1.future.value()); } TEST(LinkErrorTest, DelayedFailure) { auto pair1 = PromiseFuturePair<int>::Make(3); auto pair2 = PromiseFuturePair<void>::Make(); LinkError(pair1.promise, pair2.future); EXPECT_FALSE(pair1.future.ready()); pair2.promise.SetResult(absl::UnknownError("Msg")); ASSERT_TRUE(pair1.future.ready()); EXPECT_EQ(absl::UnknownError("Msg"), pair1.future.result().status()); } TEST(LinkTest, SetReadyInForce) { auto pair1 = PromiseFuturePair<int>::Make(); pair1.promise.ExecuteWhenForced([](Promise<int> self) { self.SetResult(5); }); auto pair2 = PromiseFuturePair<int>::Make(); Link([](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.result().value() + 2); }, pair2.promise, pair1.future); EXPECT_FALSE(pair1.future.ready()); EXPECT_FALSE(pair2.future.ready()); EXPECT_EQ(7, pair2.future.result().value()); } TEST(LinkTest, LinkAfterForceCalledWhereFutureBecomesReadyWhenForced) { auto pair1 = PromiseFuturePair<int>::Make(); auto pair2 = PromiseFuturePair<int>::Make(); pair2.promise.ExecuteWhenForced([](Promise<int> self) { self.SetResult(5); }); pair1.future.Force(); EXPECT_FALSE(pair1.future.ready()); EXPECT_FALSE(pair2.future.ready()); Link([](Promise<int> p, ReadyFuture<int> f1) { p.SetResult(f1.result().value() + 2); }, pair1.promise, pair2.future); EXPECT_TRUE(pair1.future.ready()); EXPECT_TRUE(pair2.future.ready()); EXPECT_EQ(7, pair1.future.result().value()); } TEST(LinkTest, LinkAfterForceCalledWhereFutureDoesNotBecomeReadyWhenForced) { auto pair1 = PromiseFuturePair<int>::Make(); auto pair2 = PromiseFuturePair<int>::Make(); pair1.future.Force(); EXPECT_FALSE(pair1.future.ready()); EXPECT_FALSE(pair2.future.ready()); Link([](Promise<int> p, ReadyFuture<int> f1) { p.SetResult(f1.result().value() + 2); }, pair1.promise, pair2.future); EXPECT_FALSE(pair1.future.ready()); EXPECT_FALSE(pair2.future.ready()); pair2.promise.SetResult(5); EXPECT_TRUE(pair1.future.ready()); EXPECT_TRUE(pair2.future.ready()); EXPECT_EQ(7, pair1.future.result().value()); } TEST(LinkTest, Unregister) { auto pair1 = PromiseFuturePair<int>::Make(); pair1.promise.ExecuteWhenForced([](Promise<int> p) { p.SetResult(5); }); auto pair2 = PromiseFuturePair<int>::Make(); auto sentinel = std::make_shared<int>(); auto registration = Link( [sentinel](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.result().value() + 2); }, pair2.promise, pair1.future); EXPECT_FALSE(pair1.future.ready()); EXPECT_FALSE(pair2.future.ready()); EXPECT_EQ(2, sentinel.use_count()); registration(); EXPECT_EQ(1, sentinel.use_count()); pair1.future.Force(); EXPECT_FALSE(pair2.future.ready()); } TEST(LinkTest, AlreadyReady) { auto future1 = MakeReadyFuture<int>(5); auto pair2 = PromiseFuturePair<int>::Make(); Link([](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.result().value() + 2); }, pair2.promise, future1); EXPECT_TRUE(pair2.future.ready()); EXPECT_EQ(7, pair2.future.result().value()); } TEST(LinkTest, NotNeeded) { auto pair1 = PromiseFuturePair<int>::Make(); auto pair2 = PromiseFuturePair<int>::Make(); pair2.future.reset(); EXPECT_FALSE(pair2.promise.result_needed()); auto sentinel = std::make_shared<int>(); auto registration = Link( [sentinel](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.result().value() + 2); }, pair2.promise, pair1.future); EXPECT_EQ(1, sentinel.use_count()); EXPECT_FALSE(pair1.future.ready()); EXPECT_FALSE(pair2.promise.ready()); } TEST(LinkTest, ConcurrentSetReady) { PromiseFuturePair<int> pair1, pair2, pair3; TestConcurrent( 1000, [&] { pair1 = PromiseFuturePair<int>::Make(); pair2 = PromiseFuturePair<int>::Make(); pair3 = PromiseFuturePair<int>::Make(); Link([](Promise<int> p1, ReadyFuture<int> f2, ReadyFuture<int> f3) { p1.SetResult(f2.value() + f3.value()); }, pair1.promise, pair2.future, pair3.future); }, [&] { ASSERT_TRUE(pair1.future.ready()); EXPECT_EQ(pair1.future.value(), 7); }, [&] { pair2.promise.SetResult(5); }, [&] { pair3.promise.SetResult(2); }); } TEST(LinkTest, ConcurrentLinkAndSetReady) { PromiseFuturePair<int> pair1, pair2, pair3; TestConcurrent( 1000, [&] { pair1 = PromiseFuturePair<int>::Make(); pair2 = PromiseFuturePair<int>::Make(); pair3 = PromiseFuturePair<int>::Make(); }, [&] { ASSERT_TRUE(pair1.future.ready()); EXPECT_EQ(pair1.future.value(), 7); }, [&] { Link([](Promise<int> p1, ReadyFuture<int> f2, ReadyFuture<int> f3) { p1.SetResult(f2.value() + f3.value()); }, pair1.promise, pair2.future, pair3.future); }, [&] { pair2.promise.SetResult(5); }, [&] { pair3.promise.SetResult(2); }); } TEST(LinkTest, ConcurrentUnregister) { PromiseFuturePair<int> pair1, pair2; FutureCallbackRegistration registration; std::atomic<bool> unregistered; TestConcurrent( 1000, [&] { unregistered = false; pair1 = PromiseFuturePair<int>::Make(1); pair2 = PromiseFuturePair<int>::Make(); registration = Link( [&](Promise<int> p1, ReadyFuture<int> f2) { for (int i = 0; i < 100; ++i) { EXPECT_FALSE(unregistered.load()); } }, pair1.promise, pair2.future); }, [&] { EXPECT_TRUE(unregistered.load()); }, [&] { pair2.promise.SetResult(2); }, [&] { registration.Unregister(); unregistered = true; }); } TEST(LinkTest, ConcurrentForceAndSetReady) { PromiseFuturePair<int> pair1, pair2, pair3; TestConcurrent( 1000, [&] { pair1 = PromiseFuturePair<int>::Make(1); pair2 = PromiseFuturePair<int>::Make(); pair3 = PromiseFuturePair<int>::Make(); LinkResult(pair2.promise, pair1.future); LinkResult(pair3.promise, pair2.future); }, [&] {}, [&] { pair1.promise.SetResult(2); }, [&] { pair3.future.Force(); }); } TEST(LinkTest, NoFutures) { auto pair = PromiseFuturePair<int>::Make(); Link([](Promise<int> promise) { promise.SetResult(5); }, pair.promise); ASSERT_TRUE(pair.future.ready()); ASSERT_TRUE(pair.future.result()); EXPECT_EQ(5, pair.future.value()); } TEST(LinkTest, NoCallback) { auto [promise, future] = PromiseFuturePair<int>::Make(); promise.ExecuteWhenForced([](Promise<int> promise) { promise.SetResult(5); }); { auto [linked_promise, linked_future] = PromiseFuturePair<int>::Make(); auto link = LinkResult(linked_promise, future); EXPECT_FALSE(linked_future.ready()); link.Unregister(); linked_future.Force(); EXPECT_FALSE(linked_future.ready()); EXPECT_FALSE(future.ready()); } { auto [linked_promise, linked_future] = PromiseFuturePair<int>::Make(); auto link = LinkResult(linked_promise, future); EXPECT_FALSE(linked_future.ready()); linked_future.Force(); ASSERT_TRUE(linked_future.ready()); ASSERT_TRUE(future.ready()); EXPECT_THAT(linked_future.result(), ::testing::Optional(5)); } { auto [linked_promise, linked_future] = PromiseFuturePair<int>::Make(); auto link = LinkResult(linked_promise, future); ASSERT_TRUE(linked_future.ready()); EXPECT_THAT(linked_future.result(), ::testing::Optional(5)); } } TEST(LinkErrorTest, ConcurrentForceAndSetReady) { PromiseFuturePair<void> pairA, pairB; TestConcurrent( 1000, [&] { pairA = PromiseFuturePair<void>::Make(tensorstore::MakeResult()); pairB = PromiseFuturePair<void>::Make(tensorstore::MakeResult()); LinkError(pairA.promise, pairB.future); }, [&] { EXPECT_TRUE(pairB.future.ready()); EXPECT_TRUE(pairB.future.result()); EXPECT_FALSE(pairA.future.ready()); }, [&] { pairA.future.Force(); }, [&] { pairB.promise.SetReady(); }); } TEST(LinkErrorTest, ConcurrentSetError) { PromiseFuturePair<void> pairA, pairB, pairC; TestConcurrent( 1000, [&] { pairA = PromiseFuturePair<void>::Make(tensorstore::MakeResult()); pairB = PromiseFuturePair<void>::Make(tensorstore::MakeResult()); pairC = PromiseFuturePair<void>::Make(tensorstore::MakeResult()); LinkError(pairA.promise, pairB.future, pairC.future); }, [&] { EXPECT_TRUE(pairA.future.ready()); EXPECT_TRUE(pairB.future.ready()); EXPECT_TRUE(pairC.future.ready()); EXPECT_FALSE(pairA.future.result()); EXPECT_FALSE(pairB.future.result()); EXPECT_FALSE(pairC.future.result()); }, [&] { pairB.promise.SetResult(absl::UnknownError("")); }, [&] { pairC.promise.SetResult(absl::UnknownError("")); }); } TEST(LinkErrorTest, ConcurrentForceAndSetError) { PromiseFuturePair<void> pairA, pairB; TestConcurrent( 1000, [&] { pairA = PromiseFuturePair<void>::Make(tensorstore::MakeResult()); pairB = PromiseFuturePair<void>::Make(tensorstore::MakeResult()); LinkError(pairA.promise, pairB.future); }, [&] { EXPECT_TRUE(pairB.future.ready()); EXPECT_TRUE(pairA.future.ready()); EXPECT_FALSE(pairB.future.result()); EXPECT_FALSE(pairA.future.result()); }, [&] { pairA.future.Force(); }, [&] { pairB.promise.SetResult(absl::UnknownError("")); }); } TEST(LinkErrorTest, LinkErrorVoidImmediateSuccessFailure) { auto [promise, future] = PromiseFuturePair<void>::Make(); LinkError(std::move(promise), MakeReadyFuture<void>(absl::OkStatus()), MakeReadyFuture<void>(absl::OkStatus())); ASSERT_TRUE(future.ready()); EXPECT_FALSE(future.result().ok()); } TEST(LinkErrorTest, LinkErrorVoidImmediateSuccessOk) { auto [promise, future] = PromiseFuturePair<void>::Make(absl::OkStatus()); LinkError(std::move(promise), MakeReadyFuture<void>(absl::OkStatus()), MakeReadyFuture<void>(absl::OkStatus())); ASSERT_TRUE(future.ready()); EXPECT_TRUE(future.result().ok()); } TEST(PromiseFuturePairTest, LinkImmediateSuccess) { auto future = PromiseFuturePair<int>::Link( [](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.value() + 1); }, MakeReadyFuture<int>(1)) .future; EXPECT_EQ(2, future.value()); } TEST(PromiseFuturePairTest, LinkImmediateFailure) { auto future = PromiseFuturePair<int>::Link( [](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.result()); }, MakeReadyFuture<int>(absl::UnknownError("Fail"))) .future; EXPECT_THAT(future.result(), MatchesStatus(absl::StatusCode::kUnknown, "Fail")); } TEST(PromiseFuturePairTest, LinkDeferredSuccess) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::Link( [](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.value() + 1); }, pair.future) .future; EXPECT_FALSE(future.ready()); pair.promise.SetResult(1); EXPECT_EQ(2, future.value()); } TEST(PromiseFuturePairTest, LinkDeferredFailure) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::Link( [](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.result()); }, pair.future) .future; EXPECT_FALSE(future.ready()); pair.promise.SetResult(absl::UnknownError("Fail")); EXPECT_THAT(future.result(), MatchesStatus(absl::StatusCode::kUnknown, "Fail")); } TEST(PromiseFuturePairTest, LinkResultInit) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::Link( 5, [](Promise<int> p, ReadyFuture<int> f) {}, pair.future) .future; EXPECT_FALSE(future.ready()); pair.promise.SetResult(3); EXPECT_EQ(5, future.value()); } TEST(PromiseFuturePairTest, LinkValueImmediateSuccess) { auto future = PromiseFuturePair<int>::LinkValue( [](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.value() + 1); }, MakeReadyFuture<int>(1)) .future; EXPECT_EQ(2, future.value()); } TEST(PromiseFuturePairTest, LinkValueImmediateFailure) { auto future = PromiseFuturePair<int>::LinkValue( [](Promise<int> p, ReadyFuture<int> f) {}, MakeReadyFuture<int>(absl::UnknownError("Fail"))) .future; EXPECT_THAT(future.result(), MatchesStatus(absl::StatusCode::kUnknown, "Fail")); } TEST(PromiseFuturePairTest, LinkValueDeferredSuccess) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::LinkValue( [](Promise<int> p, ReadyFuture<int> f) { p.SetResult(f.value() + 1); }, pair.future) .future; EXPECT_FALSE(future.ready()); pair.promise.SetResult(1); EXPECT_EQ(2, future.value()); } TEST(PromiseFuturePairTest, LinkValueDeferredFailure) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::LinkValue( [](Promise<int> p, ReadyFuture<int> f) {}, pair.future) .future; EXPECT_FALSE(future.ready()); pair.promise.SetResult(absl::UnknownError("Fail")); EXPECT_THAT(future.result(), MatchesStatus(absl::StatusCode::kUnknown, "Fail")); } TEST(PromiseFuturePairTest, LinkValueResultInit) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::LinkValue( 5, [](Promise<int> p, ReadyFuture<int> f) {}, pair.future) .future; EXPECT_FALSE(future.ready()); pair.promise.SetResult(3); EXPECT_EQ(5, future.value()); } TEST(PromiseFuturePairTest, LinkErrorImmediateSuccess) { auto future = PromiseFuturePair<int>::LinkError(3, MakeReadyFuture<int>(1)).future; EXPECT_EQ(3, future.value()); } TEST(PromiseFuturePairTest, LinkErrorImmediateFailure) { auto future = PromiseFuturePair<int>::LinkError( 3, MakeReadyFuture<int>(1), MakeReadyFuture<int>(absl::UnknownError("Fail"))) .future; EXPECT_THAT(future.result(), MatchesStatus(absl::StatusCode::kUnknown, "Fail")); } TEST(PromiseFuturePairTest, LinkErrorDeferredSuccess) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::LinkError(3, pair.future).future; EXPECT_FALSE(future.ready()); pair.promise.SetResult(5); EXPECT_EQ(3, future.value()); } TEST(PromiseFuturePairTest, LinkErrorDeferredFailure) { auto pair = PromiseFuturePair<int>::Make(); auto future = PromiseFuturePair<int>::LinkError(3, MakeReadyFuture<int>(1), pair.future) .future; EXPECT_FALSE(pair.future.ready()); pair.promise.SetResult(absl::UnknownError("Fail")); EXPECT_THAT(future.result(), MatchesStatus(absl::StatusCode::kUnknown, "Fail")); } TEST(LinkTest, DestroyCallback) { auto pair1 = PromiseFuturePair<int>::Make(); auto sentinel = std::make_shared<bool>(false); auto pair2 = PromiseFuturePair<void>::Make(); auto registration = Link([sentinel](Promise<void>, ReadyFuture<int>) { *sentinel = true; }, pair2.promise, pair1.future); EXPECT_EQ(2, sentinel.use_count()); pair1.promise.SetResult(1); EXPECT_EQ(true, *sentinel); EXPECT_EQ(1, sentinel.use_count()); } TEST(PromiseFuturePairTest, LinkDestroyCallback) { auto pair1 = PromiseFuturePair<int>::Make(); auto sentinel = std::make_shared<bool>(false); auto pair2 = PromiseFuturePair<void>::Link( [sentinel](Promise<void>, ReadyFuture<int>) { *sentinel = true; }, pair1.future); EXPECT_EQ(2, sentinel.use_count()); pair1.promise.SetResult(1); EXPECT_EQ(true, *sentinel); EXPECT_EQ(1, sentinel.use_count()); } TEST(WaitAllFuture, NoFuturesSpan) { std::vector<AnyFuture> futures; auto future = WaitAllFuture(futures); ASSERT_TRUE(future.ready()); ASSERT_TRUE(future.result().ok()); } TEST(WaitAllFuture, ReadyFuture) { auto future = WaitAllFuture(MakeReadyFuture<void>(absl::OkStatus()), MakeReadyFuture<void>(absl::OkStatus())); ASSERT_TRUE(future.ready()); EXPECT_TRUE(future.result().ok()); future = WaitAllFuture(MakeReadyFuture<void>(absl::OkStatus()), MakeReadyFuture<void>(absl::OkStatus()), MakeReadyFuture<void>(absl::InternalError(""))); ASSERT_TRUE(future.ready()); ASSERT_FALSE(future.result().ok()); } TEST(WaitAllFuture, ReadyFutureSpanError) { std::vector<AnyFuture> futures{MakeReadyFuture<void>(absl::OkStatus()), MakeReadyFuture<void>(absl::OkStatus())}; auto future = WaitAllFuture(futures); ASSERT_TRUE(future.ready()); EXPECT_TRUE(future.result().ok()); futures.push_back(MakeReadyFuture<void>(absl::InternalError(""))); future = WaitAllFuture(futures); ASSERT_TRUE(future.ready()); ASSERT_FALSE(future.result().ok()); } TEST(WaitAllFuture, ReadyFutureSpan) { std::vector<AnyFuture> futures; for (int i = 0; i < 17; i++) { auto future = WaitAllFuture(futures); ASSERT_TRUE(future.ready()); EXPECT_TRUE(future.result().ok()); futures.emplace_back(MakeReadyFuture<void>(absl::OkStatus())); } } TEST(WaitAllFuture, NonVoidFuture) { auto a = PromiseFuturePair<int>::Make(); auto b = PromiseFuturePair<int>::Make(); auto future = WaitAllFuture(a.future, b.future); ASSERT_FALSE(future.ready()); a.promise.SetResult(2); ASSERT_FALSE(future.ready()); b.promise.SetResult(absl::InternalError("")); ASSERT_TRUE(future.ready()); EXPECT_FALSE(future.result().ok()); } TEST(MapFutureTest, NoFutures) { auto future = MapFuture(InlineExecutor{}, [] { return 3; }); ASSERT_TRUE(future.ready()); ASSERT_TRUE(future.result()); EXPECT_EQ(3, future.value()); } TEST(MapFutureTest, BothReady) { auto a = MakeReadyFuture<int>(3); auto b = MakeReadyFuture<int>(5); auto c = MapFuture( InlineExecutor{}, [](Result<int> a, Result<int> b) -> Result<int> { return MapResult(std::plus<int>{}, a, b); }, a, b); EXPECT_EQ(8, c.result().value()); } TEST(MapFutureTest, NonConstOperator) { struct MyStruct { Result<int> operator()() { return 2; } }; Future<int> x = MapFuture(InlineExecutor{}, MyStruct{}); EXPECT_EQ(2, x.result().value()); } TEST(MapFutureTest, LValueReference) { auto a = MakeReadyFuture<int>(3); EXPECT_EQ(3, a.value()); auto b = MapFuture( InlineExecutor{}, [&](Result<int>& value) { value = 10; return 7; }, a); EXPECT_EQ(7, b.value()); EXPECT_EQ(10, a.value()); } TEST(MapFutureTest, ReturnFuture) { Future<int> a = 5; auto f = MapFuture( InlineExecutor{}, [](Result<int> a) -> Future<int> { return a.value() + 3; }, a); EXPECT_THAT(f.result(), ::testing::Optional(8)); } TEST(MapFutureValueTest, BothReady) { auto a = MakeReadyFuture<int>(3); auto b = MakeReadyFuture<int>(5); auto c = MapFutureValue(InlineExecutor{}, std::plus<int>{}, a, b); EXPECT_EQ(8, c.result().value()); } TEST(MapFutureValueTest, LValueReference) { auto a = MakeReadyFuture<int>(3); EXPECT_EQ(3, a.value()); auto b = MapFutureValue( InlineExecutor{}, [&](int& value) { value = 10; return 7; }, a); EXPECT_EQ(7, b.value()); EXPECT_EQ(10, a.value()); } TEST(MapFutureValueTest, ValueToError) { auto a = MakeReadyFuture<int>(3); auto b = MapFutureValue( InlineExecutor{}, [](int x) -> Result<int> { return absl::UnknownError(tensorstore::StrCat("Got value: ", x)); }, a); EXPECT_THAT(b.result(), MatchesStatus(absl::StatusCode::kUnknown, "Got value: 3")); } TEST(MapFutureValueTest, ReturnFuture) { Future<int> a = 5; auto f = MapFutureValue( InlineExecutor{}, [](int a) -> Future<int> { return a + 3; }, a); EXPECT_THAT(f.result(), ::testing::Optional(8)); } TEST(MapFutureErrorTest, Success) { auto pair = PromiseFuturePair<int>::Make(); auto mapped = MapFutureError( InlineExecutor{}, [](absl::Status status) { return 5; }, pair.future); EXPECT_FALSE(mapped.ready()); pair.promise.SetResult(7); EXPECT_EQ(7, mapped.result()); } TEST(MapFutureErrorTest, ErrorMappedToSuccess) { auto pair = PromiseFuturePair<int>::Make(); auto mapped = MapFutureError( InlineExecutor{}, [](absl::Status status) { EXPECT_EQ(absl::UnknownError("message"), status); return 5; }, pair.future); EXPECT_FALSE(mapped.ready()); pair.promise.SetResult(absl::UnknownError("message")); EXPECT_EQ(5, mapped.result()); } TEST(MapFutureErrorTest, ErrorMappedToError) { auto pair = PromiseFuturePair<int>::Make(); auto mapped = MapFutureError( InlineExecutor{}, [](absl::Status status) { return tensorstore::MaybeAnnotateStatus(status, "Mapped"); }, pair.future); EXPECT_FALSE(mapped.ready()); pair.promise.SetResult(absl::UnknownError("message")); EXPECT_THAT(mapped.result(), MatchesStatus(absl::StatusCode::kUnknown, "Mapped: message")); } TEST(MakeReadyFutureTest, Basic) { auto future = MakeReadyFuture(); static_assert(std::is_same_v<ReadyFuture<const void>, decltype(future)>); EXPECT_TRUE(future.ready()); EXPECT_EQ(MakeResult(), future.result()); } TEST(FutureTest, SetDeferredResult) { auto [promise, future] = PromiseFuturePair<int>::Make(); SetDeferredResult(promise, 2); EXPECT_FALSE(future.ready()); SetDeferredResult(promise, 3); EXPECT_FALSE(future.ready()); promise = Promise<int>(); ASSERT_TRUE(future.ready()); EXPECT_THAT(future.result(), ::testing::Optional(2)); } TEST(FutureTest, SetDeferredResultAfterReady) { auto [promise, future] = PromiseFuturePair<int>::Make(); promise.SetResult(1); ASSERT_TRUE(future.ready()); SetDeferredResult(promise, 2); ASSERT_TRUE(future.ready()); EXPECT_THAT(future.result(), ::testing::Optional(1)); } TEST(FutureTest, SetDeferredResultSetReady) { auto [promise, future] = PromiseFuturePair<int>::Make(); int value = 1; future.ExecuteWhenReady( [&](ReadyFuture<int> r) { value *= (r.result().ok()) ? 2 : 3; }); SetDeferredResult(promise, absl::InternalError("1")); SetDeferredResult(promise, absl::InternalError("2")); promise.SetReady(); future.Wait(); EXPECT_EQ(3, value); } TEST(FutureTest, ReturnIfError) { auto do_test = [] { TENSORSTORE_RETURN_IF_ERROR(MakeReadyFuture<int>(42).result(), false); return true; }; EXPECT_EQ(true, do_test()); } TEST(FutureTest, UntypedExecuteWhenReadyAlreadyDone) { Future<int> f(3); bool ran = false; f.UntypedExecuteWhenReady([&](AnyFuture f) { ran = true; }); EXPECT_TRUE(ran); } TEST(FutureTest, UntypedExecuteWhenReadyNotAlreadyDone) { auto [promise, future] = PromiseFuturePair<int>::Make(); bool ran = false; future.UntypedExecuteWhenReady([&](AnyFuture f) { ran = true; }); EXPECT_FALSE(ran); promise.SetResult(5); EXPECT_TRUE(ran); } TEST(FutureTest, FutureResultFuture) { auto [promise, future] = PromiseFuturePair<int>::Make(); Result<Future<int>> rf(future); Future<int> f(rf); promise.SetResult(5); EXPECT_EQ(5, f.value()); } TEST(FutureTest, Live) { #ifdef TENSORSTORE_METRICS_DISABLED GTEST_SKIP() << "metrics disabled"; #endif auto& registry = tensorstore::internal_metrics::GetMetricRegistry(); EXPECT_EQ( 0, std::get<int64_t>( registry.Collect("/tensorstore/futures/live")->values[0].value)); { auto [promise, future] = PromiseFuturePair<int>::Make(); EXPECT_NE( 0, std::get<int64_t>( registry.Collect("/tensorstore/futures/live")->values[0].value)); } EXPECT_EQ( 0, std::get<int64_t>( registry.Collect("/tensorstore/futures/live")->values[0].value)); } static void BM_Future_ExecuteWhenReady(benchmark::State& state) { int num_callbacks = state.range(0); for (auto _ : state) { auto pair = PromiseFuturePair<int>::Make(); for (int i = 0; i < num_callbacks; i++) { pair.future.ExecuteWhenReady( [](ReadyFuture<int> a) { benchmark::DoNotOptimize(a.value()); }); } pair.promise.SetResult(1); pair.future.Wait(); } } BENCHMARK(BM_Future_ExecuteWhenReady)->Range(0, 256); }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/util/future.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/util/future_test.cc
4f887a6430414cd6088e1743555015b10f116d50
4b460faa-3e02-4fe9-9e44-a87764cff48c
cpp
google/tensorstore
status
tensorstore/serialization/status.cc
tensorstore/serialization/status_test.cc
#include "absl/status/status.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/serialization/status.h" namespace tensorstore { namespace serialization { bool ErrorStatusSerializer::Encode(EncodeSink& sink, const absl::Status& status) { assert(!status.ok()); return serialization::Encode(sink, status); } bool ErrorStatusSerializer::Decode(DecodeSource& source, absl::Status& status) { if (!serialization::Decode(source, status)) return false; if (status.ok()) { source.Fail(absl::DataLossError("Expected error status")); return false; } return true; } bool Serializer<absl::Status>::Encode(EncodeSink& sink, const absl::Status& value) { if (!serialization::Encode(sink, value.code())) return false; if (value.ok()) return true; if (!serialization::Encode(sink, value.message())) return false; bool ok = true; value.ForEachPayload([&](std::string_view url, const absl::Cord& payload) { if (!ok) return; ok = serialization::EncodeTuple(sink, true, payload, url); }); if (!ok) return false; return serialization::Encode(sink, false); } bool Serializer<absl::Status>::Decode(DecodeSource& source, absl::Status& value) { absl::StatusCode code; if (!serialization::Decode(source, code)) return false; if (code == absl::StatusCode::kOk) { value = absl::OkStatus(); return true; } std::string_view message; if (!serialization::Decode(source, message)) return false; value = absl::Status(code, message); while (true) { bool has_payload; if (!serialization::Decode(source, has_payload)) return false; if (!has_payload) break; absl::Cord payload; std::string_view url; if (!serialization::DecodeTuple(source, payload, url)) return false; value.SetPayload(url, payload); } return true; } } }
#include "tensorstore/serialization/status.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "absl/strings/cord.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/serialization/test_util.h" namespace { using ::tensorstore::serialization::TestSerializationRoundTrip; TEST(StatusTest, SimpleRoundTrip) { TestSerializationRoundTrip(absl::OkStatus()); TestSerializationRoundTrip(absl::InvalidArgumentError("abc")); } TEST(StatusTest, PayloadRoundTrip) { auto status = absl::InternalError("xyz"); status.SetPayload("a", absl::Cord("b")); TestSerializationRoundTrip(status); status.SetPayload("c", absl::Cord("d")); TestSerializationRoundTrip(status); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/serialization/status.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/serialization/status_test.cc
4f887a6430414cd6088e1743555015b10f116d50
0c94eaf6-93e0-4025-945c-871916febf5b
cpp
google/tensorstore
serialization
tensorstore/serialization/serialization.cc
tensorstore/serialization/serialization_test.cc
#include "tensorstore/serialization/serialization.h" #include <cstring> #include <string_view> #include "absl/status/status.h" #include "tensorstore/util/span.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace serialization { namespace internal_serialization { void FailNonNull(DecodeSource& source) { source.Fail(serialization::DecodeError("Expected non-null value")); } void FailEof(DecodeSource& source) { source.Fail(serialization::DecodeError("Unexpected end of input")); } } void EncodeSink::Fail(absl::Status status) { assert(!status.ok()); writer().Fail(std::move(status)); } void DecodeSource::Fail(absl::Status status) { assert(!status.ok()); reader().Fail(std::move(status)); } absl::Status DecodeError() { return absl::DataLossError("Failed to decode value"); } absl::Status DecodeError(std::string_view message) { return absl::DataLossError(tensorstore::StrCat("Error decoding: ", message)); } namespace internal_serialization { absl::Status NonSerializableError() { return absl::InvalidArgumentError("Serialization not supported"); } } } }
#include "tensorstore/serialization/serialization.h" #include <cstdint> #include <map> #include <set> #include <string> #include <tuple> #include <variant> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorstore/serialization/std_map.h" #include "tensorstore/serialization/std_optional.h" #include "tensorstore/serialization/std_set.h" #include "tensorstore/serialization/std_tuple.h" #include "tensorstore/serialization/std_variant.h" #include "tensorstore/serialization/std_vector.h" #include "tensorstore/serialization/test_util.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status_testutil.h" namespace { using ::tensorstore::serialization::IsNonSerializableLike; using ::tensorstore::serialization::NonSerializable; using ::tensorstore::serialization::SerializationRoundTrip; using ::tensorstore::serialization::TestSerializationRoundTrip; TEST(SerializationTest, Bool) { TestSerializationRoundTrip(true); TestSerializationRoundTrip(false); } TEST(SerializationTest, Float) { TestSerializationRoundTrip(3.14f); TestSerializationRoundTrip(0.0f); } TEST(SerializationTest, String) { TestSerializationRoundTrip(std::string("abcdefg")); TestSerializationRoundTrip(std::string("")); } TEST(CordTest, SerializationRoundTrip) { TestSerializationRoundTrip(absl::Cord("")); TestSerializationRoundTrip(absl::Cord("abc")); } TEST(SerializationTest, Int32) { TestSerializationRoundTrip(static_cast<int32_t>(0)); TestSerializationRoundTrip(static_cast<int32_t>(3)); TestSerializationRoundTrip(static_cast<int32_t>(2147483647)); TestSerializationRoundTrip(static_cast<int32_t>(-2147483648)); } TEST(SerializationTest, VectorInt) { TestSerializationRoundTrip(std::vector<int>{}); TestSerializationRoundTrip(std::vector<int>{1, 2, 3}); } TEST(SerializationTest, VectorString) { TestSerializationRoundTrip(std::vector<std::string>{}); TestSerializationRoundTrip(std::vector<std::string>{"a", "b", "def"}); } TEST(SerializationTest, VectorVectorString) { TestSerializationRoundTrip( std::vector<std::vector<std::string>>{{"a", "b", "def"}, {"e", "f"}}); } TEST(SerializationTest, Map) { TestSerializationRoundTrip(std::map<int, std::string>{{1, "a"}, {2, "b"}}); } TEST(SerializationTest, Set) { TestSerializationRoundTrip(std::set<int>{1, 2, 3}); } TEST(SerializationTest, Tuple) { TestSerializationRoundTrip( std::tuple(std::string("abc"), 3, std::string("def"))); } TEST(SerializationTest, UniquePtrNull) { std::unique_ptr<int> ptr; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto ptr2, SerializationRoundTrip(ptr)); EXPECT_FALSE(ptr2); } TEST(SerializationTest, UniquePtrNonNull) { auto ptr = std::make_unique<int>(5); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto ptr2, SerializationRoundTrip(ptr)); EXPECT_THAT(ptr2, ::testing::Pointee(5)); } TEST(SerializationTest, SharedPtrNull) { std::shared_ptr<int> ptr; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto ptr2, SerializationRoundTrip(ptr)); EXPECT_FALSE(ptr2); } TEST(SerializationTest, SharedPtrNonNull) { auto ptr = std::make_shared<int>(5); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto ptr2, SerializationRoundTrip(ptr)); EXPECT_THAT(ptr2, ::testing::Pointee(5)); } TEST(SerializationTest, SharedPtrDuplicate) { auto ptr = std::make_shared<int>(5); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto tuple2, SerializationRoundTrip(std::make_tuple(ptr, ptr))); EXPECT_THAT(std::get<0>(tuple2), ::testing::Pointee(5)); EXPECT_EQ(std::get<0>(tuple2), std::get<1>(tuple2)); } struct Foo { std::string a; std::string b; constexpr static auto ApplyMembers = [](auto& x, auto f) { return f(x.a, x.b); }; bool operator==(const Foo& other) const { return a == other.a && b == other.b; } }; TEST(SerializationTest, ApplyMembers) { TestSerializationRoundTrip(Foo{"xyz", "abcd"}); TestSerializationRoundTrip(Foo{"", "abcd"}); } TEST(SerialiationTest, Optional) { TestSerializationRoundTrip(std::optional<int>()); TestSerializationRoundTrip(std::optional<int>(42)); } TEST(SerialiationTest, Variant) { TestSerializationRoundTrip(std::variant<int, std::string>(42)); TestSerializationRoundTrip(std::variant<int, std::string>("abc")); TestSerializationRoundTrip(std::variant<int, int>(std::in_place_index<1>, 1)); TestSerializationRoundTrip(std::variant<int, int>(std::in_place_index<0>, 0)); } static_assert(!IsNonSerializableLike<Foo>); static_assert(!IsNonSerializableLike<std::pair<Foo, Foo>>); static_assert(IsNonSerializableLike<NonSerializable<Foo>>); static_assert(IsNonSerializableLike<std::pair<Foo, NonSerializable<Foo>>>); }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/serialization/serialization.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/serialization/serialization_test.cc
4f887a6430414cd6088e1743555015b10f116d50
539747d9-ddc4-43ed-b586-0406c8dbf82e
cpp
google/tensorstore
context
tensorstore/context.cc
tensorstore/context_test.cc
#include "tensorstore/context.h" #include <stddef.h> #include <algorithm> #include <cassert> #include <memory> #include <string> #include <string_view> #include <utility> #include <vector> #include "absl/base/no_destructor.h" #include "absl/base/thread_annotations.h" #include "absl/log/absl_check.h" #include "absl/log/absl_log.h" #include "absl/status/status.h" #include "absl/strings/str_join.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include <nlohmann/json.hpp> #include "tensorstore/context_impl.h" #include "tensorstore/context_resource_provider.h" #include "tensorstore/internal/cache_key/cache_key.h" #include "tensorstore/internal/container/heterogeneous_container.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/json/value_as.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/internal/mutex.h" #include "tensorstore/internal/riegeli/delimited.h" #include "tensorstore/json_serialization_options.h" #include "tensorstore/serialization/fwd.h" #include "tensorstore/serialization/json.h" #include "tensorstore/serialization/json_bindable.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/util/quote_string.h" #include "tensorstore/util/result.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace internal_context { ResourceProviderImplBase::~ResourceProviderImplBase() = default; ResourceOrSpecBase::~ResourceOrSpecBase() = default; ResourceImplBase::~ResourceImplBase() = default; ResourceSpecImplBase::~ResourceSpecImplBase() = default; ContextImplPtr GetCreator(ResourceImplBase& resource) { absl::MutexLock lock(&resource.mutex_); auto* creator_ptr = resource.weak_creator_; if (!creator_ptr || !internal::IncrementReferenceCountIfNonZero(*creator_ptr)) { return {}; } return ContextImplPtr(creator_ptr, internal::adopt_object_ref); } void ResourceOrSpecPtrTraits::increment(ResourceOrSpecBase* p) { intrusive_ptr_increment(p); } void ResourceOrSpecPtrTraits::decrement(ResourceOrSpecBase* p) { intrusive_ptr_decrement(p); } void ResourceImplWeakPtrTraits::increment(ResourceOrSpecBase* p) { intrusive_ptr_increment(p); } void ResourceImplWeakPtrTraits::decrement(ResourceOrSpecBase* p) { intrusive_ptr_decrement(p); } void ResourceImplStrongPtrTraits::increment(ResourceImplBase* p) { intrusive_ptr_increment(p); p->spec_->provider_->AcquireContextReference(*p); } void ResourceImplStrongPtrTraits::decrement(ResourceImplBase* p) { p->spec_->provider_->ReleaseContextReference(*p); intrusive_ptr_decrement(p); } void intrusive_ptr_increment(ContextSpecImpl* p) { intrusive_ptr_increment( static_cast<internal::AtomicReferenceCount<ContextSpecImpl>*>(p)); } void intrusive_ptr_decrement(ContextSpecImpl* p) { intrusive_ptr_decrement( static_cast<internal::AtomicReferenceCount<ContextSpecImpl>*>(p)); } void intrusive_ptr_increment(ContextImpl* p) { intrusive_ptr_increment( static_cast<internal::AtomicReferenceCount<ContextImpl>*>(p)); } void intrusive_ptr_decrement(ContextImpl* p) { intrusive_ptr_decrement( static_cast<internal::AtomicReferenceCount<ContextImpl>*>(p)); } ContextImpl::ContextImpl() = default; ContextImpl::~ContextImpl() { for (const auto& resource_container : resources_) { auto& result = resource_container->result_; if (!result.ok()) continue; auto& resource = **result; absl::MutexLock lock(&resource.mutex_); if (resource.weak_creator_ == this) { resource.weak_creator_ = nullptr; } } } namespace { struct ContextProviderRegistry { absl::Mutex mutex_; internal::HeterogeneousHashSet< std::unique_ptr<const ResourceProviderImplBase>, std::string_view, &ResourceProviderImplBase::id_> providers_ ABSL_GUARDED_BY(mutex_); }; static ContextProviderRegistry& GetRegistry() { static absl::NoDestructor<ContextProviderRegistry> registrar; return *registrar; } ResourceContainer* FindCycle(ResourceContainer* container) { size_t power = 1; size_t lambda = 1; auto* tortoise = container; auto* hare = container->creation_blocked_on_; while (true) { if (!hare) return nullptr; if (tortoise == hare) return tortoise; if (power == lambda) { tortoise = hare; power *= 2; lambda = 0; } hare = hare->creation_blocked_on_; lambda += 1; } } void KillCycle(ResourceContainer* container) { std::vector<std::string> parts; auto* node = container; do { assert(node->spec_); std::string part; if (!node->spec_->key_.empty()) { tensorstore::StrAppend(&part, QuoteString(node->spec_->key_), ":"); } auto json_result = node->spec_->ToJson(IncludeDefaults{true}); if (json_result.has_value()) { tensorstore::StrAppend( &part, json_result->dump( -1, ' ', true, ::nlohmann::json::error_handler_t::ignore)); } else { tensorstore::StrAppend( &part, "unprintable spec for ", tensorstore::QuoteString(node->spec_->provider_->id_)); } parts.push_back(std::move(part)); node = node->creation_blocked_on_; } while (node != container); auto error = absl::InvalidArgumentError("Context resource reference cycle: " + absl::StrJoin(parts, " -> ")); do { auto* next = std::exchange(node->creation_blocked_on_, nullptr); node->result_ = error; node->condvar_.SignalAll(); node = next; } while (node != container); } void WaitForCompletion(absl::Mutex* mutex, ResourceContainer* container, ResourceContainer* trigger) { if (trigger) { assert(!trigger->creation_blocked_on_); trigger->creation_blocked_on_ = container; } if (!container->ready()) { container->condvar_.WaitWithTimeout(mutex, absl::Milliseconds(5)); if (!container->ready()) { if (auto* cycle_node = FindCycle(container)) { KillCycle(cycle_node); } while (!container->ready()) { container->condvar_.Wait(mutex); } } } if (trigger) { trigger->creation_blocked_on_ = nullptr; } } Result<ResourceImplStrongPtr> CreateResource(ContextImpl& context, ResourceSpecImplBase& spec, ResourceContainer* trigger) { std::unique_ptr<ResourceContainer> container(new ResourceContainer); auto* container_ptr = container.get(); container->spec_.reset(&spec); if (trigger) { assert(!trigger->creation_blocked_on_); trigger->creation_blocked_on_ = container.get(); } context.resources_.insert(std::move(container)); Result<ResourceImplStrongPtr> result{}; { internal::ScopedWriterUnlock unlock(context.root_->mutex_); result = spec.CreateResource({&context, container_ptr}); if (result.ok()) { auto& resource = **result; if (resource.spec_.get() == &spec) { absl::MutexLock lock(&resource.mutex_); assert(resource.weak_creator_ == nullptr); resource.weak_creator_ = &context; } } } container_ptr->result_ = std::move(result); if (trigger) { trigger->creation_blocked_on_ = nullptr; } container_ptr->condvar_.SignalAll(); return container_ptr->result_; } Result<ResourceImplStrongPtr> GetOrCreateResourceStrongPtr( ContextImpl& context, ResourceSpecImplBase& spec, ResourceContainer* trigger) { if (!spec.provider_) { ABSL_LOG(FATAL) << "Context resource provider not registered for: " << QuoteString(spec.key_); } const std::string_view key = spec.key_; if (key.empty()) { ResourceContainer container; container.spec_.reset(&spec); if (trigger) { absl::MutexLock lock(&context.root_->mutex_); assert(!trigger->creation_blocked_on_); trigger->creation_blocked_on_ = &container; } auto result = spec.CreateResource({&context, &container}); if (trigger) { absl::MutexLock lock(&context.root_->mutex_); trigger->creation_blocked_on_ = nullptr; } return result; } absl::MutexLock lock(&context.root_->mutex_); assert(context.spec_); #ifndef NDEBUG { auto it = context.spec_->resources_.find(key); assert(it != context.spec_->resources_.end() && it->get() == &spec); } #endif if (auto it = context.resources_.find(key); it != context.resources_.end()) { auto* container = it->get(); WaitForCompletion(&context.root_->mutex_, container, trigger); return container->result_; } return CreateResource(context, spec, trigger); } } Result<ResourceImplWeakPtr> GetOrCreateResource(ContextImpl& context, ResourceSpecImplBase& spec, ResourceContainer* trigger) { TENSORSTORE_ASSIGN_OR_RETURN( auto p, GetOrCreateResourceStrongPtr(context, spec, trigger)); p->spec_->provider_->ReleaseContextReference(*p); return ResourceImplWeakPtr(p.release(), internal::adopt_object_ref); } class ResourceReference : public ResourceSpecImplBase { public: ResourceReference(const std::string& referent) : referent_(referent) {} void EncodeCacheKey(std::string* out) const override { internal::EncodeCacheKey(out, ResourceSpecImplBase::kReference, referent_); } Result<ResourceImplStrongPtr> CreateResource( const internal::ContextResourceCreationContext& creation_context) override { std::string_view referent = referent_; auto* mutex = &creation_context.context_->root_->mutex_; absl::MutexLock lock(mutex); ContextImpl* c = creation_context.context_; if (referent.empty()) { assert(!key_.empty()); if (c->parent_) { c = c->parent_.get(); referent = provider_->id_; } else { auto default_spec = MakeDefaultResourceSpec(*provider_, key_); return internal_context::CreateResource(*c, *default_spec, creation_context.trigger_); } } while (true) { if (auto it = c->resources_.find(referent); it != c->resources_.end()) { ResourceContainer* container = it->get(); WaitForCompletion(mutex, container, creation_context.trigger_); return container->result_; } auto* context_spec = c->spec_.get(); if (context_spec) { if (auto it = context_spec->resources_.find(referent); it != context_spec->resources_.end()) { return internal_context::CreateResource(*c, **it, creation_context.trigger_); } } if (!c->parent_) { if (referent != provider_->id_) { return absl::InvalidArgumentError(tensorstore::StrCat( "Resource not defined: ", QuoteString(referent))); } auto default_spec = MakeDefaultResourceSpec(*provider_, provider_->id_); return internal_context::CreateResource(*c, *default_spec, creation_context.trigger_); } c = c->parent_.get(); } } Result<::nlohmann::json> ToJson(Context::ToJsonOptions options) override { if (referent_.empty()) return nullptr; return referent_; } ResourceSpecImplPtr UnbindContext( const internal::ContextSpecBuilder& spec_builder) final { auto& builder_impl = *internal_context::Access::impl(spec_builder); ++builder_impl.ids_[referent_]; return ResourceSpecImplPtr(this); } std::string referent_; }; void RegisterContextResourceProvider( std::unique_ptr<const ResourceProviderImplBase> provider) { auto& registry = GetRegistry(); absl::MutexLock lock(&registry.mutex_); auto id = provider->id_; if (!registry.providers_.insert(std::move(provider)).second) { ABSL_LOG(FATAL) << "Provider " << QuoteString(id) << " already registered"; } } const ResourceProviderImplBase* GetProvider(std::string_view id) { auto& registry = GetRegistry(); absl::ReaderMutexLock lock(&registry.mutex_); auto it = registry.providers_.find(id); if (it == registry.providers_.end()) return nullptr; return it->get(); } const ResourceProviderImplBase& GetProviderOrDie(std::string_view id) { auto* provider = GetProvider(id); if (!provider) { ABSL_LOG(FATAL) << "Context resource provider " << QuoteString(id) << " not registered"; } return *provider; } ResourceSpecImplPtr MakeDefaultResourceSpec( const ResourceProviderImplBase& provider, std::string_view key) { auto default_spec = provider.Default(); default_spec->provider_ = &provider; default_spec->key_ = key; default_spec->is_default_ = true; return default_spec; } std::string_view ParseResourceProvider(std::string_view key) { return key.substr(0, key.find('#')); } absl::Status ProviderNotRegisteredError(std::string_view key) { return absl::InvalidArgumentError(tensorstore::StrCat( "Invalid context resource identifier: ", QuoteString(key))); } Result<ResourceSpecImplPtr> ResourceSpecFromJson( const ResourceProviderImplBase& provider, const ::nlohmann::json& j, JsonSerializationOptions options) { ResourceSpecImplPtr impl; if (j.is_null()) { impl.reset(new ResourceReference("")); } else if (auto* s = j.get_ptr<const std::string*>()) { auto provider_id = ParseResourceProvider(*s); if (provider_id != provider.id_) { return absl::InvalidArgumentError(tensorstore::StrCat( "Invalid reference to ", QuoteString(provider.id_), " resource: ", QuoteString(*s))); } impl.reset(new ResourceReference(*s)); } else { TENSORSTORE_ASSIGN_OR_RETURN(impl, provider.FromJson(j, options)); } impl->provider_ = &provider; return impl; } Result<ResourceSpecImplPtr> ResourceSpecFromJsonWithKey( std::string_view key, const ::nlohmann::json& j, Context::FromJsonOptions options) { auto* provider = GetProvider(ParseResourceProvider(key)); ResourceSpecImplPtr impl; if (!provider) { return ProviderNotRegisteredError(key); } else { TENSORSTORE_ASSIGN_OR_RETURN(impl, ResourceSpecFromJson(*provider, j, options)); } impl->key_ = key; return impl; } Result<ResourceSpecImplPtr> ResourceSpecFromJson( std::string_view provider_id, const ::nlohmann::json& j, Context::FromJsonOptions options) { auto& provider = GetProviderOrDie(provider_id); if (j.is_null()) { return internal_json::ExpectedError(j, "non-null value"); } return ResourceSpecFromJson(provider, j, options); } ResourceOrSpecPtr DefaultResourceSpec(std::string_view provider_id) { return ToResourceOrSpecPtr( ResourceSpecFromJson(provider_id, std::string(provider_id), {}).value()); } } Context Context::Default() { Context context; context.impl_.reset(new internal_context::ContextImpl); context.impl_->root_ = context.impl_.get(); return context; } Context::Context(const Context::Spec& spec, Context parent) : impl_(new internal_context::ContextImpl) { impl_->spec_ = spec.impl_; impl_->parent_ = std::move(parent.impl_); if (impl_->parent_) { impl_->root_ = impl_->parent_->root_; } else { impl_->root_ = impl_.get(); } } Result<Context> Context::FromJson(::nlohmann::json json_spec, Context parent, FromJsonOptions options) { TENSORSTORE_ASSIGN_OR_RETURN( auto spec, Spec::FromJson(std::move(json_spec), std::move(options))); return Context(spec, std::move(parent)); } Context::Spec Context::spec() const { if (!impl_) return {}; Context::Spec spec; internal_context::Access::impl(spec) = impl_->spec_; return spec; } Context Context::parent() const { if (!impl_) return {}; Context parent_context; parent_context.impl_ = impl_->parent_; return parent_context; } namespace jb = tensorstore::internal_json_binding; TENSORSTORE_DEFINE_JSON_DEFAULT_BINDER( Context::Spec, jb::Compose<::nlohmann::json::object_t>([](auto is_loading, const auto& options, auto* obj, auto* j_obj) -> absl::Status { if constexpr (is_loading) { obj->impl_.reset(new internal_context::ContextSpecImpl); obj->impl_->resources_.reserve(j_obj->size()); for (const auto& [key, value] : *j_obj) { TENSORSTORE_ASSIGN_OR_RETURN( auto resource, internal_context::ResourceSpecFromJsonWithKey( key, value, options)); obj->impl_->resources_.insert(std::move(resource)); } } else { if (!obj->impl_) return absl::OkStatus(); for (const auto& resource_spec : obj->impl_->resources_) { TENSORSTORE_ASSIGN_OR_RETURN(auto resource_spec_json, resource_spec->ToJson(options)); assert(!resource_spec_json.is_discarded()); j_obj->emplace(resource_spec->key_, std::move(resource_spec_json)); } } return absl::OkStatus(); })) namespace internal { TENSORSTORE_DEFINE_JSON_BINDER(ContextSpecDefaultableJsonBinder, [](auto is_loading, const auto& options, auto* obj, auto* j) { return jb::DefaultInitializedValue()( is_loading, options, obj, j); }) bool IsPartialBindingContext(const Context& context) { return internal_context::Access::impl(context)->root_->bind_partial_; } void SetRecordBindingState(internal::ContextSpecBuilder& builder, bool record_binding_state) { auto& impl = internal_context::Access::impl(builder); auto ptr = impl.release(); ptr.set_tag(record_binding_state); impl.reset(ptr, internal::adopt_object_ref); } } namespace internal_context { Result<::nlohmann::json> BuilderResourceSpec::ToJson( Context::ToJsonOptions options) { ::nlohmann::json json_spec; if (!underlying_spec_->key_.empty()) { return underlying_spec_->key_; } return underlying_spec_->ToJson(options); } Result<ResourceImplStrongPtr> BuilderResourceSpec::CreateResource( const internal::ContextResourceCreationContext& creation_context) { return underlying_spec_->CreateResource(creation_context); } ResourceSpecImplPtr BuilderResourceSpec::UnbindContext( const internal::ContextSpecBuilder& spec_builder) { if (!underlying_spec_->key_.empty() && !underlying_spec_->provider_->config_only_) { return ResourceSpecImplPtr(new ResourceReference(underlying_spec_->key_)); } return underlying_spec_->UnbindContext(spec_builder); } void BuilderResourceSpec::EncodeCacheKey(std::string* out) const { underlying_spec_->EncodeCacheKey(out); } BuilderImpl::~BuilderImpl() { auto& ids = ids_; using SharedEntry = std::pair<ResourceImplBase*, ResourceEntry*>; std::vector<SharedEntry> shared_entries; for (auto& p : resources_) { const auto& key = p.first->spec_->key_; if (!key.empty()) { ids[key]++; } if (p.second.shared) { shared_entries.emplace_back(p.first.get(), &p.second); } } std::sort(shared_entries.begin(), shared_entries.end(), [](const SharedEntry& a, const SharedEntry& b) { return a.second->id < b.second->id; }); for (auto [resource, entry] : shared_entries) { std::string key = resource->spec_->key_; if (key.empty() || ids.at(key) != 1) { size_t i = 0; while (true) { key = tensorstore::StrCat(resource->spec_->provider_->id_, "#", i); if (!ids.count(key)) break; ++i; } ids[key]++; } entry->spec->underlying_spec_->key_ = key; root_->resources_.insert(entry->spec->underlying_spec_); } } void BuilderImplPtrTraits::increment(BuilderImplTaggedPtr p) { intrusive_ptr_increment( static_cast<internal::AtomicReferenceCount<BuilderImpl>*>(p.get())); } void BuilderImplPtrTraits::decrement(BuilderImplTaggedPtr p) { intrusive_ptr_decrement( static_cast<internal::AtomicReferenceCount<BuilderImpl>*>(p.get())); } } namespace internal { ContextSpecBuilder ContextSpecBuilder::Make(ContextSpecBuilder parent, Context::Spec existing_spec) { ContextSpecBuilder builder; if (existing_spec.impl_) { if (existing_spec.impl_->use_count() != 1) { existing_spec.impl_.reset( new internal_context::ContextSpecImpl(*existing_spec.impl_)); } } if (parent.impl_) { builder.impl_ = std::move(parent.impl_); builder.spec_impl_ = std::move(existing_spec.impl_); } else { builder.impl_.reset(internal_context::BuilderImplTaggedPtr( new internal_context::BuilderImpl, parent.impl_.get().tag())); if (!existing_spec.impl_) { builder.spec_impl_.reset(new internal_context::ContextSpecImpl); } else { builder.spec_impl_ = std::move(existing_spec.impl_); } builder.impl_->root_ = builder.spec_impl_; } if (builder.spec_impl_ && !builder.spec_impl_->resources_.empty()) { auto& ids = builder.impl_->ids_; for (const auto& resource_spec : builder.spec_impl_->resources_) { ids[resource_spec->key_]++; resource_spec->UnbindContext(builder); } } return builder; } Context::Spec ContextSpecBuilder::spec() const { Context::Spec spec; spec.impl_ = spec_impl_; return spec; } } namespace internal_context { ResourceSpecImplPtr ResourceImplBase::UnbindContext( const internal::ContextSpecBuilder& spec_builder) { auto spec = spec_->provider_->DoGetSpec(*this, spec_builder); spec->provider_ = spec_->provider_; spec->is_default_ = spec_->is_default_; spec->key_ = spec_->key_; return spec; } namespace { internal_context::ResourceSpecImplPtr AddResource( const internal::ContextSpecBuilder& builder, internal_context::ResourceImplBase* resource) { internal_context::ResourceImplWeakPtr resource_ptr(resource); auto* impl = internal_context::Access::impl(builder).get().get(); auto& entry = impl->resources_[resource_ptr]; if (!entry.spec) { entry.spec.reset(new internal_context::BuilderResourceSpec); auto new_spec = entry.spec; entry.spec->provider_ = resource->spec_->provider_; entry.id = impl->next_id_++; entry.shared = (resource->spec_->is_default_ || !resource->spec_->key_.empty()); auto underlying_spec = resource->UnbindContext(builder); new_spec->underlying_spec_ = std::move(underlying_spec); return new_spec; } else { entry.shared = true; return entry.spec; } } } ResourceOrSpecPtr AddResourceOrSpec(const internal::ContextSpecBuilder& builder, ResourceOrSpecTaggedPtr resource_or_spec) { assert(internal_context::Access::impl(builder)); if (!resource_or_spec) { resource_or_spec.set_tag<1>(false); return ResourceOrSpecPtr(resource_or_spec); } if (!IsResource(resource_or_spec)) { return ToResourceOrSpecPtr( static_cast<ResourceSpecImplBase*>(resource_or_spec.get()) ->UnbindContext(builder)); } else { auto new_ptr = ToResourceOrSpecPtr(AddResource( builder, static_cast<ResourceImplBase*>(resource_or_spec.get()))); if (internal::GetRecordBindingState(builder)) { auto new_tagged_ptr = new_ptr.release(); new_tagged_ptr.set_tag<1>(true); new_ptr = ResourceOrSpecPtr(new_tagged_ptr, internal::adopt_object_ref); } return new_ptr; } } absl::Status ResourceSpecFromJsonWithDefaults( std::string_view provider_id, const JsonSerializationOptions& options, ResourceOrSpecPtr& spec, ::nlohmann::json* j) { if (j->is_discarded()) { spec = internal_context::DefaultResourceSpec(provider_id); } else if (j->is_array()) { const auto& arr = j->get_ref<const ::nlohmann::json::array_t&>(); if (arr.size() != 1) { return internal_json::ExpectedError(*j, "single-element array"); } TENSORSTORE_ASSIGN_OR_RETURN( auto spec_ptr, ResourceSpecFromJson(provider_id, arr[0], options)); spec = ToResourceOrSpecPtr(std::move(spec_ptr)); if (options.preserve_bound_context_resources_) { auto tagged_ptr = spec.release(); tagged_ptr.set_tag<1>(true); spec = ResourceOrSpecPtr(tagged_ptr, internal::adopt_object_ref); } } else { TENSORSTORE_ASSIGN_OR_RETURN(auto spec_ptr, internal_context::ResourceSpecFromJson( provider_id, std::move(*j), options)); spec = ToResourceOrSpecPtr(std::move(spec_ptr)); } return absl::OkStatus(); } absl::Status ResourceSpecToJsonWithDefaults( const JsonSerializationOptions& options, ResourceOrSpecTaggedPtr spec, ::nlohmann::json* j) { if (!spec || IsResource(spec)) { *j = ::nlohmann::json(::nlohmann::json::value_t::discarded); } else { auto* spec_ptr = static_cast<ResourceSpecImplBase*>(spec.get()); TENSORSTORE_ASSIGN_OR_RETURN(*j, spec_ptr->ToJson(options)); if (options.preserve_bound_context_resources_ && IsImmediateBindingResourceSpec(spec)) { ::nlohmann::json::array_t arr(1); arr[0] = std::move(*j); *j = std::move(arr); } if (!IncludeDefaults(options).include_defaults() && j->is_string() && j->get_ref<const std::string&>() == spec_ptr->provider_->id_) { *j = ::nlohmann::json(::nlohmann::json::value_t::discarded); } } return absl::OkStatus(); } absl::Status GetOrCreateResource(ContextImpl* context, ResourceOrSpecTaggedPtr resource_or_spec, ResourceContainer* trigger, ResourceOrSpecPtr& resource) { assert(context); if (!resource_or_spec) { resource.reset(); return absl::OkStatus(); } if (IsResource(resource_or_spec)) { resource.reset(resource_or_spec); return absl::OkStatus(); } if (context->root_->bind_partial_ && !IsImmediateBindingResourceSpec(resource_or_spec)) { resource.reset(resource_or_spec); return absl::OkStatus(); } TENSORSTORE_ASSIGN_OR_RETURN( auto resource_ptr, internal_context::GetOrCreateResource( *context, static_cast<ResourceSpecImplBase&>(*resource_or_spec), trigger)); resource = ToResourceOrSpecPtr(std::move(resource_ptr)); return absl::OkStatus(); } void StripContext(ResourceOrSpecPtr& spec) { if (!spec) return; spec = internal_context::DefaultResourceSpec( IsResource(spec.get()) ? static_cast<ResourceImplBase&>(*spec).spec_->provider_->id_ : static_cast<ResourceSpecImplBase&>(*spec).provider_->id_); } namespace { [[nodiscard]] bool VerifyProviderIdMatch(serialization::DecodeSource& source, std::string_view provider_id, std::string_view key) { if (internal_context::ParseResourceProvider(key) == provider_id) { return true; } source.Fail(serialization::DecodeError(tensorstore::StrCat( "Context resource key ", tensorstore::QuoteString(key), " does not match expected provider ", tensorstore::QuoteString(provider_id)))); return false; } struct ContextResourceSpecImplSerializer { [[nodiscard]] static bool Encode( serialization::EncodeSink& sink, const internal_context::ResourceSpecImplPtr& value, JsonSerializationOptions json_serialization_options = {}) { if (!serialization::EncodeTuple(sink, value->is_default_, value->key_)) { return false; } if (value->is_default_) return true; ::nlohmann::json json; TENSORSTORE_ASSIGN_OR_RETURN( json, value->ToJson(json_serialization_options), (sink.Fail(_), false)); assert(!json.is_discarded()); return serialization::Encode(sink, json); } [[nodiscard]] bool Decode( serialization::DecodeSource& source, internal_context::ResourceSpecImplPtr& value, JsonSerializationOptions json_serialization_options = {}) { bool is_default; std::string_view key; if (!serialization::DecodeTuple(source, is_default, key)) return false; if (!key.empty() && !VerifyProviderIdMatch(source, provider_id, key)) { return false; } if (is_default) { auto& provider = internal_context::GetProviderOrDie(provider_id); value = MakeDefaultResourceSpec(provider, key); } else { std::string key_copy(key); ::nlohmann::json json_spec; if (!serialization::Decode(source, json_spec)) return false; TENSORSTORE_ASSIGN_OR_RETURN( value, internal_context::ResourceSpecFromJson(provider_id, json_spec, json_serialization_options), (source.Fail(_), false)); value->key_ = std::move(key_copy); } return true; } std::string_view provider_id; }; [[nodiscard]] bool EncodeContextSpecBuilder( serialization::EncodeSink& sink, internal::ContextSpecBuilder&& builder); [[nodiscard]] bool DecodeContextSpecBuilder( serialization::DecodeSource& source, internal_context::ContextImplPtr& context); struct ContextResourceImplSerializer { [[nodiscard]] static bool Encode( serialization::EncodeSink& sink, const internal_context::ResourceImplWeakPtr& value) { auto creator = internal_context::GetCreator(*value); if (!serialization::Encode(sink, creator)) return false; if (creator) { assert(!value->spec_->key_.empty()); return serialization::Encode(sink, value->spec_->key_); } auto builder = internal::ContextSpecBuilder::Make(); auto spec = value->UnbindContext(builder); if (!internal_context::EncodeContextSpecBuilder(sink, std::move(builder))) { return false; } return ContextResourceSpecImplSerializer::Encode(sink, spec); } [[nodiscard]] bool Decode( serialization::DecodeSource& source, internal_context::ResourceImplWeakPtr& value) const { internal_context::ContextImplPtr creator; if (!serialization::Decode(source, creator)) return false; if (creator) { return DecodeByReferenceToExistingContext(source, *creator, value); } internal_context::ContextImplPtr context_impl; if (!internal_context::DecodeContextSpecBuilder(source, context_impl)) { return false; } internal_context::ResourceSpecImplPtr resource_spec; if (!ContextResourceSpecImplSerializer{provider_id}.Decode(source, resource_spec)) { return false; } std::string key; std::swap(key, resource_spec->key_); TENSORSTORE_ASSIGN_OR_RETURN(value, internal_context::GetOrCreateResource( *context_impl, *resource_spec, nullptr), (source.Fail(_), false)); resource_spec->key_ = std::move(key); return true; } [[nodiscard]] bool DecodeByReferenceToExistingContext( serialization::DecodeSource& source, internal_context::ContextImpl& creator, internal_context::ResourceImplWeakPtr& value) const { std::string_view key; if (!serialization::Decode(source, key)) return false; if (!VerifyProviderIdMatch(source, provider_id, key)) return false; TENSORSTORE_ASSIGN_OR_RETURN( auto spec, internal_context::ResourceSpecFromJson(provider_id, key, {}), (source.Fail(_), false)); TENSORSTORE_ASSIGN_OR_RETURN( value, internal_context::GetOrCreateResource(creator, *spec, nullptr), (source.Fail(_), false)); return true; } std::string_view provider_id; }; bool EncodeContextSpecBuilder(serialization::EncodeSink& sink, internal::ContextSpecBuilder&& builder) { std::vector< std::pair<internal_context::ResourceImplWeakPtr, internal::IntrusivePtr<internal_context::BuilderResourceSpec>>> deps; auto& resources = internal_context::Access::impl(builder)->resources_; deps.reserve(resources.size()); for (auto& [resource, entry] : resources) { deps.emplace_back(resource, entry.spec); entry.shared = true; } ABSL_CHECK_EQ(internal_context::Access::impl(builder)->use_count(), 1); builder = internal::ContextSpecBuilder(); if (!serialization::WriteSize(sink.writer(), deps.size())) return false; for (size_t i = 0; i < deps.size(); ++i) { auto& [dep_resource, dep_spec] = deps[i]; if (!serialization::Encode(sink, dep_spec->underlying_spec_->key_)) { return false; } if (!sink.Indirect(dep_resource, ContextResourceImplSerializer{})) { return false; } } return true; } [[nodiscard]] bool DecodeContextResourceInContextSpecBuilder( serialization::DecodeSource& source, internal_context::ContextImpl& context_impl) { std::string key; if (!serialization::Decode(source, key)) return false; internal_context::ResourceImplWeakPtr resource; std::string_view provider_id = internal_context::ParseResourceProvider(key); if (!source.Indirect(resource, ContextResourceImplSerializer{provider_id})) { return false; } if (resource->spec_->provider_->id_ != provider_id) { source.Fail(serialization::DecodeError(tensorstore::StrCat( "Context resource has provider id ", tensorstore::QuoteString(resource->spec_->provider_->id_), " but expected ", tensorstore::QuoteString(provider_id)))); return false; } auto container = std::make_unique<internal_context::ResourceContainer>(); if (resource->spec_->key_ != key) { container->spec_.reset(new internal_context::BuilderResourceSpec); container->spec_->provider_ = resource->spec_->provider_; container->spec_->key_ = std::move(key); static_cast<internal_context::BuilderResourceSpec&>(*container->spec_) .underlying_spec_ = resource->spec_; } else { container->spec_ = resource->spec_; } container->result_.emplace(resource.get()); if (!context_impl.spec_->resources_.emplace(container->spec_).second) { source.Fail(absl::DataLossError( tensorstore::StrCat("Duplicate context resource key in Context spec ", tensorstore::QuoteString(container->spec_->key_)))); return false; } [[maybe_unused]] bool inserted_resource = context_impl.resources_.emplace(std::move(container)).second; assert(inserted_resource); return true; } bool DecodeContextSpecBuilder(serialization::DecodeSource& source, internal_context::ContextImplPtr& context) { size_t count; if (!serialization::ReadSize(source.reader(), count)) return false; internal_context::ContextImplPtr context_impl( new internal_context::ContextImpl); context_impl->spec_.reset(new internal_context::ContextSpecImpl); context_impl->root_ = context_impl.get(); while (count--) { if (!DecodeContextResourceInContextSpecBuilder(source, *context_impl)) { return false; } } context = std::move(context_impl); return true; } [[nodiscard]] bool EncodeContextResource( serialization::EncodeSink& sink, const internal_context::ResourceImplWeakPtr& resource) { return serialization::IndirectPointerSerializer< internal_context::ResourceImplWeakPtr, ContextResourceImplSerializer>() .Encode(sink, resource); } [[nodiscard]] bool DecodeContextResource( serialization::DecodeSource& source, std::string_view provider_id, internal_context::ResourceImplWeakPtr& resource) { return serialization::IndirectPointerSerializer< internal_context::ResourceImplWeakPtr, ContextResourceImplSerializer>{{provider_id}} .Decode(source, resource); } } bool EncodeContextResourceOrSpec( serialization::EncodeSink& sink, const internal_context::ResourceOrSpecPtr& resource) { const bool is_resource = internal_context::IsResource(resource.get()); if (!serialization::Encode(sink, is_resource)) return false; if (is_resource) { return EncodeContextResource( sink, internal_context::ResourceImplWeakPtr( static_cast<internal_context::ResourceImplBase*>( resource.get().get()))); } else { return ContextResourceSpecImplSerializer::Encode( sink, internal_context::ResourceSpecImplPtr( static_cast<internal_context::ResourceSpecImplBase*>( resource.get().get()))); } } bool DecodeContextResourceOrSpec( serialization::DecodeSource& source, std::string_view provider_id, internal_context::ResourceOrSpecPtr& resource) { bool is_resource; if (!serialization::Decode(source, is_resource)) return false; if (is_resource) { internal_context::ResourceImplWeakPtr resource_ptr; if (!DecodeContextResource(source, provider_id, resource_ptr)) return false; resource = internal_context::ToResourceOrSpecPtr(std::move(resource_ptr)); } else { internal_context::ResourceSpecImplPtr spec_ptr; if (!ContextResourceSpecImplSerializer{provider_id}.Decode(source, spec_ptr)) { return false; } resource = internal_context::ToResourceOrSpecPtr(std::move(spec_ptr)); } return true; } bool ContextSpecImplPtrNonNullDirectSerializer::Encode( serialization::EncodeSink& sink, const internal_context::ContextSpecImplPtr& value) { Context::Spec spec; internal_context::Access::impl(spec) = value; return serialization::JsonBindableSerializer<Context::Spec>::Encode(sink, spec); } bool ContextSpecImplPtrNonNullDirectSerializer::Decode( serialization::DecodeSource& source, internal_context::ContextSpecImplPtr& value) { Context::Spec spec; if (!serialization::JsonBindableSerializer<Context::Spec>::Decode(source, spec)) { return false; } value = internal_context::Access::impl(spec); return true; } bool ContextImplPtrNonNullDirectSerializer::Encode( serialization::EncodeSink& sink, const internal_context::ContextImplPtr& value) { return serialization::EncodeTuple(sink, value->spec_, value->parent_); } bool ContextImplPtrNonNullDirectSerializer::Decode( serialization::DecodeSource& source, internal_context::ContextImplPtr& value) { Context::Spec spec; Context parent; if (!serialization::DecodeTuple(source, spec, parent)) return false; Context context(std::move(spec), std::move(parent)); value = std::move(internal_context::Access::impl(context)); return true; } bool UntypedContextResourceImplPtrNonNullDirectSerializer::Encode( serialization::EncodeSink& sink, const internal_context::ResourceImplWeakPtr& value) { std::string_view provider_id = value->spec_->provider_->id_; if (!serialization::Encode(sink, provider_id)) return false; return ContextResourceImplSerializer{provider_id}.Encode(sink, value); } bool UntypedContextResourceImplPtrNonNullDirectSerializer::Decode( serialization::DecodeSource& source, internal_context::ResourceImplWeakPtr& value) { std::string provider_id; if (!serialization::Decode(source, provider_id)) return false; if (!internal_context::GetProvider(provider_id)) { source.Fail(internal_context::ProviderNotRegisteredError(provider_id)); return false; } return ContextResourceImplSerializer{provider_id}.Decode(source, value); } } namespace serialization { bool Serializer<Context::Spec>::Encode(EncodeSink& sink, const Context::Spec& value) { return serialization::Encode(sink, internal_context::Access::impl(value)); } bool Serializer<Context::Spec>::Decode(DecodeSource& source, Context::Spec& value) { return serialization::Decode(source, internal_context::Access::impl(value)); } bool Serializer<Context>::Encode(EncodeSink& sink, const Context& value) { return serialization::Encode(sink, internal_context::Access::impl(value)); } bool Serializer<Context>::Decode(DecodeSource& source, Context& value) { return serialization::Decode(source, internal_context::Access::impl(value)); } } } TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::internal_context::ContextSpecImplPtr, (tensorstore::serialization::IndirectPointerSerializer< tensorstore::internal_context::ContextSpecImplPtr, tensorstore::internal_context:: ContextSpecImplPtrNonNullDirectSerializer>{})) TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::internal_context::ContextImplPtr, (tensorstore::serialization::IndirectPointerSerializer< tensorstore::internal_context::ContextImplPtr, tensorstore::internal_context:: ContextImplPtrNonNullDirectSerializer>{}))
#include "tensorstore/context.h" #include <cstddef> #include <cstdint> #include <optional> #include <string> #include <tuple> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include <nlohmann/json.hpp> #include "tensorstore/context_impl.h" #include "tensorstore/context_resource_provider.h" #include "tensorstore/internal/cache_key/cache_key.h" #include "tensorstore/internal/cache_key/std_optional.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/internal/json_binding/std_optional.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/internal/testing/concurrent.h" #include "tensorstore/json_serialization_options.h" #include "tensorstore/json_serialization_options_base.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/serialization/std_tuple.h" #include "tensorstore/serialization/test_util.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" namespace tensorstore { template <typename Provider> auto* GetRawPointer(const Context::Resource<Provider>& resource) { return resource.get(); } } namespace { namespace jb = tensorstore::internal_json_binding; using ::tensorstore::Context; using ::tensorstore::IncludeDefaults; using ::tensorstore::MatchesJson; using ::tensorstore::MatchesStatus; using ::tensorstore::Result; using ::tensorstore::internal::ContextResourceCreationContext; using ::tensorstore::internal::ContextResourceRegistration; using ::tensorstore::internal::ContextResourceTraits; using ::tensorstore::internal::ContextSpecBuilder; using ::tensorstore::internal_testing::TestConcurrent; using ::tensorstore::serialization::SerializationRoundTrip; struct IntResource : public ContextResourceTraits<IntResource> { struct Spec { std::int64_t value; constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(x.value); }; }; using Resource = std::int64_t; static constexpr char id[] = "int_resource"; static Spec Default() { return {42}; } static constexpr auto JsonBinder() { return jb::Object(jb::Member( "value", jb::Projection(&Spec::value, jb::DefaultValue([](auto* v) { *v = 42; })))); } static Result<Resource> Create(Spec v, ContextResourceCreationContext context) { return v.value; } static Spec GetSpec(Resource v, const ContextSpecBuilder& builder) { return {v}; } }; struct IntConfigResource : public ContextResourceTraits<IntConfigResource> { constexpr static bool config_only = true; struct Spec { std::int64_t value; constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(x.value); }; }; using Resource = std::int64_t; static constexpr char id[] = "int_config_resource"; static Spec Default() { return {42}; } static constexpr auto JsonBinder() { return jb::Projection(&Spec::value); } static Result<Resource> Create(Spec v, ContextResourceCreationContext context) { return v.value; } static Spec GetSpec(Resource v, const ContextSpecBuilder& builder) { return {v}; } }; struct StrongRefResource : public ContextResourceTraits<StrongRefResource> { struct Spec { std::int64_t value; constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(x.value); }; }; struct Resource { size_t num_strong_references = 0; }; static constexpr char id[] = "strongref"; static Spec Default() { return Spec{42}; } static constexpr auto JsonBinder() { namespace jb = tensorstore::internal_json_binding; return jb::Object(jb::Member( "value", jb::Projection(&Spec::value, jb::DefaultValue([](auto* obj) { *obj = 7; })))); } static Result<Resource> Create(Spec v, ContextResourceCreationContext context) { return Resource{}; } static Spec GetSpec(const Resource& v, const ContextSpecBuilder& builder) { return {42}; } static void AcquireContextReference(Resource& v) { ++v.num_strong_references; } static void ReleaseContextReference(Resource& v) { --v.num_strong_references; } }; struct OptionalResource : public ContextResourceTraits<OptionalResource> { using Spec = std::optional<size_t>; using Resource = Spec; static constexpr char id[] = "optional_resource"; static Spec Default() { return {}; } static constexpr auto JsonBinder() { namespace jb = tensorstore::internal_json_binding; return jb::Object(jb::Member( "limit", jb::DefaultInitializedValue(jb::Optional( jb::Integer<size_t>(1), [] { return "shared"; })))); } static Result<Resource> Create(Spec v, ContextResourceCreationContext context) { return v; } static Spec GetSpec(Resource v, const ContextSpecBuilder& builder) { return v; } }; const ContextResourceRegistration<IntResource> int_resource_registration; const ContextResourceRegistration<IntConfigResource> int_config_resource_registration; const ContextResourceRegistration<StrongRefResource> strong_ref_resource_registration; const ContextResourceRegistration<OptionalResource> optional_resource_registration; TEST(IntResourceTest, InvalidDirectSpec) { EXPECT_THAT(Context::Resource<IntResource>::FromJson(nullptr), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected non-null value, but received: null")); EXPECT_THAT(Context::Resource<IntResource>::FromJson(3), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected object, but received: 3")); EXPECT_THAT( Context::Resource<IntResource>::FromJson("foo"), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid reference to \"int_resource\" resource: \"foo\"")); } TEST(IntResourceTest, Default) { auto context = Context::Default(); EXPECT_EQ(context, context); EXPECT_FALSE(context.parent()); auto context2 = Context::Default(); EXPECT_NE(context, context2); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson("int_resource")); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource, context.GetResource(resource_spec)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource2, context.GetResource(resource_spec)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource3, context2.GetResource(resource_spec)); EXPECT_EQ(resource, resource); EXPECT_EQ(resource, resource2); EXPECT_NE(resource, resource3); EXPECT_THAT(context.GetResource<IntResource>(), ::testing::Optional(resource)); EXPECT_THAT(context.GetResource<IntResource>("int_resource"), ::testing::Optional(resource)); EXPECT_THAT(resource, ::testing::Pointee(42)); EXPECT_THAT(context.GetResource<IntResource>({{"value", 50}}), ::testing::Optional(::testing::Pointee(50))); } TEST(IntResourceTest, ValidDirectSpec) { auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson({{"value", 7}})); EXPECT_THAT(context.GetResource(resource_spec), ::testing::Optional(::testing::Pointee(7))); } TEST(IntResourceTest, ValidIndirectSpecDefaultId) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec, Context::Spec::FromJson({{"int_resource", {{"value", 7}}}})); auto context = Context(spec); auto resource_spec = Context::Resource<IntResource>::DefaultSpec(); EXPECT_THAT(context.GetResource(resource_spec), ::testing::Optional(::testing::Pointee(7))); } TEST(IntResourceTest, ContextFromJson) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, Context::FromJson({{"int_resource", {{"value", 7}}}})); EXPECT_THAT(context.GetResource<IntResource>(), ::testing::Optional(::testing::Pointee(7))); } TEST(IntResourceTest, ValidIndirectSpecDefault) { auto context = Context::Default(); auto resource_spec = Context::Resource<IntResource>::DefaultSpec(); EXPECT_THAT(context.GetResource(resource_spec), ::testing::Optional(::testing::Pointee(42))); } TEST(IntResourceTest, ValidIndirectSpecIdentifier) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec, Context::Spec::FromJson({{"int_resource#x", {{"value", 7}}}})); auto context = Context(spec); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson("int_resource#x")); EXPECT_THAT(context.GetResource(resource_spec), ::testing::Optional(::testing::Pointee(7))); } TEST(IntResourceTest, UndefinedIndirectReference) { auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson("int_resource#x")); EXPECT_THAT(context.GetResource(resource_spec), MatchesStatus(absl::StatusCode::kInvalidArgument, "Resource not defined: \"int_resource#x\"")); } TEST(IntResourceTest, SimpleReference) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec, Context::Spec::FromJson({ {"int_resource#x", {{"value", 7}}}, {"int_resource#y", "int_resource#x"}, })); auto context = Context(spec); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson("int_resource#y")); EXPECT_THAT(context.GetResource(resource_spec), ::testing::Optional(::testing::Pointee(7))); } TEST(IntResourceTest, ReferenceCycle1) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec, Context::Spec::FromJson({{"int_resource", "int_resource"}})); auto context = Context(spec); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson("int_resource")); EXPECT_THAT(context.GetResource(resource_spec), MatchesStatus(absl::StatusCode::kInvalidArgument, "Context resource reference cycle: " "\"int_resource\":\"int_resource\"")); } TEST(IntResourceTest, ReferenceCycle2) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec, Context::Spec::FromJson({ {"int_resource#a", "int_resource#b"}, {"int_resource#b", "int_resource#a"}, })); auto context = Context(spec); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson("int_resource#a")); EXPECT_THAT(context.GetResource(resource_spec), MatchesStatus(absl::StatusCode::kInvalidArgument, "Context resource reference cycle: " "\"int_resource#b\":\"int_resource#a\" -> " "\"int_resource#a\":\"int_resource#b\"")); } TEST(IntResourceTest, Inherit) { const ::nlohmann::json json_spec1{ {"int_resource", {{"value", 7}}}, {"int_resource#a", {{"value", 9}}}, {"int_resource#d", {{"value", 42}}}, {"int_resource#c", nullptr}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec1, Context::Spec::FromJson(json_spec1)); EXPECT_THAT(spec1.ToJson(IncludeDefaults{false}), ::testing::Optional(MatchesJson({ {"int_resource", {{"value", 7}}}, {"int_resource#a", {{"value", 9}}}, {"int_resource#d", ::nlohmann::json::object_t{}}, {"int_resource#c", nullptr}, }))); EXPECT_THAT(spec1.ToJson(IncludeDefaults{true}), ::testing::Optional(MatchesJson({ {"int_resource", {{"value", 7}}}, {"int_resource#a", {{"value", 9}}}, {"int_resource#d", {{"value", 42}}}, {"int_resource#c", nullptr}, }))); ::nlohmann::json json_spec2{ {"int_resource", {{"value", 8}}}, {"int_resource#b", nullptr}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec2, Context::Spec::FromJson(json_spec2)); auto context1 = Context(spec1); auto context2 = Context(spec2, context1); EXPECT_EQ(context1, context2.parent()); EXPECT_THAT(context1.spec().ToJson(IncludeDefaults{true}), ::testing::Optional(MatchesJson(json_spec1))); EXPECT_THAT(context2.spec().ToJson(), ::testing::Optional(MatchesJson(json_spec2))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource1, context2.GetResource( Context::Resource<IntResource>::FromJson("int_resource").value())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource2, context2.GetResource( Context::Resource<IntResource>::FromJson("int_resource#a").value())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource3, context2.GetResource( Context::Resource<IntResource>::FromJson("int_resource#b").value())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource4, context2.GetResource( Context::Resource<IntResource>::FromJson("int_resource#c").value())); EXPECT_EQ(8, *resource1); EXPECT_EQ(9, *resource2); EXPECT_EQ(7, *resource3); EXPECT_EQ(42, *resource4); } TEST(IntResourceTest, Unknown) { EXPECT_THAT(Context::Spec::FromJson({ {"foo", {{"value", 7}}}, }), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid context resource identifier: \"foo\"")); } TEST(IntConfigResourceTest, ContextSpec) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, Context::FromJson({{"int_config_resource", 111}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource1, context.GetResource<IntConfigResource>()); EXPECT_THAT(resource1, ::testing::Pointee(111)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource2, context.GetResource<IntConfigResource>(222)); EXPECT_THAT(resource2, ::testing::Pointee(222)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource3, context.GetResource<IntConfigResource>(222)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource4, context.GetResource<IntConfigResource>(111)); std::string cache_key1, cache_key2, cache_key3, cache_key4; tensorstore::internal::EncodeCacheKey(&cache_key1, resource1); tensorstore::internal::EncodeCacheKey(&cache_key2, resource2); tensorstore::internal::EncodeCacheKey(&cache_key3, resource3); tensorstore::internal::EncodeCacheKey(&cache_key4, resource4); EXPECT_EQ(cache_key1, cache_key4); EXPECT_EQ(cache_key2, cache_key3); } TEST(StrongRefResourceTest, DirectSpec) { auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<StrongRefResource>::FromJson( ::nlohmann::json::object_t{})); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource, context.GetResource(resource_spec)); EXPECT_EQ(0, resource->num_strong_references); } TEST(StrongRefResourceTest, IndirectSpec) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec, Context::Spec::FromJson({{"strongref", ::nlohmann::json::object_t{}}})); auto context = Context(spec); auto resource_spec = Context::Resource<StrongRefResource>::DefaultSpec(); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource, context.GetResource(resource_spec)); EXPECT_EQ(1, resource->num_strong_references); context = Context(); EXPECT_EQ(0, resource->num_strong_references); } TEST(ContextSpecBuilderTest, Simple) { auto spec = Context::Spec::FromJson({{"int_resource", {{"value", 5}}}}).value(); auto context = Context(spec); auto resource_spec = Context::Resource<IntResource>::DefaultSpec(); auto resource = context.GetResource(resource_spec).value(); Context::Spec new_spec; Context::Resource<IntResource> new_resource_spec; { auto builder = ContextSpecBuilder::Make(); new_spec = builder.spec(); new_resource_spec = builder.AddResource(resource); } EXPECT_THAT( new_spec.ToJson(), ::testing::Optional(MatchesJson({{"int_resource", {{"value", 5}}}}))); EXPECT_THAT(new_resource_spec.ToJson(IncludeDefaults{true}), ::testing::Optional(MatchesJson("int_resource"))); auto new_context = Context(new_spec); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto new_resource, new_context.GetResource(new_resource_spec)); EXPECT_EQ(5, *new_resource); } TEST(ContextSpecBuilderTest, Default) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource, Context::Default().GetResource<IntResource>()); Context::Spec new_spec; Context::Resource<IntResource> new_resource_spec; { auto builder = ContextSpecBuilder::Make(); new_spec = builder.spec(); new_resource_spec = builder.AddResource(resource); } EXPECT_THAT( jb::ToJson(new_spec, tensorstore::internal::ContextSpecDefaultableJsonBinder, IncludeDefaults{false}), ::testing::Optional( MatchesJson({{"int_resource", ::nlohmann::json::object_t()}}))); EXPECT_THAT( new_spec.ToJson(IncludeDefaults{true}), ::testing::Optional(MatchesJson({{"int_resource", {{"value", 42}}}}))); EXPECT_THAT(new_resource_spec.ToJson(IncludeDefaults{true}), ::testing::Optional(MatchesJson("int_resource"))); auto new_context = Context(new_spec); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto new_resource, new_context.GetResource(new_resource_spec)); EXPECT_THAT(new_resource, ::testing::Pointee(42)); } TEST(ContextSpecBuilderTest, MultipleContexts) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec1, Context::Spec::FromJson({{"int_resource", {{"value", 5}}}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec2, Context::Spec::FromJson({{"int_resource", {{"value", 6}}}})); auto context1 = Context(spec1); auto context2 = Context(spec2); auto resource_spec = Context::Resource<IntResource>::DefaultSpec(); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource1, context1.GetResource(resource_spec)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource2, context2.GetResource(resource_spec)); Context::Spec new_spec; Context::Resource<IntResource> new_resource_spec1; Context::Resource<IntResource> new_resource_spec2; { auto builder = ContextSpecBuilder::Make(); new_spec = builder.spec(); new_resource_spec1 = builder.AddResource(resource1); new_resource_spec2 = builder.AddResource(resource2); } EXPECT_THAT(new_spec.ToJson(), ::testing::Optional(MatchesJson({ {"int_resource#0", {{"value", 5}}}, {"int_resource#1", {{"value", 6}}}, }))); EXPECT_EQ("int_resource#0", new_resource_spec1.ToJson()); EXPECT_EQ("int_resource#1", new_resource_spec2.ToJson()); } TEST(ContextSpecBuilderTest, Inline) { auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<IntResource>::FromJson({{"value", 5}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource, context.GetResource(resource_spec)); Context::Spec new_spec; Context::Resource<IntResource> new_resource_spec; { auto builder = ContextSpecBuilder::Make(); new_spec = builder.spec(); new_resource_spec = builder.AddResource(resource); } EXPECT_THAT(new_spec.ToJson(), ::testing::Optional(MatchesJson(::nlohmann::json::object_t()))); EXPECT_THAT(new_resource_spec.ToJson(), ::testing::Optional(MatchesJson({{"value", 5}}))); } TEST(ContextSpecBuilderTest, InlineEqualToDefault) { auto context = Context::Default(); auto resource_spec = Context::Resource<IntResource>::FromJson({{"value", 42}}).value(); auto resource = context.GetResource(resource_spec).value(); Context::Spec new_spec; Context::Resource<IntResource> new_resource_spec; { auto builder = ContextSpecBuilder::Make(); new_spec = builder.spec(); new_resource_spec = builder.AddResource(resource); } EXPECT_EQ(::nlohmann::json({}), new_spec.ToJson()); EXPECT_EQ(::nlohmann::json::object_t{}, new_resource_spec.ToJson(IncludeDefaults{false})); } TEST(ContextSpecBuilderTest, InlineShared) { auto context = Context::Default(); auto resource_spec = Context::Resource<IntResource>::FromJson({{"value", 5}}).value(); auto resource = context.GetResource(resource_spec).value(); Context::Spec new_spec; Context::Resource<IntResource> new_resource_spec1; Context::Resource<IntResource> new_resource_spec2; { auto builder = ContextSpecBuilder::Make(); new_spec = builder.spec(); new_resource_spec1 = builder.AddResource(resource); new_resource_spec2 = builder.AddResource(resource); } EXPECT_EQ(::nlohmann::json({{"int_resource#0", {{"value", 5}}}}), new_spec.ToJson()); EXPECT_EQ("int_resource#0", new_resource_spec1.ToJson()); EXPECT_EQ("int_resource#0", new_resource_spec2.ToJson()); } TEST(ContextSpecBuilderTest, ExcludeDefaultsJson) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, Context::FromJson({ {"optional_resource", {{"limit", "shared"}}}, {"optional_resource#a", {{"limit", 5}}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource1, context.GetResource<OptionalResource>()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource2, context.GetResource<OptionalResource>("optional_resource#a")); Context::Spec new_spec; Context::Resource<OptionalResource> new_resource_spec1; Context::Resource<OptionalResource> new_resource_spec2; { auto builder = ContextSpecBuilder::Make(); new_spec = builder.spec(); new_resource_spec1 = builder.AddResource(resource1); new_resource_spec2 = builder.AddResource(resource2); } EXPECT_THAT(new_spec.ToJson(tensorstore::IncludeDefaults{false}), ::testing::Optional(MatchesJson({ {"optional_resource#a", {{"limit", 5}}}, {"optional_resource", ::nlohmann::json::object_t()}, }))); EXPECT_THAT(new_spec.ToJson(tensorstore::IncludeDefaults{true}), ::testing::Optional(MatchesJson({ {"optional_resource#a", {{"limit", 5}}}, {"optional_resource", {{"limit", "shared"}}}, }))); } TEST(ContextTest, WeakCreator) { using ::tensorstore::internal_context::Access; using ::tensorstore::internal_context::GetCreator; using ::tensorstore::internal_context::ResourceImplBase; const ::nlohmann::json json_spec1{ {"int_resource", {{"value", 7}}}, {"int_resource#a", {{"value", 9}}}, {"int_resource#d", {{"value", 42}}}, {"int_resource#c", nullptr}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec1, Context::Spec::FromJson(json_spec1)); ::nlohmann::json json_spec2{ {"int_resource", {{"value", 8}}}, {"int_resource#b", nullptr}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec2, Context::Spec::FromJson(json_spec2)); auto context1 = Context(spec1); auto context2 = Context(spec2, context1); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource1, context1.GetResource<IntResource>()); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource2, context2.GetResource<IntResource>()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource2_a, context2.GetResource<IntResource>("int_resource#a")); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource2_b, context2.GetResource<IntResource>("int_resource#b")); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource2_c, context2.GetResource<IntResource>("int_resource#c")); EXPECT_EQ( Access::impl(context1), GetCreator(static_cast<ResourceImplBase&>(*Access::impl(resource1)))); EXPECT_EQ( Access::impl(context1), GetCreator(static_cast<ResourceImplBase&>(*Access::impl(resource2_a)))); EXPECT_EQ( Access::impl(context1), GetCreator(static_cast<ResourceImplBase&>(*Access::impl(resource2_b)))); EXPECT_EQ( Access::impl(context1), GetCreator(static_cast<ResourceImplBase&>(*Access::impl(resource2_c)))); EXPECT_EQ( Access::impl(context2), GetCreator(static_cast<ResourceImplBase&>(*Access::impl(resource2)))); context2 = Context(); EXPECT_EQ( Access::impl(context1), GetCreator(static_cast<ResourceImplBase&>(*Access::impl(resource1)))); EXPECT_FALSE( GetCreator(static_cast<ResourceImplBase&>(*Access::impl(resource2)))); } struct NestedResource : public ContextResourceTraits<NestedResource> { struct Spec { int value; Context::Resource<NestedResource> parent; int GetTotal() const { int total = value; if (parent.has_resource()) total += parent->GetTotal(); return total; } constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(x.value, x.parent); }; }; using Resource = Spec; static constexpr char id[] = "nested_resource"; static Spec Default() { return {42}; } static constexpr auto JsonBinder() { return jb::Object( jb::Member("value", jb::Projection(&Spec::value, jb::DefaultValue([](auto* v) { *v = 42; }))), jb::Member( "parent", jb::Projection( &Spec::parent, jb::DefaultInitializedPredicate<jb::kNeverIncludeDefaults>( [](auto* obj) { return !obj->valid(); })))); } static Result<Resource> Create(const Spec& spec, ContextResourceCreationContext context) { Resource resource = spec; TENSORSTORE_RETURN_IF_ERROR(resource.parent.BindContext(context)); return resource; } static Spec GetSpec(const Resource& resource, const ContextSpecBuilder& builder) { Spec spec = resource; UnbindContext(spec, builder); return spec; } static void UnbindContext(Spec& spec, const ContextSpecBuilder& builder) { spec.parent.UnbindContext(builder); } }; const ContextResourceRegistration<NestedResource> nested_resource_registration; TEST(NestedResourceTest, Basic) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, Context::FromJson({ {"nested_resource#a", {{"value", 1}}}, {"nested_resource#b", {{"value", 3}, {"parent", "nested_resource#a"}}}, {"nested_resource#c", {{"value", 5}, {"parent", "nested_resource#b"}}}, {"nested_resource#d", {{"value", 10}, {"parent", "nested_resource#e"}}}, {"nested_resource#e", {{"value", 15}, {"parent", "nested_resource#d"}}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto a, context.GetResource<NestedResource>("nested_resource#a")); EXPECT_FALSE(a->parent.valid()); EXPECT_EQ(1, a->GetTotal()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto b, context.GetResource<NestedResource>("nested_resource#b")); EXPECT_EQ(a, b->parent); EXPECT_EQ(4, b->GetTotal()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto c, context.GetResource<NestedResource>("nested_resource#c")); EXPECT_EQ(b, c->parent); EXPECT_EQ(9, c->GetTotal()); EXPECT_THAT( context.GetResource<NestedResource>("nested_resource#d"), MatchesStatus(absl::StatusCode::kInvalidArgument, "Context resource reference cycle: " "\"nested_resource#d\" -> " "\"nested_resource#d\":" "\\{\"parent\":\"nested_resource#e\",\"value\":10\\} -> " "\"nested_resource#e\" -> " "\"nested_resource#e\":" "\\{\"parent\":\"nested_resource#d\",\"value\":15\\}")); EXPECT_THAT(context.GetResource<NestedResource>("nested_resource#e"), MatchesStatus(absl::StatusCode::kInvalidArgument, "Context resource reference cycle: .*")); } TEST(ContextSpecBuilderTest, PartiallyBound) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context_spec, Context::Spec::FromJson({ {"nested_resource#a", {{"value", 2}}}, {"nested_resource#b", {{"value", 3}, {"parent", "nested_resource#a"}}}, })); auto context = Context(context_spec); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto resource_spec, Context::Resource<NestedResource>::FromJson("nested_resource#b")); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto resource, context.GetResource(resource_spec)); Context::Spec new_spec; Context::Resource<NestedResource> new_resource_spec1; Context::Resource<NestedResource> new_resource_spec2; { auto builder = ContextSpecBuilder::Make({}, context_spec); new_spec = builder.spec(); new_resource_spec1 = builder.AddResource(resource_spec); new_resource_spec2 = builder.AddResource(resource); } EXPECT_THAT(new_spec.ToJson(), ::testing::Optional(MatchesJson({ {"nested_resource#a", {{"value", 2}}}, {"nested_resource#b", {{"value", 3}, {"parent", "nested_resource#a"}}}, {"nested_resource#1", {{"value", 2}}}, {"nested_resource#0", {{"value", 3}, {"parent", "nested_resource#1"}}}, }))); EXPECT_THAT(new_resource_spec1.ToJson(), ::testing::Optional(MatchesJson("nested_resource#b"))); EXPECT_THAT(new_resource_spec2.ToJson(), ::testing::Optional(MatchesJson("nested_resource#0"))); } TEST(ContextSpecSerializationTest, Empty) { Context::Spec spec; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec_copy, SerializationRoundTrip(spec)); EXPECT_THAT(spec.ToJson(), ::testing::Optional(MatchesJson(::nlohmann::json::object_t()))); } TEST(ContextSpecSerializationTest, NonEmpty) { ::nlohmann::json json_spec{ {"int_resource", ::nlohmann::json::object_t()}, {"int_resource#a", "int_resource"}, {"int_resource#b", ::nlohmann::json::object_t()}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec, Context::Spec::FromJson(json_spec)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec_copy, SerializationRoundTrip(spec)); EXPECT_THAT(spec.ToJson(), ::testing::Optional(MatchesJson(json_spec))); } TEST(ContextSerializationTest, Null) { Context context; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto context_copy, SerializationRoundTrip(context)); EXPECT_FALSE(context); } TEST(ContextSerializationTest, NonNull) { ::nlohmann::json parent_json_spec{ {"int_resource#c", ::nlohmann::json::object_t()}, }; ::nlohmann::json child_json_spec{ {"int_resource", ::nlohmann::json::object_t()}, {"int_resource#a", "int_resource"}, {"int_resource#b", ::nlohmann::json::object_t()}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto parent_spec, Context::Spec::FromJson(parent_json_spec)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto child_spec, Context::Spec::FromJson(child_json_spec)); Context parent_context(parent_spec); Context child_context(child_spec, parent_context); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto child_context_copy, SerializationRoundTrip(child_context)); EXPECT_THAT(child_context_copy.spec().ToJson(), ::testing::Optional(child_json_spec)); EXPECT_THAT(child_context_copy.parent().spec().ToJson(), ::testing::Optional(parent_json_spec)); EXPECT_FALSE(child_context_copy.parent().parent()); } TEST(ContextSerializationTest, Shared) { ::nlohmann::json parent_json_spec{ {"int_resource#c", {{"value", 7}}}, }; ::nlohmann::json child_json_spec{ {"int_resource", {{"value", 5}}}, {"int_resource#a", "int_resource"}, {"int_resource#b", {{"value", 6}}}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto parent_spec, Context::Spec::FromJson(parent_json_spec)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto child_spec, Context::Spec::FromJson(child_json_spec)); Context parent_context(parent_spec); Context child_context(child_spec, parent_context); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto res_parent, parent_context.GetResource<IntResource>()); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto res_child, child_context.GetResource<IntResource>()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto res_a, child_context.GetResource<IntResource>("int_resource#a")); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto res_b, child_context.GetResource<IntResource>("int_resource#b")); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto res_c_child, child_context.GetResource<IntResource>("int_resource#c")); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto res_c_parent, parent_context.GetResource<IntResource>("int_resource#c")); EXPECT_EQ(res_child, res_a); EXPECT_EQ(res_c_child, res_c_parent); EXPECT_NE(res_child, res_parent); EXPECT_NE(res_a, res_b); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto copy, SerializationRoundTrip(std::make_tuple( parent_context, child_context, res_parent, res_child, res_a, res_b, res_c_child, res_c_parent))); auto [copy_parent_context, copy_child_context, copy_res_parent, copy_res_child, copy_res_a, copy_res_b, copy_res_c_child, copy_res_c_parent] = copy; EXPECT_EQ(copy_parent_context, copy_child_context.parent()); EXPECT_THAT(copy_child_context.GetResource<IntResource>("int_resource#a"), ::testing::Optional(copy_res_a)); EXPECT_THAT(copy_child_context.GetResource<IntResource>("int_resource#b"), ::testing::Optional(copy_res_b)); EXPECT_THAT(copy_child_context.GetResource<IntResource>("int_resource#c"), ::testing::Optional(copy_res_c_child)); EXPECT_THAT(copy_parent_context.GetResource<IntResource>("int_resource#c"), ::testing::Optional(copy_res_c_parent)); } TEST(ContextTest, ConcurrentCreateSingleResource) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec, Context::Spec::FromJson({{"int_resource", {{"value", 5}}}})); Context context; TestConcurrent<3>( 100, [&] { context = Context(spec); }, [&] {}, [&](auto i) { TENSORSTORE_EXPECT_OK(context.GetResource<IntResource>()); }); } TEST(ContextTest, ConcurrentCreateMultipleResources) { std::vector<std::string> resource_keys{"int_resource#a", "int_resource#b"}; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec, Context::Spec::FromJson({ {resource_keys[0], {{"value", 5}}}, {resource_keys[1], {{"value", 6}}}, })); Context context; TestConcurrent<4>( 100, [&] { context = Context(spec); }, [&] {}, [&](auto i) { TENSORSTORE_EXPECT_OK(context.GetResource<IntResource>( resource_keys[i % resource_keys.size()])); }); } TEST(ContextTest, ConcurrentCreateInParent) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto spec, Context::Spec::FromJson({{"int_resource", {{"value", 5}}}})); Context context; TestConcurrent<3>( 100, [&] { context = Context(spec); }, [&] {}, [&](auto i) { Context child({}, context); TENSORSTORE_EXPECT_OK(child.GetResource<IntResource>()); }); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/context.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/context_test.cc
4f887a6430414cd6088e1743555015b10f116d50
c9209c28-d4bd-437f-92df-e2eb3d2bf2b6
cpp
google/tensorstore
unit
tensorstore/internal/json_binding/unit.cc
tensorstore/util/unit_test.cc
#include "tensorstore/internal/json_binding/unit.h" #include <cmath> #include <string> #include "absl/status/status.h" #include <nlohmann/json_fwd.hpp> #include "tensorstore/internal/json/value_as.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/internal/json_binding/std_tuple.h" #include "tensorstore/util/unit.h" namespace tensorstore { namespace internal_json_binding { TENSORSTORE_DEFINE_JSON_BINDER( UnitJsonBinder, [](auto is_loading, const auto& options, auto* obj, ::nlohmann::json* j) -> absl::Status { if constexpr (is_loading) { if (auto* s = j->get_ptr<const std::string*>()) { *obj = Unit(*s); return absl::OkStatus(); } else if (j->is_number()) { *obj = Unit(j->get<double>(), ""); return absl::OkStatus(); } } return HeterogeneousArray( Projection<&Unit::multiplier>(Validate([](const auto& options, auto* num) { if (*num > 0 && std::isfinite(*num)) return absl::OkStatus(); return internal_json::ExpectedError(*num, "finite positive number"); })), Projection<&Unit::base_unit>())(is_loading, options, obj, j); }); TENSORSTORE_DEFINE_JSON_BINDER( StringOnlyUnitJsonBinder, Compose<std::string>([](auto is_loading, const auto& options, auto* obj, std::string* j) -> absl::Status { if constexpr (is_loading) { *obj = Unit(*j); } else { *j = obj->to_string(); } return absl::OkStatus(); })); } }
#include "tensorstore/util/unit.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/strings/str_cat.h" #include "tensorstore/internal/json_binding/gtest.h" #include "tensorstore/internal/json_binding/unit.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/serialization/test_util.h" #include "tensorstore/util/str_cat.h" namespace { using ::tensorstore::TestJsonBinderRoundTrip; using ::tensorstore::TestJsonBinderRoundTripJsonOnlyInexact; using ::tensorstore::Unit; using ::tensorstore::serialization::TestSerializationRoundTrip; TEST(UnitTest, DefaultConstruct) { Unit u; EXPECT_EQ(1, u.multiplier); EXPECT_EQ("", u.base_unit); } TEST(UnitTest, Compare) { Unit a(5, "nm"); Unit b(5.5, "nm"); Unit c(5, "um"); Unit d; EXPECT_EQ(a, a); EXPECT_EQ(b, b); EXPECT_EQ(c, c); EXPECT_EQ(d, d); EXPECT_NE(a, b); EXPECT_NE(a, c); EXPECT_NE(a, d); EXPECT_NE(b, c); EXPECT_NE(b, d); EXPECT_NE(c, d); } TEST(UnitTest, Ostream) { EXPECT_EQ("5.5 nm", tensorstore::StrCat(Unit(5.5, "nm"))); EXPECT_EQ("nm", tensorstore::StrCat(Unit(1, "nm"))); EXPECT_EQ("5", tensorstore::StrCat(Unit(5, ""))); EXPECT_EQ("1", tensorstore::StrCat(Unit(1, ""))); } TEST(UnitTest, ConvertToString) { EXPECT_EQ("5.5 nm", Unit(5.5, "nm").to_string()); EXPECT_EQ("nm", Unit(1, "nm").to_string()); EXPECT_EQ("5", Unit(5, "").to_string()); EXPECT_EQ("1", Unit(1, "").to_string()); EXPECT_EQ("1", absl::StrCat(Unit(1, ""))); } TEST(UnitTest, MultiplierBaseUnit) { Unit u = {5, "nm"}; EXPECT_EQ(5, u.multiplier); EXPECT_EQ("nm", u.base_unit); } TEST(UnitTest, Unit) { EXPECT_EQ(Unit(4, "nm"), Unit("4nm")); EXPECT_EQ(Unit(4, "nm"), Unit("4.nm")); EXPECT_EQ(Unit(4e-3, "nm"), Unit("4e-3nm")); EXPECT_EQ(Unit(.4, "nm"), Unit(".4nm")); EXPECT_EQ(Unit(.4, "nm"), Unit(".4 nm")); EXPECT_EQ(Unit(.4, "nm"), Unit(" .4 nm")); EXPECT_EQ(Unit(.4, "nm"), Unit(" .4 nm ")); EXPECT_EQ(Unit(4e-3, "nm"), Unit("+4e-3nm")); EXPECT_EQ(Unit(-4e-3, "nm"), Unit("-4e-3nm")); EXPECT_EQ(Unit(4.5, "nm"), Unit("4.5nm")); EXPECT_EQ(Unit(1, "nm"), Unit("nm")); EXPECT_EQ(Unit(4, ""), Unit("4")); EXPECT_EQ(Unit(1, ""), Unit("")); EXPECT_EQ(Unit(3, "nm @ 50"), Unit("3 nm @ 50")); } TEST(UnitTest, JsonRoundTrip) { TestJsonBinderRoundTrip<Unit>({ {Unit(4, "nm"), {4, "nm"}}, {Unit(4.5, "nm"), {4.5, "nm"}}, {Unit(4.5, ""), {4.5, ""}}, }); } TEST(UnitTest, JsonRoundTripInexact) { TestJsonBinderRoundTripJsonOnlyInexact<Unit>({ {"4nm", {4, "nm"}}, {4, {4, ""}}, {"nm", {1, "nm"}}, }); } TEST(SerializationTest, Basic) { TestSerializationRoundTrip(Unit("4nm")); TestSerializationRoundTrip(Unit("4")); TestSerializationRoundTrip(Unit("nm")); TestSerializationRoundTrip(Unit("")); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/internal/json_binding/unit.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/util/unit_test.cc
4f887a6430414cd6088e1743555015b10f116d50
6709acfa-25b3-45ca-86e4-21b8908657e7
cpp
google/tensorstore
batch
tensorstore/serialization/batch.cc
tensorstore/batch_test.cc
#include "tensorstore/serialization/batch.h" #include "absl/status/status.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace serialization { BatchEncodeSink::BatchEncodeSink(riegeli::Writer& writer) : EncodeSink(writer) {} BatchEncodeSink::~BatchEncodeSink() = default; bool BatchEncodeSink::DoIndirect(const std::type_info& type, ErasedEncodeWrapperFunction encode, std::shared_ptr<void> object) { auto [it, inserted] = indirect_map_.emplace(object, indirect_map_.size()); return serialization::WriteSize(writer(), it->second) && (!inserted || encode(*this, object)); } BatchDecodeSource::BatchDecodeSource(riegeli::Reader& reader) : DecodeSource(reader) {} BatchDecodeSource::~BatchDecodeSource() = default; bool BatchDecodeSource::DoIndirect(const std::type_info& type, ErasedDecodeWrapperFunction decode, std::shared_ptr<void>& value) { size_t id; if (!serialization::ReadSize(reader(), id)) return false; if (id > indirect_objects_.size()) { Fail(DecodeError(tensorstore::StrCat("Indirect object index ", id, " out of range [0, ", indirect_objects_.size(), ")"))); return false; } if (id < indirect_objects_.size()) { auto& entry = indirect_objects_[id]; if (*entry.type != type) { Fail(absl::InvalidArgumentError(tensorstore::StrCat( "Type mismatch for indirect object, received ", entry.type->name(), " but expected ", type.name()))); return false; } value = entry.value; return true; } indirect_objects_.emplace_back(); if (!decode(*this, value)) return false; auto& entry = indirect_objects_[id]; entry.type = &type; entry.value = value; return true; } } }
#include "tensorstore/batch.h" #include <stddef.h> #include <functional> #include <string> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "tensorstore/batch_impl.h" namespace { using ::tensorstore::Batch; using ::testing::ElementsAre; using Log = std::vector<std::string>; template <typename T> struct Entry : public Batch::Impl::Entry { using KeyParam = T; Entry(Log& log, size_t nesting_depth, T key) : Batch::Impl::Entry(nesting_depth), key_(key), log(log) {} T key_; T key() const { return key_; } virtual void Submit(Batch::View batch) { log.push_back(absl::StrCat("begin_submit ", key())); for (auto& submit_func : submit_funcs) { submit_func(batch); } log.push_back(absl::StrCat("end_submit ", key())); delete this; } std::vector<std::function<void(Batch::View batch)>> submit_funcs; Log& log; }; template <typename T> void AddFunc(Log& log, Batch::View batch, size_t nesting_depth, T key, std::function<void(Batch::View)> func) { auto& entry = Batch::Impl::From(batch)->GetEntry<Entry<T>>( key, [&] { return std::make_unique<Entry<T>>(log, nesting_depth, key); }); entry.submit_funcs.emplace_back(std::move(func)); } TEST(BatchTest, SingleNestingDepth) { Log log; auto batch = Batch::New(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 2; ++j) { AddFunc<int>(log, batch, 0, i, [&log, i, j](Batch::View batch) { log.emplace_back(absl::StrFormat("i=%d, j=%d", i, j)); }); } } EXPECT_THAT(log, ElementsAre()); batch.Release(); EXPECT_THAT(log, ::testing::UnorderedElementsAre( "begin_submit 0", "i=0, j=0", "i=0, j=1", "end_submit 0", "begin_submit 1", "i=1, j=0", "i=1, j=1", "end_submit 1", "begin_submit 2", "i=2, j=0", "i=2, j=1", "end_submit 2")); } TEST(BatchTest, MultipleNestingDepths) { Log log; auto batch = Batch::New(); for (int nesting_depth : {2, 3, 0}) { AddFunc<int>(log, batch, nesting_depth, nesting_depth, [](Batch::View batch) {}); } EXPECT_THAT(log, ElementsAre()); batch.Release(); EXPECT_THAT(log, ::testing::ElementsAre("begin_submit 3", "end_submit 3", "begin_submit 2", "end_submit 2", "begin_submit 0", "end_submit 0")); } TEST(BatchTest, MultipleTypes) { Log log; auto batch = Batch::New(); AddFunc<int>(log, batch, 0, 42, [](Batch::View batch) {}); AddFunc<float>(log, batch, 0, 1.5, [](Batch::View batch) {}); EXPECT_THAT(log, ElementsAre()); batch.Release(); EXPECT_THAT(log, ::testing::ElementsAre("begin_submit 42", "end_submit 42", "begin_submit 1.5", "end_submit 1.5")); } TEST(BatchTest, Async) { Log log; auto batch = Batch::New(); Batch saved_batch{Batch::no_batch}; AddFunc<int>(log, batch, 2, 2, [&](Batch::View batch) { saved_batch = batch; }); AddFunc<int>(log, batch, 1, 3, [](Batch::View batch) {}); batch.Release(); EXPECT_THAT(log, ElementsAre("begin_submit 2", "end_submit 2")); log.clear(); AddFunc<int>(log, saved_batch, 1, 1, [](Batch::View batch) {}); saved_batch.Release(); EXPECT_THAT( log, ::testing::UnorderedElementsAre("begin_submit 1", "end_submit 1", "begin_submit 3", "end_submit 3")); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/serialization/batch.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/batch_test.cc
4f887a6430414cd6088e1743555015b10f116d50
d5254719-24c1-4a2c-931b-bfce7b9085fb
cpp
google/tensorstore
virtual_chunked
tensorstore/driver/virtual_chunked/virtual_chunked.cc
tensorstore/driver/virtual_chunked/virtual_chunked_test.cc
#include "tensorstore/virtual_chunked.h" #include <stddef.h> #include <algorithm> #include <atomic> #include <memory> #include <numeric> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tensorstore/array.h" #include "tensorstore/box.h" #include "tensorstore/chunk_layout.h" #include "tensorstore/codec_spec.h" #include "tensorstore/context.h" #include "tensorstore/contiguous_layout.h" #include "tensorstore/data_type.h" #include "tensorstore/driver/chunk_cache_driver.h" #include "tensorstore/driver/driver.h" #include "tensorstore/driver/driver_handle.h" #include "tensorstore/driver/driver_spec.h" #include "tensorstore/driver/registry.h" #include "tensorstore/index.h" #include "tensorstore/index_interval.h" #include "tensorstore/index_space/dimension_units.h" #include "tensorstore/index_space/index_domain.h" #include "tensorstore/index_space/index_domain_builder.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/index_transform_builder.h" #include "tensorstore/internal/async_write_array.h" #include "tensorstore/internal/cache/async_cache.h" #include "tensorstore/internal/cache/cache.h" #include "tensorstore/internal/cache/cache_pool_resource.h" #include "tensorstore/internal/cache/chunk_cache.h" #include "tensorstore/internal/chunk_grid_specification.h" #include "tensorstore/internal/data_copy_concurrency_resource.h" #include "tensorstore/internal/integer_overflow.h" #include "tensorstore/internal/memory.h" #include "tensorstore/kvstore/generation.h" #include "tensorstore/open_mode.h" #include "tensorstore/open_options.h" #include "tensorstore/rank.h" #include "tensorstore/serialization/absl_time.h" #include "tensorstore/serialization/std_optional.h" #include "tensorstore/staleness_bound.h" #include "tensorstore/strided_layout.h" #include "tensorstore/transaction.h" #include "tensorstore/util/byte_strided_pointer.h" #include "tensorstore/util/element_pointer.h" #include "tensorstore/util/future.h" #include "tensorstore/util/garbage_collection/garbage_collection.h" #include "tensorstore/util/garbage_collection/std_optional.h" #include "tensorstore/util/result.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace virtual_chunked { namespace { class VirtualChunkedCache : public internal::ConcreteChunkCache { using Base = internal::ConcreteChunkCache; public: using Base::Base; template <typename EntryOrNode> void DoRead(EntryOrNode& node, AsyncCacheReadRequest request); class Entry : public internal::ChunkCache::Entry { public: using OwningCache = VirtualChunkedCache; using internal::ChunkCache::Entry::Entry; void DoRead(AsyncCacheReadRequest request) override { GetOwningCache(*this).DoRead(*this, std::move(request)); } }; class TransactionNode : public internal::ChunkCache::TransactionNode { public: using OwningCache = VirtualChunkedCache; using internal::ChunkCache::TransactionNode::TransactionNode; std::atomic<bool> marked_as_terminal_{false}; absl::Status DoInitialize( internal::OpenTransactionPtr& transaction) override { SetReadsCommitted(); return internal::ChunkCache::TransactionNode::DoInitialize(transaction); } absl::Status OnModified() override { if (!marked_as_terminal_.exchange(true, std::memory_order_acq_rel)) { return this->MarkAsTerminal(); } return absl::OkStatus(); } std::string Describe() override; void DoRead(AsyncCacheReadRequest request) override { GetOwningCache(*this).DoRead(*this, std::move(request)); } void Commit() override; void InitiateWriteback(absl::Time staleness_bound); }; Entry* DoAllocateEntry() final { return new Entry; } size_t DoGetSizeofEntry() final { return sizeof(Entry); } TransactionNode* DoAllocateTransactionNode( internal::AsyncCache::Entry& entry) final { return new TransactionNode(static_cast<Entry&>(entry)); } std::vector<Index> grid_origin_for_read_function_; DimensionUnitsVector dimension_units_; std::vector<DimensionIndex> inner_order_; ReadFunction read_function_; WriteFunction write_function_; Context::Resource<internal::DataCopyConcurrencyResource> data_copy_concurrency_; Context::Resource<internal::CachePoolResource> cache_pool_; }; bool GetPermutedPartialArray( VirtualChunkedCache::Entry& entry, ArrayView<const void> full_array, Array<const void, dynamic_rank, offset_origin>& partial_array) { auto& cache = static_cast<VirtualChunkedCache&>(GetOwningCache(entry)); const auto& component_spec = cache.grid().components.front(); const DimensionIndex rank = component_spec.rank(); span<const Index> cell_shape = component_spec.shape(); span<const Index> cell_indices = entry.cell_indices(); span<const DimensionIndex> inner_order = cache.inner_order_; span<const Index> grid_origin_for_read_function = cache.grid_origin_for_read_function_; BoxView<> domain_bounds = component_spec.array_spec.valid_data_bounds; partial_array.layout().set_rank(rank); ByteStridedPointer<const void> data = full_array.byte_strided_pointer(); for (DimensionIndex component_dim = 0; component_dim < rank; ++component_dim) { const DimensionIndex external_dim = inner_order[component_dim]; const Index byte_stride = full_array.byte_strides()[component_dim]; partial_array.byte_strides()[external_dim] = byte_stride; Index grid_origin_value = grid_origin_for_read_function[external_dim]; Index chunk_start = cell_indices[component_dim] * cell_shape[component_dim]; Index chunk_end = chunk_start + cell_shape[component_dim]; Index request_start = std::max(chunk_start, domain_bounds.origin()[component_dim]); Index request_end = std::min(chunk_end, domain_bounds[component_dim].exclusive_max()); if (request_start >= request_end) { return false; } partial_array.origin()[external_dim] = request_start + grid_origin_value; partial_array.shape()[external_dim] = request_end - request_start; data -= internal::wrap_on_overflow::Multiply( byte_stride, chunk_start + grid_origin_value); } partial_array.element_pointer() = ElementPointer<const void>(data, full_array.dtype()); return true; } template <typename EntryOrNode> void VirtualChunkedCache::DoRead(EntryOrNode& node, AsyncCacheReadRequest request) { auto& cache = GetOwningCache(node); if (!cache.read_function_) { node.ReadError(absl::InvalidArgumentError( "Write-only virtual chunked view requires chunk-aligned writes")); return; } auto& executor = cache.executor(); executor([&node, staleness_bound = request.staleness_bound] { auto& entry = GetOwningEntry(node); auto& cache = GetOwningCache(entry); const auto& component_spec = cache.grid().components.front(); span<const Index> cell_shape = component_spec.shape(); auto full_array = AllocateArray(cell_shape, c_order, default_init, component_spec.dtype()); Array<const void, dynamic_rank, offset_origin> partial_array; auto read_data = tensorstore::internal::make_shared_for_overwrite<ReadData[]>(1); if (!GetPermutedPartialArray(entry, full_array, partial_array)) { node.ReadSuccess( {std::move(read_data), {StorageGeneration::NoValue(), absl::InfiniteFuture()}}); return; } read_data.get()[0] = full_array; ReadParameters read_params; read_params.executor_ = cache.executor(); { ReadLock<ReadData> lock{node}; read_params.if_not_equal_ = lock.stamp().generation; } read_params.staleness_bound_ = staleness_bound; auto read_future = cache.read_function_(ConstDataTypeCast<void>(std::move(partial_array)), std::move(read_params)); read_future.Force(); read_future.ExecuteWhenReady( [&node, read_data = std::move(read_data)]( ReadyFuture<TimestampedStorageGeneration> future) mutable { auto& r = future.result(); if (!r.ok()) { node.ReadError(std::move(r).status()); return; } if (StorageGeneration::IsUnknown(r->generation)) { ReadState read_state; { ReadLock<ReadData> lock{node}; read_state = lock.read_state(); } read_state.stamp.time = r->time; node.ReadSuccess(std::move(read_state)); return; } node.ReadSuccess({std::move(read_data), std::move(*r)}); return; }); }); } std::string VirtualChunkedCache::TransactionNode::Describe() { auto& entry = GetOwningEntry(*this); auto& cache = GetOwningCache(entry); auto domain = cache.grid().GetValidCellDomain(0, entry.cell_indices()); if (domain.is_empty()) return {}; return tensorstore::StrCat("write to virtual chunk ", domain); } void VirtualChunkedCache::TransactionNode::Commit() { if (!GetOwningCache(*this).write_function_) { SetError(absl::InternalError( "No write function specified to virtual_chunked driver")); this->WritebackError(); return; } InitiateWriteback(absl::InfinitePast()); internal::ChunkCache::TransactionNode::Commit(); } void VirtualChunkedCache::TransactionNode::InitiateWriteback( absl::Time staleness_bound) { struct ApplyReceiver { TransactionNode& self; void set_value(AsyncCache::ReadState update) { GetOwningCache(self).executor()( [node = &self, update = std::move(update)] { auto* read_data = static_cast<const ReadData*>(update.data.get()); SharedArray<const void> full_array; auto& entry = GetOwningEntry(*node); auto& cache = GetOwningCache(*node); if (read_data && read_data[0].valid()) { full_array = read_data[0]; } else { full_array = node->component_specs()[0].array_spec.GetFillValueForDomain( cache.grid().GetCellDomain(0, entry.cell_indices())); } Array<const void, dynamic_rank, offset_origin> partial_array; if (!GetPermutedPartialArray(entry, full_array, partial_array)) { node->WritebackSuccess( {std::move(update.data), {StorageGeneration::NoValue(), absl::InfiniteFuture()}}); return; } WriteParameters write_params; write_params.if_equal_ = StorageGeneration::Clean(update.stamp.generation); write_params.executor_ = cache.executor(); auto write_future = cache.write_function_(std::move(partial_array), std::move(write_params)); write_future.Force(); write_future.ExecuteWhenReady( [node = node, update = std::move(update), full_array = std::move(full_array)]( ReadyFuture<TimestampedStorageGeneration> future) mutable { auto& r = future.result(); if (!r.ok()) { node->SetError(std::move(r).status()); node->WritebackError(); return; } if (StorageGeneration::IsUnknown(r->generation)) { node->InitiateWriteback(r->time); return; } update.stamp = std::move(*r); node->WritebackSuccess(std::move(update)); }); }); } void set_error(absl::Status error) { self.SetError(std::move(error)); self.WritebackError(); } void set_cancel() { ABSL_UNREACHABLE(); } }; AsyncCache::TransactionNode::ApplyOptions apply_options; apply_options.staleness_bound = staleness_bound; this->DoApply(std::move(apply_options), ApplyReceiver{*this}); } class VirtualChunkedDriverSpec : public internal::RegisteredDriverSpec<VirtualChunkedDriverSpec, internal::DriverSpec> { public: constexpr static const char id[] = "virtual_chunked"; std::optional<ReadFunction> read_function; std::optional<WriteFunction> write_function; Context::Resource<internal::DataCopyConcurrencyResource> data_copy_concurrency; Context::Resource<internal::CachePoolResource> cache_pool; StalenessBound data_staleness; constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(internal::BaseCast<internal::DriverSpec>(x), x.read_function, x.write_function, x.data_copy_concurrency, x.cache_pool, x.data_staleness); }; OpenMode open_mode() const override { return OpenMode::open; } Future<internal::Driver::Handle> Open( internal::DriverOpenRequest request) const override; absl::Status ApplyOptions(SpecOptions&& options) override { if (options.kvstore.valid()) { return absl::InvalidArgumentError( "virtual_chunked driver does not support a kvstore"); } if (options.recheck_cached_data.specified()) { data_staleness = StalenessBound(options.recheck_cached_data); } if (options.recheck_cached_metadata.specified()) { return absl::InvalidArgumentError( "virtual_chunked driver does not support recheck_cached_metadata"); } return schema.Set(static_cast<Schema&&>(options)); } }; class VirtualChunkedDriver; using VirtualChunkedDriverBase = internal::RegisteredDriver< VirtualChunkedDriver, internal::ChunkGridSpecificationDriver< VirtualChunkedCache, internal::ChunkCacheReadWriteDriverMixin< VirtualChunkedDriver, internal::Driver>>>; class VirtualChunkedDriver : public VirtualChunkedDriverBase { using Base = VirtualChunkedDriverBase; public: using Base::Base; Result<internal::TransformedDriverSpec> GetBoundSpec( internal::OpenTransactionPtr transaction, IndexTransformView<> transform) override; static Result<internal::Driver::Handle> OpenFromSpecData( Transaction transaction, const VirtualChunkedDriverSpec& spec, ReadWriteMode read_write_mode = ReadWriteMode::dynamic); Result<CodecSpec> GetCodec() override { return CodecSpec{}; } Result<DimensionUnitsVector> GetDimensionUnits() override { return cache()->dimension_units_; } Result<SharedArray<const void>> GetFillValue( IndexTransformView<> transform) override { return {std::in_place}; } Result<ChunkLayout> GetChunkLayout(IndexTransformView<> transform) override { return internal::GetChunkLayoutFromGrid(cache()->grid().components[0]) | transform; } }; Result<internal::TransformedDriverSpec> VirtualChunkedDriver::GetBoundSpec( internal::OpenTransactionPtr transaction, IndexTransformView<> transform) { auto driver_spec = internal::DriverSpec::Make<VirtualChunkedDriverSpec>(); driver_spec->context_binding_state_ = ContextBindingState::bound; auto& cache = *this->cache(); if (cache.read_function_) { driver_spec->read_function = cache.read_function_; } if (cache.write_function_) { driver_spec->write_function = cache.write_function_; } driver_spec->data_copy_concurrency = cache.data_copy_concurrency_; driver_spec->cache_pool = cache.cache_pool_; driver_spec->data_staleness = this->data_staleness_bound(); const DimensionIndex rank = this->rank(); TENSORSTORE_RETURN_IF_ERROR(driver_spec->schema.Set(RankConstraint{rank})); TENSORSTORE_RETURN_IF_ERROR(driver_spec->schema.Set(dtype())); TENSORSTORE_RETURN_IF_ERROR( driver_spec->schema.Set(Schema::DimensionUnits(cache.dimension_units_))); TENSORSTORE_RETURN_IF_ERROR( driver_spec->schema.Set(ChunkLayout::InnerOrder(cache.inner_order_))); TENSORSTORE_RETURN_IF_ERROR(driver_spec->schema.Set( ChunkLayout::GridOrigin(cache.grid_origin_for_read_function_))); span<const DimensionIndex> inner_order = cache.inner_order_; span<const Index> grid_origin_for_read_function = cache.grid_origin_for_read_function_; const auto& component_spec = cache.grid().components[component_index()]; IndexTransformBuilder external_to_output_transform_builder(rank, rank); IndexDomainBuilder external_domain_builder(rank); Index chunk_shape[kMaxRank]; for (DimensionIndex component_dim = 0; component_dim < rank; ++component_dim) { const DimensionIndex external_dim = inner_order[component_dim]; const Index offset = grid_origin_for_read_function[external_dim]; chunk_shape[external_dim] = component_spec.shape()[component_dim]; external_to_output_transform_builder.output_single_input_dimension( external_dim, offset, 1, component_dim); TENSORSTORE_ASSIGN_OR_RETURN( external_domain_builder.bounds()[external_dim], ShiftInterval( component_spec.array_spec.valid_data_bounds[component_dim], offset)); } TENSORSTORE_ASSIGN_OR_RETURN(auto external_to_output_transform, external_to_output_transform_builder.Finalize()); TENSORSTORE_ASSIGN_OR_RETURN(auto external_domain, external_domain_builder.Finalize()); TENSORSTORE_RETURN_IF_ERROR(driver_spec->schema.Set( ChunkLayout::ChunkShape(span<const Index>(&chunk_shape[0], rank)))); TENSORSTORE_RETURN_IF_ERROR( driver_spec->schema.Set(std::move(external_domain))); internal::TransformedDriverSpec spec; TENSORSTORE_ASSIGN_OR_RETURN( spec.transform, ComposeTransforms(external_to_output_transform, transform)); spec.driver_spec = std::move(driver_spec); return spec; } Result<internal::Driver::Handle> VirtualChunkedDriver::OpenFromSpecData( Transaction transaction, const VirtualChunkedDriverSpec& spec, ReadWriteMode read_write_mode) { if ((read_write_mode & ReadWriteMode::read) == ReadWriteMode::read && !spec.read_function) { return absl::InvalidArgumentError("Reading not supported"); } if ((read_write_mode & ReadWriteMode::write) == ReadWriteMode::write && !spec.write_function) { return absl::InvalidArgumentError("Writing not supported"); } if (read_write_mode == ReadWriteMode::dynamic) { read_write_mode = (spec.read_function ? ReadWriteMode::read : ReadWriteMode{}) | (spec.write_function ? ReadWriteMode::write : ReadWriteMode{}); } const DimensionIndex rank = spec.schema.rank(); if (rank == dynamic_rank) { return absl::InvalidArgumentError("rank must be specified"); } DataType dtype = spec.schema.dtype(); if (!dtype.valid()) { return absl::InvalidArgumentError("dtype must be specified"); } IndexDomain<> domain = spec.schema.domain(); if (!domain.valid()) { domain = IndexDomain<>(rank); } domain = WithImplicitDimensions(std::move(domain), false, false); Box<> chunk_template(rank); std::vector<DimensionIndex> inner_order(rank); { ChunkLayout chunk_layout = spec.schema.chunk_layout(); if (chunk_layout.codec_chunk_shape().hard_constraint) { return absl::InvalidArgumentError("codec_chunk_shape not supported"); } if (spec.schema.fill_value().valid()) { return absl::InvalidArgumentError("fill_value not supported"); } TENSORSTORE_RETURN_IF_ERROR( internal::ChooseReadWriteChunkGrid(chunk_layout, domain.box(), chunk_template), tensorstore::MaybeAnnotateStatus(_, "Failed to compute chunk grid")); if (auto requested_inner_order = chunk_layout.inner_order(); requested_inner_order.valid()) { std::copy_n(requested_inner_order.begin(), rank, inner_order.begin()); } else { std::iota(inner_order.begin(), inner_order.end(), DimensionIndex(0)); } } auto external_dimension_units = spec.schema.dimension_units(); Box<> adjusted_component_domain(rank); DimensionUnitsVector component_units(rank); for (DimensionIndex component_dim = 0; component_dim < rank; ++component_dim) { const DimensionIndex external_dim = inner_order[component_dim]; TENSORSTORE_ASSIGN_OR_RETURN( adjusted_component_domain[component_dim], ShiftIntervalBackward(domain[external_dim], chunk_template.origin()[external_dim])); if (external_dimension_units.valid()) { component_units[component_dim] = external_dimension_units[external_dim]; } } internal::Driver::Handle handle; handle.transaction = std::move(transaction); { IndexTransformBuilder transform_builder(rank, rank); transform_builder.input_domain(domain); for (DimensionIndex component_dim = 0; component_dim < rank; ++component_dim) { const DimensionIndex external_dim = inner_order[component_dim]; transform_builder.output_single_input_dimension( component_dim, -chunk_template.origin()[external_dim], 1, external_dim); } TENSORSTORE_ASSIGN_OR_RETURN(handle.transform, transform_builder.Finalize()); } auto cache = internal::GetCache<VirtualChunkedCache>(spec.cache_pool->get(), "", [&] { auto fill_value = BroadcastArray(AllocateArray(span<const Index>{}, c_order, value_init, spec.schema.dtype()), BoxView<>(rank)) .value(); std::vector<Index> chunk_shape(rank); for (DimensionIndex component_dim = 0; component_dim < rank; ++component_dim) { const DimensionIndex external_dim = inner_order[component_dim]; chunk_shape[component_dim] = chunk_template.shape()[external_dim]; } internal::ChunkGridSpecification::ComponentList components; components.emplace_back( internal::AsyncWriteArray::Spec{ std::move(fill_value), std::move(adjusted_component_domain)}, std::move(chunk_shape)); auto cache = std::make_unique<VirtualChunkedCache>( internal::ChunkGridSpecification(std::move(components)), spec.data_copy_concurrency->executor); cache->dimension_units_ = std::move(component_units); if (spec.read_function) { cache->read_function_ = *spec.read_function; } if (spec.write_function) { cache->write_function_ = *spec.write_function; } cache->inner_order_ = std::move(inner_order); cache->grid_origin_for_read_function_.assign( chunk_template.origin().begin(), chunk_template.origin().end()); cache->cache_pool_ = spec.cache_pool; cache->data_copy_concurrency_ = spec.data_copy_concurrency; return cache; }); handle.driver = internal::MakeReadWritePtr<VirtualChunkedDriver>( read_write_mode, VirtualChunkedDriver::Initializer{ std::move(cache), 0, spec.data_staleness.BoundAtOpen(absl::Now())}); return handle; } Future<internal::Driver::Handle> VirtualChunkedDriverSpec::Open( internal::DriverOpenRequest request) const { return VirtualChunkedDriver::OpenFromSpecData( internal::TransactionState::ToTransaction(std::move(request.transaction)), *this, request.read_write_mode); } } namespace internal_virtual_chunked { Result<internal::Driver::Handle> MakeDriver( virtual_chunked::ReadFunction read_function, virtual_chunked::WriteFunction write_function, OpenOptions&& options) { VirtualChunkedDriverSpec spec; if (read_function) { spec.read_function = std::move(read_function); } if (write_function) { spec.write_function = std::move(write_function); } spec.schema = static_cast<Schema&&>(options); if (!options.context) { options.context = Context::Default(); } TENSORSTORE_ASSIGN_OR_RETURN( spec.cache_pool, options.context.GetResource<internal::CachePoolResource>()); TENSORSTORE_ASSIGN_OR_RETURN( spec.data_copy_concurrency, options.context.GetResource<internal::DataCopyConcurrencyResource>()); if (options.recheck_cached_data.specified()) { spec.data_staleness = StalenessBound(options.recheck_cached_data); } return VirtualChunkedDriver::OpenFromSpecData(std::move(options.transaction), spec); } } } namespace garbage_collection { template <> struct GarbageCollection<virtual_chunked::VirtualChunkedDriver> { static void Visit(GarbageCollectionVisitor& visitor, const virtual_chunked::VirtualChunkedDriver& value) { garbage_collection::GarbageCollectionVisit(visitor, value.cache()->read_function_); garbage_collection::GarbageCollectionVisit(visitor, value.cache()->write_function_); } }; } } namespace { const tensorstore::internal::SerializationOnlyDriverRegistration< tensorstore::virtual_chunked::VirtualChunkedDriverSpec> driver_registration; }
#include "tensorstore/virtual_chunked.h" #include <memory> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "absl/synchronization/mutex.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "tensorstore/array.h" #include "tensorstore/chunk_layout.h" #include "tensorstore/context.h" #include "tensorstore/data_type.h" #include "tensorstore/index.h" #include "tensorstore/index_space/dim_expression.h" #include "tensorstore/internal/queue_testutil.h" #include "tensorstore/kvstore/generation.h" #include "tensorstore/kvstore/test_util.h" #include "tensorstore/open_mode.h" #include "tensorstore/rank.h" #include "tensorstore/schema.h" #include "tensorstore/serialization/function.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/serialization/test_util.h" #include "tensorstore/staleness_bound.h" #include "tensorstore/strided_layout.h" #include "tensorstore/tensorstore.h" #include "tensorstore/transaction.h" #include "tensorstore/util/future.h" #include "tensorstore/util/iterate_over_index_range.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status_testutil.h" namespace { using ::tensorstore::DimensionIndex; using ::tensorstore::dynamic_rank; using ::tensorstore::Future; using ::tensorstore::Index; using ::tensorstore::MatchesStatus; using ::tensorstore::Promise; using ::tensorstore::Result; using ::tensorstore::span; using ::tensorstore::StorageGeneration; using ::tensorstore::TimestampedStorageGeneration; using ::tensorstore::internal::ConcurrentQueue; using ::tensorstore::internal::UniqueNow; using ::tensorstore::serialization::SerializationRoundTrip; template <typename... Option> Result<tensorstore::TensorStore<Index, dynamic_rank, tensorstore::ReadWriteMode::read>> CoordinatesView(DimensionIndex dim, Option&&... option) { return tensorstore::VirtualChunked<Index>( tensorstore::NonSerializable{[dim](auto output, auto read_params) -> Future<TimestampedStorageGeneration> { tensorstore::IterateOverIndexRange( output.domain(), [&](span<const Index> indices) { output(indices) = indices[dim]; }); return TimestampedStorageGeneration{StorageGeneration::FromString(""), absl::Now()}; }}, std::forward<Option>(option)...); } template <typename... Option> Result<tensorstore::TensorStore<Index, dynamic_rank, tensorstore::ReadWriteMode::read>> SerializableCoordinatesView(DimensionIndex dim, Option&&... option) { return tensorstore::VirtualChunked<Index>( tensorstore::serialization::BindFront( [](DimensionIndex dim, auto output, auto read_params) -> Future<TimestampedStorageGeneration> { tensorstore::IterateOverIndexRange(output.domain(), [&](span<const Index> indices) { output(indices) = indices[dim]; }); return TimestampedStorageGeneration{ StorageGeneration::FromString(""), absl::Now()}; }, dim), std::forward<Option>(option)...); } using RequestLayout = ::tensorstore::StridedLayout<dynamic_rank, ::tensorstore::offset_origin>; template <typename... Option> Result<tensorstore::TensorStore<void, dynamic_rank, tensorstore::ReadWriteMode::read>> LoggingView(std::vector<RequestLayout>& requests, Option&&... option) { auto mutex = std::make_shared<absl::Mutex>(); return tensorstore::VirtualChunked( tensorstore::NonSerializable{ [mutex, &requests](auto output, auto read_params) -> Future<TimestampedStorageGeneration> { tensorstore::InitializeArray(output); absl::MutexLock lock(mutex.get()); requests.emplace_back(output.layout()); return TimestampedStorageGeneration{ StorageGeneration::FromString(""), absl::Now()}; }}, std::forward<Option>(option)...); } template <typename Element, DimensionIndex Rank, typename Parameters> struct Request { tensorstore::Array<Element, Rank, tensorstore::offset_origin> array; Parameters params; Promise<TimestampedStorageGeneration> promise; }; template <typename Element, DimensionIndex Rank, typename Parameters> auto EnqueueRequestHandler( ConcurrentQueue<Request<Element, Rank, Parameters>>& queue) { return tensorstore::NonSerializable{ [&queue]( tensorstore::Array<Element, Rank, tensorstore::offset_origin> array, Parameters params) -> Future<TimestampedStorageGeneration> { auto [promise, future] = tensorstore::PromiseFuturePair< TimestampedStorageGeneration>::Make(); queue.push({std::move(array), std::move(params), std::move(promise)}); return future; }}; } template <typename Element, DimensionIndex Rank> using ReadRequest = Request<Element, Rank, tensorstore::virtual_chunked::ReadParameters>; template <typename Element, DimensionIndex Rank> using WriteRequest = Request<const Element, Rank, tensorstore::virtual_chunked::WriteParameters>; template <typename Element, DimensionIndex Rank, typename... Option> Result< tensorstore::TensorStore<Element, Rank, tensorstore::ReadWriteMode::read>> MockView(ConcurrentQueue<ReadRequest<Element, Rank>>& queue, Option&&... option) { return tensorstore::VirtualChunked<Element, Rank>( EnqueueRequestHandler(queue), std::forward<Option>(option)...); } template <typename Element, DimensionIndex Rank, typename... Option> Result<tensorstore::TensorStore<Element, Rank, tensorstore::ReadWriteMode::read_write>> MockView(ConcurrentQueue<ReadRequest<Element, Rank>>& read_queue, ConcurrentQueue<WriteRequest<Element, Rank>>& write_queue, Option&&... option) { return tensorstore::VirtualChunked<Element, Rank>( EnqueueRequestHandler(read_queue), EnqueueRequestHandler(write_queue), std::forward<Option>(option)...); } template <typename Element, DimensionIndex Rank, typename... Option> Result< tensorstore::TensorStore<Element, Rank, tensorstore::ReadWriteMode::write>> MockView(ConcurrentQueue<WriteRequest<Element, Rank>>& write_queue, Option&&... option) { return tensorstore::VirtualChunkedWriteOnly<Element, Rank>( EnqueueRequestHandler(write_queue), std::forward<Option>(option)...); } TEST(VirtualChunkedTest, Coordinates) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto coords0, CoordinatesView(0, tensorstore::Schema::Shape({2, 3}))); EXPECT_THAT(tensorstore::Read(coords0).result(), ::testing::Optional( tensorstore::MakeArray<Index>({{0, 0, 0}, {1, 1, 1}}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto coords1, CoordinatesView(1, tensorstore::Schema::Shape({2, 3}))); EXPECT_THAT(tensorstore::Read(coords1).result(), ::testing::Optional( tensorstore::MakeArray<Index>({{0, 1, 2}, {0, 1, 2}}))); } TEST(VirtualChunkedTest, CoordinatesUnbounded) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto coords0, CoordinatesView(0, tensorstore::RankConstraint{2})); EXPECT_THAT( tensorstore::Read<tensorstore::zero_origin>( coords0 | tensorstore::Dims(0, 1).SizedInterval({1000, 2}, {2, 3})) .result(), ::testing::Optional(tensorstore::MakeArray<Index>( {{1000, 1000, 1000}, {1001, 1001, 1001}}))); } TEST(VirtualChunkedTest, CoordinatesInnerOrder) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto coords0, CoordinatesView(0, tensorstore::Schema::Shape({2, 3}), tensorstore::ChunkLayout::InnerOrder({1, 0}))); EXPECT_THAT(tensorstore::Read(coords0).result(), ::testing::Optional( tensorstore::MakeArray<Index>({{0, 0, 0}, {1, 1, 1}}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto coords1, CoordinatesView(1, tensorstore::Schema::Shape({2, 3}), tensorstore::ChunkLayout::InnerOrder({1, 0}))); EXPECT_THAT(tensorstore::Read(coords1).result(), ::testing::Optional( tensorstore::MakeArray<Index>({{0, 1, 2}, {0, 1, 2}}))); } TEST(VirtualChunkedTest, SerializableCoordinatesInnerOrder) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto coords0_orig, SerializableCoordinatesView( 0, tensorstore::Schema::Shape({2, 3}), tensorstore::ChunkLayout::InnerOrder({1, 0}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto coords0, SerializationRoundTrip(coords0_orig)); EXPECT_THAT(tensorstore::Read(coords0).result(), ::testing::Optional( tensorstore::MakeArray<Index>({{0, 0, 0}, {1, 1, 1}}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto coords1_orig, SerializableCoordinatesView( 1, tensorstore::Schema::Shape({2, 3}), tensorstore::ChunkLayout::InnerOrder({1, 0}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto coords1, SerializationRoundTrip(coords1_orig)); EXPECT_THAT(tensorstore::Read(coords1).result(), ::testing::Optional( tensorstore::MakeArray<Index>({{0, 1, 2}, {0, 1, 2}}))); } TEST(VirtualChunkedTest, ReadChunkShape) { std::vector<RequestLayout> requests; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto view, LoggingView(requests, tensorstore::dtype_v<bool>, tensorstore::Schema::Shape({2, 3}), tensorstore::ChunkLayout::ReadChunkShape({2, 1}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto chunk_layout, view.chunk_layout()); EXPECT_THAT(chunk_layout.read_chunk_shape(), ::testing::ElementsAre(2, 1)); TENSORSTORE_ASSERT_OK(tensorstore::Read(view)); EXPECT_THAT(requests, ::testing::UnorderedElementsAre( RequestLayout({0, 0}, {2, 1}, {1, 1}), RequestLayout({0, 1}, {2, 1}, {1, 1}), RequestLayout({0, 2}, {2, 1}, {1, 1}))); } TEST(VirtualChunkedTest, InnerOrder) { std::vector<RequestLayout> requests; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto view, LoggingView(requests, tensorstore::dtype_v<bool>, tensorstore::Schema::Shape({3, 4, 5}), tensorstore::ChunkLayout::InnerOrder({2, 0, 1}), tensorstore::ChunkLayout::ReadChunkShape({2, 3, 4}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto chunk_layout, view.chunk_layout()); EXPECT_THAT(chunk_layout.read_chunk_shape(), ::testing::ElementsAre(2, 3, 4)); EXPECT_THAT(chunk_layout.inner_order(), ::testing::ElementsAre(2, 0, 1)); TENSORSTORE_ASSERT_OK(tensorstore::Read(view)); EXPECT_THAT(requests, ::testing::UnorderedElementsAreArray({ RequestLayout({0, 0, 0}, {2, 3, 4}, {3, 1, 6}), RequestLayout({2, 0, 0}, {1, 3, 4}, {3, 1, 6}), RequestLayout({0, 3, 0}, {2, 1, 4}, {3, 1, 6}), RequestLayout({2, 3, 0}, {1, 1, 4}, {3, 1, 6}), RequestLayout({0, 0, 4}, {2, 3, 1}, {3, 1, 6}), RequestLayout({2, 0, 4}, {1, 3, 1}, {3, 1, 6}), RequestLayout({0, 3, 4}, {2, 1, 1}, {3, 1, 6}), RequestLayout({2, 3, 4}, {1, 1, 1}, {3, 1, 6}), })); } TEST(VirtualChunkedTest, NoRecheckCache) { ConcurrentQueue<ReadRequest<int, 0>> requests; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, tensorstore::Context::FromJson( {{"cache_pool", {{"total_bytes_limit", 10000000}}}})); auto mock_view = MockView<int, 0>( requests, tensorstore::RecheckCachedData{false}, context); auto read_future = tensorstore::Read(mock_view); { auto request = requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_not_equal()); request.array() = 42; request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString("abc"), absl::Now())); } EXPECT_THAT(read_future.result(), ::testing::Optional(tensorstore::MakeScalarArray<int>(42))); read_future = tensorstore::Read(mock_view); EXPECT_THAT(read_future.result(), ::testing::Optional(tensorstore::MakeScalarArray<int>(42))); } TEST(VirtualChunkedTest, RecheckCache) { ConcurrentQueue<ReadRequest<int, 0>> requests; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, tensorstore::Context::FromJson( {{"cache_pool", {{"total_bytes_limit", 10000000}}}})); auto mock_view = MockView<int, 0>(requests, context); auto read_future = tensorstore::Read(mock_view); { auto request = requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_not_equal()); request.array() = 42; request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString("abc"), absl::Now())); } EXPECT_THAT(read_future.result(), ::testing::Optional(tensorstore::MakeScalarArray<int>(42))); UniqueNow(); read_future = tensorstore::Read(mock_view); { auto request = requests.pop(); EXPECT_EQ(StorageGeneration::FromString("abc"), request.params.if_not_equal()); request.array() = 43; request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::Unknown(), absl::Now())); } EXPECT_THAT(read_future.result(), ::testing::Optional(tensorstore::MakeScalarArray<int>(42))); } TEST(VirtualChunkedTest, RecheckCacheImmutable) { ConcurrentQueue<ReadRequest<int, 0>> requests; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, tensorstore::Context::FromJson( {{"cache_pool", {{"total_bytes_limit", 10000000}}}})); auto mock_view = MockView<int, 0>(requests, tensorstore::RecheckCachedData{true}, context); auto read_future = tensorstore::Read(mock_view); { auto request = requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_not_equal()); request.array() = 42; request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::InfiniteFuture())); } EXPECT_THAT(read_future.result(), ::testing::Optional(tensorstore::MakeScalarArray<int>(42))); UniqueNow(); read_future = tensorstore::Read(mock_view); EXPECT_THAT(read_future.result(), ::testing::Optional(tensorstore::MakeScalarArray<int>(42))); } TEST(VirtualChunkedTest, ReadWrite) { ConcurrentQueue<ReadRequest<int, 1>> read_requests; ConcurrentQueue<WriteRequest<int, 1>> write_requests; auto mock_view = MockView<int, 1>(read_requests, write_requests, tensorstore::Schema::Shape({2})); auto write_future = tensorstore::Write(tensorstore::MakeScalarArray<int>(42), mock_view | tensorstore::Dims(0).IndexSlice(0)); write_future.Force(); { auto request = read_requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_not_equal()); request.array(0) = 1; request.array(1) = 2; request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString("gen1"), absl::Now())); } { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::FromString("gen1"), request.params.if_equal()); EXPECT_EQ(tensorstore::MakeArray<int>({42, 2}), request.array); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString("gen2"), absl::Now())); } TENSORSTORE_ASSERT_OK(write_future); } TEST(VirtualChunkedTest, ReadWriteWrite) { ConcurrentQueue<ReadRequest<int, 1>> read_requests; ConcurrentQueue<WriteRequest<int, 1>> write_requests; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto context, tensorstore::Context::FromJson( {{"cache_pool", {{"total_bytes_limit", 1000000}}}})); auto mock_view = MockView<int, 1>(read_requests, write_requests, context, tensorstore::Schema::Shape({2})); { auto write_future = tensorstore::Write(tensorstore::MakeScalarArray<int>(42), mock_view | tensorstore::Dims(0).IndexSlice(0)); write_future.Force(); { auto request = read_requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_not_equal()); request.array(0) = 1; request.array(1) = 2; request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::InfiniteFuture())); } { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::FromString(""), request.params.if_equal()); EXPECT_EQ(tensorstore::MakeArray<int>({42, 2}), request.array); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::InfiniteFuture())); } TENSORSTORE_ASSERT_OK(write_future); } { auto write_future = tensorstore::Write(tensorstore::MakeScalarArray<int>(50), mock_view | tensorstore::Dims(0).IndexSlice(1)); write_future.Force(); { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::FromString(""), request.params.if_equal()); EXPECT_EQ(tensorstore::MakeArray<int>({42, 50}), request.array); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::InfiniteFuture())); } TENSORSTORE_ASSERT_OK(write_future); } } TEST(VirtualChunkedTest, Write) { ConcurrentQueue<WriteRequest<int, 1>> write_requests; auto mock_view = MockView<int, 1>(write_requests, tensorstore::Schema::Shape({6}), tensorstore::ChunkLayout::ChunkShape({4})); { auto write_future = tensorstore::Write( tensorstore::MakeScalarArray<int>(42), mock_view | tensorstore::Dims(0).SizedInterval(0, 4)); write_future.Force(); { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_equal()); EXPECT_EQ(tensorstore::MakeArray<int>({42, 42, 42, 42}), request.array); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::Now())); } TENSORSTORE_ASSERT_OK(write_future); } { auto write_future = tensorstore::Write( tensorstore::MakeScalarArray<int>(42), mock_view | tensorstore::Dims(0).SizedInterval(4, 2)); write_future.Force(); { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_equal()); EXPECT_EQ(tensorstore::MakeOffsetArray<int>({4}, {42, 42}), request.array); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::Now())); } TENSORSTORE_ASSERT_OK(write_future); } } TEST(VirtualChunkedTest, WriteFillValue) { ConcurrentQueue<WriteRequest<int, 0>> write_requests; auto mock_view = MockView<int, 0>(write_requests); auto write_future = tensorstore::Write(tensorstore::MakeScalarArray<int>(0), mock_view); write_future.Force(); { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_equal()); EXPECT_EQ(tensorstore::MakeScalarArray<int>(0), request.array); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::Now())); } TENSORSTORE_ASSERT_OK(write_future); } TEST(VirtualChunkedTest, WriteOnlyError) { ConcurrentQueue<WriteRequest<int, 1>> write_requests; auto mock_view = MockView<int, 1>(write_requests, tensorstore::Schema::Shape({2})); EXPECT_THAT( tensorstore::Write(tensorstore::MakeScalarArray<int>(42), mock_view | tensorstore::Dims(0).IndexSlice(0)) .result(), MatchesStatus( absl::StatusCode::kInvalidArgument, "Write-only virtual chunked view requires chunk-aligned writes")); } TEST(VirtualChunkedTest, AtomicSingleChunk) { tensorstore::Transaction transaction(tensorstore::atomic_isolated); ConcurrentQueue<WriteRequest<int, 1>> write_requests; auto mock_view = MockView<int, 1>(write_requests, tensorstore::Schema::Shape({6}), tensorstore::ChunkLayout::ChunkShape({4}), transaction); TENSORSTORE_ASSERT_OK(tensorstore::Write( tensorstore::MakeScalarArray<int>(42), mock_view | tensorstore::Dims(0).HalfOpenInterval(0, 4))); auto future = transaction.CommitAsync(); { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_equal()); EXPECT_EQ(tensorstore::MakeArray<int>({42, 42, 42, 42}), request.array); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::Now())); } TENSORSTORE_ASSERT_OK(future); } TEST(VirtualChunkedTest, AtomicMultipleChunks) { tensorstore::Transaction transaction(tensorstore::atomic_isolated); ConcurrentQueue<WriteRequest<int, 1>> write_requests; auto mock_view = MockView<int, 1>(write_requests, tensorstore::Schema::Shape({6}), tensorstore::ChunkLayout::ChunkShape({4}), transaction); EXPECT_THAT( tensorstore::Write(tensorstore::MakeScalarArray<int>(42), mock_view) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot write to virtual chunk .* and write to virtual " "chunk .* as single atomic transaction")); } TEST(VirtualChunkedTest, NonAtomicSingleChunk) { tensorstore::Transaction transaction(tensorstore::isolated); ConcurrentQueue<WriteRequest<int, 1>> write_requests; auto mock_view = MockView<int, 1>(write_requests, tensorstore::Schema::Shape({6}), tensorstore::ChunkLayout::ChunkShape({4}), transaction); TENSORSTORE_ASSERT_OK( tensorstore::Write(tensorstore::MakeScalarArray<int>(42), mock_view)); auto future = transaction.CommitAsync(); for (int i = 0; i < 2; ++i) { auto request = write_requests.pop(); EXPECT_EQ(StorageGeneration::Unknown(), request.params.if_equal()); request.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString(""), absl::Now())); } TENSORSTORE_ASSERT_OK(future); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/driver/virtual_chunked/virtual_chunked.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/driver/virtual_chunked/virtual_chunked_test.cc
4f887a6430414cd6088e1743555015b10f116d50
7bcdd45e-32f6-4fdb-87c7-38510f150311
cpp
google/tensorstore
transaction
tensorstore/kvstore/transaction.cc
tensorstore/kvstore/transaction_test.cc
#include "tensorstore/kvstore/transaction.h" #include <stddef.h> #include <stdint.h> #include <cassert> #include <iterator> #include <memory> #include <new> #include <optional> #include <string> #include <string_view> #include <utility> #include "absl/base/optimization.h" #include "absl/container/btree_map.h" #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "absl/types/compare.h" #include "tensorstore/internal/compare.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/metrics/counter.h" #include "tensorstore/internal/metrics/metadata.h" #include "tensorstore/internal/source_location.h" #include "tensorstore/kvstore/byte_range.h" #include "tensorstore/kvstore/driver.h" #include "tensorstore/kvstore/generation.h" #include "tensorstore/kvstore/key_range.h" #include "tensorstore/kvstore/operations.h" #include "tensorstore/kvstore/read_modify_write.h" #include "tensorstore/transaction.h" #include "tensorstore/util/execution/execution.h" #include "tensorstore/util/execution/future_sender.h" #include "tensorstore/util/future.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace internal_kvstore { namespace { auto& kvstore_transaction_retries = internal_metrics::Counter<int64_t>::New( "/tensorstore/kvstore/transaction_retries", internal_metrics::MetricMetadata("Count of kvstore transaction retries")); template <typename Controller> void ReportWritebackError(Controller controller, std::string_view action, const absl::Status& error, SourceLocation loc = SourceLocation::current()) { controller.Error(kvstore::Driver::AnnotateErrorWithKeyDescription( controller.DescribeKey(controller.GetKey()), action, error, loc)); } template <typename Controller> void PerformWriteback(Driver* driver, Controller controller, ReadResult read_result) { if (!StorageGeneration::IsDirty(read_result.stamp.generation)) { if (!StorageGeneration::IsConditional(read_result.stamp.generation) || read_result.stamp.time > controller.GetTransactionNode() .transaction() ->commit_start_time()) { controller.Success(std::move(read_result.stamp)); return; } ReadOptions read_options; auto if_not_equal = StorageGeneration::Clean(std::move(read_result.stamp.generation)); read_options.generation_conditions.if_not_equal = if_not_equal; read_options.byte_range = OptionalByteRangeRequest{0, 0}; auto future = driver->Read(controller.GetKey(), std::move(read_options)); future.Force(); std::move(future).ExecuteWhenReady( [controller, if_not_equal = std::move(if_not_equal)]( ReadyFuture<ReadResult> future) mutable { auto& r = future.result(); if (!r.ok()) { ReportWritebackError(controller, "reading", r.status()); } else if (r->aborted() || r->stamp.generation == if_not_equal) { controller.Success(std::move(r->stamp)); } else { controller.Retry(r->stamp.time); } }); return; } WriteOptions write_options; assert(!read_result.aborted()); write_options.generation_conditions.if_equal = StorageGeneration::Clean(std::move(read_result.stamp.generation)); auto future = driver->Write(controller.GetKey(), std::move(read_result).optional_value(), std::move(write_options)); future.Force(); std::move(future).ExecuteWhenReady( [controller](ReadyFuture<TimestampedStorageGeneration> future) mutable { auto& r = future.result(); if (!r.ok()) { ReportWritebackError(controller, "writing", r.status()); } else if (StorageGeneration::IsUnknown(r->generation)) { controller.Retry(r->time); } else { controller.Success(std::move(*r)); } }); } void StartWriteback(ReadModifyWriteEntry& entry, absl::Time staleness_bound = absl::InfinitePast()); void DeletedEntryDone(DeleteRangeEntry& dr_entry, bool error, size_t count = 1); void EntryDone(SinglePhaseMutation& single_phase_mutation, bool error, size_t count = 1); [[maybe_unused]] void CheckInvariants(ReadModifyWriteEntry* entry) { do { assert(!(entry->flags_ & ReadModifyWriteEntry::kDeleted)); if (entry->prev_) { assert(entry->prev_->single_phase_mutation().phase_number_ <= entry->single_phase_mutation().phase_number_); assert(entry->prev_->key_ == entry->key_); } entry = entry->prev_; } while (entry); } [[maybe_unused]] void CheckInvariants(MultiPhaseMutation& multi_phase, bool commit_started) { absl::btree_map<size_t, size_t> phase_entry_count; for (auto* single_phase_mutation = &multi_phase.phases_;;) { if (single_phase_mutation != &multi_phase.phases_) { assert(single_phase_mutation->phase_number_ > single_phase_mutation->prev_->phase_number_); } for (MutationEntry * tree_entry = single_phase_mutation->entries_.begin().to_pointer(), *tree_next; tree_entry; tree_entry = tree_next) { ++phase_entry_count[tree_entry->single_phase_mutation().phase_number_]; if (commit_started) { assert(&tree_entry->single_phase_mutation() == single_phase_mutation); } else { assert(&tree_entry->single_phase_mutation() == single_phase_mutation || single_phase_mutation == multi_phase.phases_.prev_); } tree_next = MutationEntryTree::Traverse(*tree_entry, MutationEntryTree::kRight); if (tree_next) { assert(tree_next->key_ > tree_entry->key_); if (tree_entry->entry_type() != kReadModifyWrite) { [[maybe_unused]] auto* dr_entry = static_cast<DeleteRangeEntry*>(tree_entry); assert(KeyRange::CompareExclusiveMaxAndKey(dr_entry->exclusive_max_, tree_next->key_) <= 0); } } if (tree_entry->entry_type() == kReadModifyWrite) { auto* rmw_entry = static_cast<ReadModifyWriteEntry*>(tree_entry); CheckInvariants(rmw_entry); } else { auto* dr_entry = static_cast<DeleteRangeEntry*>(tree_entry); if (dr_entry->entry_type() == kDeleteRangePlaceholder) { --phase_entry_count[tree_entry->single_phase_mutation() .phase_number_]; assert(dr_entry->superseded_.empty()); } assert(KeyRange::CompareKeyAndExclusiveMax( dr_entry->key_, dr_entry->exclusive_max_) < 0); for (ReadModifyWriteEntryTree::iterator entry = dr_entry->superseded_.begin(), next; entry != dr_entry->superseded_.end(); entry = next) { next = std::next(entry); if (next) { assert(next->key_ > entry->key_); } assert(entry->entry_type() == kReadModifyWrite); assert(&entry->single_phase_mutation() == &dr_entry->single_phase_mutation()); assert(entry->key_ >= dr_entry->key_); assert(KeyRange::CompareKeyAndExclusiveMax( entry->key_, dr_entry->exclusive_max_) < 0); assert(entry->flags_ & ReadModifyWriteEntry::kDeleted); if (entry->prev_) { CheckInvariants(entry->prev_); } } } } single_phase_mutation = single_phase_mutation->next_; if (single_phase_mutation == &multi_phase.phases_) break; } for (auto* single_phase_mutation = &multi_phase.phases_; single_phase_mutation->next_ != &multi_phase.phases_; single_phase_mutation = single_phase_mutation->next_) { if (single_phase_mutation->phase_number_ < multi_phase.GetTransactionNode().phase()) { assert(single_phase_mutation->entries_.empty()); } } } #ifdef TENSORSTORE_INTERNAL_KVSTORETORE_TRANSACTION_DEBUG inline void DebugCheckInvariants(MultiPhaseMutation& multi_phase, bool commit_started) { CheckInvariants(multi_phase, commit_started); } class DebugCheckInvariantsInDestructor { public: explicit DebugCheckInvariantsInDestructor(MultiPhaseMutation& multi_phase, bool commit_started) : multi_phase_(multi_phase), commit_started_(commit_started) {} ~DebugCheckInvariantsInDestructor() { CheckInvariants(multi_phase_, commit_started_); } private: MultiPhaseMutation& multi_phase_; bool commit_started_; }; #else inline void DebugCheckInvariants(MultiPhaseMutation& multi_phase, bool commit_started) {} class DebugCheckInvariantsInDestructor { public: explicit DebugCheckInvariantsInDestructor(MultiPhaseMutation& multi_phase, bool commit_started) {} }; #endif void DestroyReadModifyWriteSequence(ReadModifyWriteEntry* entry) { if (auto* next_rmw = entry->next_read_modify_write()) { next_rmw->prev_ = nullptr; } auto& multi_phase = entry->multi_phase(); while (true) { auto* prev = entry->prev_; multi_phase.FreeReadModifyWriteEntry(entry); if (!prev) break; entry = prev; } } auto CompareToEntry(MutationEntry& e) { return [&e](MutationEntry& other) { return internal::CompareResultAsWeakOrdering(e.key_.compare(other.key_)); }; } void InsertIntoPriorPhase(MutationEntry* entry) { if (entry->entry_type() == kDeleteRangePlaceholder) { delete static_cast<DeleteRangeEntry*>(entry); return; } entry->single_phase_mutation().entries_.FindOrInsert( CompareToEntry(*entry), [entry] { return entry; }); } DeleteRangeEntry* MakeDeleteRangeEntry( MutationEntryType entry_type, SinglePhaseMutation& assigned_single_phase_mutation, KeyRange&& range) { auto* entry = new DeleteRangeEntry; entry->key_ = std::move(range.inclusive_min); entry->exclusive_max_ = std::move(range.exclusive_max); entry->single_phase_mutation_ = {&assigned_single_phase_mutation, static_cast<uintptr_t>(entry_type)}; return entry; } DeleteRangeEntry* InsertDeleteRangeEntry( MutationEntryType entry_type, SinglePhaseMutation& insert_single_phase_mutation, SinglePhaseMutation& assigned_single_phase_mutation, KeyRange&& range, MutationEntryTree::InsertPosition position) { assert(entry_type == kDeleteRange || entry_type == kDeleteRangePlaceholder); auto* entry = MakeDeleteRangeEntry(entry_type, assigned_single_phase_mutation, std::move(range)); insert_single_phase_mutation.entries_.Insert(position, *entry); return entry; } ReadModifyWriteEntry* MakeReadModifyWriteEntry( SinglePhaseMutation& assigned_single_phase_mutation, std::string&& key) { auto* entry = assigned_single_phase_mutation.multi_phase_ ->AllocateReadModifyWriteEntry(); entry->key_ = std::move(key); entry->single_phase_mutation_ = {&assigned_single_phase_mutation, 0}; return entry; } SinglePhaseMutation& GetCurrentSinglePhaseMutation( MultiPhaseMutation& multi_phase) { size_t phase = multi_phase.GetTransactionNode().transaction()->phase(); SinglePhaseMutation* single_phase_mutation; if (multi_phase.phases_.phase_number_ == internal::TransactionState::kInvalidPhase) { single_phase_mutation = &multi_phase.phases_; single_phase_mutation->phase_number_ = phase; } else { single_phase_mutation = multi_phase.phases_.prev_; assert(single_phase_mutation->phase_number_ <= phase); if (single_phase_mutation->phase_number_ != phase) { auto* new_single_phase_mutation = new SinglePhaseMutation; std::swap(new_single_phase_mutation->entries_, single_phase_mutation->entries_); new_single_phase_mutation->next_ = &multi_phase.phases_; new_single_phase_mutation->prev_ = single_phase_mutation; new_single_phase_mutation->phase_number_ = phase; new_single_phase_mutation->prev_->next_ = new_single_phase_mutation; new_single_phase_mutation->next_->prev_ = new_single_phase_mutation; new_single_phase_mutation->multi_phase_ = &multi_phase; single_phase_mutation = new_single_phase_mutation; } } return *single_phase_mutation; } struct Controller { ReadModifyWriteEntry* entry_; internal::TransactionState::Node& GetTransactionNode() { return entry_->multi_phase().GetTransactionNode(); } std::string DescribeKey(std::string_view key) { return entry_->multi_phase().DescribeKey(key); } const Key& GetKey() { return entry_->key_; } void Success(TimestampedStorageGeneration new_stamp) { if (auto* dr_entry = static_cast<DeleteRangeEntry*>(entry_->next_)) { DeletedEntryDone(*dr_entry, false); return; } WritebackSuccess(*entry_, std::move(new_stamp)); EntryDone(entry_->single_phase_mutation(), false); } void Error(absl::Status error) { auto* dr_entry = static_cast<DeleteRangeEntry*>(entry_->next_); auto& single_phase_mutation = entry_->single_phase_mutation(); entry_->multi_phase().RecordEntryWritebackError(*entry_, std::move(error)); if (dr_entry) { DeletedEntryDone(*dr_entry, true); } else { EntryDone(single_phase_mutation, true); } } void Retry(absl::Time time) { kvstore_transaction_retries.Increment(); StartWriteback(*entry_, time); } }; void ReceiveWritebackCommon(ReadModifyWriteEntry& entry, ReadResult& read_result) { TENSORSTORE_KVSTORE_DEBUG_LOG( entry, "ReceiveWritebackCommon: state=", read_result.state, ", stamp=", read_result.stamp); auto flags = (entry.flags_ & ~(ReadModifyWriteEntry::kTransitivelyUnconditional | ReadModifyWriteEntry::kDirty | ReadModifyWriteEntry::kTransitivelyDirty)) | ReadModifyWriteEntry::kWritebackProvided; if (!StorageGeneration::IsConditional(read_result.stamp.generation)) { flags |= ReadModifyWriteEntry::kTransitivelyUnconditional; } if (read_result.stamp.generation.ClearNewlyDirty()) { flags |= ReadModifyWriteEntry::kDirty; } if (read_result.state != ReadResult::kUnspecified) { flags |= ReadModifyWriteEntry::kTransitivelyDirty; } entry.flags_ = flags; } void StartWriteback(ReadModifyWriteEntry& entry, absl::Time staleness_bound) { TENSORSTORE_KVSTORE_DEBUG_LOG( entry, "StartWriteback: staleness_bound=", staleness_bound); for (auto* e = &entry;;) { e->flags_ &= ~(ReadModifyWriteEntry::kWritebackProvided | ReadModifyWriteEntry::kTransitivelyDirty); e = e->prev_; if (!e) break; } ReadModifyWriteSource::WritebackOptions writeback_options; writeback_options.staleness_bound = staleness_bound; writeback_options.writeback_mode = (entry.flags_ & ReadModifyWriteEntry::kDeleted) ? ReadModifyWriteSource::kValidateOnly : ReadModifyWriteSource::kNormalWriteback; if (!entry.prev_ && !(entry.flags_ & ReadModifyWriteEntry::kDeleted)) { struct WritebackReceiverImpl { ReadModifyWriteEntry* entry_; void set_error(absl::Status error) { ReportWritebackError(Controller{entry_}, "writing", error); } void set_cancel() { ABSL_UNREACHABLE(); } void set_value(ReadResult read_result) { ReceiveWritebackCommon(*entry_, read_result); entry_->multi_phase().Writeback(*entry_, *entry_, std::move(read_result)); } }; entry.source_->KvsWriteback(std::move(writeback_options), WritebackReceiverImpl{&entry}); return; } struct SequenceWritebackReceiverImpl { struct State { ReadModifyWriteEntry* entry; absl::Time staleness_bound; ReadResult read_result; ReadModifyWriteEntry* source_entry = nullptr; ReadModifyWriteEntry* GetLastReadModifyWriteEntry() { auto* e = entry; while (auto* next = e->next_read_modify_write()) e = next; return e; } }; std::unique_ptr<State> state_; void set_error(absl::Status error) { ReportWritebackError(Controller{state_->GetLastReadModifyWriteEntry()}, "writing", error); } void set_cancel() { ABSL_UNREACHABLE(); } void set_value(ReadResult read_result) { auto& entry = *state_->entry; ReceiveWritebackCommon(entry, read_result); if (!state_->entry->next_ && !(state_->entry->flags_ & ReadModifyWriteEntry::kDeleted)) { state_->read_result = std::move(read_result); state_->source_entry = &entry; } else { assert(!StorageGeneration::IsConditional( state_->read_result.stamp.generation)); if (state_->read_result.state == ReadResult::kUnspecified) { TENSORSTORE_KVSTORE_DEBUG_LOG( entry, "Replacing: existing_result state=", state_->read_result.state, ", stamp=", state_->read_result.stamp, ", new_result state=", read_result.state, ", stamp=", read_result.stamp); state_->read_result = std::move(read_result); state_->source_entry = &entry; } else { state_->read_result.stamp.time = read_result.stamp.time; TENSORSTORE_KVSTORE_DEBUG_LOG(entry, "Conditioning: existing_stamp=", state_->read_result.stamp.generation, ", new_stamp=", read_result.stamp); state_->read_result.stamp.generation = StorageGeneration::Condition( state_->read_result.stamp.generation, std::move(read_result.stamp.generation)); } } if (entry.flags_ & ReadModifyWriteEntry::kTransitivelyUnconditional) { const bool unmodified = state_->read_result.state == ReadResult::kUnspecified; auto GetPrevSupersededEntryToWriteback = [&](ReadModifyWriteEntry* entry) -> ReadModifyWriteEntry* { while (true) { entry = entry->prev_; if (!entry) return nullptr; if (unmodified) { if (!(entry->flags_ & ReadModifyWriteEntry::kWritebackProvided) || (entry->flags_ & ReadModifyWriteEntry::kTransitivelyDirty)) { return entry; } } else { if (!(entry->flags_ & (ReadModifyWriteEntry::kWritebackProvided | ReadModifyWriteEntry::kTransitivelyUnconditional))) { return entry; } } } }; if (auto* prev = GetPrevSupersededEntryToWriteback(&entry)) { state_->entry = prev; TENSORSTORE_KVSTORE_DEBUG_LOG(*prev, "Continuing writeback validate only"); ReadModifyWriteSource::WritebackOptions writeback_options; writeback_options.staleness_bound = state_->staleness_bound; writeback_options.writeback_mode = unmodified ? ReadModifyWriteSource::kNormalWriteback : ReadModifyWriteSource::kValidateOnly; prev->source_->KvsWriteback(std::move(writeback_options), std::move(*this)); return; } } auto* last_entry = state_->GetLastReadModifyWriteEntry(); if (last_entry->next_) { state_->read_result.state = ReadResult::kUnspecified; } TENSORSTORE_KVSTORE_DEBUG_LOG(*last_entry, "No remaining skipped entries, forwarding " "to MultiPhaseMutation::Writeback: ", state_->read_result.stamp); last_entry->multi_phase().Writeback( *last_entry, state_->source_entry ? *state_->source_entry : *last_entry, std::move(state_->read_result)); } }; auto state = std::unique_ptr<SequenceWritebackReceiverImpl::State>( new SequenceWritebackReceiverImpl::State{&entry, staleness_bound}); if (entry.flags_ & ReadModifyWriteEntry::kDeleted) { state->read_result.state = ReadResult::kMissing; } entry.source_->KvsWriteback(std::move(writeback_options), SequenceWritebackReceiverImpl{std::move(state)}); } void HandleDeleteRangeDone(DeleteRangeEntry& dr_entry) { const bool error = dr_entry.remaining_entries_.HasError(); if (error) { WritebackError(dr_entry); } else { WritebackSuccess(dr_entry); } EntryDone(dr_entry.single_phase_mutation(), error); } void DeletedEntryDone(DeleteRangeEntry& dr_entry, bool error, size_t count) { if (error) dr_entry.remaining_entries_.SetError(); if (!dr_entry.remaining_entries_.DecrementCount(count)) return; if (dr_entry.remaining_entries_.HasError()) { HandleDeleteRangeDone(dr_entry); return; } dr_entry.multi_phase().WritebackDelete(dr_entry); } std::string DescribeEntry(MutationEntry& entry) { return tensorstore::StrCat( entry.entry_type() == kReadModifyWrite ? "read/write " : "delete ", entry.multi_phase().DescribeKey(entry.key_)); } void EntryDone(SinglePhaseMutation& single_phase_mutation, bool error, size_t count) { auto& multi_phase = *single_phase_mutation.multi_phase_; if (error) single_phase_mutation.remaining_entries_.SetError(); if (!single_phase_mutation.remaining_entries_.DecrementCount(count)) { return; } multi_phase.AllEntriesDone(single_phase_mutation); } } void ReadModifyWriteEntry::KvsRead( ReadModifyWriteTarget::TransactionalReadOptions options, ReadModifyWriteTarget::ReadReceiver receiver) { struct ReadReceiverImpl { ReadModifyWriteEntry* entry_; ReadModifyWriteTarget::ReadReceiver receiver_; void set_cancel() { execution::set_cancel(receiver_); } void set_value(ReadResult read_result) { { assert(!StorageGeneration::IsUnknown(read_result.stamp.generation)); absl::MutexLock lock(&entry_->mutex()); ReceiveWritebackCommon(*entry_->prev_, read_result); entry_->flags_ |= (entry_->prev_->flags_ & ReadModifyWriteEntry::kTransitivelyUnconditional); } execution::set_value(receiver_, std::move(read_result)); } void set_error(absl::Status error) { execution::set_error(receiver_, std::move(error)); } }; if (flags_ & ReadModifyWriteEntry::kPrevDeleted) { execution::set_value( receiver, ReadResult::Missing( {StorageGeneration::Dirty(StorageGeneration::Unknown()), absl::InfiniteFuture()})); } else if (prev_) { TENSORSTORE_KVSTORE_DEBUG_LOG(*prev_, "Requesting writeback for read"); ReadModifyWriteSource::WritebackOptions writeback_options; writeback_options.generation_conditions.if_not_equal = std::move(options.generation_conditions.if_not_equal); writeback_options.staleness_bound = options.staleness_bound; writeback_options.writeback_mode = ReadModifyWriteSource::kSpecifyUnchangedWriteback; this->prev_->source_->KvsWriteback( std::move(writeback_options), ReadReceiverImpl{this, std::move(receiver)}); } else { multi_phase().Read(*this, std::move(options), std::move(receiver)); } } bool ReadModifyWriteEntry::KvsReadsCommitted() { return prev_ == nullptr && !(flags_ & ReadModifyWriteEntry::kPrevDeleted) && multi_phase().MultiPhaseReadsCommitted(); } void DestroyPhaseEntries(SinglePhaseMutation& single_phase_mutation) { auto& multi_phase = *single_phase_mutation.multi_phase_; for (MutationEntryTree::iterator tree_entry = single_phase_mutation.entries_.begin(), tree_next; tree_entry != single_phase_mutation.entries_.end(); tree_entry = tree_next) { tree_next = std::next(tree_entry); single_phase_mutation.entries_.Remove(*tree_entry); if (tree_entry->entry_type() == kReadModifyWrite) { DestroyReadModifyWriteSequence( static_cast<ReadModifyWriteEntry*>(&*tree_entry)); } else { auto& dr_entry = static_cast<DeleteRangeEntry&>(*tree_entry); for (ReadModifyWriteEntryTree::iterator entry = dr_entry.superseded_.begin(), next; entry != dr_entry.superseded_.end(); entry = next) { next = std::next(entry); dr_entry.superseded_.Remove(*entry); DestroyReadModifyWriteSequence(entry.to_pointer()); } delete &dr_entry; } } if (&single_phase_mutation != &multi_phase.phases_) { single_phase_mutation.prev_->next_ = single_phase_mutation.next_; single_phase_mutation.next_->prev_ = single_phase_mutation.prev_; delete &single_phase_mutation; } } namespace { void InvalidateReadStateGoingBackward(ReadModifyWriteEntry* entry) { do { entry->source_->KvsInvalidateReadState(); entry = entry->prev_; } while (entry); } } void InvalidateReadState(SinglePhaseMutation& single_phase_mutation) { for (auto& entry : single_phase_mutation.entries_) { if (entry.entry_type() == kReadModifyWrite) { InvalidateReadStateGoingBackward( static_cast<ReadModifyWriteEntry*>(&entry)); } else { for (auto& deleted_entry : static_cast<DeleteRangeEntry&>(entry).superseded_) { InvalidateReadStateGoingBackward(&deleted_entry); } } } } void WritebackSuccess(ReadModifyWriteEntry& entry, TimestampedStorageGeneration new_stamp) { assert(!entry.next_read_modify_write()); for (ReadModifyWriteEntry* e = &entry;;) { e->source_->KvsWritebackSuccess(new_stamp); bool dirty = static_cast<bool>(e->flags_ & ReadModifyWriteEntry::kDirty); e = e->prev_; if (!e) break; if (dirty || !(e->flags_ & ReadModifyWriteEntry::kWritebackProvided)) { new_stamp.generation = StorageGeneration::Unknown(); new_stamp.time = absl::InfiniteFuture(); } } } void WritebackError(ReadModifyWriteEntry& entry) { assert(!entry.next_read_modify_write()); if (entry.flags_ & ReadModifyWriteEntry::kError) return; entry.flags_ |= ReadModifyWriteEntry::kError; for (ReadModifyWriteEntry* e = &entry;;) { e->source_->KvsWritebackError(); e = e->prev_; if (!e) break; } } void WritebackError(DeleteRangeEntry& entry) { for (auto& e : entry.superseded_) { WritebackError(e); } } void WritebackSuccess(DeleteRangeEntry& entry) { for (auto& e : entry.superseded_) { WritebackSuccess(e, TimestampedStorageGeneration{StorageGeneration::Unknown(), absl::InfiniteFuture()}); } } void WritebackError(MutationEntry& entry) { if (entry.entry_type() == kReadModifyWrite) { WritebackError(static_cast<ReadModifyWriteEntry&>(entry)); } else { WritebackError(static_cast<DeleteRangeEntry&>(entry)); } } void WritebackError(SinglePhaseMutation& single_phase_mutation) { for (auto& entry : single_phase_mutation.entries_) { WritebackError(entry); } } MultiPhaseMutation::MultiPhaseMutation() { phases_.next_ = phases_.prev_ = &phases_; phases_.phase_number_ = internal::TransactionState::kInvalidPhase; phases_.multi_phase_ = this; } SinglePhaseMutation& MultiPhaseMutation::GetCommittingPhase() { auto* single_phase_mutation = &phases_; auto initial_phase_number = single_phase_mutation->phase_number_; if (initial_phase_number != this->GetTransactionNode().phase() && initial_phase_number != internal::TransactionState::kInvalidPhase) { single_phase_mutation = single_phase_mutation->next_; assert(single_phase_mutation->phase_number_ == this->GetTransactionNode().phase()); } return *single_phase_mutation; } void MultiPhaseMutation::AllEntriesDone( SinglePhaseMutation& single_phase_mutation) { size_t next_phase = 0; if (single_phase_mutation.next_ != &this->phases_) { next_phase = single_phase_mutation.next_->phase_number_; } DestroyPhaseEntries(single_phase_mutation); this->PhaseCommitDone(next_phase); } namespace { void InvalidateReadStateGoingForward(ReadModifyWriteEntry* entry) { auto& single_phase_mutation = entry->single_phase_mutation(); do { entry->source_->KvsInvalidateReadState(); entry->flags_ &= ~ReadModifyWriteEntry::kTransitivelyUnconditional; entry = entry->next_read_modify_write(); } while (entry && (&entry->single_phase_mutation() == &single_phase_mutation)); } void WritebackPhase( SinglePhaseMutation& single_phase_mutation, absl::Time staleness_bound, absl::FunctionRef<bool(ReadModifyWriteEntry& entry)> predicate) { assert(single_phase_mutation.remaining_entries_.IsDone()); size_t entry_count = 0; for (auto& entry : single_phase_mutation.entries_) { if (entry.entry_type() == kReadModifyWrite) { auto& rmw_entry = static_cast<ReadModifyWriteEntry&>(entry); if (auto* next = static_cast<ReadModifyWriteEntry*>(rmw_entry.next_)) { assert(next->entry_type() == kReadModifyWrite); assert(&next->single_phase_mutation() != &single_phase_mutation); next->prev_ = nullptr; InvalidateReadStateGoingForward(next); rmw_entry.next_ = nullptr; } if (predicate(rmw_entry)) { ++entry_count; StartWriteback(rmw_entry, staleness_bound); } } else { auto& dr_entry = static_cast<DeleteRangeEntry&>(entry); assert(dr_entry.remaining_entries_.IsDone()); ++entry_count; size_t deleted_entry_count = 0; for (auto& deleted_entry : dr_entry.superseded_) { auto& rmw_entry = static_cast<ReadModifyWriteEntry&>(deleted_entry); rmw_entry.next_ = &dr_entry; if (predicate(rmw_entry)) { ++deleted_entry_count; StartWriteback(static_cast<ReadModifyWriteEntry&>(deleted_entry), staleness_bound); } } DeletedEntryDone(dr_entry, false, -deleted_entry_count); } } EntryDone(single_phase_mutation, false, -entry_count); } } void MultiPhaseMutation::CommitNextPhase() { size_t cur_phase_number = GetTransactionNode().phase(); DebugCheckInvariants(*this, false); { DebugCheckInvariantsInDestructor debug_check(*this, true); if (cur_phase_number == 0) { if (phases_.next_ != &phases_) { auto* last_phase = phases_.prev_; for (MutationEntryTree::iterator entry = last_phase->entries_.begin(), next; entry != last_phase->entries_.end(); entry = next) { next = std::next(entry); if (&entry->single_phase_mutation() != last_phase) { last_phase->entries_.Remove(*entry); InsertIntoPriorPhase(entry.to_pointer()); } } } if (cur_phase_number != phases_.phase_number_) { this->PhaseCommitDone(phases_.phase_number_); return; } } } auto& single_phase_mutation = GetCommittingPhase(); WritebackPhase(single_phase_mutation, absl::InfinitePast(), [](ReadModifyWriteEntry& entry) { return true; }); } void MultiPhaseMutation::AbortRemainingPhases() { for (auto* single_phase_mutation = &phases_;;) { auto* next = single_phase_mutation->next_; DestroyPhaseEntries(*single_phase_mutation); if (next == &phases_) break; single_phase_mutation = next; } } MultiPhaseMutation::ReadModifyWriteStatus MultiPhaseMutation::ReadModifyWrite( size_t& phase, Key key, ReadModifyWriteSource& source) { DebugCheckInvariantsInDestructor debug_check(*this, false); #ifndef NDEBUG mutex().AssertHeld(); #endif auto& single_phase_mutation = GetCurrentSinglePhaseMutation(*this); phase = single_phase_mutation.phase_number_; auto* entry = MakeReadModifyWriteEntry(single_phase_mutation, std::move(key)); entry->source_ = &source; entry->source_->KvsSetTarget(*entry); auto find_result = single_phase_mutation.entries_.Find( [key = std::string_view(entry->key_)](MutationEntry& existing_entry) { auto c = key.compare(existing_entry.key_); if (c <= 0) return internal::CompareResultAsWeakOrdering(c); if (existing_entry.entry_type() == kReadModifyWrite) { return absl::weak_ordering::greater; } return KeyRange::CompareKeyAndExclusiveMax( key, static_cast<DeleteRangeEntry&>(existing_entry) .exclusive_max_) < 0 ? absl::weak_ordering::equivalent : absl::weak_ordering::greater; }); if (!find_result.found) { const bool was_empty = single_phase_mutation.entries_.empty(); single_phase_mutation.entries_.Insert(find_result.insert_position(), *entry); return was_empty ? ReadModifyWriteStatus::kAddedFirst : ReadModifyWriteStatus::kAddedSubsequent; } single_phase_mutation.entries_.Replace(*find_result.node, *entry); if (find_result.node->entry_type() == kReadModifyWrite) { auto* existing_entry = static_cast<ReadModifyWriteEntry*>(find_result.node); assert(existing_entry->key_ == entry->key_); if (&existing_entry->single_phase_mutation() != &single_phase_mutation) { InsertIntoPriorPhase(existing_entry); } existing_entry->source_->KvsRevoke(); assert(existing_entry->next_ == nullptr); entry->prev_ = existing_entry; existing_entry->next_ = entry; return ReadModifyWriteStatus::kExisting; } auto* existing_entry = static_cast<DeleteRangeEntry*>(find_result.node); assert(existing_entry->key_ <= entry->key_); assert(KeyRange::CompareKeyAndExclusiveMax( entry->key_, existing_entry->exclusive_max_) < 0); entry->flags_ |= (ReadModifyWriteEntry::kPrevDeleted | ReadModifyWriteEntry::kTransitivelyUnconditional); if (&existing_entry->single_phase_mutation() != &single_phase_mutation) { if (existing_entry->key_ != entry->key_) { InsertDeleteRangeEntry(kDeleteRangePlaceholder, single_phase_mutation, existing_entry->single_phase_mutation(), KeyRange{existing_entry->key_, entry->key_}, {entry, MutationEntryTree::kLeft}); } if (auto successor = KeyRange::Successor(entry->key_); successor != existing_entry->exclusive_max_) { InsertDeleteRangeEntry( kDeleteRangePlaceholder, single_phase_mutation, existing_entry->single_phase_mutation(), KeyRange{std::move(successor), existing_entry->exclusive_max_}, {entry, MutationEntryTree::kRight}); } InsertIntoPriorPhase(existing_entry); return ReadModifyWriteStatus::kExisting; } auto split_result = existing_entry->superseded_.FindSplit( [key = std::string_view(entry->key_)](MutationEntry& e) { return internal::CompareResultAsWeakOrdering(key.compare(e.key_)); }); if (split_result.center) { split_result.center->flags_ &= ~ReadModifyWriteEntry::kDeleted; entry->prev_ = split_result.center; split_result.center->next_ = entry; } if (existing_entry->key_ != entry->key_) { auto* dr_entry = InsertDeleteRangeEntry( kDeleteRange, single_phase_mutation, existing_entry->single_phase_mutation(), KeyRange{std::move(existing_entry->key_), entry->key_}, {entry, MutationEntryTree::kLeft}); dr_entry->superseded_ = std::move(split_result.trees[0]); } else { assert(split_result.trees[0].empty()); } existing_entry->key_ = KeyRange::Successor(entry->key_); if (existing_entry->key_ != existing_entry->exclusive_max_) { single_phase_mutation.entries_.Insert({entry, MutationEntryTree::kRight}, *existing_entry); existing_entry->superseded_ = std::move(split_result.trees[1]); } else { assert(split_result.trees[1].empty()); delete existing_entry; } return ReadModifyWriteStatus::kExisting; } void MultiPhaseMutation::DeleteRange(KeyRange range) { #ifndef NDEBUG mutex().AssertHeld(); #endif if (range.empty()) return; DebugCheckInvariantsInDestructor debug_check(*this, false); auto& single_phase_mutation = GetCurrentSinglePhaseMutation(*this); auto find_result = single_phase_mutation.entries_.FindBound<MutationEntryTree::kLeft>( [&](MutationEntry& existing_entry) { if (existing_entry.entry_type() == kReadModifyWrite) { return existing_entry.key_ < range.inclusive_min; } else { return KeyRange::CompareExclusiveMaxAndKey( static_cast<DeleteRangeEntry&>(existing_entry) .exclusive_max_, range.inclusive_min) <= 0; } }); DeleteRangeEntry* new_entry = nullptr; ReadModifyWriteEntryTree superseded; DeleteRangeEntry insert_placeholder; single_phase_mutation.entries_.Insert(find_result.insert_position(), insert_placeholder); for (MutationEntry *existing_entry = find_result.found_node(), *next; existing_entry; existing_entry = next) { if (KeyRange::CompareKeyAndExclusiveMax(existing_entry->key_, range.exclusive_max) >= 0) { break; } next = MutationEntryTree::Traverse(*existing_entry, MutationEntryTree::kRight); single_phase_mutation.entries_.Remove(*existing_entry); if (existing_entry->entry_type() == kReadModifyWrite) { auto* existing_rmw_entry = static_cast<ReadModifyWriteEntry*>(existing_entry); existing_rmw_entry->source_->KvsRevoke(); if (&existing_rmw_entry->single_phase_mutation() != &single_phase_mutation) { InsertIntoPriorPhase(existing_entry); } else { existing_rmw_entry->flags_ |= ReadModifyWriteEntry::kDeleted; [[maybe_unused]] bool inserted = superseded .FindOrInsert(CompareToEntry(*existing_rmw_entry), [=] { return existing_rmw_entry; }) .second; assert(inserted); } } else { auto* existing_dr_entry = static_cast<DeleteRangeEntry*>(existing_entry); if (&existing_dr_entry->single_phase_mutation() != &single_phase_mutation) { if (KeyRange::CompareExclusiveMax( range.exclusive_max, existing_dr_entry->exclusive_max_) < 0) { InsertDeleteRangeEntry( kDeleteRangePlaceholder, single_phase_mutation, existing_dr_entry->single_phase_mutation(), KeyRange{range.exclusive_max, existing_dr_entry->exclusive_max_}, {&insert_placeholder, MutationEntryTree::kRight}); } if (existing_dr_entry->key_ < range.inclusive_min) { InsertDeleteRangeEntry( kDeleteRangePlaceholder, single_phase_mutation, existing_dr_entry->single_phase_mutation(), KeyRange{existing_dr_entry->key_, range.inclusive_min}, {&insert_placeholder, MutationEntryTree::kLeft}); } InsertIntoPriorPhase(existing_dr_entry); } else { superseded = ReadModifyWriteEntryTree::Join( superseded, existing_dr_entry->superseded_); if (!new_entry) { new_entry = existing_dr_entry; } else { new_entry->exclusive_max_ = std::move(existing_dr_entry->exclusive_max_); delete existing_dr_entry; } } } } if (new_entry) { if (range.inclusive_min < new_entry->key_) { new_entry->key_ = std::move(range.inclusive_min); } if (KeyRange::CompareExclusiveMax(range.exclusive_max, new_entry->exclusive_max_) > 0) { new_entry->exclusive_max_ = std::move(range.exclusive_max); } } else { new_entry = MakeDeleteRangeEntry(kDeleteRange, single_phase_mutation, std::move(range)); } new_entry->superseded_ = std::move(superseded); single_phase_mutation.entries_.Replace(insert_placeholder, *new_entry); } std::string MultiPhaseMutation::DescribeFirstEntry() { assert(!phases_.prev_->entries_.empty()); return DescribeEntry(*phases_.prev_->entries_.begin()); } ReadModifyWriteEntry* MultiPhaseMutation::AllocateReadModifyWriteEntry() { return new ReadModifyWriteEntry; } void MultiPhaseMutation::FreeReadModifyWriteEntry(ReadModifyWriteEntry* entry) { delete entry; } void ReadDirectly(Driver* driver, ReadModifyWriteEntry& entry, ReadModifyWriteTarget::TransactionalReadOptions&& options, ReadModifyWriteTarget::ReadReceiver&& receiver) { ReadOptions kvstore_options; kvstore_options.staleness_bound = options.staleness_bound; kvstore_options.generation_conditions.if_not_equal = std::move(options.generation_conditions.if_not_equal); kvstore_options.batch = std::move(options.batch); execution::submit(driver->Read(entry.key_, std::move(kvstore_options)), std::move(receiver)); } void WritebackDirectly(Driver* driver, ReadModifyWriteEntry& entry, ReadResult&& read_result) { assert(read_result.stamp.time != absl::InfinitePast()); PerformWriteback(driver, Controller{&entry}, std::move(read_result)); } void WritebackDirectly(Driver* driver, DeleteRangeEntry& entry) { auto future = driver->DeleteRange(KeyRange{entry.key_, entry.exclusive_max_}); future.Force(); std::move(future).ExecuteWhenReady([&entry](ReadyFuture<const void> future) { auto& r = future.result(); if (!r.ok()) { entry.multi_phase().GetTransactionNode().SetError(r.status()); entry.remaining_entries_.SetError(); } HandleDeleteRangeDone(entry); }); } void MultiPhaseMutation::RecordEntryWritebackError(ReadModifyWriteEntry& entry, absl::Status error) { this->GetTransactionNode().SetError(std::move(error)); WritebackError(entry); } void AtomicMultiPhaseMutationBase::RetryAtomicWriteback( absl::Time staleness_bound) { auto& single_phase_mutation = GetCommittingPhase(); WritebackPhase( single_phase_mutation, staleness_bound, [&](ReadModifyWriteEntry& entry) { return static_cast<ReadModifyWriteEntryWithStamp&>(entry).IsOutOfDate( staleness_bound); }); } ReadModifyWriteEntry* AtomicMultiPhaseMutation::AllocateReadModifyWriteEntry() { return new BufferedReadModifyWriteEntry; } void AtomicMultiPhaseMutation::FreeReadModifyWriteEntry( ReadModifyWriteEntry* entry) { delete static_cast<BufferedReadModifyWriteEntry*>(entry); } void AtomicMultiPhaseMutationBase::AtomicWritebackReady( ReadModifyWriteEntry& entry) { if (auto* dr_entry = static_cast<DeleteRangeEntry*>(entry.next_)) { DeletedEntryDone(*dr_entry, false); } else { EntryDone(entry.single_phase_mutation(), false); } } void AtomicMultiPhaseMutation::Writeback(ReadModifyWriteEntry& entry, ReadModifyWriteEntry& source_entry, ReadResult&& read_result) { assert(read_result.stamp.time != absl::InfinitePast()); auto& buffered = static_cast<BufferedReadModifyWriteEntry&>(entry); buffered.stamp() = std::move(read_result.stamp); buffered.value_state_ = read_result.state; buffered.value_ = std::move(read_result.value); AtomicWritebackReady(entry); } void AtomicMultiPhaseMutationBase::WritebackDelete(DeleteRangeEntry& entry) { EntryDone(entry.single_phase_mutation(), false); } void AtomicMultiPhaseMutationBase::AtomicCommitWritebackSuccess() { for (auto& entry : GetCommittingPhase().entries_) { if (entry.entry_type() == kReadModifyWrite) { auto& rmw_entry = static_cast<ReadModifyWriteEntryWithStamp&>(entry); internal_kvstore::WritebackSuccess(rmw_entry, std::move(rmw_entry.stamp_)); } else { auto& dr_entry = static_cast<DeleteRangeEntry&>(entry); internal_kvstore::WritebackSuccess(dr_entry); } } } void AtomicMultiPhaseMutationBase::RevokeAllEntries() { assert(phases_.next_ == &phases_); for (auto& entry : phases_.entries_) { if (entry.entry_type() != kReadModifyWrite) continue; auto& rmw_entry = static_cast<ReadModifyWriteEntry&>(entry); rmw_entry.source_->KvsRevoke(); } } namespace { absl::Status GetNonAtomicReadModifyWriteError( NonAtomicTransactionNode& node, MultiPhaseMutation::ReadModifyWriteStatus modify_status) { if (!node.transaction()->atomic()) { return absl::OkStatus(); } using ReadModifyWriteStatus = MultiPhaseMutation::ReadModifyWriteStatus; if (modify_status == ReadModifyWriteStatus::kAddedFirst) { return node.MarkAsTerminal(); } if (modify_status == ReadModifyWriteStatus::kAddedSubsequent) { absl::MutexLock lock(&node.mutex_); auto& single_phase_mutation = *node.phases_.prev_; MutationEntry* e0 = single_phase_mutation.entries_.begin().to_pointer(); assert(e0); MutationEntry* e1 = MutationEntryTree::Traverse(*e0, MutationEntryTree::kRight); assert(e1); auto error = internal::TransactionState::Node::GetAtomicError( DescribeEntry(*e0), DescribeEntry(*e1)); node.transaction()->RequestAbort(error); return error; } return absl::OkStatus(); } class ReadViaExistingTransactionNode : public internal::TransactionState::Node, public ReadModifyWriteSource { public: ReadViaExistingTransactionNode() : internal::TransactionState::Node(nullptr) {} void PrepareForCommit() override { intrusive_ptr_increment(this); this->PrepareDone(); this->ReadyForCommit(); } void Commit() override { intrusive_ptr_decrement(this); } void Abort() override { AbortDone(); } void KvsSetTarget(ReadModifyWriteTarget& target) override { target_ = &target; } void KvsInvalidateReadState() override {} void KvsWriteback( ReadModifyWriteSource::WritebackOptions options, ReadModifyWriteSource::WritebackReceiver receiver) override { ReadModifyWriteTarget::TransactionalReadOptions read_options = options; if (options.writeback_mode != ReadModifyWriteSource::kSpecifyUnchangedWriteback) { TimestampedStorageGeneration expected_stamp; { absl::MutexLock lock(&mutex_); expected_stamp = expected_stamp_; } if (StorageGeneration::IsUnknown(expected_stamp.generation)) { execution::set_value( receiver, ReadResult::Unspecified( TimestampedStorageGeneration::Unconditional())); return; } if (StorageGeneration::IsClean(expected_stamp.generation) && expected_stamp.time >= read_options.staleness_bound) { execution::set_value( receiver, ReadResult::Unspecified(std::move(expected_stamp))); return; } } struct ReadReceiverImpl { ReadViaExistingTransactionNode& node_; ReadModifyWriteSource::WritebackReceiver receiver_; void set_value(ReadResult read_result) { bool mismatch; { absl::MutexLock lock(&node_.mutex_); mismatch = !StorageGeneration::EqualOrUnspecified( read_result.stamp.generation, node_.expected_stamp_.generation); } if (mismatch) { execution::set_error(receiver_, absl::AbortedError("Generation mismatch")); return; } execution::set_value(receiver_, std::move(read_result)); } void set_cancel() { execution::set_cancel(receiver_); } void set_error(absl::Status error) { execution::set_error(receiver_, std::move(error)); } }; target_->KvsRead(std::move(read_options), ReadReceiverImpl{*this, std::move(receiver)}); } void KvsWritebackError() override { this->CommitDone(); } void KvsRevoke() override {} void KvsWritebackSuccess(TimestampedStorageGeneration new_stamp) override { this->CommitDone(); } absl::Mutex mutex_; TimestampedStorageGeneration expected_stamp_; ReadModifyWriteTarget* target_; }; } Future<ReadResult> ReadViaExistingTransaction( Driver* driver, internal::OpenTransactionPtr& transaction, size_t& phase, Key key, kvstore::TransactionalReadOptions options) { auto [promise, future] = PromiseFuturePair<ReadResult>::Make(); using Node = ReadViaExistingTransactionNode; internal::WeakTransactionNodePtr<Node> node; node.reset(new Node); TENSORSTORE_RETURN_IF_ERROR( driver->ReadModifyWrite(transaction, phase, std::move(key), *node)); node->SetTransaction(*transaction); node->SetPhase(phase); TENSORSTORE_RETURN_IF_ERROR(node->Register()); struct InitialReadReceiverImpl { internal::OpenTransactionNodePtr<Node> node_; Promise<ReadResult> promise_; void set_value(ReadResult read_result) { if (node_->transaction()->mode() & repeatable_read) { absl::MutexLock lock(&node_->mutex_); node_->expected_stamp_ = read_result.stamp; } promise_.SetResult(std::move(read_result)); } void set_cancel() {} void set_error(absl::Status error) { promise_.SetResult(std::move(error)); } }; node->target_->KvsRead(std::move(options), InitialReadReceiverImpl{ internal::OpenTransactionNodePtr<Node>(node.get()), std::move(promise)}); return std::move(future); } namespace { class WriteViaExistingTransactionNode : public internal::TransactionState::Node, public ReadModifyWriteSource { public: WriteViaExistingTransactionNode() : internal::TransactionState::Node(nullptr) {} void PrepareForCommit() override { intrusive_ptr_increment(this); this->PrepareDone(); this->ReadyForCommit(); } void Commit() override { intrusive_ptr_decrement(this); } void Abort() override { AbortDone(); } void KvsSetTarget(ReadModifyWriteTarget& target) override { target_ = &target; } void KvsInvalidateReadState() override {} void KvsWriteback( ReadModifyWriteSource::WritebackOptions options, ReadModifyWriteSource::WritebackReceiver receiver) override { if (!StorageGeneration::IsConditional(read_result_.stamp.generation)) { execution::set_value(receiver, read_result_); return; } ReadModifyWriteTarget::TransactionalReadOptions read_options; read_options.generation_conditions.if_not_equal = StorageGeneration::Clean(read_result_.stamp.generation); read_options.staleness_bound = options.staleness_bound; struct ReadReceiverImpl { WriteViaExistingTransactionNode& source_; ReadModifyWriteSource::WritebackReceiver receiver_; void set_value(ReadResult read_result) { auto& existing_generation = source_.read_result_.stamp.generation; auto clean_generation = StorageGeneration::Clean(existing_generation); if (read_result.stamp.generation == clean_generation || (source_.if_equal_no_value_ && read_result.state == ReadResult::kMissing)) { source_.read_result_.stamp = std::move(read_result.stamp); source_.read_result_.stamp.generation.MarkDirty(); } else { assert( !StorageGeneration::IsNewlyDirty(read_result.stamp.generation)); source_.read_result_ = std::move(read_result); source_.if_equal_no_value_ = false; } execution::set_value(receiver_, source_.read_result_); } void set_cancel() { execution::set_cancel(receiver_); } void set_error(absl::Status error) { execution::set_error(receiver_, std::move(error)); } }; target_->KvsRead(std::move(read_options), ReadReceiverImpl{*this, std::move(receiver)}); } void KvsWritebackError() override { this->CommitDone(); } void KvsRevoke() override {} void KvsWritebackSuccess(TimestampedStorageGeneration new_stamp) override { if (!StorageGeneration::IsNewlyDirty(read_result_.stamp.generation)) { new_stamp = TimestampedStorageGeneration{}; } else if (new_stamp.time == absl::InfiniteFuture()) { new_stamp.generation = StorageGeneration::Invalid(); } promise_.SetResult(std::move(new_stamp)); this->CommitDone(); } Promise<TimestampedStorageGeneration> promise_; ReadResult read_result_; bool if_equal_no_value_; ReadModifyWriteTarget* target_; }; } Future<TimestampedStorageGeneration> WriteViaExistingTransaction( Driver* driver, internal::OpenTransactionPtr& transaction, size_t& phase, Key key, std::optional<Value> value, WriteOptions options) { TimestampedStorageGeneration stamp; if (StorageGeneration::IsUnknown(options.generation_conditions.if_equal)) { stamp.time = absl::InfiniteFuture(); } else { assert(StorageGeneration::IsClean(options.generation_conditions.if_equal)); stamp.time = absl::Time(); } bool if_equal_no_value = StorageGeneration::IsNoValue(options.generation_conditions.if_equal); stamp.generation = std::move(options.generation_conditions.if_equal); stamp.generation.MarkDirty(); auto [promise, future] = PromiseFuturePair<TimestampedStorageGeneration>::Make(); using Node = WriteViaExistingTransactionNode; internal::WeakTransactionNodePtr<Node> node; node.reset(new Node); node->promise_ = promise; node->read_result_ = value ? ReadResult::Value(*std::move(value), std::move(stamp)) : ReadResult::Missing(std::move(stamp)); node->if_equal_no_value_ = if_equal_no_value; TENSORSTORE_RETURN_IF_ERROR( driver->ReadModifyWrite(transaction, phase, std::move(key), *node)); node->SetTransaction(*transaction); node->SetPhase(phase); TENSORSTORE_RETURN_IF_ERROR(node->Register()); LinkError(std::move(promise), transaction->future()); return std::move(future); } Future<TimestampedStorageGeneration> WriteViaTransaction( Driver* driver, Key key, std::optional<Value> value, WriteOptions options) { internal::OpenTransactionPtr transaction; size_t phase; return WriteViaExistingTransaction(driver, transaction, phase, std::move(key), std::move(value), std::move(options)); } } namespace kvstore { absl::Status Driver::ReadModifyWrite(internal::OpenTransactionPtr& transaction, size_t& phase, Key key, ReadModifyWriteSource& source) { TENSORSTORE_ASSIGN_OR_RETURN( auto node, internal_kvstore::GetTransactionNode< internal_kvstore::NonAtomicTransactionNode>(this, transaction)); internal_kvstore::MultiPhaseMutation::ReadModifyWriteStatus rmw_status; { absl::MutexLock lock(&node->mutex_); rmw_status = node->ReadModifyWrite(phase, std::move(key), source); } return internal_kvstore::GetNonAtomicReadModifyWriteError(*node, rmw_status); } absl::Status Driver::TransactionalDeleteRange( const internal::OpenTransactionPtr& transaction, KeyRange range) { if (range.empty()) return absl::OkStatus(); if (transaction && transaction->atomic()) { auto error = absl::InvalidArgumentError( tensorstore::StrCat("Cannot delete range starting at ", this->DescribeKey(range.inclusive_min), " as single atomic transaction")); transaction->RequestAbort(error); return error; } return internal_kvstore::AddDeleteRange< internal_kvstore::NonAtomicTransactionNode>(this, transaction, std::move(range)); } } }
#include "tensorstore/transaction.h" #include <utility> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/time/clock.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/kvstore/byte_range.h" #include "tensorstore/kvstore/generation.h" #include "tensorstore/kvstore/kvstore.h" #include "tensorstore/kvstore/mock_kvstore.h" #include "tensorstore/kvstore/operations.h" #include "tensorstore/kvstore/read_result.h" #include "tensorstore/kvstore/test_matchers.h" #include "tensorstore/kvstore/test_util.h" #include "tensorstore/util/status_testutil.h" namespace { namespace kvstore = tensorstore::kvstore; using ::tensorstore::MatchesStatus; using ::tensorstore::OptionalByteRangeRequest; using ::tensorstore::StorageGeneration; using ::tensorstore::TimestampedStorageGeneration; using ::tensorstore::Transaction; using ::tensorstore::internal::MatchesKvsReadResult; using ::tensorstore::internal::MockKeyValueStore; using ::tensorstore::kvstore::KvStore; using ::tensorstore::kvstore::ReadResult; TEST(KvStoreTest, WriteThenRead) { auto mock_driver = MockKeyValueStore::Make(); Transaction txn(tensorstore::isolated); KvStore store(mock_driver, "", txn); TENSORSTORE_ASSERT_OK(kvstore::Write(store, "a", absl::Cord("value"))); EXPECT_THAT(kvstore::Read(store, "a").result(), ::testing::Optional(MatchesKvsReadResult(absl::Cord("value")))); auto future = txn.CommitAsync(); { auto req = mock_driver->write_requests.pop(); EXPECT_THAT(req.key, "a"); EXPECT_THAT(req.value, ::testing::Optional(absl::Cord("value"))); EXPECT_THAT(req.options.generation_conditions.if_equal, StorageGeneration::Unknown()); req.promise.SetResult(TimestampedStorageGeneration( StorageGeneration::FromString("abc"), absl::Now())); } TENSORSTORE_ASSERT_OK(future); } TEST(KvStoreTest, ReadWithoutRepeatableReadIsolation) { auto mock_driver = MockKeyValueStore::Make(); Transaction txn(tensorstore::isolated); KvStore store(mock_driver, "", txn); { auto read_future = kvstore::Read(store, "a"); { auto req = mock_driver->read_requests.pop(); EXPECT_THAT(req.key, "a"); req.promise.SetResult(ReadResult::Value( absl::Cord("value"), TimestampedStorageGeneration(StorageGeneration::FromString("abc"), absl::Now()))); } EXPECT_THAT(read_future.result(), ::testing::Optional(MatchesKvsReadResult(absl::Cord("value")))); } TENSORSTORE_ASSERT_OK(txn.CommitAsync().result()); } TEST(KvStoreTest, ReadWithRepeatableReadIsolation) { auto mock_driver = MockKeyValueStore::Make(); Transaction txn(tensorstore::isolated | tensorstore::repeatable_read); KvStore store(mock_driver, "", txn); { auto read_future = kvstore::Read(store, "a"); { auto req = mock_driver->read_requests.pop(); EXPECT_THAT(req.key, "a"); req.promise.SetResult(ReadResult::Value( absl::Cord("value"), TimestampedStorageGeneration(StorageGeneration::FromString("abc"), absl::Now()))); } EXPECT_THAT(read_future.result(), ::testing::Optional(MatchesKvsReadResult(absl::Cord("value")))); } auto future = txn.CommitAsync(); { auto req = mock_driver->read_requests.pop(); EXPECT_THAT(req.key, "a"); EXPECT_THAT(req.options.byte_range, OptionalByteRangeRequest(0, 0)); EXPECT_THAT(req.options.generation_conditions.if_not_equal, StorageGeneration::FromString("abc")); req.promise.SetResult(ReadResult::Unspecified(TimestampedStorageGeneration( StorageGeneration::FromString("abc"), absl::Now()))); } TENSORSTORE_ASSERT_OK(future); } TEST(KvStoreTest, ReadInvalidOptionIfEqual) { auto mock_driver = MockKeyValueStore::Make(); Transaction txn(tensorstore::isolated); KvStore store(mock_driver, "", txn); kvstore::ReadOptions options; options.generation_conditions.if_equal = StorageGeneration::FromString("abc"); EXPECT_THAT(kvstore::Read(store, "a", std::move(options)).result(), MatchesStatus(absl::StatusCode::kUnimplemented)); } TEST(KvStoreTest, ReadInvalidOptionByteRange) { auto mock_driver = MockKeyValueStore::Make(); Transaction txn(tensorstore::isolated); KvStore store(mock_driver, "", txn); kvstore::ReadOptions options; options.byte_range = OptionalByteRangeRequest{5, 10}; EXPECT_THAT(kvstore::Read(store, "a", std::move(options)).result(), MatchesStatus(absl::StatusCode::kUnimplemented)); } TEST(KvStoreTest, ReadMismatch) { auto mock_driver = MockKeyValueStore::Make(); Transaction txn(tensorstore::isolated | tensorstore::repeatable_read); KvStore store(mock_driver, "", txn); { auto read_future = kvstore::Read(store, "a"); { auto req = mock_driver->read_requests.pop(); EXPECT_THAT(req.key, "a"); req.promise.SetResult(ReadResult::Value( absl::Cord("value"), TimestampedStorageGeneration(StorageGeneration::FromString("abc"), absl::Now()))); } EXPECT_THAT(read_future.result(), ::testing::Optional(MatchesKvsReadResult(absl::Cord("value")))); } auto future = txn.CommitAsync(); { auto req = mock_driver->read_requests.pop(); EXPECT_THAT(req.key, "a"); EXPECT_THAT(req.options.byte_range, OptionalByteRangeRequest(0, 0)); EXPECT_THAT(req.options.generation_conditions.if_not_equal, StorageGeneration::FromString("abc")); req.promise.SetResult(ReadResult::Missing(TimestampedStorageGeneration( StorageGeneration::FromString("def"), absl::Now()))); } { auto req = mock_driver->read_requests.pop(); EXPECT_THAT(req.key, "a"); req.promise.SetResult(ReadResult::Missing(TimestampedStorageGeneration( StorageGeneration::FromString("def"), absl::Now()))); } EXPECT_THAT(future.result(), MatchesStatus(absl::StatusCode::kAborted, "Error writing \"a\": Generation mismatch")); } TEST(KvStoreTest, ListInvalid) { auto mock_driver = MockKeyValueStore::Make(); Transaction txn(tensorstore::isolated); KvStore store(mock_driver, "", txn); EXPECT_THAT(kvstore::ListFuture(store).result(), MatchesStatus(absl::StatusCode::kUnimplemented)); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/kvstore/transaction.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/kvstore/transaction_test.cc
4f887a6430414cd6088e1743555015b10f116d50
425d073d-3f27-40e9-99b6-df84309bd750
cpp
google/tensorstore
data_type
tensorstore/internal/json_binding/data_type.cc
tensorstore/internal/json_binding/data_type_test.cc
#include "tensorstore/internal/json_binding/data_type.h" #include <string> #include "absl/status/status.h" #include <nlohmann/json.hpp> #include "tensorstore/data_type.h" #include "tensorstore/internal/json/json.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/util/quote_string.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace internal_json_binding { TENSORSTORE_DEFINE_JSON_BINDER(DataTypeJsonBinder, [](auto is_loading, const auto& options, auto* obj, ::nlohmann::json* j) { if constexpr (is_loading) { return internal_json_binding::Compose<std::string>( [](auto is_loading, const auto& options, DataType* obj, auto* id) { *obj = tensorstore::GetDataType(*id); if (!obj->valid()) { return absl::Status( absl::StatusCode::kInvalidArgument, tensorstore::StrCat("Unsupported data type: ", tensorstore::QuoteString(*id))); } return absl::OkStatus(); })(is_loading, options, obj, j); } else { if (!obj->valid()) { *j = ::nlohmann::json(::nlohmann::json::value_t::discarded); } else if (obj->id() == DataTypeId::custom) { return absl::Status(absl::StatusCode::kInvalidArgument, "Data type has no canonical identifier"); } else { *j = obj->name(); } return absl::OkStatus(); } }) TENSORSTORE_DEFINE_JSON_BINDER(OptionalDataTypeJsonBinder, [](auto is_loading, const auto& options, auto* obj, ::nlohmann::json* j) { if constexpr (is_loading) { if (j->is_discarded()) { *obj = DataType{}; return absl::OkStatus(); } } return DataTypeJsonBinder(is_loading, options, obj, j); }) TENSORSTORE_DEFINE_JSON_BINDER( ConstrainedDataTypeJsonBinder, [](auto is_loading, const auto& options, auto* obj, ::nlohmann::json* j) { return Validate( [](const auto& options, DataType* d) { if (options.dtype().valid() && d->valid() && options.dtype() != *d) { return absl::InvalidArgumentError( tensorstore::StrCat("Expected data type of ", options.dtype(), " but received: ", *d)); } return absl::OkStatus(); }, DefaultValue([dtype = options.dtype()](DataType* d) { *d = dtype; }))( is_loading, options, obj, j); }) } }
#include "tensorstore/internal/json_binding/data_type.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include <nlohmann/json.hpp> #include "tensorstore/data_type.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/gtest.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/json_serialization_options_base.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status_testutil.h" using ::tensorstore::DataType; using ::tensorstore::dtype_v; using ::tensorstore::MatchesStatus; namespace jb = tensorstore::internal_json_binding; namespace { struct X {}; TEST(DataTypeJsonBinderTest, ToJson) { EXPECT_THAT(jb::ToJson(DataType(dtype_v<std::int32_t>)), ::testing::Optional(::nlohmann::json("int32"))); EXPECT_THAT(jb::ToJson(DataType(dtype_v<bool>)), ::testing::Optional(::nlohmann::json("bool"))); EXPECT_THAT(jb::ToJson(DataType(dtype_v<X>)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Data type has no canonical identifier")); EXPECT_THAT(jb::ToJson(DataType{}), ::testing::Optional(tensorstore::MatchesJson( ::nlohmann::json(::nlohmann::json::value_t::discarded)))); } TEST(DataTypeJsonBinderTest, FromJson) { EXPECT_THAT(jb::FromJson<DataType>(::nlohmann::json("int32")), ::testing::Optional(dtype_v<std::int32_t>)); EXPECT_THAT(jb::FromJson<DataType>(::nlohmann::json("bool")), ::testing::Optional(dtype_v<bool>)); EXPECT_THAT(jb::FromJson<DataType>(::nlohmann::json("invalid")), MatchesStatus(absl::StatusCode::kInvalidArgument, "Unsupported data type: \"invalid\"")); EXPECT_THAT(jb::FromJson<DataType>( ::nlohmann::json(::nlohmann::json::value_t::discarded)), ::testing::Optional(DataType{})); EXPECT_THAT(jb::FromJson<DataType>( ::nlohmann::json(::nlohmann::json::value_t::discarded), tensorstore::internal_json_binding::DataTypeJsonBinder), MatchesStatus(absl::StatusCode::kInvalidArgument)); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/internal/json_binding/data_type.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/internal/json_binding/data_type_test.cc
4f887a6430414cd6088e1743555015b10f116d50
dda443db-0507-43c0-b3f0-6587d86c0f40
cpp
google/tensorstore
spec
tensorstore/kvstore/spec.cc
tensorstore/driver/zarr/spec_test.cc
#include "tensorstore/kvstore/spec.h" #include <string> #include <string_view> #include <utility> #include "absl/status/status.h" #include <nlohmann/json.hpp> #include "tensorstore/context.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/kvstore/driver.h" #include "tensorstore/kvstore/registry.h" #include "tensorstore/serialization/fwd.h" #include "tensorstore/serialization/registry.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/util/garbage_collection/garbage_collection.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" using ::tensorstore::internal::IntrusivePtr; namespace tensorstore { namespace kvstore { void intrusive_ptr_increment(const DriverSpec* p) { intrusive_ptr_increment( static_cast<const internal::AtomicReferenceCount<DriverSpec>*>(p)); } void intrusive_ptr_decrement(const DriverSpec* p) { intrusive_ptr_decrement( static_cast<const internal::AtomicReferenceCount<DriverSpec>*>(p)); } DriverSpec::~DriverSpec() = default; absl::Status DriverSpec::NormalizeSpec(std::string& path) { return absl::OkStatus(); } Result<std::string> DriverSpec::ToUrl(std::string_view path) const { return absl::UnimplementedError("URL representation not supported"); } absl::Status DriverSpec::ApplyOptions(DriverSpecOptions&& options) { return absl::OkStatus(); } Result<Spec> DriverSpec::GetBase(std::string_view path) const { return {std::in_place}; } Result<Spec> Spec::base() const { return driver->GetBase(path); } ContextBindingState DriverSpecPtr::context_binding_state() const { return get()->context_binding_state_; } void EncodeCacheKeyAdl(std::string* out, const DriverSpecPtr& ptr) { return ptr->EncodeCacheKey(out); } TENSORSTORE_DEFINE_JSON_DEFAULT_BINDER(Spec, [](auto is_loading, const auto& options, auto* obj, auto* j) { if constexpr (is_loading) { if (auto* s = j->template get_ptr<const std::string*>()) { TENSORSTORE_ASSIGN_OR_RETURN(*obj, Spec::FromUrl(*s)); return absl::OkStatus(); } } else { if (!obj->valid()) { *j = ::nlohmann::json::value_t::discarded; return absl::OkStatus(); } } namespace jb = tensorstore::internal_json_binding; auto& registry = internal_kvstore::GetDriverRegistry(); return jb::NestedContextJsonBinder(jb::Object( jb::Member("driver", jb::Projection<&Spec::driver>(registry.KeyBinder())), jb::Initialize([](Spec* p) { const_cast<DriverSpec&>(*p->driver).context_binding_state_ = ContextBindingState::unbound; }), jb::Member("context", jb::Projection( [](const Spec& p) -> Context::Spec& { return const_cast<Context::Spec&>( p.driver->context_spec_); }, internal::ContextSpecDefaultableJsonBinder)), jb::Member("path", jb::Projection( [](auto& p) -> decltype(auto) { return (p.path); }, jb::DefaultInitializedValue())), [&](auto is_loading, const auto& options, auto* obj, auto* j) { if constexpr (is_loading) { TENSORSTORE_RETURN_IF_ERROR(registry.RegisteredObjectBinder()( is_loading, {options, obj->path}, &obj->driver, j)); return const_cast<DriverSpec&>(*obj->driver).NormalizeSpec(obj->path); } else { return registry.RegisteredObjectBinder()(is_loading, options, &obj->driver, j); } }))(is_loading, options, obj, j); }) absl::Status DriverSpecPtr::Set(DriverSpecOptions&& options) { if (options.minimal_spec) { if ((*this)->use_count() != 1) *this = (*this)->Clone(); TENSORSTORE_RETURN_IF_ERROR( const_cast<DriverSpec*>(get())->ApplyOptions(std::move(options))); } return absl::OkStatus(); } absl::Status DriverSpecPtr::Set(SpecConvertOptions&& options) { internal::ApplyContextBindingMode( *this, options.context_binding_mode, ContextBindingMode::retain); if (options.context) { TENSORSTORE_RETURN_IF_ERROR(BindContext(options.context)); } return Set(static_cast<DriverSpecOptions&&>(options)); } absl::Status DriverSpecPtr::BindContext(const Context& context) { return internal::BindContextCopyOnWriteWithNestedContext(*this, context); } absl::Status Spec::Set(SpecConvertOptions&& options) { return driver.Set(std::move(options)); } void DriverSpecPtr::UnbindContext( const internal::ContextSpecBuilder& context_builder) { internal::UnbindContextCopyOnWriteWithNestedContext(*this, context_builder); } void DriverSpecPtr::StripContext() { internal::StripContextCopyOnWriteWithNestedContext(*this); } absl::Status Spec::BindContext(const Context& context) { return driver.BindContext(context); } void Spec::UnbindContext(const internal::ContextSpecBuilder& context_builder) { driver.UnbindContext(context_builder); } void Spec::StripContext() { driver.StripContext(); } Result<std::string> Spec::ToUrl() const { if (!driver) { return absl::InvalidArgumentError("Invalid kvstore spec"); } return driver->ToUrl(path); } bool operator==(const Spec& a, const Spec& b) { if (!a.valid() || !b.valid()) { return a.valid() == b.valid(); } return internal::ContextBindableSpecsSameViaJson(a, b); } } namespace serialization { namespace { using DriverSpecPtrNonNullDirectSerializer = RegistrySerializer<internal::IntrusivePtr<const kvstore::DriverSpec>>; using DriverSpecPtrSerializer = IndirectPointerSerializer<internal::IntrusivePtr<const kvstore::DriverSpec>, DriverSpecPtrNonNullDirectSerializer>; using DriverSpecPtrNonNullSerializer = NonNullIndirectPointerSerializer< internal::IntrusivePtr<const kvstore::DriverSpec>, DriverSpecPtrNonNullDirectSerializer>; } } namespace internal_json_binding { TENSORSTORE_DEFINE_JSON_BINDER( KvStoreSpecAndPathJsonBinder, Sequence(Member("kvstore", DefaultInitializedPredicate([](auto* obj) { return !obj->valid(); })), LoadSave(OptionalMember( "path", Compose<std::string>([](auto is_loading, const auto& options, auto* obj, std::string* j) { if (!obj->valid()) { return absl::InvalidArgumentError( "\"path\" must be specified in conjunction with " "\"kvstore\""); } obj->AppendPathComponent(*j); return absl::OkStatus(); }))))) } } TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::kvstore::DriverSpecPtr, tensorstore::serialization::DriverSpecPtrSerializer()) TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::kvstore::Spec, tensorstore::serialization::ApplyMembersSerializer< tensorstore::kvstore::Spec>()) TENSORSTORE_DEFINE_GARBAGE_COLLECTION_SPECIALIZATION( tensorstore::kvstore::DriverSpec, tensorstore::garbage_collection::PolymorphicGarbageCollection< tensorstore::kvstore::DriverSpec>) TENSORSTORE_DEFINE_GARBAGE_COLLECTION_SPECIALIZATION( tensorstore::kvstore::Spec, tensorstore::garbage_collection::ApplyMembersGarbageCollection< tensorstore::kvstore::Spec>) TENSORSTORE_DEFINE_GARBAGE_COLLECTION_SPECIALIZATION( tensorstore::kvstore::DriverSpecPtr, tensorstore::garbage_collection::IndirectPointerGarbageCollection< tensorstore::kvstore::DriverSpecPtr>)
#include "tensorstore/driver/zarr/spec.h" #include <stdint.h> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <nlohmann/json.hpp> #include "tensorstore/codec_spec.h" #include "tensorstore/driver/zarr/metadata.h" #include "tensorstore/index_space/index_domain_builder.h" #include "tensorstore/internal/json_binding/gtest.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" namespace { using ::tensorstore::ChunkLayout; using ::tensorstore::CodecSpec; using ::tensorstore::dtype_v; using ::tensorstore::MatchesJson; using ::tensorstore::MatchesStatus; using ::tensorstore::Schema; using ::tensorstore::internal_zarr::GetFieldIndex; using ::tensorstore::internal_zarr::ParseDType; using ::tensorstore::internal_zarr::ParseSelectedField; using ::tensorstore::internal_zarr::SelectedField; using ::tensorstore::internal_zarr::ZarrMetadata; using ::tensorstore::internal_zarr::ZarrPartialMetadata; TEST(ParsePartialMetadataTest, InvalidZarrFormat) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"zarr_format", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"zarr_format\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidChunks) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"chunks", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"chunks\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidShape) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"shape", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"shape\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidCompressor) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"compressor", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"compressor\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidOrder) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"order", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"order\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidDType) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"dtype", "2"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"dtype\": .*")}, }); } TEST(ParsePartialMetadataTest, InvalidFilters) { tensorstore::TestJsonBinderFromJson<ZarrPartialMetadata>({ {{{"filters", "x"}}, MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"filters\": .*")}, }); } TEST(ParsePartialMetadataTest, Empty) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto result, ZarrPartialMetadata::FromJson(::nlohmann::json::object_t{})); EXPECT_EQ(std::nullopt, result.zarr_format); EXPECT_EQ(std::nullopt, result.order); EXPECT_EQ(std::nullopt, result.compressor); EXPECT_EQ(std::nullopt, result.filters); EXPECT_EQ(std::nullopt, result.dtype); EXPECT_EQ(std::nullopt, result.fill_value); EXPECT_EQ(std::nullopt, result.shape); EXPECT_EQ(std::nullopt, result.chunks); } ::nlohmann::json GetMetadataSpec() { return {{"zarr_format", 2}, {"chunks", {3, 2}}, {"shape", {100, 100}}, {"order", "C"}, {"filters", nullptr}, {"fill_value", nullptr}, {"dtype", "<i2"}, {"compressor", {{"id", "blosc"}, {"blocksize", 0}, {"clevel", 5}, {"cname", "lz4"}, {"shuffle", -1}}}}; } TEST(ParsePartialMetadataTest, Complete) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto result, ZarrPartialMetadata::FromJson(GetMetadataSpec())); EXPECT_EQ(2, result.zarr_format); EXPECT_EQ(tensorstore::c_order, result.order); ASSERT_TRUE(result.compressor); EXPECT_EQ((::nlohmann::json{{"id", "blosc"}, {"blocksize", 0}, {"clevel", 5}, {"cname", "lz4"}, {"shuffle", -1}}), ::nlohmann::json(*result.compressor)); ASSERT_TRUE(result.dtype); EXPECT_EQ("<i2", ::nlohmann::json(*result.dtype)); ASSERT_TRUE(result.fill_value); ASSERT_EQ(1, result.fill_value->size()); EXPECT_FALSE((*result.fill_value)[0].valid()); ASSERT_TRUE(result.shape); EXPECT_THAT(*result.shape, ::testing::ElementsAre(100, 100)); ASSERT_TRUE(result.chunks); EXPECT_THAT(*result.chunks, ::testing::ElementsAre(3, 2)); } TEST(ParseSelectedFieldTest, Null) { EXPECT_EQ(SelectedField(), ParseSelectedField(nullptr)); } TEST(ParseSelectedFieldTest, InvalidString) { EXPECT_THAT( ParseSelectedField(""), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected null or non-empty string, but received: \"\"")); } TEST(ParseSelectedFieldTest, String) { EXPECT_EQ(SelectedField("label"), ParseSelectedField("label")); } TEST(ParseSelectedFieldTest, InvalidType) { EXPECT_THAT( ParseSelectedField(true), MatchesStatus(absl::StatusCode::kInvalidArgument, "Expected null or non-empty string, but received: true")); } TEST(GetFieldIndexTest, Null) { EXPECT_EQ(0u, GetFieldIndex(ParseDType("<i4").value(), SelectedField())); EXPECT_THAT( GetFieldIndex( ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}) .value(), SelectedField()), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Must specify a \"field\" that is one of: \\[\"x\",\"y\"\\]")); } TEST(GetFieldIndexTest, String) { EXPECT_THAT( GetFieldIndex(ParseDType("<i4").value(), "x"), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Requested field \"x\" but dtype does not have named fields")); EXPECT_EQ(0u, GetFieldIndex(ParseDType(::nlohmann::json::array_t{ {"x", "<i4"}, {"y", "<u2"}}) .value(), "x")); EXPECT_EQ(1u, GetFieldIndex(ParseDType(::nlohmann::json::array_t{ {"x", "<i4"}, {"y", "<u2"}}) .value(), "y")); EXPECT_THAT( GetFieldIndex( ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}) .value(), "z"), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Requested field \"z\" is not one of: \\[\"x\",\"y\"\\]")); } TEST(EncodeSelectedFieldTest, NonEmpty) { auto dtype = ParseDType(::nlohmann::json::array_t{{"x", "<i4"}, {"y", "<u2"}}).value(); EXPECT_EQ("x", EncodeSelectedField(0, dtype)); EXPECT_EQ("y", EncodeSelectedField(1, dtype)); } TEST(EncodeSelectedFieldTest, Empty) { auto dtype = ParseDType("<i4").value(); EXPECT_EQ("", EncodeSelectedField(0, dtype)); } template <typename... Option> tensorstore::Result<::nlohmann::json> GetNewMetadataFromOptions( ::nlohmann::json partial_metadata_json, std::string selected_field, Option&&... option) { Schema schema; if (absl::Status status; !((status = schema.Set(std::forward<Option>(option))).ok() && ...)) { return status; } TENSORSTORE_ASSIGN_OR_RETURN( auto partial_metadata, ZarrPartialMetadata::FromJson(partial_metadata_json)); TENSORSTORE_ASSIGN_OR_RETURN( auto new_metadata, GetNewMetadata(partial_metadata, selected_field, schema)); return new_metadata->ToJson(); } TEST(GetNewMetadataTest, FullMetadata) { EXPECT_THAT(GetNewMetadataFromOptions({{"chunks", {8, 10}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"shape", {5, 6}}}, {}), ::testing::Optional(MatchesJson({ {"chunks", {8, 10}}, {"compressor", nullptr}, {"dtype", "<i4"}, {"fill_value", nullptr}, {"filters", nullptr}, {"order", "C"}, {"shape", {5, 6}}, {"zarr_format", 2}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, NoShape) { EXPECT_THAT( GetNewMetadataFromOptions( {{"chunks", {2, 3}}, {"dtype", "<i4"}, {"compressor", nullptr}}, {}), MatchesStatus(absl::StatusCode::kInvalidArgument, "domain must be specified")); } TEST(GetNewMetadataTest, AutomaticChunks) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"dtype", "<i4"}, {"compressor", nullptr}}, {}), ::testing::Optional(MatchesJson({ {"chunks", {2, 3}}, {"compressor", nullptr}, {"dtype", "<i4"}, {"fill_value", nullptr}, {"filters", nullptr}, {"order", "C"}, {"shape", {2, 3}}, {"zarr_format", 2}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, NoDtype) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"chunks", {2, 3}}, {"compressor", nullptr}}, {}), MatchesStatus(absl::StatusCode::kInvalidArgument, "\"dtype\" must be specified")); } TEST(GetNewMetadataTest, NoCompressor) { EXPECT_THAT(GetNewMetadataFromOptions( {{"shape", {2, 3}}, {"chunks", {2, 3}}, {"dtype", "<i4"}}, {}), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {2, 3}}, {"chunks", {2, 3}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, IntegerOverflow) { EXPECT_THAT( GetNewMetadataFromOptions( {{"shape", {4611686018427387903, 4611686018427387903}}, {"chunks", {4611686018427387903, 4611686018427387903}}, {"dtype", "<i4"}, {"compressor", nullptr}}, {}), MatchesStatus( absl::StatusCode::kInvalidArgument, "Product of chunk dimensions " "\\{4611686018427387903, 4611686018427387903\\} is too large")); } TEST(GetNewMetadataTest, SchemaDomainDtype) { EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), {}, tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value(), dtype_v<int32_t>), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {101, 101, 101}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDomainDtypeFillValue) { EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), {}, tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value(), dtype_v<int32_t>, Schema::FillValue{tensorstore::MakeScalarArray<int32_t>(5)}), ::testing::Optional(MatchesJson({ {"fill_value", 5}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {101, 101, 101}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaObjectWithDomainDtypeFillValue) { Schema schema; TENSORSTORE_ASSERT_OK(schema.Set(tensorstore::IndexDomainBuilder(3) .shape({1000, 2000, 3000}) .Finalize() .value())); TENSORSTORE_ASSERT_OK(schema.Set(dtype_v<int32_t>)); TENSORSTORE_ASSERT_OK( schema.Set(Schema::FillValue{tensorstore::MakeScalarArray<int32_t>(5)})); EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), {}, schema), ::testing::Optional(MatchesJson({ {"fill_value", 5}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {1000, 2000, 3000}}, {"chunks", {101, 101, 101}}, {"dtype", "<i4"}, {"compressor", { {"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}, }}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeShapeCodec) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), {}, Schema::Shape({100, 200}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderC) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), {}, Schema::Shape({100, 200}), ChunkLayout::InnerOrder({0, 1}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderFortran) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t(), {}, Schema::Shape({100, 200}), ChunkLayout::InnerOrder({1, 0}), dtype_v<int32_t>, codec), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "F"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderFortranFieldShape) { EXPECT_THAT(GetNewMetadataFromOptions( { {"compressor", nullptr}, {"dtype", {{"x", "<u4", {2, 3}}}}, }, "x", Schema::Shape({100, 200, 2, 3}), ChunkLayout::InnerOrder({1, 0, 2, 3})), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "F"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", {{"x", "<u4", {2, 3}}}}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderInvalid) { EXPECT_THAT( GetNewMetadataFromOptions( ::nlohmann::json::object_t(), {}, Schema::Shape({100, 200, 300}), ChunkLayout::InnerOrder({2, 0, 1}), dtype_v<int32_t>), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid \"inner_order\" constraint: \\{2, 0, 1\\}")); } TEST(GetNewMetadataTest, SchemaDtypeInnerOrderInvalidSoft) { EXPECT_THAT(GetNewMetadataFromOptions( {{"compressor", nullptr}}, {}, Schema::Shape({100, 200, 300}), ChunkLayout::InnerOrder({2, 0, 1}, false), dtype_v<int32_t>), ::testing::Optional(MatchesJson({ {"fill_value", nullptr}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200, 300}}, {"chunks", {100, 102, 102}}, {"dtype", "<i4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaStructuredDtypeInvalidFillValue) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", ::nlohmann::json::array_t{{"x", "<u4"}, {"y", "<i4"}}}}, "x", Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), MatchesStatus( absl::StatusCode::kInvalidArgument, "Invalid fill_value: Cannot specify fill_value through schema for " "structured zarr data type \\[.*")); } TEST(GetNewMetadataTest, SchemaFillValueMismatch) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", "<u4"}, {"fill_value", 42}}, {}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(43))), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid fill_value: .*")); } TEST(GetNewMetadataTest, SchemaFillValueMismatchNull) { EXPECT_THAT( GetNewMetadataFromOptions( {{"dtype", "<u4"}, {"fill_value", nullptr}}, {}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid fill_value: .*")); } TEST(GetNewMetadataTest, SchemaFillValueRedundant) { EXPECT_THAT( GetNewMetadataFromOptions( { {"dtype", "<u4"}, {"fill_value", 42}, {"compressor", nullptr}, }, {}, Schema::Shape({100, 200}), Schema::FillValue(tensorstore::MakeScalarArray<uint32_t>(42))), ::testing::Optional(MatchesJson({ {"fill_value", 42}, {"filters", nullptr}, {"zarr_format", 2}, {"order", "C"}, {"shape", {100, 200}}, {"chunks", {100, 200}}, {"dtype", "<u4"}, {"compressor", nullptr}, {"dimension_separator", "."}, }))); } TEST(GetNewMetadataTest, SchemaCodecChunkShape) { EXPECT_THAT(GetNewMetadataFromOptions( ::nlohmann::json::object_t{}, {}, Schema::Shape({100, 200}), dtype_v<uint32_t>, ChunkLayout::CodecChunkShape({5, 6})), MatchesStatus(absl::StatusCode::kInvalidArgument, "codec_chunk_shape not supported")); } TEST(GetNewMetadataTest, CodecMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec, CodecSpec::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); EXPECT_THAT( GetNewMetadataFromOptions({{"compressor", {{"id", "blosc"}}}}, {}, Schema::Shape({100, 200}), dtype_v<int32_t>, codec), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot merge codec spec .* with .*: \"compressor\" does not match")); } TEST(GetNewMetadataTest, SelectedFieldDtypeNotSpecified) { EXPECT_THAT( GetNewMetadataFromOptions(::nlohmann::json::object_t(), "x", Schema::Shape({100, 200}), dtype_v<int32_t>), MatchesStatus(absl::StatusCode::kInvalidArgument, "\"dtype\" must be specified in \"metadata\" if " "\"field\" is specified")); } TEST(GetNewMetadataTest, SelectedFieldInvalid) { EXPECT_THAT( GetNewMetadataFromOptions({{"dtype", {{"x", "<u4", {2}}, {"y", "<i4"}}}}, "z", Schema::Shape({100, 200})), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Requested field \"z\" is not one of: \\[\"x\",\"y\"\\]")); } TEST(GetNewMetadataTest, InvalidDtype) { EXPECT_THAT(GetNewMetadataFromOptions(::nlohmann::json::object_t(), {}, dtype_v<tensorstore::dtypes::json_t>, Schema::Shape({100, 200})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Data type not supported: json")); } TEST(GetNewMetadataTest, InvalidDomain) { EXPECT_THAT( GetNewMetadataFromOptions(::nlohmann::json::object_t(), {}, dtype_v<int32_t>, tensorstore::IndexDomainBuilder(2) .origin({1, 2}) .shape({100, 200}) .Finalize() .value()), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid domain: .*")); } TEST(GetNewMetadataTest, DomainIncompatibleWithFieldShape) { EXPECT_THAT( GetNewMetadataFromOptions({{"dtype", {{"x", "<u4", {2, 3}}}}}, "x", Schema::Shape({100, 200, 2, 4})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Invalid domain: .*")); } TEST(GetNewMetadataTest, DomainIncompatibleWithMetadataRank) { EXPECT_THAT( GetNewMetadataFromOptions({{"chunks", {100, 100}}}, {}, dtype_v<int32_t>, Schema::Shape({100, 200, 300})), MatchesStatus( absl::StatusCode::kInvalidArgument, "Rank specified by schema \\(3\\) is not compatible with metadata")); } TEST(ValidateMetadataTest, Success) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto partial_metadata, ZarrPartialMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_EXPECT_OK(ValidateMetadata(metadata, partial_metadata)); } TEST(ValidateMetadataTest, Unconstrained) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto partial_metadata, ZarrPartialMetadata::FromJson(::nlohmann::json::object_t{})); TENSORSTORE_EXPECT_OK(ValidateMetadata(metadata, partial_metadata)); } TEST(ValidateMetadataTest, ShapeMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["shape"] = {7, 8}; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT( ValidateMetadata(metadata, partial_metadata), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Expected \"shape\" of \\[7,8\\] but received: \\[100,100\\]")); } TEST(ValidateMetadataTest, ChunksMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["chunks"] = {1, 1}; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus( absl::StatusCode::kFailedPrecondition, "Expected \"chunks\" of \\[1,1\\] but received: \\[3,2\\]")); } TEST(ValidateMetadataTest, OrderMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["order"] = "F"; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"order\" of \"F\" but received: \"C\"")); } TEST(ValidateMetadataTest, CompressorMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["compressor"] = nullptr; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"compressor\" of null but received: " "\\{\"blocksize\":0,\"clevel\":5,\"cname\":\"lz4\"," "\"id\":\"blosc\",\"shuffle\":-1\\}")); } TEST(ValidateMetadataTest, DTypeMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["dtype"] = ">i4"; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT( ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"dtype\" of \">i4\" but received: \"<i2\"")); } TEST(ValidateMetadataTest, FillValueMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto metadata, ZarrMetadata::FromJson(GetMetadataSpec())); ::nlohmann::json spec = GetMetadataSpec(); spec["fill_value"] = 1; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto partial_metadata, ZarrPartialMetadata::FromJson(spec)); EXPECT_THAT(ValidateMetadata(metadata, partial_metadata), MatchesStatus(absl::StatusCode::kFailedPrecondition, "Expected \"fill_value\" of 1 but received: null")); } TEST(ZarrCodecSpecTest, Merge) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto codec1, CodecSpec::FromJson({{"driver", "zarr"}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec2, CodecSpec::FromJson({{"driver", "zarr"}, {"filters", nullptr}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec3, CodecSpec::FromJson({{"driver", "zarr"}, {"compressor", nullptr}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec4, CodecSpec::FromJson({{"driver", "zarr"}, {"compressor", {{"id", "blosc"}}}})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto codec5, CodecSpec::FromJson( {{"driver", "zarr"}, {"compressor", nullptr}, {"filters", nullptr}})); EXPECT_THAT(CodecSpec::Merge(codec1, codec1), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(codec3, codec3), ::testing::Optional(codec3)); EXPECT_THAT(CodecSpec::Merge(codec1, CodecSpec()), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(CodecSpec(), codec1), ::testing::Optional(codec1)); EXPECT_THAT(CodecSpec::Merge(CodecSpec(), CodecSpec()), ::testing::Optional(CodecSpec())); EXPECT_THAT(CodecSpec::Merge(codec1, codec2), ::testing::Optional(codec2)); EXPECT_THAT(CodecSpec::Merge(codec1, codec3), ::testing::Optional(codec3)); EXPECT_THAT(CodecSpec::Merge(codec2, codec3), ::testing::Optional(codec5)); EXPECT_THAT( CodecSpec::Merge(codec3, codec4), MatchesStatus( absl::StatusCode::kInvalidArgument, "Cannot merge codec spec .* with .*: \"compressor\" does not match")); } TEST(ZarrCodecSpecTest, RoundTrip) { tensorstore::TestJsonBinderRoundTripJsonOnly<tensorstore::CodecSpec>({ ::nlohmann::json::value_t::discarded, { {"driver", "zarr"}, {"compressor", nullptr}, {"filters", nullptr}, }, { {"driver", "zarr"}, {"compressor", {{"id", "blosc"}, {"cname", "lz4"}, {"clevel", 5}, {"blocksize", 0}, {"shuffle", -1}}}, {"filters", nullptr}, }, }); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/kvstore/spec.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/driver/zarr/spec_test.cc
4f887a6430414cd6088e1743555015b10f116d50
cfb1aa9b-3c0d-4dc7-a715-a854d74496a6
cpp
google/tensorstore
chunk_layout
tensorstore/chunk_layout.cc
tensorstore/chunk_layout_test.cc
#include "tensorstore/chunk_layout.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <atomic> #include <cassert> #include <cstdlib> #include <cstring> #include <limits> #include <memory> #include <ostream> #include <string_view> #include <type_traits> #include <utility> #include "absl/base/optimization.h" #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include "tensorstore/box.h" #include "tensorstore/index.h" #include "tensorstore/index_interval.h" #include "tensorstore/index_space/dimension_permutation.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/json.h" #include "tensorstore/index_space/output_index_method.h" #include "tensorstore/internal/integer_overflow.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/dimension_indexed.h" #include "tensorstore/internal/json_binding/enum.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/json_serialization_options_base.h" #include "tensorstore/rank.h" #include "tensorstore/serialization/fwd.h" #include "tensorstore/serialization/json_bindable.h" #include "tensorstore/util/dimension_set.h" #include "tensorstore/util/division.h" #include "tensorstore/util/maybe_hard_constraint.h" #include "tensorstore/util/result.h" #include "tensorstore/util/small_bit_set.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace { using Usage = ChunkLayout::Usage; using Storage = ChunkLayout::Storage; using StoragePtr = ChunkLayout::StoragePtr; constexpr auto kNumUsages = ChunkLayout::kNumUsages; namespace jb = tensorstore::internal_json_binding; enum class HardConstraintBit { inner_order, write_chunk_elements, read_chunk_elements, codec_chunk_elements, }; struct OriginValueTraits { using Element = Index; constexpr static Index kDefaultValue = kImplicit; constexpr static bool IsSoftConstraintValue(Index value) { return false; } constexpr static bool IsValid(Index x) { return x == kImplicit || IsFiniteIndex(x); } static Result<Index> TransformInputValue(Index value, Index offset, Index stride) { if (stride < 0) value = value - 1; Index new_value; if (internal::MulOverflow(stride, value, &new_value) || internal::AddOverflow(new_value, offset, &new_value) || !IsFiniteIndex(new_value)) { return absl::OutOfRangeError(tensorstore::StrCat( "Integer overflow transforming input origin ", value, " by offset ", offset, " and stride ", stride)); } return new_value; } static Result<Index> TransformOutputValue(Index value, Index offset, Index stride) { Index new_value; if (internal::SubOverflow(value, offset, &new_value) || !IsFiniteIndex(new_value)) { return absl::OutOfRangeError(tensorstore::StrCat( "Integer overflow transforming output origin ", value, " by offset ", offset, " and stride ", stride)); } new_value = CeilOfRatio(((stride > 0) ? new_value : new_value - 1), stride); return new_value; } }; struct ShapeValueTraits { using Element = Index; constexpr static Index kDefaultValue = ChunkLayout::kDefaultShapeValue; constexpr static bool IsSoftConstraintValue(Index value) { return value == -1; } constexpr static bool IsValid(Index x) { return x == -1 || x >= 0; } static Result<Index> TransformInputValue(Index value, Index offset, Index stride) { Index new_value; if (stride == std::numeric_limits<Index>::min() || internal::MulOverflow(std::abs(stride), value, &new_value)) { return absl::OutOfRangeError(tensorstore::StrCat( "Integer overflow computing abs(", stride, ") * ", value)); } return new_value; } static Result<Index> TransformOutputValue(Index value, Index offset, Index stride) { assert(stride != 0); const Index gcd = tensorstore::GreatestCommonDivisor(stride, value); return value / gcd; } }; struct AspectRatioValueTraits { using Element = double; constexpr static double kDefaultValue = ChunkLayout::kDefaultAspectRatioValue; constexpr static bool IsSoftConstraintValue(double value) { return false; } constexpr static bool IsValid(double x) { return x >= 0; } static Result<double> TransformInputValue(double value, Index offset, Index stride) { return value * std::abs(static_cast<double>(stride)); } static Result<double> TransformOutputValue(double value, Index offset, Index stride) { return value / std::abs(static_cast<double>(stride)); } }; struct ChunkLayoutData { int8_t rank_; SmallBitSet<8> hard_constraint_ = false; DimensionSet grid_origin_hard_constraint_; DimensionSet chunk_shape_hard_constraint_[kNumUsages]; DimensionSet chunk_aspect_ratio_hard_constraint_[kNumUsages]; Index chunk_elements_[kNumUsages] = {kImplicit, kImplicit, kImplicit}; }; bool IsHardConstraint(const ChunkLayoutData& impl, HardConstraintBit bit) { return impl.hard_constraint_[static_cast<int>(bit)]; } void SetHardConstraintBit(ChunkLayoutData& impl, HardConstraintBit bit) { impl.hard_constraint_[static_cast<int>(bit)] = true; } } struct ChunkLayout::Storage : public ChunkLayoutData { explicit Storage(DimensionIndex rank) : ChunkLayoutData{static_cast<int8_t>(rank)} { Initialize(); } Storage(const Storage& other) : ChunkLayoutData(other) { std::memcpy(static_cast<void*>(this + 1), static_cast<const void*>(&other + 1), TotalBytesAfterHeader( std::max(DimensionIndex(0), DimensionIndex(rank_)))); } Storage(const Storage& other, DimensionIndex new_rank) : ChunkLayoutData(other) { rank_ = new_rank; Initialize(); } void Initialize() { if (DimensionIndex rank = rank_; rank > 0) { std::fill_n(this->grid_origin(), NumOriginElements(rank), OriginValueTraits::kDefaultValue); std::fill_n(this->chunk_shapes(), NumShapeElements(rank), ShapeValueTraits::kDefaultValue); std::fill_n(this->chunk_aspect_ratios(), NumAspectRatioElements(rank), AspectRatioValueTraits::kDefaultValue); std::fill_n(this->inner_order(), NumInnerOrderElements(rank), static_cast<DimensionIndex>(-1)); } } constexpr static size_t NumOriginElements(DimensionIndex rank) { return rank; } constexpr static size_t NumShapeElements(DimensionIndex rank) { return kNumUsages * rank; } constexpr static size_t NumAspectRatioElements(DimensionIndex rank) { return kNumUsages * rank; } constexpr static size_t NumInnerOrderElements(DimensionIndex rank) { return rank; } constexpr static size_t TotalBytesAfterHeader(DimensionIndex rank) { return sizeof(Index) * NumOriginElements(rank) + sizeof(Index) * NumShapeElements(rank) + sizeof(double) * NumAspectRatioElements(rank) + sizeof(DimensionIndex) * NumInnerOrderElements(rank); } Index* grid_origin() { return reinterpret_cast<Index*>(this + 1); } Index* chunk_shapes() { return grid_origin() + rank_; } tensorstore::span<Index> chunk_shape(size_t usage_index) { return {chunk_shapes() + rank_ * usage_index, rank_}; } double* chunk_aspect_ratios() { return reinterpret_cast<double*>(chunk_shapes() + NumShapeElements(rank_)); } tensorstore::span<double> chunk_aspect_ratio(size_t usage_index) { return {chunk_aspect_ratios() + rank_ * usage_index, rank_}; } DimensionIndex* inner_order() { return reinterpret_cast<DimensionIndex*>(chunk_aspect_ratios() + NumAspectRatioElements(rank_)); } static StoragePtr Allocate(DimensionIndex rank) { rank = std::max(rank, DimensionIndex(0)); assert(rank < kMaxRank); const size_t total_bytes = sizeof(Storage) + TotalBytesAfterHeader(rank); StoragePtr ptr(static_cast<Storage*>(std::malloc(total_bytes)), internal::adopt_object_ref); return ptr; } static Storage& EnsureUnique(StoragePtr& ptr, DimensionIndex rank, StoragePtr& storage_to_be_destroyed) { if (!ptr) { ptr = Allocate(rank); new (ptr.get()) Storage(rank); } else if (ptr->ref_count_.load(std::memory_order_acquire) != 1) { auto new_ptr = Allocate(ptr->rank_); new (new_ptr.get()) Storage(*ptr); storage_to_be_destroyed = std::move(ptr); ptr = std::move(new_ptr); } return *ptr; } std::atomic<size_t> ref_count_{1}; }; void intrusive_ptr_increment(Storage* p) { p->ref_count_.fetch_add(1, std::memory_order_acq_rel); } void intrusive_ptr_decrement(Storage* p) { if (p->ref_count_.fetch_sub(1, std::memory_order_acq_rel) == 1) { std::free(p); } } namespace { void ClearHardConstraintBits(Storage& impl) { impl.hard_constraint_ = false; impl.grid_origin_hard_constraint_ = false; for (int i = 0; i < kNumUsages; ++i) { impl.chunk_shape_hard_constraint_[i] = false; impl.chunk_aspect_ratio_hard_constraint_[i] = false; } } bool HasAnyHardConstraints(const Storage& impl) { if (IsHardConstraint(impl, HardConstraintBit::inner_order)) return true; if (impl.grid_origin_hard_constraint_) return true; for (int i = 0; i < kNumUsages; ++i) { if (impl.chunk_shape_hard_constraint_[i]) return true; } return false; } absl::Status RankMismatchError(DimensionIndex new_rank, DimensionIndex existing_rank) { return absl::InvalidArgumentError(tensorstore::StrCat( "Rank ", new_rank, " does not match existing rank ", existing_rank)); } absl::Status EnsureRank(StoragePtr& ptr, DimensionIndex rank, StoragePtr& storage_to_be_destroyed) { TENSORSTORE_RETURN_IF_ERROR(tensorstore::ValidateRank(rank)); if (!ptr || ptr->rank_ == rank) { Storage::EnsureUnique(ptr, rank, storage_to_be_destroyed); return absl::OkStatus(); } if (ptr->rank_ == dynamic_rank) { auto new_ptr = Storage::Allocate(rank); new (new_ptr.get()) Storage(*ptr, rank); storage_to_be_destroyed = std::move(ptr); ptr = std::move(new_ptr); return absl::OkStatus(); } return RankMismatchError(rank, ptr->rank_); } template <typename T, typename U> absl::Status MismatchError(const T& existing_value, const U& new_value) { return absl::InvalidArgumentError(tensorstore::StrCat( "New hard constraint (", new_value, ") does not match existing hard constraint (", existing_value, ")")); } template <typename Traits> absl::Status MergeVectorInto( MaybeHardConstraintSpan<typename Traits::Element> in_vector, typename Traits::Element* out_vector, DimensionSet& out_hard_constraint) { using Element = typename Traits::Element; DimensionIndex rank = in_vector.size(); if (DimensionSet dims_to_check = in_vector.hard_constraint & out_hard_constraint; dims_to_check) { for (DimensionIndex i = 0; i < rank; ++i) { if (!dims_to_check[i]) continue; Element x = in_vector[i]; if (x != Traits::kDefaultValue && out_vector[i] != x) { return absl::InvalidArgumentError(tensorstore::StrCat( "New hard constraint (", x, ") for dimension ", i, " does not match existing hard constraint (", out_vector[i], ")")); } } } for (DimensionIndex i = 0; i < rank; ++i) { Element x = in_vector[i]; if (x == Traits::kDefaultValue) continue; const bool in_hard_constraint_value = in_vector.hard_constraint[i]; if (in_hard_constraint_value || out_vector[i] == Traits::kDefaultValue) { out_vector[i] = x; out_hard_constraint[i] = out_hard_constraint[i] || in_hard_constraint_value; } } return absl::OkStatus(); } template <typename Traits> absl::Status ValidateAndMergeVectorInto( MaybeHardConstraintSpan<typename Traits::Element> in_vector, typename Traits::Element* out_vector, DimensionSet& out_hard_constraint) { using Element = typename Traits::Element; DimensionIndex rank = in_vector.size(); if (rank == 0) return absl::OkStatus(); for (DimensionIndex i = 0; i < in_vector.size(); ++i) { const Element value = in_vector[i]; if (!Traits::IsValid(value)) { return absl::InvalidArgumentError(tensorstore::StrCat( "Invalid value for dimension ", i, ": ", in_vector)); } if (Traits::IsSoftConstraintValue(value)) { in_vector.hard_constraint[i] = false; } } return MergeVectorInto<Traits>(in_vector, out_vector, out_hard_constraint); } ChunkLayout::ChunkShapeBase GetChunkShape(const ChunkLayout& self, Usage usage) { auto* storage = self.storage_.get(); if (!storage || storage->rank_ <= 0) { return ChunkLayout::ChunkShapeBase(); } const size_t usage_index = static_cast<size_t>(usage); return ChunkLayout::ChunkShapeBase( storage->chunk_shape(usage_index), storage->chunk_shape_hard_constraint_[usage_index]); } ChunkLayout::ChunkAspectRatioBase GetChunkAspectRatio(const ChunkLayout& self, Usage usage) { auto* storage = self.storage_.get(); if (!storage || storage->rank_ <= 0) { return ChunkLayout::ChunkAspectRatioBase(); } const size_t usage_index = static_cast<size_t>(usage); return ChunkLayout::ChunkAspectRatioBase( storage->chunk_aspect_ratio(usage_index), storage->chunk_aspect_ratio_hard_constraint_[usage_index]); } constexpr inline HardConstraintBit GetChunkElementsHardConstraintBit( Usage usage) { return static_cast<HardConstraintBit>( static_cast<int>(HardConstraintBit::write_chunk_elements) + static_cast<int>(usage)); } ChunkLayout::ChunkElementsBase GetChunkElements(const ChunkLayout& self, Usage usage) { auto* storage = self.storage_.get(); if (!storage) return ChunkLayout::ChunkElementsBase(); const size_t usage_index = static_cast<size_t>(usage); return ChunkLayout::ChunkElementsBase( storage->chunk_elements_[usage_index], IsHardConstraint(*storage, GetChunkElementsHardConstraintBit(usage))); } ChunkLayout::GridView GetGridConstraints(const ChunkLayout& self, Usage usage) { return ChunkLayout::GridView(GetChunkShape(self, usage), GetChunkAspectRatio(self, usage), GetChunkElements(self, usage)); } absl::Status SetInnerOrderInternal(ChunkLayout& self, ChunkLayout::InnerOrder value, StoragePtr& storage_to_be_destroyed) { if (!IsValidPermutation(value)) { return absl::InvalidArgumentError( tensorstore::StrCat("Invalid permutation: ", value)); } const DimensionIndex rank = value.size(); TENSORSTORE_RETURN_IF_ERROR( EnsureRank(self.storage_, rank, storage_to_be_destroyed)); auto& impl = *self.storage_; DimensionIndex* inner_order = impl.inner_order(); if (inner_order[0] != -1) { if (!value.hard_constraint) return absl::OkStatus(); if (IsHardConstraint(impl, HardConstraintBit::inner_order)) { if (!std::equal(value.data(), value.data() + rank, inner_order)) { return MismatchError( tensorstore::span<const DimensionIndex>(inner_order, rank), tensorstore::span<const DimensionIndex>(value)); } return absl::OkStatus(); } } std::copy_n(value.begin(), rank, inner_order); if (value.hard_constraint) { SetHardConstraintBit(impl, HardConstraintBit::inner_order); } return absl::OkStatus(); } absl::Status SetGridOriginInternal(ChunkLayout& self, MaybeHardConstraintSpan<Index> value, StoragePtr& storage_to_be_destroyed) { const DimensionIndex rank = value.size(); TENSORSTORE_RETURN_IF_ERROR( EnsureRank(self.storage_, rank, storage_to_be_destroyed)); return ValidateAndMergeVectorInto<OriginValueTraits>( value, self.storage_->grid_origin(), self.storage_->grid_origin_hard_constraint_); } absl::Status SetChunkShapeInternal(ChunkLayout& self, MaybeHardConstraintSpan<Index> value, Usage usage, StoragePtr& storage_to_be_destroyed) { const size_t usage_index = static_cast<size_t>(usage); const DimensionIndex rank = value.size(); TENSORSTORE_RETURN_IF_ERROR( EnsureRank(self.storage_, rank, storage_to_be_destroyed)); return ValidateAndMergeVectorInto<ShapeValueTraits>( value, self.storage_->chunk_shape(usage_index).data(), self.storage_->chunk_shape_hard_constraint_[usage_index]); } absl::Status SetChunkShape(ChunkLayout& self, MaybeHardConstraintSpan<Index> value, Usage usage, StoragePtr& storage_to_be_destroyed) { TENSORSTORE_RETURN_IF_ERROR( SetChunkShapeInternal(self, value, usage, storage_to_be_destroyed), tensorstore::MaybeAnnotateStatus( _, tensorstore::StrCat("Error setting ", usage, "_chunk shape"))); return absl::OkStatus(); } absl::Status SetChunkAspectRatioInternal(ChunkLayout& self, MaybeHardConstraintSpan<double> value, Usage usage, StoragePtr& storage_to_be_destroyed) { const size_t usage_index = static_cast<size_t>(usage); const DimensionIndex rank = value.size(); TENSORSTORE_RETURN_IF_ERROR( EnsureRank(self.storage_, rank, storage_to_be_destroyed)); return ValidateAndMergeVectorInto<AspectRatioValueTraits>( value, self.storage_->chunk_aspect_ratio(usage_index).data(), self.storage_->chunk_aspect_ratio_hard_constraint_[usage_index]); } absl::Status SetChunkAspectRatio(ChunkLayout& self, MaybeHardConstraintSpan<double> value, Usage usage, StoragePtr& storage_to_be_destroyed) { TENSORSTORE_RETURN_IF_ERROR( SetChunkAspectRatioInternal(self, value, usage, storage_to_be_destroyed), tensorstore::MaybeAnnotateStatus( _, tensorstore::StrCat("Error setting ", usage, "_chunk aspect_ratio"))); return absl::OkStatus(); } template <typename HardConstraintRef> absl::Status SetChunkElementsInternal(Index& elements, HardConstraintRef is_hard_constraint, ChunkLayout::ChunkElementsBase value) { if (value.valid()) { if (value < 0) { return absl::InvalidArgumentError( tensorstore::StrCat("Invalid value: ", value.value)); } if (elements != kImplicit) { if (!value.hard_constraint) return absl::OkStatus(); if (is_hard_constraint && elements != value.value) { return MismatchError(elements, value.value); } } elements = value.value; if (value.hard_constraint) { is_hard_constraint = true; } } return absl::OkStatus(); } absl::Status SetChunkElementsInternal(ChunkLayout& self, ChunkLayout::ChunkElementsBase value, Usage usage, StoragePtr& storage_to_be_destroyed) { if (!value.valid()) return absl::OkStatus(); auto& impl = Storage::EnsureUnique(self.storage_, dynamic_rank, storage_to_be_destroyed); return SetChunkElementsInternal( impl.chunk_elements_[static_cast<size_t>(usage)], impl.hard_constraint_[static_cast<size_t>( GetChunkElementsHardConstraintBit(usage))], value); } absl::Status SetChunkElements(ChunkLayout& self, ChunkLayout::ChunkElementsBase value, Usage usage, StoragePtr& storage_to_be_destroyed) { TENSORSTORE_RETURN_IF_ERROR( SetChunkElementsInternal(self, value, usage, storage_to_be_destroyed), tensorstore::MaybeAnnotateStatus( _, tensorstore::StrCat("Error setting ", usage, "_chunk elements"))); return absl::OkStatus(); } absl::Status SetGridConstraints(ChunkLayout& self, const ChunkLayout::GridView& value, Usage usage, StoragePtr& storage_to_be_destroyed) { if (value.shape().valid()) { TENSORSTORE_RETURN_IF_ERROR( SetChunkShape(self, value.shape(), usage, storage_to_be_destroyed)); } if (value.aspect_ratio().valid()) { TENSORSTORE_RETURN_IF_ERROR(SetChunkAspectRatio( self, value.aspect_ratio(), usage, storage_to_be_destroyed)); } if (value.elements().valid()) { TENSORSTORE_RETURN_IF_ERROR(SetChunkElements(self, value.elements(), usage, storage_to_be_destroyed)); } return absl::OkStatus(); } absl::Status SetChunkLayout(ChunkLayout& self, ChunkLayout other, bool hard_constraint) { if (!other.storage_) return absl::OkStatus(); if (!self.storage_) { self.storage_ = std::move(other.storage_); if (!hard_constraint) { StoragePtr storage_to_be_destroyed; ClearHardConstraintBits(Storage::EnsureUnique( self.storage_, self.storage_->rank_, storage_to_be_destroyed)); } return absl::OkStatus(); } { auto inner_order = other.inner_order(); if (!hard_constraint) inner_order.hard_constraint = false; TENSORSTORE_RETURN_IF_ERROR(self.Set(inner_order)); } { auto grid_origin = other.grid_origin(); if (!hard_constraint) grid_origin.hard_constraint = false; TENSORSTORE_RETURN_IF_ERROR(self.Set(grid_origin)); } StoragePtr storage_to_be_destroyed; for (Usage usage : ChunkLayout::kUsages) { TENSORSTORE_RETURN_IF_ERROR(SetGridConstraints( self, ChunkLayout::GridView(GetGridConstraints(other, usage), hard_constraint), usage, storage_to_be_destroyed)); } return absl::OkStatus(); } } DimensionIndex ChunkLayout::rank() const { if (storage_) return storage_->rank_; return dynamic_rank; } bool ChunkLayout::HasHardConstraints() const { if (!storage_) return false; return HasAnyHardConstraints(*storage_); } absl::Status ChunkLayout::Set(RankConstraint value) { if (value.rank == dynamic_rank) return absl::OkStatus(); StoragePtr storage_to_be_destroyed; return EnsureRank(storage_, value.rank, storage_to_be_destroyed); } ChunkLayout::InnerOrder ChunkLayout::inner_order() const { if (storage_) { const DimensionIndex rank = storage_->rank_; if (rank > 0) { const DimensionIndex* inner_order = storage_->inner_order(); if (inner_order[0] != -1) { return InnerOrder( tensorstore::span(inner_order, rank), IsHardConstraint(*storage_, HardConstraintBit::inner_order)); } } } return InnerOrder(); } absl::Status ChunkLayout::Set(InnerOrder value) { if (!value.valid()) return absl::OkStatus(); StoragePtr storage_to_be_destroyed; TENSORSTORE_RETURN_IF_ERROR( SetInnerOrderInternal(*this, value, storage_to_be_destroyed), tensorstore::MaybeAnnotateStatus(_, "Error setting inner_order")); return absl::OkStatus(); } ChunkLayout::GridOrigin ChunkLayout::grid_origin() const { if (storage_) { const DimensionIndex rank = storage_->rank_; if (rank > 0) { return GridOrigin(tensorstore::span<const Index>(storage_->grid_origin(), storage_->rank_), storage_->grid_origin_hard_constraint_); } } return GridOrigin(); } absl::Status ChunkLayout::Set(GridOrigin value) { if (!value.valid()) return absl::OkStatus(); StoragePtr storage_to_be_destroyed; TENSORSTORE_RETURN_IF_ERROR( SetGridOriginInternal(*this, value, storage_to_be_destroyed), tensorstore::MaybeAnnotateStatus(_, "Error setting grid_origin")); return absl::OkStatus(); } #define TENSORSTORE_INTERNAL_DO_DEFINE_FOR_USAGE(NAME, USAGE) \ template <> \ absl::Status ChunkLayout::Set<USAGE>(const GridViewFor<USAGE>& value) { \ StoragePtr storage_to_be_destroyed; \ return SetGridConstraints(*this, value, USAGE, storage_to_be_destroyed); \ } \ ChunkLayout::GridViewFor<USAGE> ChunkLayout::NAME##_chunk() const { \ return ChunkLayout::GridViewFor<USAGE>(GetGridConstraints(*this, USAGE)); \ } \ ChunkLayout::ChunkShapeFor<USAGE> ChunkLayout::NAME##_chunk_shape() const { \ return ChunkLayout::ChunkShapeFor<USAGE>(GetChunkShape(*this, USAGE)); \ } \ ChunkLayout::ChunkAspectRatioFor<USAGE> \ ChunkLayout::NAME##_chunk_aspect_ratio() const { \ return ChunkLayout::ChunkAspectRatioFor<USAGE>( \ GetChunkAspectRatio(*this, USAGE)); \ } \ ChunkLayout::ChunkElementsFor<USAGE> ChunkLayout::NAME##_chunk_elements() \ const { \ return ChunkLayout::ChunkElementsFor<USAGE>( \ GetChunkElements(*this, USAGE)); \ } \ TENSORSTORE_INTERNAL_DO_DEFINE_FOR_USAGE(write, Usage::kWrite) TENSORSTORE_INTERNAL_DO_DEFINE_FOR_USAGE(read, Usage::kRead) TENSORSTORE_INTERNAL_DO_DEFINE_FOR_USAGE(codec, Usage::kCodec) #undef TENSORSTORE_INTERNAL_DO_DEFINE_FOR_USAGE template <> absl::Status ChunkLayout::Set<ChunkLayout::kUnspecifiedUsage>( const GridViewFor<ChunkLayout::kUnspecifiedUsage>& value) { StoragePtr storage_to_be_destroyed; if (value.usage() == kUnspecifiedUsage) { TENSORSTORE_RETURN_IF_ERROR(SetGridConstraints(*this, value, Usage::kWrite, storage_to_be_destroyed)); TENSORSTORE_RETURN_IF_ERROR(SetGridConstraints(*this, value, Usage::kRead, storage_to_be_destroyed)); TENSORSTORE_RETURN_IF_ERROR( SetGridConstraints(*this, CodecChunk(value.aspect_ratio()), Usage::kCodec, storage_to_be_destroyed)); return absl::OkStatus(); } return SetGridConstraints(*this, value, value.usage(), storage_to_be_destroyed); } ChunkLayout::GridView ChunkLayout::operator[](Usage usage) const { assert(usage != kUnspecifiedUsage); return GetGridConstraints(*this, usage); } ChunkLayout::ChunkLayout(ChunkLayout layout, bool hard_constraint) { storage_ = std::move(layout.storage_); if (!hard_constraint && storage_) { StoragePtr storage_to_be_destroyed; ClearHardConstraintBits(Storage::EnsureUnique(storage_, storage_->rank_, storage_to_be_destroyed)); } } absl::Status ChunkLayout::Set(ChunkLayout value) { return SetChunkLayout(*this, value, true); } namespace { template <typename BaseBinder> constexpr auto HardSoftMemberPairJsonBinder(const char* name, const char* soft_constraint_name, BaseBinder base_binder) { return jb::Sequence( jb::Member(name, base_binder(true)), jb::Member(soft_constraint_name, base_binder(false))); } template <typename ElementBinder> constexpr auto DimensionIndexedFixedArrayJsonBinder( DimensionIndex& rank, ElementBinder element_binder) { return jb::DimensionIndexedVector( &rank, [](auto& x) -> size_t { ABSL_UNREACHABLE(); }, [](auto& x, size_t n) { return absl::OkStatus(); }, [](auto& x, size_t i) -> decltype(auto) { return (&x)[i]; }, element_binder); } template <typename Traits> bool VectorIsDefault(tensorstore::span<const typename Traits::Element> vec) { return std::all_of(vec.begin(), vec.end(), [](typename Traits::Element x) { return x == Traits::kDefaultValue; }); } bool GridConstraintsUnset(const ChunkLayout& self, Usage usage) { return VectorIsDefault<ShapeValueTraits>(GetChunkShape(self, usage)) && VectorIsDefault<AspectRatioValueTraits>( GetChunkAspectRatio(self, usage)) && !GetChunkElements(self, usage).valid(); } bool AllRankDependentConstraintsUnset(Storage& storage) { const DimensionIndex rank = storage.rank_; if (rank <= 0) return true; if (storage.inner_order()[0] != -1) return false; if (auto* origin = storage.grid_origin(); std::any_of(origin, origin + rank, [](auto x) { return x != OriginValueTraits::kDefaultValue; })) { return false; } if (auto* shapes = storage.chunk_shapes(); std::any_of(shapes, shapes + Storage::NumShapeElements(rank), [](auto x) { return x != ShapeValueTraits::kDefaultValue; })) { return false; } if (auto* aspect_ratios = storage.chunk_aspect_ratios(); std::any_of( aspect_ratios, aspect_ratios + Storage::NumAspectRatioElements(rank), [](auto x) { return x != AspectRatioValueTraits::kDefaultValue; })) { return false; } return true; } bool AllConstraintsUnset(const ChunkLayout& self) { if (!self.storage_) return true; auto& storage = *self.storage_; if (storage.rank_ != dynamic_rank) return false; if (std::any_of(storage.chunk_elements_, storage.chunk_elements_ + kNumUsages, [](Index x) { return x != kImplicit; })) { return false; } const DimensionIndex rank = storage.rank_; if (rank <= 0) return true; return AllRankDependentConstraintsUnset(storage); } template <typename Wrapper, typename Traits, typename Getter, typename Setter> constexpr auto VectorJsonBinder(Getter getter, Setter setter) { using ElementType = typename Wrapper::value_type; return [=](bool hard_constraint) { return [=](auto is_loading, const auto& options, auto* obj, auto* j) { constexpr auto element_binder = jb::MapValue( jb::DefaultBinder<>, std::pair(Traits::kDefaultValue, nullptr)); if constexpr (is_loading) { if (j->is_discarded()) return absl::OkStatus(); ElementType value[kMaxRank]; DimensionIndex rank = dynamic_rank; TENSORSTORE_RETURN_IF_ERROR(DimensionIndexedFixedArrayJsonBinder( rank, element_binder)(is_loading, options, &value[0], j)); return setter(*obj, Wrapper(tensorstore::span<const ElementType>(value, rank), hard_constraint)); } else { auto vec = getter(*obj); if (!vec.valid()) { return absl::OkStatus(); } ElementType new_vec[kMaxRank]; bool has_value = false; for (DimensionIndex i = 0; i < vec.size(); ++i) { if (vec.hard_constraint[i] == hard_constraint && vec[i] != Traits::kDefaultValue) { new_vec[i] = vec[i]; has_value = true; } else { new_vec[i] = Traits::kDefaultValue; } } if (!has_value) return absl::OkStatus(); tensorstore::span<const ElementType> new_span(new_vec, vec.size()); return jb::Array(element_binder)(is_loading, options, &new_span, j); } }; }; } constexpr auto InnerOrderJsonBinder(bool hard_constraint) { return [=](auto is_loading, const auto& options, auto* obj, auto* j) { if constexpr (is_loading) { if (j->is_discarded() || j->is_null()) { return absl::OkStatus(); } DimensionIndex value[kMaxRank]; DimensionIndex rank = dynamic_rank; TENSORSTORE_RETURN_IF_ERROR(DimensionIndexedFixedArrayJsonBinder( rank, jb::Integer<DimensionIndex>(0, kMaxRank - 1))( is_loading, options, &value[0], j)); StoragePtr storage_to_be_destroyed; return SetInnerOrderInternal( *obj, ChunkLayout::InnerOrder( tensorstore::span<const DimensionIndex>(value, rank), hard_constraint), storage_to_be_destroyed); } else { auto vec = obj->inner_order(); if (vec.valid() && vec.hard_constraint == hard_constraint) { *j = static_cast<::nlohmann::json>(vec); } return absl::OkStatus(); } }; } constexpr auto StandaloneGridJsonBinder() { return jb::Object( HardSoftMemberPairJsonBinder( "shape", "shape_soft_constraint", VectorJsonBinder<ChunkLayout::ChunkShapeBase, ShapeValueTraits>( [](auto& self) { return self.shape(); }, [](auto& self, ChunkLayout::ChunkShapeBase value) { return self.Set(value); })), HardSoftMemberPairJsonBinder( "aspect_ratio", "aspect_ratio_soft_constraint", VectorJsonBinder<ChunkLayout::ChunkAspectRatioBase, AspectRatioValueTraits>( [](auto& self) { return self.aspect_ratio(); }, [](auto& self, ChunkLayout::ChunkAspectRatioBase value) { return self.Set(value); })), HardSoftMemberPairJsonBinder( "elements", "elements_soft_constraint", [](bool hard_constraint) { return jb::GetterSetter( [=](auto& self) -> Index { auto value = self.elements(); if (value.hard_constraint != hard_constraint) return kImplicit; return value.value; }, [=](auto& self, Index value) { return self.Set( ChunkLayout::ChunkElementsBase(value, hard_constraint)); }, jb::DefaultPredicate<jb::kNeverIncludeDefaults>( [](auto* obj) { *obj = kImplicit; }, [](auto* obj) { return *obj == kImplicit; })); })); } constexpr auto GridConstraintsJsonBinder(Usage usage) { return jb::Object( HardSoftMemberPairJsonBinder( "shape", "shape_soft_constraint", VectorJsonBinder<ChunkLayout::ChunkShapeBase, ShapeValueTraits>( [=](auto& self) { return GetChunkShape(self, usage); }, [=](auto& self, ChunkLayout::ChunkShapeBase value) { StoragePtr storage_to_be_destroyed; if (usage != ChunkLayout::kUnspecifiedUsage) { return SetChunkShapeInternal(self, value, usage, storage_to_be_destroyed); } TENSORSTORE_RETURN_IF_ERROR(SetChunkShapeInternal( self, value, Usage::kWrite, storage_to_be_destroyed)); TENSORSTORE_RETURN_IF_ERROR(SetChunkShapeInternal( self, value, Usage::kRead, storage_to_be_destroyed)); return absl::OkStatus(); })), HardSoftMemberPairJsonBinder( "aspect_ratio", "aspect_ratio_soft_constraint", VectorJsonBinder<ChunkLayout::ChunkAspectRatioBase, AspectRatioValueTraits>( [=](auto& self) { return GetChunkAspectRatio(self, usage); }, [=](auto& self, ChunkLayout::ChunkAspectRatioBase value) { StoragePtr storage_to_be_destroyed; if (usage != ChunkLayout::kUnspecifiedUsage) { return SetChunkAspectRatioInternal(self, value, usage, storage_to_be_destroyed); } TENSORSTORE_RETURN_IF_ERROR(SetChunkAspectRatioInternal( self, value, Usage::kWrite, storage_to_be_destroyed)); TENSORSTORE_RETURN_IF_ERROR(SetChunkAspectRatioInternal( self, value, Usage::kRead, storage_to_be_destroyed)); TENSORSTORE_RETURN_IF_ERROR(SetChunkAspectRatioInternal( self, value, Usage::kCodec, storage_to_be_destroyed)); return absl::OkStatus(); })), HardSoftMemberPairJsonBinder( "elements", "elements_soft_constraint", [=](bool hard_constraint) { return jb::GetterSetter( [=](auto& self) -> Index { auto value = GetChunkElements(self, usage); if (value.hard_constraint != hard_constraint) return kImplicit; return value.value; }, [=](auto& self, Index value) { ChunkLayout::ChunkElementsBase elements(value, hard_constraint); StoragePtr storage_to_be_destroyed; if (usage != ChunkLayout::kUnspecifiedUsage) { return SetChunkElementsInternal(self, elements, usage, storage_to_be_destroyed); } TENSORSTORE_RETURN_IF_ERROR(SetChunkElementsInternal( self, elements, Usage::kWrite, storage_to_be_destroyed)); TENSORSTORE_RETURN_IF_ERROR(SetChunkElementsInternal( self, elements, Usage::kRead, storage_to_be_destroyed)); return absl::OkStatus(); }, jb::DefaultPredicate<jb::kNeverIncludeDefaults>( [](auto* obj) { *obj = kImplicit; }, [](auto* obj) { return *obj == kImplicit; })); })); } constexpr auto DefaultableGridConstraintsJsonBinder(Usage usage) { return jb::DefaultPredicate<jb::kNeverIncludeDefaults>( [](auto* obj) {}, [=](auto* obj) { if (!obj->storage_) return true; return GridConstraintsUnset(*obj, usage); }, GridConstraintsJsonBinder(usage)); } } TENSORSTORE_DEFINE_JSON_DEFAULT_BINDER( ChunkLayout, jb::Object(jb::Member("rank", jb::Compose<DimensionIndex>( [](auto is_loading, const auto& options, auto* obj, auto* rank) { if constexpr (is_loading) { return obj->Set(RankConstraint{*rank}); } else { const DimensionIndex rank_value = obj->rank(); *rank = (rank_value == dynamic_rank || !AllRankDependentConstraintsUnset( *obj->storage_)) ? dynamic_rank : rank_value; return absl::OkStatus(); } }, jb::ConstrainedRankJsonBinder)), HardSoftMemberPairJsonBinder("inner_order", "inner_order_soft_constraint", InnerOrderJsonBinder), HardSoftMemberPairJsonBinder( "grid_origin", "grid_origin_soft_constraint", VectorJsonBinder<ChunkLayout::GridOrigin, OriginValueTraits>( [](auto& self) { return self.grid_origin(); }, [](auto& self, ChunkLayout::GridOrigin value) { StoragePtr storage_to_be_destroyed; return SetGridOriginInternal(self, value, storage_to_be_destroyed); })), jb::LoadSave(jb::Member("chunk", DefaultableGridConstraintsJsonBinder( ChunkLayout::kUnspecifiedUsage))), jb::Member("write_chunk", DefaultableGridConstraintsJsonBinder(Usage::kWrite)), jb::Member("read_chunk", DefaultableGridConstraintsJsonBinder(Usage::kRead)), jb::Member("codec_chunk", DefaultableGridConstraintsJsonBinder(Usage::kCodec)))) TENSORSTORE_DEFINE_JSON_DEFAULT_BINDER(ChunkLayout::Grid, StandaloneGridJsonBinder()) namespace { template <typename Traits> static absl::Status TransformInputVector( IndexTransformView<> transform, tensorstore::span<const typename Traits::Element> in_vec, DimensionSet in_hard_constraint, tensorstore::span<typename Traits::Element> out_vec, DimensionSet& out_hard_constraint) { using Element = typename Traits::Element; const DimensionIndex output_rank = transform.output_rank(); const DimensionIndex input_rank = transform.input_rank(); assert(input_rank == in_vec.size()); assert(output_rank == out_vec.size()); Element in_vec_copy[kMaxRank]; std::copy_n(in_vec.begin(), input_rank, in_vec_copy); std::fill_n(out_vec.begin(), output_rank, Traits::kDefaultValue); out_hard_constraint = false; DimensionSet remaining_in_hard_constraint = in_hard_constraint; for (DimensionIndex output_dim = 0; output_dim < output_rank; ++output_dim) { const auto map = transform.output_index_maps()[output_dim]; if (map.method() != OutputIndexMethod::single_input_dimension || map.stride() == 0) { continue; } const DimensionIndex input_dim = map.input_dimension(); Element value = in_vec_copy[input_dim]; remaining_in_hard_constraint[input_dim] = false; if (value == Traits::kDefaultValue) continue; TENSORSTORE_ASSIGN_OR_RETURN( value, Traits::TransformInputValue(value, map.offset(), map.stride()), MaybeAnnotateStatus( _, tensorstore::StrCat("Error transforming input dimension ", input_dim, " -> output dimension ", output_dim))); out_vec[output_dim] = value; if (in_hard_constraint[input_dim] && value != Traits::kDefaultValue) { out_hard_constraint[output_dim] = true; } } for (DimensionIndex input_dim = 0; input_dim < input_rank; ++input_dim) { if (in_vec[input_dim] == Traits::kDefaultValue) continue; if (!remaining_in_hard_constraint[input_dim]) continue; return absl::InvalidArgumentError(tensorstore::StrCat( "No output dimension corresponds to input dimension ", input_dim)); } return absl::OkStatus(); } template <typename Traits> static absl::Status TransformOutputVector( IndexTransformView<> transform, DimensionSet one_to_one_input_dims, tensorstore::span<const typename Traits::Element> out_vec, DimensionSet out_hard_constraint, tensorstore::span<typename Traits::Element> in_vec, DimensionSet& in_hard_constraint) { using Element = typename Traits::Element; const DimensionIndex input_rank = transform.input_rank(); const DimensionIndex output_rank = transform.output_rank(); assert(output_rank == out_vec.size()); assert(input_rank == in_vec.size()); Element out_vec_copy[kMaxRank]; std::copy_n(out_vec.begin(), output_rank, out_vec_copy); std::fill_n(in_vec.begin(), input_rank, Traits::kDefaultValue); in_hard_constraint = false; for (DimensionIndex output_dim = 0; output_dim < output_rank; ++output_dim) { const auto map = transform.output_index_maps()[output_dim]; if (map.method() != OutputIndexMethod::single_input_dimension || map.stride() == 0) { continue; } const DimensionIndex input_dim = map.input_dimension(); if (!one_to_one_input_dims[input_dim]) continue; Element value = out_vec_copy[output_dim]; if (value == Traits::kDefaultValue) continue; TENSORSTORE_ASSIGN_OR_RETURN( value, Traits::TransformOutputValue(value, map.offset(), map.stride()), MaybeAnnotateStatus( _, tensorstore::StrCat("Error transforming output dimension ", output_dim, " -> input dimension ", input_dim))); in_vec[input_dim] = value; if (value != Traits::kDefaultValue) { in_hard_constraint[input_dim] = out_hard_constraint[output_dim]; } } return absl::OkStatus(); } absl::Status TransformOutputGridConstraints(Storage& output_storage, Storage& input_storage, DimensionSet one_to_one_input_dims, IndexTransformView<> transform, size_t usage_index) { input_storage.chunk_elements_[usage_index] = output_storage.chunk_elements_[usage_index]; TENSORSTORE_RETURN_IF_ERROR( TransformOutputVector<ShapeValueTraits>( transform, one_to_one_input_dims, output_storage.chunk_shape(usage_index), output_storage.chunk_shape_hard_constraint_[usage_index], input_storage.chunk_shape(usage_index), input_storage.chunk_shape_hard_constraint_[usage_index]), tensorstore::MaybeAnnotateStatus(_, "Error transforming shape")); TENSORSTORE_RETURN_IF_ERROR( TransformOutputVector<AspectRatioValueTraits>( transform, one_to_one_input_dims, output_storage.chunk_aspect_ratio(usage_index), output_storage.chunk_aspect_ratio_hard_constraint_[usage_index], input_storage.chunk_aspect_ratio(usage_index), input_storage.chunk_aspect_ratio_hard_constraint_[usage_index]), tensorstore::MaybeAnnotateStatus(_, "Error transforming aspect_ratio")); return absl::OkStatus(); } absl::Status TransformInputGridConstraints(Storage& input_storage, Storage& output_storage, IndexTransformView<> transform, size_t usage_index) { output_storage.chunk_elements_[usage_index] = input_storage.chunk_elements_[usage_index]; TENSORSTORE_RETURN_IF_ERROR( TransformInputVector<ShapeValueTraits>( transform, input_storage.chunk_shape(usage_index), input_storage.chunk_shape_hard_constraint_[usage_index], output_storage.chunk_shape(usage_index), output_storage.chunk_shape_hard_constraint_[usage_index]), tensorstore::MaybeAnnotateStatus(_, "Error transforming shape")); TENSORSTORE_RETURN_IF_ERROR( TransformInputVector<AspectRatioValueTraits>( transform, input_storage.chunk_aspect_ratio(usage_index), input_storage.chunk_aspect_ratio_hard_constraint_[usage_index], output_storage.chunk_aspect_ratio(usage_index), output_storage.chunk_aspect_ratio_hard_constraint_[usage_index]), tensorstore::MaybeAnnotateStatus(_, "Error transforming aspect_ratio")); return absl::OkStatus(); } } Result<ChunkLayout> ApplyIndexTransform(IndexTransformView<> transform, ChunkLayout output_constraints) { if (!transform.valid() || !output_constraints.storage_) { return output_constraints; } const DimensionIndex output_rank = transform.output_rank(); const DimensionIndex input_rank = transform.input_rank(); const DimensionIndex output_constraints_rank = output_constraints.rank(); if (!RankConstraint::EqualOrUnspecified(output_constraints_rank, transform.output_rank())) { return absl::InvalidArgumentError(tensorstore::StrCat( "Cannot transform constraints of rank ", output_constraints_rank, " by index transform of rank ", input_rank, " -> ", output_rank)); } if (output_constraints_rank <= 0) return output_constraints; ChunkLayout input_constraints; Storage* output_storage; if (output_rank == input_rank) { StoragePtr storage_to_be_destroyed; input_constraints = std::move(output_constraints); output_storage = &Storage::EnsureUnique( input_constraints.storage_, input_rank, storage_to_be_destroyed); } else { input_constraints.storage_ = Storage::Allocate(input_rank); new (input_constraints.storage_.get()) Storage(input_rank); output_storage = output_constraints.storage_.get(); } input_constraints.storage_->hard_constraint_ = output_storage->hard_constraint_; if (auto* inner_order = output_storage->inner_order(); inner_order[0] != -1) { TransformOutputDimensionOrder( transform, {inner_order, output_rank}, {input_constraints.storage_->inner_order(), input_rank}); } DimensionSet one_to_one_input_dims = internal::GetOneToOneInputDimensions(transform).one_to_one; TENSORSTORE_RETURN_IF_ERROR( TransformOutputVector<OriginValueTraits>( transform, one_to_one_input_dims, tensorstore::span<const Index>(output_storage->grid_origin(), output_rank), output_storage->grid_origin_hard_constraint_, tensorstore::span<Index>(input_constraints.storage_->grid_origin(), input_rank), input_constraints.storage_->grid_origin_hard_constraint_), tensorstore::MaybeAnnotateStatus(_, "Error transforming grid_origin")); for (size_t usage_index = 0; usage_index < kNumUsages; ++usage_index) { TENSORSTORE_RETURN_IF_ERROR( TransformOutputGridConstraints( *output_storage, *input_constraints.storage_, one_to_one_input_dims, transform, usage_index), tensorstore::MaybeAnnotateStatus( _, tensorstore::StrCat("Error transforming ", static_cast<Usage>(usage_index), "_chunk"))); } return input_constraints; } Result<ChunkLayout> ApplyInverseIndexTransform(IndexTransformView<> transform, ChunkLayout input_constraints) { if (!transform.valid() || !input_constraints.storage_) { return input_constraints; } const DimensionIndex output_rank = transform.output_rank(); const DimensionIndex input_rank = transform.input_rank(); const DimensionIndex input_constraints_rank = input_constraints.rank(); if (!RankConstraint::EqualOrUnspecified(input_constraints_rank, transform.input_rank())) { return absl::InvalidArgumentError(tensorstore::StrCat( "Cannot transform constraints of rank ", input_constraints_rank, " by index transform of rank ", input_rank, " -> ", output_rank)); } if (input_constraints_rank <= 0) return input_constraints; ChunkLayout output_constraints; Storage* input_storage; if (output_rank == input_rank) { StoragePtr storage_to_be_destroyed; output_constraints = std::move(input_constraints); input_storage = &Storage::EnsureUnique( output_constraints.storage_, output_rank, storage_to_be_destroyed); } else { output_constraints.storage_ = Storage::Allocate(output_rank); new (output_constraints.storage_.get()) Storage(output_rank); input_storage = input_constraints.storage_.get(); } output_constraints.storage_->hard_constraint_ = input_storage->hard_constraint_; if (auto* inner_order = input_storage->inner_order(); inner_order[0] != -1) { TransformInputDimensionOrder( transform, {inner_order, input_rank}, {output_constraints.storage_->inner_order(), output_rank}); } TENSORSTORE_RETURN_IF_ERROR( TransformInputVector<OriginValueTraits>( transform, tensorstore::span<const Index>(input_storage->grid_origin(), input_rank), input_storage->grid_origin_hard_constraint_, tensorstore::span<Index>(output_constraints.storage_->grid_origin(), output_rank), output_constraints.storage_->grid_origin_hard_constraint_), tensorstore::MaybeAnnotateStatus(_, "Error transforming grid_origin")); for (size_t usage_index = 0; usage_index < kNumUsages; ++usage_index) { TENSORSTORE_RETURN_IF_ERROR( TransformInputGridConstraints(*input_storage, *output_constraints.storage_, transform, usage_index), tensorstore::MaybeAnnotateStatus( _, tensorstore::StrCat("Error transforming ", static_cast<Usage>(usage_index), "_chunk"))); } return output_constraints; } bool operator==(const ChunkLayout& a, const ChunkLayout& b) { if (!a.storage_) { if (!b.storage_) return true; return AllConstraintsUnset(b); } if (!b.storage_) { return AllConstraintsUnset(a); } auto& a_storage = *a.storage_; auto& b_storage = *b.storage_; if (a_storage.hard_constraint_ != b_storage.hard_constraint_ || a_storage.grid_origin_hard_constraint_ != b_storage.grid_origin_hard_constraint_ || !internal::RangesEqual( tensorstore::span(a_storage.chunk_shape_hard_constraint_), tensorstore::span(b_storage.chunk_shape_hard_constraint_)) || !internal::RangesEqual( tensorstore::span(a_storage.chunk_aspect_ratio_hard_constraint_), tensorstore::span(b_storage.chunk_aspect_ratio_hard_constraint_)) || !std::equal(a_storage.chunk_elements_, a_storage.chunk_elements_ + kNumUsages, b_storage.chunk_elements_)) { return false; } const DimensionIndex rank = a_storage.rank_; if (rank <= 0 || rank != b_storage.rank_) { return AllRankDependentConstraintsUnset(a_storage) && AllRankDependentConstraintsUnset(b_storage); } if (auto* a_inner_order = a_storage.inner_order(); !std::equal( a_inner_order, a_inner_order + rank, b_storage.inner_order())) { return false; } if (auto* a_origin = a_storage.grid_origin(); !std::equal(a_origin, a_origin + rank, b_storage.grid_origin())) { return false; } if (auto* a_shapes = a_storage.chunk_shapes(); !std::equal(a_shapes, a_shapes + Storage::NumShapeElements(rank), b_storage.chunk_shapes())) { return false; } if (auto* a_aspect_ratios = a_storage.chunk_aspect_ratios(); !std::equal(a_aspect_ratios, a_aspect_ratios + Storage::NumAspectRatioElements(rank), b_storage.chunk_aspect_ratios())) { return false; } return true; } std::ostream& operator<<(std::ostream& os, const ChunkLayout& x) { return os << ::nlohmann::json(x).dump(); } namespace internal { constexpr Index kDefaultChunkElements = 1024 * 1024; namespace { void ChooseChunkSizeFromAspectRatio( tensorstore::span<const double> aspect_ratio, tensorstore::span<Index> chunk_shape, Index target_chunk_elements, BoxView<> domain, absl::FunctionRef<Index(DimensionIndex dim, Index value)> map_size) { const DimensionIndex rank = chunk_shape.size(); assert(aspect_ratio.size() == rank); assert(domain.rank() == rank); double max_chunk_shape[kMaxRank]; for (DimensionIndex i = 0; i < rank; ++i) { double max_size = target_chunk_elements; if (IndexInterval bounds = domain[i]; IsFinite(bounds)) { max_size = std::min(max_size, std::max(1.0, static_cast<double>(bounds.size()))); } max_size = std::min(max_size, 0x1.0p62); max_chunk_shape[i] = max_size; } const auto get_chunk_size = [&](DimensionIndex i, double factor) -> Index { if (const Index size = chunk_shape[i]; size != 0) return size; Index size = std::max(Index(1), static_cast<Index>(std::min(aspect_ratio[i] * factor, max_chunk_shape[i]))); size = map_size(i, size); return size; }; const auto get_total_elements = [&](double factor) -> Index { Index total = 1; #ifdef TENSORSTORE_INTERNAL_CHUNK_LAYOUT_DEBUG Index cur_chunk_shape[kMaxRank]; #endif for (DimensionIndex i = 0; i < rank; ++i) { const Index size = get_chunk_size(i, factor); #ifdef TENSORSTORE_INTERNAL_CHUNK_LAYOUT_DEBUG cur_chunk_shape[i] = size; #endif if (internal::MulOverflow(size, total, &total)) { total = std::numeric_limits<Index>::max(); break; } } #ifdef TENSORSTORE_INTERNAL_CHUNK_LAYOUT_DEBUG ABSL_LOG(INFO) << "factor=" << factor << ", chunk_shape=" << tensorstore::span<const Index>(&cur_chunk_shape[0], rank) << ", total=" << total; #endif return total; }; double min_factor_increment = std::numeric_limits<double>::infinity(); double max_factor = 0; for (DimensionIndex i = 0; i < rank; ++i) { if (chunk_shape[i] != 0) continue; const double factor = aspect_ratio[i]; min_factor_increment = std::min(min_factor_increment, 1.0 / factor); max_factor = std::max(max_factor, max_chunk_shape[i] / factor); } min_factor_increment /= 2; max_factor *= 2; double min_factor = min_factor_increment; Index max_factor_elements = get_total_elements(max_factor); while (min_factor + min_factor_increment < max_factor) { double mid_factor = min_factor + (max_factor - min_factor) / 2.0; Index mid_factor_elements = get_total_elements(mid_factor); if (mid_factor_elements >= target_chunk_elements) { max_factor = mid_factor; max_factor_elements = mid_factor_elements; } if (mid_factor_elements <= target_chunk_elements) { min_factor = mid_factor; } } const double factor = max_factor_elements == target_chunk_elements ? max_factor : min_factor; for (DimensionIndex i = 0; i < rank; ++i) { chunk_shape[i] = get_chunk_size(i, factor); } } absl::Status ChooseChunkGridOrigin( tensorstore::span<const Index> origin_constraints, tensorstore::span<const Index> domain_origin, tensorstore::span<const Index> chunk_shape, tensorstore::span<Index> grid_origin) { const DimensionIndex rank = grid_origin.size(); if (!origin_constraints.empty()) { if (origin_constraints.size() != rank) { return absl::InvalidArgumentError(tensorstore::StrCat( "Rank of constraints (", origin_constraints.size(), ") does not match rank of domain (", rank, ")")); } std::copy_n(origin_constraints.begin(), rank, grid_origin.begin()); } else { std::fill_n(grid_origin.begin(), rank, kImplicit); } for (DimensionIndex i = 0; i < rank; ++i) { Index& origin_value = grid_origin[i]; if (origin_value == kImplicit) { const Index domain_origin_value = domain_origin[i]; if (domain_origin_value == -kInfIndex) { origin_value = 0; } else { origin_value = NonnegativeMod(domain_origin_value, chunk_shape[i]); } } TENSORSTORE_ASSIGN_OR_RETURN( auto interval, IndexInterval::Sized(origin_value, chunk_shape[i]), tensorstore::MaybeAnnotateStatus( _, tensorstore::StrCat("Invalid chunk constraints for dimension ", i))); grid_origin[i] = interval.inclusive_min(); } return absl::OkStatus(); } absl::Status InitializeChunkShape(ChunkLayout::ChunkShapeBase shape_constraints, BoxView<> domain, tensorstore::span<Index> chunk_shape, DimensionSet& shape_hard_constraint) { const DimensionIndex rank = chunk_shape.size(); DimensionSet hard_constraint = false; if (shape_constraints.valid()) { if (shape_constraints.size() != rank) { return absl::InvalidArgumentError( tensorstore::StrCat("Rank of constraints (", shape_constraints.size(), ") does not match rank of domain (", rank, ")")); } std::copy_n(shape_constraints.begin(), rank, chunk_shape.begin()); hard_constraint = shape_constraints.hard_constraint; } else { std::fill_n(chunk_shape.begin(), rank, 0); } for (DimensionIndex i = 0; i < rank; ++i) { Index& chunk_size = chunk_shape[i]; if (chunk_size == 0) { hard_constraint[i] = false; continue; } if (chunk_size == -1) { IndexInterval bounds = domain[i]; if (!IsFinite(bounds)) { return absl::InvalidArgumentError( tensorstore::StrCat("Cannot match chunk size for dimension ", i, " to unbounded domain ", bounds)); } chunk_size = std::max(Index(1), bounds.size()); } } shape_hard_constraint = hard_constraint; return absl::OkStatus(); } absl::Status CompleteChunkShapeFromAspectRatio( BoxView<> domain, ChunkLayout::ChunkAspectRatioBase aspect_ratio_constraints, ChunkLayout::ChunkElementsBase elements_constraint, absl::FunctionRef<Index(DimensionIndex dim, Index value)> map_size, tensorstore::span<Index> chunk_shape) { const DimensionIndex rank = chunk_shape.size(); if (std::any_of(chunk_shape.begin(), chunk_shape.end(), [](Index x) { return x == 0; })) { double aspect_ratio[kMaxRank]; if (aspect_ratio_constraints.valid()) { if (aspect_ratio_constraints.size() != rank) { return absl::InvalidArgumentError(tensorstore::StrCat( "Rank of constraints (", aspect_ratio_constraints.size(), ") does not match rank of domain (", rank, ")")); } std::copy_n(aspect_ratio_constraints.begin(), rank, aspect_ratio); for (DimensionIndex i = 0; i < rank; ++i) { if (aspect_ratio[i] == 0) { aspect_ratio[i] = 1; } } } else { std::fill_n(aspect_ratio, rank, 1); } Index target_chunk_elements = kDefaultChunkElements; if (elements_constraint.valid()) { target_chunk_elements = elements_constraint; } ChooseChunkSizeFromAspectRatio( tensorstore::span<const double>(aspect_ratio, rank), chunk_shape, target_chunk_elements, domain, map_size); } return absl::OkStatus(); } } absl::Status ChooseChunkShape(ChunkLayout::GridView shape_constraints, BoxView<> domain, tensorstore::span<Index> chunk_shape) { assert(domain.rank() == chunk_shape.size()); DimensionSet shape_hard_constraint; TENSORSTORE_RETURN_IF_ERROR(InitializeChunkShape( shape_constraints.shape(), domain, chunk_shape, shape_hard_constraint)); constexpr auto map_size = [](DimensionIndex dim, Index size) { return size; }; return CompleteChunkShapeFromAspectRatio( domain, shape_constraints.aspect_ratio(), shape_constraints.elements(), map_size, chunk_shape); } absl::Status ChooseChunkGrid(tensorstore::span<const Index> origin_constraints, ChunkLayout::GridView shape_constraints, BoxView<> domain, MutableBoxView<> chunk_template) { TENSORSTORE_RETURN_IF_ERROR( ChooseChunkShape(shape_constraints, domain, chunk_template.shape())); return ChooseChunkGridOrigin(origin_constraints, domain.origin(), chunk_template.shape(), chunk_template.origin()); } absl::Status ChooseReadWriteChunkGrid(const ChunkLayout& constraints, BoxView<> domain, MutableBoxView<> chunk_template) { ChunkLayout combined_constraints = constraints; TENSORSTORE_RETURN_IF_ERROR( combined_constraints.Set( ChunkLayout::ReadChunk(constraints.write_chunk())), tensorstore::MaybeAnnotateStatus(_, "write_chunk constraints not compatible " "with existing read_chunk constraints")); return ChooseChunkGrid(combined_constraints.grid_origin(), combined_constraints.read_chunk(), domain, chunk_template); } Index FindNearestDivisor(Index dividend, Index target, Index max_search_distance = 1000000) { if (target >= dividend) { return dividend; } if ((dividend % target) == 0) { return target; } for (Index offset = 1; offset < max_search_distance; ++offset) { if (target > offset && (dividend % (target - offset)) == 0) { return target - offset; } if ((dividend % (target + offset)) == 0) { return target + offset; } } return dividend; } Index FindNearestMultiple(Index divisor, Index target) { if (target < divisor) { return divisor; } const Index lower = target / divisor * divisor; const Index upper = lower + divisor; if (target - lower <= upper - target) { return lower; } else { return upper; } } absl::Status ChooseReadWriteChunkShapes( ChunkLayout::GridView read_constraints, ChunkLayout::GridView write_constraints, BoxView<> domain, tensorstore::span<Index> read_chunk_shape, tensorstore::span<Index> write_chunk_shape) { DimensionIndex rank = write_chunk_shape.size(); assert(read_chunk_shape.size() == rank); assert(domain.rank() == rank); DimensionSet write_shape_hard_constraint; DimensionSet read_shape_hard_constraint; TENSORSTORE_RETURN_IF_ERROR( InitializeChunkShape(write_constraints.shape(), domain, write_chunk_shape, write_shape_hard_constraint)); TENSORSTORE_RETURN_IF_ERROR(InitializeChunkShape(read_constraints.shape(), domain, read_chunk_shape, read_shape_hard_constraint)); for (DimensionIndex i = 0; i < rank; ++i) { Index& read_size = read_chunk_shape[i]; Index& write_size = write_chunk_shape[i]; if (read_size == 0 || write_size == 0 || ((write_size % read_size) == 0)) { continue; } const bool read_hard_constraint = read_shape_hard_constraint[i]; const bool write_hard_constraint = write_shape_hard_constraint[i]; if (read_hard_constraint && write_hard_constraint) { return absl::InvalidArgumentError(tensorstore::StrCat( "Incompatible chunk size constraints for dimension ", i, ": read size of ", read_size, ", write size of ", write_size)); } if (read_hard_constraint && !write_hard_constraint) { write_size = FindNearestMultiple(read_size, write_size); continue; } if (!read_hard_constraint) { read_size = FindNearestDivisor(write_size, read_size, 1000000); continue; } } const auto map_read_size = [&](DimensionIndex i, Index size) { const Index write_size = write_chunk_shape[i]; if (write_size != 0) { size = FindNearestDivisor(write_size, size, 1000000); } return size; }; TENSORSTORE_RETURN_IF_ERROR(CompleteChunkShapeFromAspectRatio( domain, read_constraints.aspect_ratio(), read_constraints.elements(), map_read_size, read_chunk_shape)); const auto map_write_size = [&](DimensionIndex i, Index size) { const Index read_size = read_chunk_shape[i]; return FindNearestMultiple(read_size, size); }; TENSORSTORE_RETURN_IF_ERROR(CompleteChunkShapeFromAspectRatio( domain, write_constraints.aspect_ratio(), write_constraints.elements(), map_write_size, write_chunk_shape)); return absl::OkStatus(); } } absl::Status ChunkLayout::Finalize() { const DimensionIndex rank = this->rank(); if (rank == dynamic_rank) { return absl::InvalidArgumentError("rank must be specified"); } { StoragePtr storage_to_be_destroyed; Storage::EnsureUnique(storage_, rank, storage_to_be_destroyed); } auto& impl = *storage_; auto origin = impl.grid_origin(); for (DimensionIndex dim = 0; dim < rank; ++dim) { if (!impl.grid_origin_hard_constraint_[dim]) { return absl::InvalidArgumentError(tensorstore::StrCat( "No grid_origin hard constraint for dimension ", dim)); } if (!IsFiniteIndex(origin[dim])) { return absl::InvalidArgumentError( tensorstore::StrCat("Invalid grid_origin: ", origin)); } } for (Usage usage : ChunkLayout::kUsages) { const size_t usage_index = static_cast<size_t>(usage); auto status = [&]() -> absl::Status { auto shape = impl.chunk_shape(usage_index); auto& shape_hard_constraint = impl.chunk_shape_hard_constraint_[usage_index]; for (DimensionIndex dim = 0; dim < rank; ++dim) { const Index origin_value = origin[dim]; Index& size_value = shape[dim]; if (!shape_hard_constraint[dim]) { size_value = 0; } if (!IndexInterval::ValidSized(origin_value, size_value) || !IsFiniteIndex(origin_value + size_value)) { return absl::InvalidArgumentError(tensorstore::StrCat( "Invalid origin/shape: origin=", origin, ", shape=", shape)); } if (size_value == 0 && usage == Usage::kRead) { auto write_shape = impl.chunk_shape(static_cast<size_t>(Usage::kWrite)); size_value = write_shape[dim]; shape_hard_constraint[dim] = impl.chunk_shape_hard_constraint_[static_cast<size_t>( Usage::kWrite)][dim]; } } impl.chunk_aspect_ratio_hard_constraint_[usage_index] = false; impl.hard_constraint_[static_cast<size_t>( GetChunkElementsHardConstraintBit(usage))] = false; impl.chunk_elements_[usage_index] = kImplicit; std::fill_n(impl.chunk_aspect_ratio(usage_index).begin(), rank, 0); return absl::OkStatus(); }(); if (!status.ok()) { return tensorstore::MaybeAnnotateStatus( status, tensorstore::StrCat("Invalid ", usage, " chunk grid")); } } auto write_chunk_shape = impl.chunk_shape(static_cast<size_t>(Usage::kWrite)); auto read_chunk_shape = impl.chunk_shape(static_cast<size_t>(Usage::kRead)); for (DimensionIndex dim = 0; dim < rank; ++dim) { const Index read_size = read_chunk_shape[dim]; const Index write_size = write_chunk_shape[dim]; if (read_size == 0) continue; if ((write_size % read_size) != 0) { return absl::InvalidArgumentError(tensorstore::StrCat( "write chunk shape ", write_chunk_shape, " is not a multiple of read chunk shape ", read_chunk_shape)); } } return absl::OkStatus(); } namespace { constexpr auto UsageJsonBinder() { return jb::Enum<ChunkLayout::Usage, std::string_view>({ {ChunkLayout::Usage::kWrite, "write"}, {ChunkLayout::Usage::kRead, "read"}, {ChunkLayout::Usage::kCodec, "codec"}, }); } } std::ostream& operator<<(std::ostream& os, ChunkLayout::Usage usage) { std::string_view s; UsageJsonBinder()(std::false_type{}, jb::NoOptions{}, &usage, &s) .IgnoreError(); return os << s; } Result<ChunkLayout::Usage> ChunkLayout::ParseUsage(std::string_view s) { Usage usage; TENSORSTORE_RETURN_IF_ERROR(UsageJsonBinder()(std::true_type{}, jb::NoOptions{}, &usage, &s)); return usage; } ChunkLayout::Grid::Grid(const Grid& other) : rank_(other.rank_), elements_hard_constraint_(other.elements_hard_constraint_), shape_hard_constraint_(other.shape_hard_constraint_), aspect_ratio_hard_constraint_(other.aspect_ratio_hard_constraint_), elements_(other.elements_) { const DimensionIndex rank = other.rank_; if (rank > 0) { shape_.reset(new Index[rank]); std::copy_n(other.shape_.get(), rank, shape_.get()); aspect_ratio_.reset(new double[rank]); std::copy_n(other.aspect_ratio_.get(), rank, aspect_ratio_.get()); } } ChunkLayout::Grid& ChunkLayout::Grid::operator=(const Grid& other) { const DimensionIndex new_rank = other.rank_; if (new_rank <= 0) { shape_.reset(); aspect_ratio_.reset(); } else { if (new_rank != rank_) { shape_.reset(new Index[new_rank]); aspect_ratio_.reset(new double[new_rank]); } std::copy_n(other.shape_.get(), new_rank, shape_.get()); std::copy_n(other.aspect_ratio_.get(), new_rank, aspect_ratio_.get()); } rank_ = new_rank; elements_hard_constraint_ = other.elements_hard_constraint_; shape_hard_constraint_ = other.shape_hard_constraint_; aspect_ratio_hard_constraint_ = other.aspect_ratio_hard_constraint_; elements_ = other.elements_; return *this; } ChunkLayout::Grid::~Grid() = default; absl::Status ChunkLayout::Grid::Set(RankConstraint value) { const DimensionIndex rank = value.rank; if (rank == dynamic_rank || rank == rank_) { return absl::OkStatus(); } TENSORSTORE_RETURN_IF_ERROR(ValidateRank(rank)); if (!RankConstraint::EqualOrUnspecified(rank_, rank)) { return RankMismatchError(rank, rank_); } rank_ = rank; if (rank > 0) { shape_.reset(new Index[rank]); std::fill_n(shape_.get(), rank, ShapeValueTraits::kDefaultValue); aspect_ratio_.reset(new double[rank]); std::fill_n(aspect_ratio_.get(), rank, AspectRatioValueTraits::kDefaultValue); } return absl::OkStatus(); } namespace { template <typename Traits> absl::Status SetVectorProperty( ChunkLayout::Grid& self, std::unique_ptr<typename Traits::Element[]>& vec, DimensionSet& hard_constraint, MaybeHardConstraintSpan<typename Traits::Element> value) { if (!value.valid()) return absl::OkStatus(); const DimensionIndex rank = value.size(); TENSORSTORE_RETURN_IF_ERROR(self.Set(RankConstraint(rank))); return ValidateAndMergeVectorInto<Traits>(value, vec.get(), hard_constraint); } } absl::Status ChunkLayout::Grid::Set(Shape value) { return SetVectorProperty<ShapeValueTraits>(*this, shape_, shape_hard_constraint_, value); } absl::Status ChunkLayout::Grid::Set(AspectRatio value) { return SetVectorProperty<AspectRatioValueTraits>( *this, aspect_ratio_, aspect_ratio_hard_constraint_, value); } absl::Status ChunkLayout::Grid::Set(Elements value) { return SetChunkElementsInternal<bool&>(elements_, elements_hard_constraint_, value); } absl::Status ChunkLayout::Grid::Set(const GridView& value) { TENSORSTORE_RETURN_IF_ERROR(Set(value.shape())); TENSORSTORE_RETURN_IF_ERROR(Set(value.aspect_ratio())); TENSORSTORE_RETURN_IF_ERROR(Set(value.elements())); return absl::OkStatus(); } bool operator==(const ChunkLayout::Grid& a, const ChunkLayout::Grid& b) { const DimensionIndex rank = a.rank_; if (rank != b.rank_ || a.elements_hard_constraint_ != b.elements_hard_constraint_ || a.shape_hard_constraint_ != b.shape_hard_constraint_ || a.aspect_ratio_hard_constraint_ != b.aspect_ratio_hard_constraint_ || a.elements_ != b.elements_) { return false; } return rank <= 0 || (std::equal(a.shape_.get(), a.shape_.get() + rank, b.shape_.get()) && std::equal(a.aspect_ratio_.get(), a.aspect_ratio_.get() + rank, b.aspect_ratio_.get())); } absl::Status ChunkLayout::GetChunkTemplate(Usage usage, MutableBoxView<> box) const { assert(usage == kRead || usage == kWrite); const DimensionIndex rank = this->rank(); if (rank == dynamic_rank) { box.Fill(); return absl::OkStatus(); } if (rank != box.rank()) { return absl::InvalidArgumentError(tensorstore::StrCat( "Rank of chunk layout (", rank, ") does not match expected rank (", box.rank(), ")")); } auto grid_origin = this->grid_origin(); auto shape = (*this)[usage].shape(); for (DimensionIndex i = 0; i < rank; ++i) { if (grid_origin[i] == kImplicit || !grid_origin.hard_constraint[i] || shape[i] == 0 || !shape.hard_constraint[i]) { box[i] = IndexInterval::Infinite(); continue; } TENSORSTORE_ASSIGN_OR_RETURN( box[i], IndexInterval::Sized(grid_origin[i], shape[i]), tensorstore::MaybeAnnotateStatus( _, tensorstore::StrCat( "Incompatible grid origin/chunk shape for dimension ", i))); } return absl::OkStatus(); } } TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::ChunkLayout, tensorstore::serialization::JsonBindableSerializer< tensorstore::ChunkLayout>()) TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::ChunkLayout::Grid, tensorstore::serialization::JsonBindableSerializer< tensorstore::ChunkLayout::Grid>())
#include "tensorstore/chunk_layout.h" #include <stddef.h> #include <algorithm> #include <array> #include <cstdlib> #include <random> #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/container/flat_hash_map.h" #include "absl/random/bit_gen_ref.h" #include "absl/random/random.h" #include "absl/status/status.h" #include "tensorstore/box.h" #include "tensorstore/index.h" #include "tensorstore/index_space/dim_expression.h" #include "tensorstore/index_space/index_domain_builder.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/index_transform_builder.h" #include "tensorstore/index_space/index_transform_testutil.h" #include "tensorstore/index_space/output_index_method.h" #include "tensorstore/internal/json_binding/bindable.h" #include "tensorstore/internal/json_binding/gtest.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/internal/testing/random_seed.h" #include "tensorstore/json_serialization_options_base.h" #include "tensorstore/rank.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/serialization/test_util.h" #include "tensorstore/util/dimension_set.h" #include "tensorstore/util/division.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" #include "tensorstore/util/str_cat.h" namespace { using ::tensorstore::Box; using ::tensorstore::BoxView; using ::tensorstore::ChunkLayout; using ::tensorstore::DimensionIndex; using ::tensorstore::DimensionSet; using ::tensorstore::Dims; using ::tensorstore::dynamic_rank; using ::tensorstore::Index; using ::tensorstore::IndexDomainBuilder; using ::tensorstore::IndexTransformBuilder; using ::tensorstore::IndexTransformView; using ::tensorstore::kImplicit; using ::tensorstore::kInfIndex; using ::tensorstore::kMaxRank; using ::tensorstore::MatchesJson; using ::tensorstore::MatchesStatus; using ::tensorstore::internal::ChooseChunkGrid; using ::tensorstore::internal::ChooseChunkShape; using ::tensorstore::internal::ChooseReadWriteChunkShapes; using ::tensorstore::internal::MakeRandomDimensionOrder; using ::testing::Optional; using Usage = ChunkLayout::Usage; TEST(ChunkLayoutTest, SingleLevelRank0) { ChunkLayout layout; TENSORSTORE_ASSERT_OK(layout.Set(tensorstore::RankConstraint(0))); TENSORSTORE_ASSERT_OK(layout.Finalize()); ASSERT_EQ(0, layout.rank()); EXPECT_THAT(layout.inner_order(), ::testing::ElementsAre()); EXPECT_THAT(layout | tensorstore::IdentityTransform(0), Optional(layout)); EXPECT_THAT(layout.read_chunk().shape(), ::testing::ElementsAre()); } TEST(ChunkLayoutTest, SingleLevelRank1) { ChunkLayout layout; TENSORSTORE_ASSERT_OK(layout.Set(ChunkLayout::GridOrigin({0}))); TENSORSTORE_ASSERT_OK(layout.Set(ChunkLayout::WriteChunkShape({5}))); TENSORSTORE_ASSERT_OK(layout.Finalize()); ASSERT_EQ(1, layout.rank()); EXPECT_THAT(layout.inner_order(), ::testing::ElementsAre()); EXPECT_THAT(layout.grid_origin(), ::testing::ElementsAre(0)); EXPECT_THAT(layout.read_chunk_shape(), ::testing::ElementsAre(5)); EXPECT_THAT(layout.write_chunk_shape(), ::testing::ElementsAre(5)); EXPECT_THAT(layout | tensorstore::IdentityTransform(1), Optional(layout)); } using HierarchicalGridCell = std::array<std::vector<Index>, 3>; HierarchicalGridCell GetHierarchicalGridCell( const ChunkLayout& layout, tensorstore::span<const Index> position) { const DimensionIndex rank = layout.rank(); auto origin = layout.grid_origin(); HierarchicalGridCell hier_grid_cell; for (Usage usage : ChunkLayout::kUsages) { auto& grid_cell = hier_grid_cell[static_cast<int>(usage)]; grid_cell.resize(rank); auto grid = layout[usage]; for (DimensionIndex i = 0; i < rank; ++i) { const Index size = grid.shape()[i]; if (size == 0) { grid_cell[i] = 0; continue; } const Index x = position[i] - origin[i]; grid_cell[i] = tensorstore::FloorOfRatio(x, size); } } return hier_grid_cell; } void TestGridCorrespondence(absl::BitGenRef gen, const ChunkLayout& output_layout, const ChunkLayout& input_layout, IndexTransformView<> transform) { const DimensionIndex output_rank = transform.output_rank(); const DimensionIndex input_rank = transform.input_rank(); ASSERT_EQ(output_layout.rank(), output_rank); ASSERT_EQ(input_layout.rank(), input_rank); HierarchicalGridCell output_chunk_divisors; for (Usage usage : ChunkLayout::kUsages) { auto& divisors = output_chunk_divisors[static_cast<size_t>(usage)]; divisors.resize(output_rank, 1); for (DimensionIndex output_dim = 0; output_dim < output_rank; ++output_dim) { const auto map = transform.output_index_maps()[output_dim]; if (map.method() != tensorstore::OutputIndexMethod::single_input_dimension) { continue; } auto size = output_layout[usage].shape()[output_dim]; if (size == 0) continue; divisors[output_dim] = std::abs(map.stride()) / tensorstore::GreatestCommonDivisor(map.stride(), size); } } SCOPED_TRACE(tensorstore::StrCat("output_layout=", output_layout)); SCOPED_TRACE(tensorstore::StrCat("input_layout=", input_layout)); SCOPED_TRACE( tensorstore::StrCat("output_chunk_divisors=", ::testing::PrintToString(output_chunk_divisors))); absl::flat_hash_map<HierarchicalGridCell, HierarchicalGridCell> output_to_input_cell_map; absl::flat_hash_map<HierarchicalGridCell, HierarchicalGridCell> input_to_output_cell_map; std::vector<Index> input_pos(input_rank); std::vector<Index> output_pos(output_rank); const auto test_point = [&] { TENSORSTORE_ASSERT_OK(transform.TransformIndices(input_pos, output_pos)); auto input_cell = GetHierarchicalGridCell(input_layout, input_pos); auto output_cell = GetHierarchicalGridCell(output_layout, output_pos); SCOPED_TRACE(tensorstore::StrCat("orig_output_cell=", ::testing::PrintToString(output_cell))); for (Usage usage : ChunkLayout::kUsages) { const size_t usage_index = static_cast<size_t>(usage); for (DimensionIndex output_dim = 0; output_dim < output_rank; ++output_dim) { auto& out_cell = output_cell[usage_index][output_dim]; out_cell = tensorstore::FloorOfRatio( out_cell, output_chunk_divisors[usage_index][output_dim]); } } SCOPED_TRACE( tensorstore::StrCat("input_pos=", tensorstore::span(input_pos))); SCOPED_TRACE( tensorstore::StrCat("output_pos=", tensorstore::span(output_pos))); SCOPED_TRACE(tensorstore::StrCat("input_cell=", ::testing::PrintToString(input_cell))); SCOPED_TRACE(tensorstore::StrCat("output_cell=", ::testing::PrintToString(output_cell))); auto input_it = output_to_input_cell_map.emplace(output_cell, input_cell).first; auto output_it = input_to_output_cell_map.emplace(input_cell, output_cell).first; EXPECT_EQ(input_it->second, input_cell); EXPECT_EQ(output_it->second, output_cell); }; constexpr size_t kNumSamplePoints = 10; for (size_t sample_i = 0; sample_i < kNumSamplePoints; ++sample_i) { for (DimensionIndex input_dim = 0; input_dim < input_rank; ++input_dim) { input_pos[input_dim] = absl::Uniform<Index>(absl::IntervalClosedClosed, gen, -40, 40); } for (DimensionIndex dir_input_dim = 0; dir_input_dim < input_rank; ++dir_input_dim) { const Index initial_pos = input_pos[dir_input_dim]; for (Index i = -20; i <= 20; ++i) { input_pos[dir_input_dim] = initial_pos + i; test_point(); } input_pos[dir_input_dim] = initial_pos; } } } template <typename Expr> void TestApplyIndexTransform(::nlohmann::json a, const Expr& expr, ::nlohmann::json b) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto a_layout, ChunkLayout::FromJson(a)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto b_layout, ChunkLayout::FromJson(b)); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto transform, tensorstore::IdentityTransform(a_layout.rank()) | expr); EXPECT_THAT(a_layout | transform, ::testing::Optional(b_layout)); } struct MakeRandomChunkLayoutParameters { DimensionIndex min_rank = 1; DimensionIndex max_rank = 3; }; ChunkLayout MakeRandomChunkLayout( absl::BitGenRef gen, const MakeRandomChunkLayoutParameters& p = {}) { const DimensionIndex rank = absl::Uniform<DimensionIndex>( absl::IntervalClosedClosed, gen, p.min_rank, p.max_rank); ChunkLayout layout; TENSORSTORE_CHECK_OK(layout.Set(tensorstore::RankConstraint(rank))); if (absl::Bernoulli(gen, 0.5)) { DimensionIndex inner_order[kMaxRank]; MakeRandomDimensionOrder(gen, tensorstore::span(inner_order, rank)); TENSORSTORE_CHECK_OK(layout.Set( ChunkLayout::InnerOrder(tensorstore::span(inner_order, rank)))); } else { } Index grid_origin[kMaxRank]; for (DimensionIndex dim = 0; dim < rank; ++dim) { grid_origin[dim] = absl::Uniform<Index>(absl::IntervalClosedClosed, gen, -5, 5); } TENSORSTORE_CHECK_OK(layout.Set( ChunkLayout::GridOrigin(tensorstore::span(grid_origin, rank)))); const auto set_grid = [&](Usage usage) { if (absl::Bernoulli(gen, 0.3)) { return; } Index shape[kMaxRank]; std::fill_n(shape, rank, 0); for (DimensionIndex dim = 0; dim < rank; ++dim) { if (absl::Bernoulli(gen, 0.3)) { continue; } Index size; if (usage == Usage::kWrite && layout.read_chunk_shape()[dim] != 0) { const Index read_size = layout.read_chunk_shape()[dim]; size = absl::Uniform<Index>(absl::IntervalClosedClosed, gen, 1, 5) * read_size; } else { size = absl::Uniform<Index>(absl::IntervalClosedClosed, gen, 1, usage == Usage::kCodec ? 5 : 10); } shape[dim] = size; } TENSORSTORE_CHECK_OK(layout.Set( ChunkLayout::Chunk(ChunkLayout::ChunkShapeBase( tensorstore::span<const Index>(shape, rank)), usage))); }; set_grid(Usage::kCodec); set_grid(Usage::kRead); set_grid(Usage::kWrite); TENSORSTORE_CHECK_OK(layout.Finalize()); return layout; } TEST(ChunkLayoutTest, Json) { tensorstore::TestJsonBinderRoundTripJsonOnly<ChunkLayout>( { { {"rank", 0}, }, { {"rank", 2}, }, { {"grid_origin", {1, 2}}, {"write_chunk", { {"shape", {10, 11}}, }}, {"inner_order", {1, 0}}, }, }, tensorstore::internal_json_binding::DefaultBinder<>, tensorstore::IncludeDefaults{false}); } TEST(ChunkLayoutTest, JsonExcludeDefaults) { tensorstore::TestJsonBinderRoundTripJsonOnly<ChunkLayout>( {{ {"grid_origin", {1, 2}}, {"write_chunk", { {"shape", {10, 11}}, }}, {"inner_order", {1, 0}}, }}, tensorstore::internal_json_binding::DefaultBinder<>, tensorstore::IncludeDefaults{false}); } TEST(ChunkLayoutTest, Rank2Translate) { TestApplyIndexTransform( { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"inner_order", {1, 0}}, }, Dims(0, 1).TranslateBy(5), { {"grid_origin", {5, 6}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"inner_order", {1, 0}}, }); } TEST(ChunkLayoutTest, Rank2Transpose) { TestApplyIndexTransform( { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"inner_order", {1, 0}}, }, Dims(1, 0).Transpose(), { {"grid_origin", {1, 0}}, {"write_chunk", { {"shape", {20, 10}}, }}, {"inner_order", {0, 1}}, }); } TEST(ChunkLayoutTest, Rank2TransposeWithGridOrder) { TestApplyIndexTransform( { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"inner_order", {1, 0}}, }, Dims(1, 0).Transpose(), { {"grid_origin", {1, 0}}, {"write_chunk", { {"shape", {20, 10}}, }}, {"inner_order", {0, 1}}, }); } TEST(ChunkLayoutTest, Rank2Stride) { TestApplyIndexTransform( { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"inner_order", {0, 1}}, }, Dims(0, 1).Stride(2), { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {5, 10}}, }}, {"inner_order", {0, 1}}, }); } TEST(ChunkLayoutTest, Rank2StrideNotEvenlyDisibile) { TestApplyIndexTransform( { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"inner_order", {0, 1}}, }, Dims(0, 1).Stride(6), { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {5, 10}}, }}, {"inner_order", {0, 1}}, }); } TEST(ChunkLayoutTest, Rank2StrideNegative) { TestApplyIndexTransform( { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"inner_order", {0, 1}}, }, Dims(0, 1).Stride(-2), { {"grid_origin", {1, 0}}, {"write_chunk", { {"shape", {5, 10}}, }}, {"inner_order", {0, 1}}, }); } TEST(ChunkLayoutTest, Rank2TwoLevelStrideNegative) { TestApplyIndexTransform( { {"grid_origin", {0, 1}}, {"write_chunk", { {"shape", {10, 20}}, }}, {"read_chunk", { {"shape", {5, 5}}, }}, {"inner_order", {0, 1}}, }, Dims(0, 1).TranslateBy({2, 3}).Stride(-2), { {"grid_origin", {0, -1}}, {"write_chunk", { {"shape", {5, 10}}, }}, {"read_chunk", { {"shape", {5, 5}}, }}, {"inner_order", {0, 1}}, }); } TEST(ApplyIndexTransformTest, RandomInvertible) { constexpr size_t kNumIterations = 10; for (size_t iteration = 0; iteration < kNumIterations; ++iteration) { std::minstd_rand gen{tensorstore::internal_testing::GetRandomSeedForTest( "TENSORSTORE_INTERNAL_LAYOUT_TEST_SEED")}; MakeRandomChunkLayoutParameters layout_p; auto output_layout = MakeRandomChunkLayout(gen, layout_p); tensorstore::internal::MakeStridedIndexTransformForOutputSpaceParameters transform_p; transform_p.new_dims_are_singleton = false; auto transform = tensorstore::internal::MakeRandomStridedIndexTransformForOutputSpace( gen, tensorstore::IdentityTransform(output_layout.rank()).domain(), transform_p); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto input_layout, output_layout | transform); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto new_output_layout, ApplyInverseIndexTransform(transform, input_layout)); SCOPED_TRACE(tensorstore::StrCat("transform=", transform)); EXPECT_EQ(output_layout, new_output_layout) << "input_layout=" << input_layout; TestGridCorrespondence(gen, output_layout, input_layout, transform); } } TEST(ApplyIndexTransformTest, RandomNonInvertibleUnaligned) { constexpr size_t kNumIterations = 10; for (size_t iteration = 0; iteration < kNumIterations; ++iteration) { std::minstd_rand gen{tensorstore::internal_testing::GetRandomSeedForTest( "TENSORSTORE_INTERNAL_LAYOUT_TEST_SEED")}; MakeRandomChunkLayoutParameters layout_p; auto output_layout = MakeRandomChunkLayout(gen, layout_p); tensorstore::internal::MakeStridedIndexTransformForOutputSpaceParameters transform_p; transform_p.new_dims_are_singleton = false; transform_p.max_stride = 3; auto transform = tensorstore::internal::MakeRandomStridedIndexTransformForOutputSpace( gen, tensorstore::IdentityTransform(output_layout.rank()).domain(), transform_p); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto input_layout, output_layout | transform); SCOPED_TRACE(tensorstore::StrCat("transform=", transform)); TestGridCorrespondence(gen, output_layout, input_layout, transform); } } TEST(ApplyIndexTransformTest, RandomNonInvertibleAligned) { constexpr size_t kNumIterations = 10; for (size_t iteration = 0; iteration < kNumIterations; ++iteration) { std::minstd_rand gen{tensorstore::internal_testing::GetRandomSeedForTest( "TENSORSTORE_INTERNAL_LAYOUT_TEST_SEED")}; MakeRandomChunkLayoutParameters layout_p; auto input_layout = MakeRandomChunkLayout(gen, layout_p); tensorstore::internal::MakeStridedIndexTransformForInputSpaceParameters transform_p; transform_p.max_stride = 3; auto transform = tensorstore::internal::MakeRandomStridedIndexTransformForInputSpace( gen, tensorstore::IdentityTransform(input_layout.rank()).domain(), transform_p); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto output_layout, ApplyInverseIndexTransform(transform, input_layout)); SCOPED_TRACE(tensorstore::StrCat("transform=", transform)); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto new_input_layout, ApplyIndexTransform(transform, output_layout)); EXPECT_EQ(input_layout, new_input_layout) << "output_layout=" << output_layout; TestGridCorrespondence(gen, output_layout, input_layout, transform); } } TEST(ChunkLayoutTest, DefaultConstruct) { ChunkLayout x; EXPECT_EQ(dynamic_rank, x.rank()); EXPECT_FALSE(x.inner_order().valid()); EXPECT_FALSE(x.grid_origin().valid()); EXPECT_FALSE(x.read_chunk().aspect_ratio().valid()); } TEST(ChunkLayoutTest, ConstraintsJson) { tensorstore::TestJsonBinderRoundTripJsonOnly<ChunkLayout>({ { {"write_chunk", { {"elements_soft_constraint", 5}, }}, }, { {"grid_origin", {1, 2}}, {"write_chunk", { {"shape", {10, 11}}, }}, {"inner_order", {1, 0}}, }, { {"grid_origin", {1, 2}}, {"write_chunk", { {"shape", {10, 11}}, }}, {"inner_order_soft_constraint", {1, 0}}, }, { {"grid_origin", {nullptr, nullptr, 3}}, {"grid_origin_soft_constraint", {4, nullptr, nullptr}}, {"write_chunk", {{"elements_soft_constraint", 1000}, {"shape", {5, nullptr, 6}}}}, {"read_chunk", {{"elements", 100}, {"shape_soft_constraint", {nullptr, 10, nullptr}}, {"aspect_ratio", {nullptr, 1, 2}}}}, {"codec_chunk", {{"aspect_ratio_soft_constraint", {nullptr, 2, 1}}}}, {"inner_order", {2, 1, 0}}, }, }); } TEST(ChunkLayoutTest, JsonRoundTripInexact) { tensorstore::TestJsonBinderRoundTripJsonOnlyInexact<ChunkLayout>({ {{ {"chunk", {{"elements", 50}}}, }, { {"read_chunk", {{"elements", 50}}}, {"write_chunk", {{"elements", 50}}}, }}, {{ {"chunk", {{"elements_soft_constraint", 50}}}, }, { {"read_chunk", {{"elements_soft_constraint", 50}}}, {"write_chunk", {{"elements_soft_constraint", 50}}}, }}, {{ {"read_chunk", {{"shape", {-1, 2, 3}}}}, }, { {"read_chunk", {{"shape", {nullptr, 2, 3}}, {"shape_soft_constraint", {-1, nullptr, nullptr}}}}, }}, {{ {"chunk", {{"elements_soft_constraint", 50}}}, {"read_chunk", {{"elements_soft_constraint", 60}}}, }, { {"read_chunk", {{"elements_soft_constraint", 50}}}, {"write_chunk", {{"elements_soft_constraint", 50}}}, }}, {{ {"chunk", {{"elements_soft_constraint", 50}}}, {"read_chunk", {{"elements", 60}}}, }, { {"read_chunk", {{"elements", 60}}}, {"write_chunk", {{"elements_soft_constraint", 50}}}, }}, {{ {"chunk", {{"aspect_ratio", {2, 3}}}}, }, { {"codec_chunk", {{"aspect_ratio", {2, 3}}}}, {"read_chunk", {{"aspect_ratio", {2, 3}}}}, {"write_chunk", {{"aspect_ratio", {2, 3}}}}, }}, {{ {"chunk", {{"aspect_ratio_soft_constraint", {2, 3}}}}, }, { {"codec_chunk", {{"aspect_ratio_soft_constraint", {2, 3}}}}, {"read_chunk", {{"aspect_ratio_soft_constraint", {2, 3}}}}, {"write_chunk", {{"aspect_ratio_soft_constraint", {2, 3}}}}, }}, {{ {"chunk", {{"shape", {2, 3}}}}, }, { {"read_chunk", {{"shape", {2, 3}}}}, {"write_chunk", {{"shape", {2, 3}}}}, }}, {{ {"chunk", {{"shape_soft_constraint", {2, 3}}}}, }, { {"read_chunk", {{"shape_soft_constraint", {2, 3}}}}, {"write_chunk", {{"shape_soft_constraint", {2, 3}}}}, }}, {{ {"chunk", {{"shape_soft_constraint", {2, 3}}}}, {"read_chunk", {{"shape", {4, nullptr}}}}, }, { {"read_chunk", { {"shape_soft_constraint", {nullptr, 3}}, {"shape", {4, nullptr}}, }}, {"write_chunk", {{"shape_soft_constraint", {2, 3}}}}, }}, }); } TEST(ChunkLayoutTest, CompareAllUnset) { ChunkLayout a; ChunkLayout b; EXPECT_FALSE(b.Set(ChunkLayout::InnerOrder({2, 3, 4})).ok()); EXPECT_EQ(a, b); EXPECT_EQ(b, a); } TEST(ChunkLayoutTest, CompareInnerOrder) { tensorstore::TestCompareDistinctFromJson<ChunkLayout>({ ::nlohmann::json::object_t(), {{"inner_order", {0, 1}}}, {{"inner_order", {0, 1, 2}}}, {{"inner_order", {0, 2, 1}}}, {{"inner_order_soft_constraint", {0, 2, 1}}}, }); } TEST(ChunkLayoutTest, CompareChunkElements) { for (std::string prefix : {"codec", "read", "write"}) { tensorstore::TestCompareDistinctFromJson<ChunkLayout>({ ::nlohmann::json::object_t(), {{prefix + "_chunk", {{"elements", 42}}}}, {{prefix + "_chunk", {{"elements", 43}}}}, {{prefix + "_chunk", {{"elements_soft_constraint", 42}}}}, }); } } TEST(ChunkLayoutTest, CompareChunkAspectRatio) { for (std::string prefix : {"codec", "read", "write"}) { tensorstore::TestCompareDistinctFromJson<ChunkLayout>({ ::nlohmann::json::object_t(), {{prefix + "_chunk", {{"aspect_ratio", {1, 2, nullptr}}}}}, {{prefix + "_chunk", {{"aspect_ratio", {1, 1, nullptr}}}}}, {{prefix + "_chunk", { {"aspect_ratio", {1, 1, nullptr}}, {"aspect_ratio_soft_constraint", {nullptr, nullptr, 4}}, }}}, {{prefix + "_chunk", {{"aspect_ratio_soft_constraint", {1, 2, nullptr}}}}}, }); } } TEST(ChunkLayoutTest, CompareGridOrigin) { tensorstore::TestCompareDistinctFromJson<ChunkLayout>({ ::nlohmann::json::object_t(), {{"grid_origin", {1, 2, nullptr}}}, {{"grid_origin", {1, 1, nullptr}}}, { {"grid_origin", {1, 1, nullptr}}, {"grid_origin_soft_constraint", {nullptr, nullptr, 4}}, }, {{"grid_origin_soft_constraint", {1, 2, nullptr}}}, }); } TEST(ChunkLayoutTest, CompareChunkShape) { for (std::string prefix : {"codec", "read", "write"}) { tensorstore::TestCompareDistinctFromJson<ChunkLayout>({ ::nlohmann::json::object_t(), {{prefix + "_chunk", {{"shape", {1, 2, nullptr}}}}}, {{prefix + "_chunk", {{"shape", {1, 1, nullptr}}}}}, {{prefix + "_chunk", { {"shape", {1, 1, nullptr}}, {"shape_soft_constraint", {nullptr, nullptr, 4}}, }}}, {{prefix + "_chunk", {{"shape_soft_constraint", {1, 2, nullptr}}}}}, }); } } TEST(ChunkLayoutTest, SetUnspecifiedUsage) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::Chunk(ChunkLayout::ChunkShape({5, 6, 0}), ChunkLayout::ChunkAspectRatio({2, 1, 0}), ChunkLayout::ChunkElements(42)))); EXPECT_THAT(constraints.ToJson(), ::testing::Optional(MatchesJson({ {"write_chunk", {{"shape", {5, 6, nullptr}}, {"aspect_ratio", {2, 1, nullptr}}, {"elements", 42}}}, {"read_chunk", {{"shape", {5, 6, nullptr}}, {"aspect_ratio", {2, 1, nullptr}}, {"elements", 42}}}, {"codec_chunk", {{"aspect_ratio", {2, 1, nullptr}}}}, }))); } TEST(ChunkLayoutConstraintsTest, ApplyIndexTransformRandomInvertible) { constexpr size_t kNumIterations = 10; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto output_constraints, ChunkLayout::FromJson({ {"codec_chunk", {{"elements_soft_constraint", 20}, {"aspect_ratio", {1, 2, 3}}, {"shape", {nullptr, 4, 5}}}}, {"read_chunk", {{"elements", 30}, {"aspect_ratio", {4, 5, 6}}, {"shape_soft_constraint", {6, nullptr, 7}}}}, {"write_chunk", {{"elements", 40}, {"aspect_ratio_soft_constraint", {7, 8, 9}}, {"shape", {8, 9, nullptr}}}}, {"grid_origin", {nullptr, nullptr, 11}}, {"inner_order_soft_constraint", {2, 0, 1}}, })); for (size_t iteration = 0; iteration < kNumIterations; ++iteration) { std::minstd_rand gen{tensorstore::internal_testing::GetRandomSeedForTest( "TENSORSTORE_INTERNAL_LAYOUT_CONSTRAINTS_TEST_SEED")}; tensorstore::internal::MakeStridedIndexTransformForOutputSpaceParameters transform_p; transform_p.new_dims_are_singleton = true; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto domain, IndexDomainBuilder(output_constraints.rank()).Finalize()); auto transform = tensorstore::internal::MakeRandomStridedIndexTransformForOutputSpace( gen, domain, transform_p); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto inverse_transform, InverseTransform(transform)); SCOPED_TRACE(tensorstore::StrCat("transform=", transform)); SCOPED_TRACE(tensorstore::StrCat("inverse_transform=", inverse_transform)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto input_constraints, output_constraints | transform); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto input_constraints2, ApplyInverseIndexTransform(inverse_transform, output_constraints)); EXPECT_EQ(input_constraints, input_constraints2) << "output_constraints=" << output_constraints; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto output_constraints2, ApplyInverseIndexTransform(transform, input_constraints)); EXPECT_EQ(output_constraints, output_constraints2) << "input_constraints=" << input_constraints; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto new_output_constraints, input_constraints | inverse_transform); EXPECT_EQ(output_constraints, new_output_constraints) << "input_constraints=" << input_constraints; } } TEST(ChunkLayoutTest, ApplyIndexTransformNoRank) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto new_constraints, constraints | tensorstore::Dims(0, 1).TranslateBy(5)); EXPECT_EQ(constraints, new_constraints); } TEST(ChunkLayoutTest, ApplyIndexTransform) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto constraints, ChunkLayout::FromJson({ {"inner_order", {0, 1, 2}}, {"grid_origin", {1, 2, 3}}, {"read_chunk", {{"shape", {4, 5, 6}}}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto expected_new_constraints, ChunkLayout::FromJson({ {"inner_order", {2, 1, 0}}, {"grid_origin", {8, 7, 6}}, {"read_chunk", {{"shape", {6, 5, 4}}}}, })); EXPECT_THAT( constraints | tensorstore::Dims(2, 1, 0).TranslateBy(5).Transpose(), ::testing::Optional(expected_new_constraints)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto expected_new_inverse_constraints, ChunkLayout::FromJson({ {"inner_order", {2, 1, 0}}, {"grid_origin", {-2, -3, -4}}, {"read_chunk", {{"shape", {6, 5, 4}}}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto transform, tensorstore::IdentityTransform(3) | tensorstore::Dims(2, 1, 0).TranslateBy(5).Transpose()); EXPECT_THAT(ApplyInverseIndexTransform(transform, constraints), ::testing::Optional(expected_new_inverse_constraints)); } TEST(ChunkLayoutTest, ApplyIndexTransformOverflow) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto constraints, ChunkLayout::FromJson({ {"grid_origin", {0, 0, 0}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto transform, tensorstore::IdentityTransform(3) | tensorstore::Dims(0).TranslateBy(kInfIndex)); EXPECT_THAT(constraints | transform, MatchesStatus( absl::StatusCode::kOutOfRange, "Error transforming grid_origin: " "Error transforming output dimension 0 -> input dimension 0: " "Integer overflow transforming output origin 0 by offset .* " "and stride 1")); EXPECT_THAT(ApplyInverseIndexTransform(transform, constraints), MatchesStatus( absl::StatusCode::kOutOfRange, "Error transforming grid_origin: " "Error transforming input dimension 0 -> output dimension 0: " "Integer overflow transforming input origin 0 by offset .* " "and stride 1")); } TEST(ChunkLayoutTest, ApplyInverseIndexTransformMissingInputDimensionRequired) { ChunkLayout input_constraints; TENSORSTORE_ASSERT_OK(input_constraints.Set(ChunkLayout::GridOrigin({5, 6}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto transform, IndexTransformBuilder(2, 1) .output_single_input_dimension(0, 1) .Finalize()); EXPECT_THAT( ApplyInverseIndexTransform(transform, input_constraints), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error transforming grid_origin: " "No output dimension corresponds to input dimension 0")); } TEST(ChunkLayoutTest, ApplyInverseIndexTransformMissingInputDimensionNotRequired) { ChunkLayout input_constraints; TENSORSTORE_ASSERT_OK(input_constraints.Set( ChunkLayout::GridOrigin({5, 6}, false))); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto transform, IndexTransformBuilder(2, 1) .output_single_input_dimension(0, 1) .Finalize()); ChunkLayout output_constraints; TENSORSTORE_ASSERT_OK(output_constraints.Set( ChunkLayout::GridOrigin({6}, false))); EXPECT_THAT(ApplyInverseIndexTransform(transform, input_constraints), ::testing::Optional(output_constraints)); } TEST(ChunkLayoutTest, ApplyIndexTransformKnownRankNullTransform) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto constraints, ChunkLayout::FromJson({ {"inner_order", {2, 1, 0}}, })); EXPECT_THAT(constraints | tensorstore::IndexTransform<>(), ::testing::Optional(constraints)); EXPECT_THAT( ApplyInverseIndexTransform(tensorstore::IndexTransform<>(), constraints), ::testing::Optional(constraints)); } TEST(ChunkLayoutTest, ApplyIndexTransformRankMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto constraints, ChunkLayout::FromJson({ {"inner_order", {2, 1, 0}}, })); EXPECT_THAT(constraints | tensorstore::IdentityTransform(2), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot transform constraints of rank 3 by index " "transform of rank 2 -> 2")); EXPECT_THAT(ApplyInverseIndexTransform(tensorstore::IdentityTransform(2), constraints), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot transform constraints of rank 3 by index " "transform of rank 2 -> 2")); } TEST(ChunkLayoutTest, ApplyIndexTransformUnknownRankNullTransform) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto constraints, ChunkLayout::FromJson({ {"read_chunk", {{"elements", 42}}}, })); EXPECT_THAT(constraints | tensorstore::IndexTransform<>(), ::testing::Optional(constraints)); EXPECT_THAT( ApplyInverseIndexTransform(tensorstore::IndexTransform<>(), constraints), ::testing::Optional(constraints)); } TEST(ChunkLayoutTest, InnerOrder) { ChunkLayout constraints; EXPECT_FALSE(constraints.inner_order().valid()); EXPECT_FALSE(constraints.inner_order().hard_constraint); EXPECT_FALSE(constraints.inner_order().valid()); EXPECT_THAT(constraints.inner_order(), ::testing::ElementsAre()); TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::InnerOrder({0, 2, 1}, false))); EXPECT_EQ(3, constraints.rank()); EXPECT_FALSE(constraints.inner_order().hard_constraint); EXPECT_THAT(constraints.inner_order(), ::testing::ElementsAre(0, 2, 1)); EXPECT_THAT( constraints.Set(ChunkLayout::InnerOrder({0, 2, 2})), MatchesStatus( absl::StatusCode::kInvalidArgument, "Error setting inner_order: Invalid permutation: \\{0, 2, 2\\}")); EXPECT_THAT( constraints.Set( ChunkLayout::InnerOrder({0, 2, 2}, false)), MatchesStatus( absl::StatusCode::kInvalidArgument, "Error setting inner_order: Invalid permutation: \\{0, 2, 2\\}")); TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::InnerOrder({1, 2, 0}, false))); EXPECT_FALSE(constraints.inner_order().hard_constraint); EXPECT_THAT(constraints.inner_order(), ::testing::ElementsAre(0, 2, 1)); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::InnerOrder({2, 1, 0}))); EXPECT_TRUE(constraints.inner_order().hard_constraint); EXPECT_THAT(constraints.inner_order(), ::testing::ElementsAre(2, 1, 0)); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::InnerOrder({2, 1, 0}))); TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::InnerOrder({0, 2, 1}, false))); EXPECT_TRUE(constraints.inner_order().hard_constraint); EXPECT_THAT(constraints.inner_order(), ::testing::ElementsAre(2, 1, 0)); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::InnerOrder())); EXPECT_THAT( constraints.Set(ChunkLayout::InnerOrder({0, 1, 2})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting inner_order: " "New hard constraint \\(\\{0, 1, 2\\}\\) does not match " "existing hard constraint \\(\\{2, 1, 0\\}\\)")); EXPECT_TRUE(constraints.inner_order().hard_constraint); EXPECT_THAT(constraints.inner_order(), ::testing::ElementsAre(2, 1, 0)); } TEST(ChunkLayoutTest, GridOrigin) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::GridOrigin( {1, kImplicit, kImplicit}, false))); EXPECT_EQ(3, constraints.rank()); EXPECT_THAT(constraints.grid_origin(), ::testing::ElementsAre(1, kImplicit, kImplicit)); EXPECT_EQ(0, constraints.grid_origin().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::GridOrigin({2, 3, kImplicit}, false))); EXPECT_THAT(constraints.grid_origin(), ::testing::ElementsAre(1, 3, kImplicit)); EXPECT_EQ(0, constraints.grid_origin().hard_constraint.to_uint()); EXPECT_THAT(constraints.Set(ChunkLayout::GridOrigin({kInfIndex, 2, 3})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting grid_origin: " "Invalid value for dimension 0: .*")); EXPECT_THAT(constraints.Set( ChunkLayout::GridOrigin({2, 3}, false)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting grid_origin: " "Rank 2 does not match existing rank 3")); TENSORSTORE_ASSERT_OK( constraints.Set(ChunkLayout::GridOrigin({kImplicit, 4, kImplicit}))); EXPECT_THAT(constraints.grid_origin(), ::testing::ElementsAre(1, 4, kImplicit)); EXPECT_EQ(0b10, constraints.grid_origin().hard_constraint.to_uint()); EXPECT_THAT(constraints.Set(ChunkLayout::GridOrigin({3, 5, kImplicit})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting grid_origin: " "New hard constraint \\(5\\) for dimension 1 " "does not match existing hard constraint \\(4\\)")); EXPECT_THAT(constraints.grid_origin(), ::testing::ElementsAre(1, 4, kImplicit)); EXPECT_EQ(0b10, constraints.grid_origin().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::GridOrigin({1, 4, 5}))); EXPECT_THAT(constraints.grid_origin(), ::testing::ElementsAre(1, 4, 5)); EXPECT_EQ(0b111, constraints.grid_origin().hard_constraint.to_uint()); } TEST(ChunkLayoutTest, ReadChunkShape) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::ReadChunkShape({100, 0, 0}, false))); EXPECT_EQ(3, constraints.rank()); EXPECT_THAT(constraints.read_chunk_shape(), ::testing::ElementsAre(100, 0, 0)); EXPECT_THAT(constraints.read_chunk().shape(), ::testing::ElementsAre(100, 0, 0)); EXPECT_EQ(0, constraints.read_chunk_shape().hard_constraint.to_uint()); EXPECT_EQ(0, constraints.read_chunk().shape().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::ReadChunkShape({2, 300, 0}, false))); EXPECT_THAT(constraints.read_chunk().shape(), ::testing::ElementsAre(100, 300, 0)); EXPECT_EQ(0, constraints.read_chunk_shape().hard_constraint.to_uint()); EXPECT_THAT(constraints.Set(ChunkLayout::ReadChunkShape({-5, 300, 3})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk shape: " "Invalid value for dimension 0: .*")); EXPECT_THAT(constraints.Set(ChunkLayout::ReadChunkShape( {2, 3}, false)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk shape: " "Rank 2 does not match existing rank 3")); TENSORSTORE_ASSERT_OK( constraints.Set(ChunkLayout::ReadChunkShape({0, 4, 0}))); EXPECT_THAT(constraints.read_chunk_shape(), ::testing::ElementsAre(100, 4, 0)); EXPECT_EQ(0b10, constraints.read_chunk_shape().hard_constraint.to_uint()); EXPECT_EQ(0b10, constraints.read_chunk().shape().hard_constraint.to_uint()); EXPECT_THAT(constraints.Set(ChunkLayout::ReadChunkShape({100, 5, 0})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk shape: " "New hard constraint \\(5\\) for dimension 1 " "does not match existing hard constraint \\(4\\)")); EXPECT_THAT(constraints.read_chunk_shape(), ::testing::ElementsAre(100, 4, 0)); EXPECT_EQ(0b10, constraints.read_chunk_shape().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK( constraints.Set(ChunkLayout::ReadChunkShape({100, 4, 5}))); EXPECT_THAT(constraints.read_chunk_shape(), ::testing::ElementsAre(100, 4, 5)); EXPECT_EQ(0b111, constraints.read_chunk_shape().hard_constraint.to_uint()); } TEST(ChunkLayoutTest, WriteChunkShape) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::WriteChunkShape({100, 0, 0}, false))); EXPECT_EQ(3, constraints.rank()); EXPECT_THAT(constraints.write_chunk_shape(), ::testing::ElementsAre(100, 0, 0)); EXPECT_THAT(constraints.write_chunk().shape(), ::testing::ElementsAre(100, 0, 0)); EXPECT_EQ(0, constraints.write_chunk_shape().hard_constraint.to_uint()); EXPECT_EQ(0, constraints.write_chunk().shape().hard_constraint.to_uint()); } TEST(ChunkLayoutTest, ReadChunkAspectRatio) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::ReadChunkAspectRatio({2, 0, 0}, false))); EXPECT_EQ(3, constraints.rank()); EXPECT_THAT(constraints.read_chunk_aspect_ratio(), ::testing::ElementsAre(2, 0, 0)); EXPECT_THAT(constraints.read_chunk().aspect_ratio(), ::testing::ElementsAre(2, 0, 0)); EXPECT_EQ(0, constraints.read_chunk_aspect_ratio().hard_constraint.to_uint()); EXPECT_EQ(0, constraints.read_chunk().aspect_ratio().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::ReadChunkAspectRatio( {3, 1.5, 0}, false))); EXPECT_THAT(constraints.read_chunk().aspect_ratio(), ::testing::ElementsAre(2, 1.5, 0)); EXPECT_EQ(0, constraints.read_chunk_aspect_ratio().hard_constraint.to_uint()); EXPECT_THAT(constraints.Set(ChunkLayout::ReadChunkAspectRatio({-5, 1.5, 3})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk aspect_ratio: " "Invalid value for dimension 0: .*")); EXPECT_THAT(constraints.Set(ChunkLayout::ReadChunkAspectRatio( {2, 3}, false)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk aspect_ratio: " "Rank 2 does not match existing rank 3")); TENSORSTORE_ASSERT_OK( constraints.Set(ChunkLayout::ReadChunkAspectRatio({0, 4, 0}))); EXPECT_THAT(constraints.read_chunk_aspect_ratio(), ::testing::ElementsAre(2, 4, 0)); EXPECT_EQ(0b10, constraints.read_chunk_aspect_ratio().hard_constraint.to_uint()); EXPECT_EQ(0b10, constraints.read_chunk().aspect_ratio().hard_constraint.to_uint()); EXPECT_THAT(constraints.Set(ChunkLayout::ReadChunkAspectRatio({2, 5, 0})), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk aspect_ratio: " "New hard constraint \\(5\\) for dimension 1 " "does not match existing hard constraint \\(4\\)")); EXPECT_THAT(constraints.read_chunk_aspect_ratio(), ::testing::ElementsAre(2, 4, 0)); EXPECT_EQ(0b10, constraints.read_chunk_aspect_ratio().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK( constraints.Set(ChunkLayout::ReadChunkAspectRatio({2, 4, 5}))); EXPECT_THAT(constraints.read_chunk_aspect_ratio(), ::testing::ElementsAre(2, 4, 5)); EXPECT_EQ(0b111, constraints.read_chunk_aspect_ratio().hard_constraint.to_uint()); } TEST(ChunkLayoutTest, WriteChunkAspectRatio) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::WriteChunkAspectRatio( {2, 0, 0}, false))); EXPECT_EQ(3, constraints.rank()); EXPECT_THAT(constraints.write_chunk_aspect_ratio(), ::testing::ElementsAre(2, 0, 0)); EXPECT_THAT(constraints.write_chunk().aspect_ratio(), ::testing::ElementsAre(2, 0, 0)); EXPECT_EQ(0, constraints.write_chunk_aspect_ratio().hard_constraint.to_uint()); EXPECT_EQ(0, constraints.write_chunk().aspect_ratio().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::WriteChunkAspectRatio( {3, 1.5, 0}, false))); EXPECT_THAT(constraints.write_chunk().aspect_ratio(), ::testing::ElementsAre(2, 1.5, 0)); EXPECT_EQ(0, constraints.write_chunk_aspect_ratio().hard_constraint.to_uint()); } TEST(ChunkLayoutTest, CodecChunkAspectRatio) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::CodecChunkAspectRatio( {2, 0, 0}, false))); EXPECT_EQ(3, constraints.rank()); EXPECT_THAT(constraints.codec_chunk_aspect_ratio(), ::testing::ElementsAre(2, 0, 0)); EXPECT_THAT(constraints.codec_chunk().aspect_ratio(), ::testing::ElementsAre(2, 0, 0)); EXPECT_EQ(0, constraints.codec_chunk_aspect_ratio().hard_constraint.to_uint()); EXPECT_EQ(0, constraints.codec_chunk().aspect_ratio().hard_constraint.to_uint()); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::CodecChunkAspectRatio( {3, 1.5, 0}, false))); EXPECT_THAT(constraints.codec_chunk().aspect_ratio(), ::testing::ElementsAre(2, 1.5, 0)); EXPECT_EQ(0, constraints.codec_chunk_aspect_ratio().hard_constraint.to_uint()); } TEST(ChunkLayoutTest, ReadChunkElements) { ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::ReadChunkElements(kImplicit, false))); EXPECT_EQ(kImplicit, constraints.read_chunk_elements()); TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::ReadChunkElements(42, false))); EXPECT_EQ(42, constraints.read_chunk_elements()); EXPECT_EQ(42, constraints.read_chunk().elements()); EXPECT_EQ(false, constraints.read_chunk_elements().hard_constraint); EXPECT_EQ(false, constraints.read_chunk().elements().hard_constraint); TENSORSTORE_ASSERT_OK(constraints.Set( ChunkLayout::ReadChunkElements(43, false))); EXPECT_EQ(42, constraints.read_chunk().elements()); EXPECT_EQ(false, constraints.read_chunk_elements().hard_constraint); EXPECT_THAT(constraints.Set(ChunkLayout::ReadChunkElements(-5)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk elements: " "Invalid value: -5")); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::ReadChunkElements(45))); EXPECT_EQ(45, constraints.read_chunk_elements()); EXPECT_EQ(true, constraints.read_chunk_elements().hard_constraint); EXPECT_EQ(true, constraints.read_chunk().elements().hard_constraint); EXPECT_THAT( constraints.Set(ChunkLayout::ReadChunkElements(46)), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error setting read_chunk elements: " "New hard constraint \\(46\\) " "does not match existing hard constraint \\(45\\)")); EXPECT_EQ(45, constraints.read_chunk_elements()); EXPECT_EQ(true, constraints.read_chunk_elements().hard_constraint); TENSORSTORE_ASSERT_OK(constraints.Set(ChunkLayout::ReadChunkElements(45))); EXPECT_EQ(45, constraints.read_chunk_elements()); EXPECT_EQ(true, constraints.read_chunk_elements().hard_constraint); } TEST(ChunkLayoutTest, SetPreciseChunkLayout) { ::nlohmann::json layout_json{ {"inner_order", {0, 1, 2}}, {"grid_origin", {1, 2, 3}}, {"write_chunk", {{"shape", {100, 200, 300}}}}, {"read_chunk", {{"shape", {10, 20, 30}}}}, {"codec_chunk", {{"shape", {4, 5, 6}}}}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto layout, ChunkLayout::FromJson(layout_json)); ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set(layout)); EXPECT_THAT(constraints.ToJson(), ::testing::Optional(MatchesJson(layout_json))); EXPECT_EQ(ChunkLayout(layout), constraints); } TEST(ChunkLayoutTest, SetPreciseChunkLayoutAsSoftConstraints) { ::nlohmann::json layout_json{ {"inner_order", {0, 1, 2}}, {"grid_origin", {1, 2, 3}}, {"write_chunk", {{"shape", {100, 200, 300}}}}, {"read_chunk", {{"shape", {10, 20, 30}}}}, {"codec_chunk", {{"shape", {4, 5, 6}}}}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto layout, ChunkLayout::FromJson(layout_json)); ChunkLayout constraints; TENSORSTORE_ASSERT_OK( constraints.Set(ChunkLayout(layout, false))); EXPECT_THAT(constraints.ToJson(), ::testing::Optional(MatchesJson({ {"inner_order_soft_constraint", {0, 1, 2}}, {"grid_origin_soft_constraint", {1, 2, 3}}, {"write_chunk", {{"shape_soft_constraint", {100, 200, 300}}}}, {"read_chunk", {{"shape_soft_constraint", {10, 20, 30}}}}, {"codec_chunk", {{"shape_soft_constraint", {4, 5, 6}}}}, }))); EXPECT_EQ(constraints, ChunkLayout(ChunkLayout(layout), false)); ChunkLayout constraints2; TENSORSTORE_ASSERT_OK( constraints2.Set(ChunkLayout(layout, false))); EXPECT_EQ(constraints, constraints2); } TEST(ChunkLayoutTest, SetChunkLayout) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto layout_a, ChunkLayout::FromJson({ {"inner_order", {0, 1, 2}}, {"grid_origin_soft_constraint", {1, 2, 3}}, {"write_chunk", { {"shape_soft_constraint", {100, 200, 300}}, {"elements", 42}, }}, {"read_chunk", { {"shape", {nullptr, 20, 30}}, {"shape_soft_constraint", {100, nullptr, nullptr}}, {"elements_soft_constraint", 50}, }}, {"codec_chunk", {{"aspect_ratio", {4, 5, 6}}}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto layout_b, ChunkLayout::FromJson({ {"inner_order_soft_constraint", {2, 0, 1}}, {"grid_origin", {4, 5, 6}}, {"write_chunk", { {"shape", {200, 400, 900}}, {"elements", 42}, }}, {"read_chunk", { {"shape", {10, nullptr, 30}}, {"elements", 50}, }}, })); ChunkLayout constraints; TENSORSTORE_ASSERT_OK(constraints.Set(layout_a)); TENSORSTORE_ASSERT_OK(constraints.Set(layout_b)); EXPECT_THAT(constraints.ToJson(), ::testing::Optional(MatchesJson({ {"inner_order", {0, 1, 2}}, {"grid_origin", {4, 5, 6}}, {"write_chunk", { {"shape", {200, 400, 900}}, {"elements", 42}, }}, {"read_chunk", { {"shape", {10, 20, 30}}, {"elements", 50}, }}, {"codec_chunk", { {"aspect_ratio", {4, 5, 6}}, }}, }))); constraints = layout_a; TENSORSTORE_ASSERT_OK( constraints.Set(ChunkLayout(layout_b, false))); EXPECT_THAT(constraints.ToJson(), ::testing::Optional(MatchesJson({ {"inner_order", {0, 1, 2}}, {"grid_origin_soft_constraint", {1, 2, 3}}, {"write_chunk", { {"shape_soft_constraint", {100, 200, 300}}, {"elements", 42}, }}, {"read_chunk", { {"shape", {nullptr, 20, 30}}, {"shape_soft_constraint", {100, nullptr, nullptr}}, {"elements_soft_constraint", 50}, }}, {"codec_chunk", { {"aspect_ratio", {4, 5, 6}}, }}, }))); } TEST(ChunkLayoutTest, CopyOnWriteWithRankSet) { ChunkLayout a; TENSORSTORE_ASSERT_OK(a.Set(ChunkLayout::InnerOrder({0, 1, 2}))); EXPECT_THAT(a.ToJson(), ::testing::Optional(MatchesJson({{"inner_order", {0, 1, 2}}}))); ChunkLayout b = a; TENSORSTORE_ASSERT_OK(b.Set(ChunkLayout::GridOrigin({1, 2, 3}))); EXPECT_THAT(a.ToJson(), ::testing::Optional(MatchesJson({{"inner_order", {0, 1, 2}}}))); EXPECT_THAT(b.ToJson(), ::testing::Optional(MatchesJson({ {"inner_order", {0, 1, 2}}, {"grid_origin", {1, 2, 3}}, }))); } TEST(ChunkLayoutTest, CopyOnWriteWithRankNotSet) { ChunkLayout a; TENSORSTORE_ASSERT_OK(a.Set(ChunkLayout::ReadChunkElements(5))); EXPECT_THAT( a.ToJson(), ::testing::Optional(MatchesJson({{"read_chunk", {{"elements", 5}}}}))); ChunkLayout b = a; TENSORSTORE_ASSERT_OK(b.Set(ChunkLayout::GridOrigin({1, 2, 3}))); EXPECT_THAT( a.ToJson(), ::testing::Optional(MatchesJson({{"read_chunk", {{"elements", 5}}}}))); EXPECT_THAT(b.ToJson(), ::testing::Optional(MatchesJson({ {"read_chunk", {{"elements", 5}}}, {"grid_origin", {1, 2, 3}}, }))); } TEST(ChunkLayoutTest, Ostream) { ChunkLayout a; EXPECT_EQ("{}", tensorstore::StrCat(a)); } TEST(ChooseChunkGridTest, Rank0) { Box box(0); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(), BoxView(0), box)); } TEST(ChooseChunkGridTest, Rank1Unconstrained) { Box box(1); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(), BoxView(1), box)); EXPECT_EQ(Box<1>({1024 * 1024}), box); } TEST(ChooseChunkGridTest, Rank2Unconstrained) { Box box(2); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(), BoxView(2), box)); EXPECT_EQ(Box({1024, 1024}), box); } TEST(ChooseChunkGridTest, Rank3Unconstrained) { Box box(3); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(), BoxView(3), box)); EXPECT_EQ(Box({101, 101, 101}), box); } TEST(ChooseChunkGridTest, Rank4Unconstrained) { Box box(4); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(), BoxView(4), box)); EXPECT_EQ(Box({32, 32, 32, 32}), box); } TEST(ChooseChunkGridTest, Rank1ElementsConstrained) { Box box(1); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( tensorstore::span<const Index>({42}), ChunkLayout::GridView(ChunkLayout::ChunkElementsBase(9000)), BoxView(1), box)); EXPECT_EQ(Box<1>({42}, {9000}), box); } TEST(ChooseChunkGridTest, Rank1ShapeConstrained) { Box box(1); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( tensorstore::span<const Index>({42}), ChunkLayout::GridView(ChunkLayout::ChunkShape({55})), BoxView(1), box)); EXPECT_EQ(Box<1>({42}, {55}), box); } TEST(ChooseChunkGridTest, Rank1ShapeFullExtent) { Box box(1); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( tensorstore::span<const Index>({42}), ChunkLayout::GridView( ChunkLayout::ChunkShape({-1}), ChunkLayout::ChunkAspectRatio(), ChunkLayout::ChunkElements(10)), BoxView<1>({100}), box)); EXPECT_EQ(Box<1>({42}, {100}), box); EXPECT_THAT( ChooseChunkGrid( tensorstore::span<const Index>({42}), ChunkLayout::GridView( ChunkLayout::ChunkShape({-1}), ChunkLayout::ChunkAspectRatio(), ChunkLayout::ChunkElements(10)), BoxView(1), box), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot match chunk size for dimension 0 to " "unbounded domain \\(-inf, \\+inf\\)")); } TEST(ChooseChunkGridTest, Rank1BoundedDomain) { Box box(1); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkElementsBase(9000)), BoxView<1>({42}, {1000}), box)); EXPECT_EQ(Box<1>({42}, {1000}), box); } TEST(ChunkLayoutTest, ChooseChunkGridRank1BoundedDomainOriginConstrained) { Box box(1); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( tensorstore::span<const Index>({45}), ChunkLayout::GridView(ChunkLayout::ChunkElementsBase(9000)), BoxView<1>({42}, {1000}), box)); EXPECT_EQ(Box<1>({45}, {1000}), box); } TEST(ChooseChunkGridTest, Rank2AspectRatio) { Box box(2); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkShape(), ChunkLayout::ChunkAspectRatio({1.0, 2.0}), ChunkLayout::ChunkElements(200)), BoxView(2), box)); EXPECT_EQ(Box({10, 20}), box); } TEST(ChooseChunkGridTest, Rank3AspectRatio) { Box box(3); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkShape(), ChunkLayout::ChunkAspectRatio({1.0, 0, 2.0}), ChunkLayout::ChunkElements(2000)), BoxView(3), box)); EXPECT_EQ(Box({10, 10, 20}), box); } TEST(ChooseChunkGridTest, Rank3AspectRatioWithChunkShapeConstraint) { Box box(3); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkShape({0, 1, 0}), ChunkLayout::ChunkAspectRatio({1.0, 0, 2.0}), ChunkLayout::ChunkElements(200)), BoxView(3), box)); EXPECT_EQ(Box({10, 1, 20}), box); } TEST(ChooseChunkGridTest, Rank3AspectRatioLarge1) { Box box(3); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkShape(), ChunkLayout::ChunkAspectRatio({1.0, 1.0, 1e30}), ChunkLayout::ChunkElements(200)), BoxView(3), box)); EXPECT_EQ(Box({1, 1, 200}), box); } TEST(ChooseChunkGridTest, Rank3AspectRatioLarge2) { Box box(3); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkShape(), ChunkLayout::ChunkAspectRatio({1.0, 1e30, 1e30}), ChunkLayout::ChunkElements(100)), BoxView(3), box)); EXPECT_EQ(Box({1, 10, 10}), box); } TEST(ChooseChunkGridTest, Rank3AspectRatioLarge3) { Box box(3); TENSORSTORE_ASSERT_OK(ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkShape(), ChunkLayout::ChunkAspectRatio({1.0, 1e30, 1e30}), ChunkLayout::ChunkElements(Index(1) << 40)), BoxView(3), box)); EXPECT_EQ(Box({1, Index(1) << 20, Index(1) << 20}), box); } TEST(ChooseChunkGridTest, GridOriginRankMismatch) { Box box(3); EXPECT_THAT( ChooseChunkGrid( tensorstore::span<const Index>({1, 2}), ChunkLayout::GridView(), BoxView(3), box), MatchesStatus( absl::StatusCode::kInvalidArgument, "Rank of constraints \\(2\\) does not match rank of domain \\(3\\)")); } TEST(ChooseChunkGridTest, ShapeConstraintRankMismatch) { Box box(3); EXPECT_THAT( ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkShape({1, 2})), BoxView(3), box), MatchesStatus( absl::StatusCode::kInvalidArgument, "Rank of constraints \\(2\\) does not match rank of domain \\(3\\)")); } TEST(ChooseChunkGridTest, AspectRatioConstraintRankMismatch) { Box box(3); EXPECT_THAT( ChooseChunkGrid( {}, ChunkLayout::GridView(ChunkLayout::ChunkAspectRatio({1, 2})), BoxView(3), box), MatchesStatus( absl::StatusCode::kInvalidArgument, "Rank of constraints \\(2\\) does not match rank of domain \\(3\\)")); } TEST(ChunkLayoutGridTest, Basic) { ChunkLayout::Grid grid; TENSORSTORE_EXPECT_OK(grid.Set(ChunkLayout::ChunkShape({10, 11}))); EXPECT_EQ(2, grid.rank()); EXPECT_THAT(grid.shape(), ::testing::ElementsAre(10, 11)); } TEST(ChunkLayoutGridTest, Json) { tensorstore::TestJsonBinderRoundTripJsonOnly<ChunkLayout::Grid>( { { {"shape", {10, 11}}, {"aspect_ratio", {2, nullptr}}, {"aspect_ratio_soft_constraint", {nullptr, 3}}, {"elements_soft_constraint", 10000}, }, }, tensorstore::internal_json_binding::DefaultBinder<>, tensorstore::IncludeDefaults{false}); } TEST(ChunkLayoutSerializationTest, SerializationRoundTrip) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto chunk_layout, ChunkLayout::FromJson({ {"grid_origin", {nullptr, nullptr, 3}}, {"grid_origin_soft_constraint", {4, nullptr, nullptr}}, {"write_chunk", {{"elements_soft_constraint", 1000}, {"shape", {5, nullptr, 6}}}}, {"read_chunk", {{"elements", 100}, {"shape_soft_constraint", {nullptr, 10, nullptr}}, {"aspect_ratio", {nullptr, 1, 2}}}}, {"codec_chunk", {{"aspect_ratio_soft_constraint", {nullptr, 2, 1}}}}, {"inner_order", {2, 1, 0}}, })); tensorstore::serialization::TestSerializationRoundTrip(chunk_layout); } TEST(ChooseChunkShapeTest, Elements) { Index chunk_shape[kMaxRank] = {0}; TENSORSTORE_ASSERT_OK(ChooseChunkShape( ChunkLayout::GridView( ChunkLayout::ChunkElementsBase(1000, false)), BoxView({0, 0, 0}, {2000, 2000, 2000}), tensorstore::span<Index>(chunk_shape, 3))); EXPECT_THAT(tensorstore::span<Index>(chunk_shape, 3), testing::ElementsAre(10, 10, 10)); TENSORSTORE_ASSERT_OK(ChooseChunkShape( ChunkLayout::GridView( ChunkLayout::ChunkElementsBase(1000, true)), BoxView({0, 0, 0}, {2000, 2000, 1}), tensorstore::span<Index>(chunk_shape, 3))); EXPECT_THAT(tensorstore::span<Index>(chunk_shape, 3), testing::ElementsAre(31, 31, 1)); } TEST(ChooseChunkShapeTest, AspectRatio) { Index chunk_shape[kMaxRank] = {0}; TENSORSTORE_ASSERT_OK(ChooseChunkShape( ChunkLayout::GridView( ChunkLayout::ChunkAspectRatioBase({3, 2, 1}, true)), BoxView({0, 0, 0}, {2000, 2000, 2000}), tensorstore::span<Index>(chunk_shape, 3))); EXPECT_THAT(tensorstore::span<Index>(chunk_shape, 3), testing::ElementsAre(167, 111, 55)); TENSORSTORE_ASSERT_OK(ChooseChunkShape( ChunkLayout::GridView( ChunkLayout::ChunkAspectRatioBase({3, 2, 1}, false)), BoxView({0, 0, 0}, {2000, 2000, 1}), tensorstore::span<Index>(chunk_shape, 3))); EXPECT_THAT(tensorstore::span<Index>(chunk_shape, 3), testing::ElementsAre(1254, 836, 1)); } TEST(ChooseChunkShapeTest, Shape) { Index chunk_shape[kMaxRank] = {0}; TENSORSTORE_ASSERT_OK(ChooseChunkShape( ChunkLayout::GridView( ChunkLayout::ChunkShapeBase({30, 20, 10}, false)), BoxView({0, 0, 0}, {2000, 2000, 2000}), tensorstore::span<Index>(chunk_shape, 3))); EXPECT_THAT(tensorstore::span<Index>(chunk_shape, 3), testing::ElementsAre(30, 20, 10)); TENSORSTORE_ASSERT_OK(ChooseChunkShape( ChunkLayout::GridView( ChunkLayout::ChunkShapeBase({30, 20, 10}, false)), BoxView({0, 0, 0}, {2000, 2000, 1}), tensorstore::span<Index>(chunk_shape, 3))); EXPECT_THAT(tensorstore::span<Index>(chunk_shape, 3), testing::ElementsAre(30, 20, 10)); } TEST(ChooseReadWriteChunkShapesTest, Unconstrained) { Index read_chunk_shape[3]; Index write_chunk_shape[3]; TENSORSTORE_ASSERT_OK(ChooseReadWriteChunkShapes( ChunkLayout::GridView(), ChunkLayout::GridView(), BoxView(3), read_chunk_shape, write_chunk_shape)); EXPECT_THAT(read_chunk_shape, ::testing::ElementsAre(101, 101, 101)); EXPECT_THAT(write_chunk_shape, ::testing::ElementsAre(101, 101, 101)); } TEST(ChooseReadWriteChunkShapesTest, ShapeNonMultiple) { Index read_chunk_shape[4]; Index write_chunk_shape[4]; TENSORSTORE_ASSERT_OK(ChooseReadWriteChunkShapes( ChunkLayout::GridView(ChunkLayout::ChunkShapeBase( {5, 11, 20, 8}, DimensionSet::FromBools({false, false, true, true}))), ChunkLayout::GridView(ChunkLayout::ChunkShapeBase( {6, 30, 41, 16}, DimensionSet::FromBools({false, true, false, true}))), BoxView(4), read_chunk_shape, write_chunk_shape)); EXPECT_THAT(read_chunk_shape, ::testing::ElementsAre(6, 10, 20, 8)); EXPECT_THAT(write_chunk_shape, ::testing::ElementsAre(6, 30, 40, 16)); } TEST(ChooseReadWriteChunkShapesTest, ShapeIncompatible) { Index read_chunk_shape[1]; Index write_chunk_shape[1]; EXPECT_THAT(ChooseReadWriteChunkShapes( ChunkLayout::GridView( ChunkLayout::ChunkShapeBase({5}, true)), ChunkLayout::GridView(ChunkLayout::ChunkShapeBase({6}, true)), BoxView(1), read_chunk_shape, write_chunk_shape), MatchesStatus(absl::StatusCode::kInvalidArgument, "Incompatible chunk size constraints for dimension " "0: read size of 5, write size of 6")); } TEST(ChooseReadWriteChunkShapesTest, ReadShapeConstrained) { Index read_chunk_shape[2]; Index write_chunk_shape[2]; TENSORSTORE_ASSERT_OK(ChooseReadWriteChunkShapes( ChunkLayout::GridView( ChunkLayout::ChunkShapeBase({5, 7})), ChunkLayout::GridView(ChunkLayout::ChunkElementsBase(100)), BoxView(2), read_chunk_shape, write_chunk_shape)); EXPECT_THAT(read_chunk_shape, ::testing::ElementsAre(5, 7)); EXPECT_THAT(write_chunk_shape, ::testing::ElementsAre(10, 7)); } TEST(ChooseReadWriteChunkShapesTest, WriteShapeConstrained) { Index read_chunk_shape[2]; Index write_chunk_shape[2]; TENSORSTORE_ASSERT_OK(ChooseReadWriteChunkShapes( ChunkLayout::GridView( ChunkLayout::ChunkElementsBase(36)), ChunkLayout::GridView(ChunkLayout::ChunkShapeBase({10, 14})), BoxView(2), read_chunk_shape, write_chunk_shape)); EXPECT_THAT(read_chunk_shape, ::testing::ElementsAre(5, 7)); EXPECT_THAT(write_chunk_shape, ::testing::ElementsAre(10, 14)); } TEST(HasHardConstraints, Basic) { ChunkLayout layout; EXPECT_FALSE(layout.HasHardConstraints()); TENSORSTORE_ASSERT_OK(layout.Set(tensorstore::RankConstraint{2})); EXPECT_FALSE(layout.HasHardConstraints()); { auto layout1 = layout; TENSORSTORE_ASSERT_OK(layout1.Set( tensorstore::ChunkLayout::InnerOrder({0, 1}, false))); EXPECT_FALSE(layout1.HasHardConstraints()); } { auto layout1 = layout; TENSORSTORE_ASSERT_OK(layout1.Set( tensorstore::ChunkLayout::InnerOrder({0, 1}, true))); EXPECT_TRUE(layout1.HasHardConstraints()); } { auto layout1 = layout; TENSORSTORE_ASSERT_OK(layout1.Set( tensorstore::ChunkLayout::GridOrigin({100, 200}, false))); EXPECT_FALSE(layout1.HasHardConstraints()); } { auto layout1 = layout; TENSORSTORE_ASSERT_OK( layout1.Set(tensorstore::ChunkLayout::GridOrigin({100, 200}))); EXPECT_TRUE(layout1.HasHardConstraints()); } { auto layout1 = layout; TENSORSTORE_ASSERT_OK(layout1.Set( tensorstore::ChunkLayout::ReadChunkShape({100, 200}, false))); EXPECT_FALSE(layout1.HasHardConstraints()); } { auto layout1 = layout; TENSORSTORE_ASSERT_OK( layout1.Set(tensorstore::ChunkLayout::ReadChunkShape({100, 200}))); EXPECT_TRUE(layout1.HasHardConstraints()); } { auto layout1 = layout; TENSORSTORE_ASSERT_OK( layout1.Set(tensorstore::ChunkLayout::ReadChunkAspectRatio({1, 1}))); EXPECT_FALSE(layout1.HasHardConstraints()); } { auto layout1 = layout; TENSORSTORE_ASSERT_OK( layout1.Set(tensorstore::ChunkLayout::ReadChunkElements(200))); EXPECT_FALSE(layout1.HasHardConstraints()); } } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/chunk_layout.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/chunk_layout_test.cc
4f887a6430414cd6088e1743555015b10f116d50
416c9ceb-73a8-4e36-b70f-7ac1a8c89534
cpp
google/tensorstore
cast
tensorstore/driver/cast/cast.cc
tensorstore/driver/cast/cast_test.cc
#include "tensorstore/driver/cast/cast.h" #include <cassert> #include <utility> #include "absl/status/status.h" #include "tensorstore/array.h" #include "tensorstore/array_storage_statistics.h" #include "tensorstore/chunk_layout.h" #include "tensorstore/codec_spec.h" #include "tensorstore/context.h" #include "tensorstore/data_type.h" #include "tensorstore/data_type_conversion.h" #include "tensorstore/driver/chunk.h" #include "tensorstore/driver/driver.h" #include "tensorstore/driver/driver_handle.h" #include "tensorstore/driver/driver_spec.h" #include "tensorstore/driver/registry.h" #include "tensorstore/index.h" #include "tensorstore/index_space/dimension_units.h" #include "tensorstore/index_space/index_domain.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/internal/arena.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/internal/lock_collection.h" #include "tensorstore/internal/nditerable_data_type_conversion.h" #include "tensorstore/internal/type_traits.h" #include "tensorstore/json_serialization_options.h" #include "tensorstore/kvstore/kvstore.h" #include "tensorstore/kvstore/spec.h" #include "tensorstore/open_mode.h" #include "tensorstore/open_options.h" #include "tensorstore/rank.h" #include "tensorstore/schema.h" #include "tensorstore/spec.h" #include "tensorstore/transaction.h" #include "tensorstore/util/execution/any_receiver.h" #include "tensorstore/util/execution/execution.h" #include "tensorstore/util/executor.h" #include "tensorstore/util/future.h" #include "tensorstore/util/iterate.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace internal_cast_driver { namespace { using ::tensorstore::internal::Arena; using ::tensorstore::internal::DataTypeConversionLookupResult; using ::tensorstore::internal::IntrusivePtr; using ::tensorstore::internal::NDIterable; using ::tensorstore::internal::OpenTransactionPtr; using ::tensorstore::internal::ReadChunk; using ::tensorstore::internal::TransformedDriverSpec; using ::tensorstore::internal::WriteChunk; namespace jb = tensorstore::internal_json_binding; class CastDriverSpec : public internal::RegisteredDriverSpec<CastDriverSpec, internal::DriverSpec> { public: constexpr static const char id[] = "cast"; TransformedDriverSpec base; constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(internal::BaseCast<internal::DriverSpec>(x), x.base); }; OpenMode open_mode() const override { return base.driver_spec->open_mode(); } absl::Status ApplyOptions(SpecOptions&& options) override { TENSORSTORE_RETURN_IF_ERROR(schema.Set(options.dtype())); options.Override(DataType()).IgnoreError(); return internal::TransformAndApplyOptions(base, std::move(options)); } constexpr static auto default_json_binder = jb::Object( jb::Member("base", [](auto is_loading, const auto& options, auto* obj, auto* j) { return jb::Projection<&CastDriverSpec::base>()( is_loading, JsonSerializationOptions(options, DataType(), obj->schema.rank()), obj, j); }), jb::Initialize([](auto* obj) -> absl::Status { if (obj->base.transform.valid()) { TENSORSTORE_RETURN_IF_ERROR(obj->schema.Set( RankConstraint{obj->base.transform.input_rank()})); } DataType dtype = obj->schema.dtype(); DimensionIndex rank = obj->schema.rank(); SpecOptions base_options; static_cast<Schema&>(base_options) = std::exchange(obj->schema, {}); obj->schema.Set(dtype).IgnoreError(); obj->schema.Set(RankConstraint{rank}).IgnoreError(); return obj->ApplyOptions(std::move(base_options)); })); Result<IndexDomain<>> GetDomain() const override { return internal::GetEffectiveDomain(base); } Result<ChunkLayout> GetChunkLayout() const override { return internal::GetEffectiveChunkLayout(base); } Result<CodecSpec> GetCodec() const override { return internal::GetEffectiveCodec(base); } Result<SharedArray<const void>> GetFillValue( IndexTransformView<> transform) const override { TENSORSTORE_ASSIGN_OR_RETURN( auto adjusted_transform, tensorstore::ComposeOptionalTransforms(base.transform, transform)); TENSORSTORE_ASSIGN_OR_RETURN( auto fill_value, base.driver_spec->GetFillValue(adjusted_transform)); if (!fill_value.valid()) return {std::in_place}; auto dtype = schema.dtype(); if (dtype == fill_value.dtype()) return fill_value; auto converter = internal::GetDataTypeConverter(fill_value.dtype(), dtype); if (!(converter.flags & DataTypeConversionFlags::kSupported)) { return {std::in_place}; } return MakeCopy(fill_value, skip_repeated_elements, dtype); } Result<DimensionUnitsVector> GetDimensionUnits() const override { return internal::GetEffectiveDimensionUnits(base); } kvstore::Spec GetKvstore() const override { return base.driver_spec->GetKvstore(); } Result<TransformedDriverSpec> GetBase( IndexTransformView<> transform) const override { TransformedDriverSpec new_base; TENSORSTORE_ASSIGN_OR_RETURN( new_base.transform, ComposeOptionalTransforms(base.transform, transform)); new_base.driver_spec = base.driver_spec; return new_base; } Future<internal::Driver::Handle> Open( internal::DriverOpenRequest request) const override { DataType target_dtype = schema.dtype(); if (!target_dtype.valid()) { return absl::InvalidArgumentError("dtype must be specified"); } auto read_write_mode = request.read_write_mode; return MapFutureValue( InlineExecutor{}, [target_dtype, read_write_mode](internal::Driver::Handle handle) -> Result<internal::Driver::Handle> { return MakeCastDriver(std::move(handle), target_dtype, read_write_mode); }, internal::OpenDriver(base, std::move(request))); } }; class CastDriver : public internal::RegisteredDriver<CastDriver, internal::Driver> { public: Result<TransformedDriverSpec> GetBoundSpec( internal::OpenTransactionPtr transaction, IndexTransformView<> transform) override { auto driver_spec = internal::DriverSpec::Make<CastDriverSpec>(); driver_spec->context_binding_state_ = ContextBindingState::bound; TENSORSTORE_ASSIGN_OR_RETURN( driver_spec->base, base_driver_->GetBoundSpec(std::move(transaction), transform)); driver_spec->schema.Set(target_dtype_).IgnoreError(); const DimensionIndex base_rank = base_driver_->rank(); driver_spec->schema.Set(RankConstraint{base_rank}).IgnoreError(); TransformedDriverSpec spec; spec.transform = std::exchange(driver_spec->base.transform, {}); spec.driver_spec = std::move(driver_spec); return spec; } Result<ChunkLayout> GetChunkLayout(IndexTransformView<> transform) override { return base_driver_->GetChunkLayout(transform); } Result<CodecSpec> GetCodec() override { return base_driver_->GetCodec(); } Result<SharedArray<const void>> GetFillValue( IndexTransformView<> transform) override { if (!(input_conversion_.flags & DataTypeConversionFlags::kSupported)) { return {std::in_place}; } TENSORSTORE_ASSIGN_OR_RETURN(auto base_fill_value, base_driver_->GetFillValue(transform)); if (!base_fill_value.valid()) return {std::in_place}; if (base_fill_value.dtype() == target_dtype_) { return base_fill_value; } return tensorstore::MakeCopy(base_fill_value, skip_repeated_elements, target_dtype_); } Result<DimensionUnitsVector> GetDimensionUnits() override { return base_driver_->GetDimensionUnits(); } KvStore GetKvstore(const Transaction& transaction) override { return base_driver_->GetKvstore(transaction); } Result<internal::DriverHandle> GetBase( ReadWriteMode read_write_mode, IndexTransformView<> transform, const Transaction& transaction) override { internal::DriverHandle base_handle; base_handle.driver = base_driver_; base_handle.driver.set_read_write_mode(read_write_mode); base_handle.transform = transform; base_handle.transaction = transaction; return base_handle; } Future<ArrayStorageStatistics> GetStorageStatistics( GetStorageStatisticsRequest request) override { return base_driver_->GetStorageStatistics(std::move(request)); } explicit CastDriver(internal::DriverPtr base, DataType target_dtype, DataTypeConversionLookupResult input_conversion, DataTypeConversionLookupResult output_conversion) : base_driver_(std::move(base)), target_dtype_(target_dtype), input_conversion_(input_conversion), output_conversion_(output_conversion) {} DataType dtype() override { return target_dtype_; } DimensionIndex rank() override { return base_driver_->rank(); } Executor data_copy_executor() override { return base_driver_->data_copy_executor(); } void Read(ReadRequest request, ReadChunkReceiver receiver) override; void Write(WriteRequest request, WriteChunkReceiver receiver) override; Future<IndexTransform<>> ResolveBounds( ResolveBoundsRequest request) override { return base_driver_->ResolveBounds(std::move(request)); } Future<IndexTransform<>> Resize(ResizeRequest request) override { return base_driver_->Resize(std::move(request)); } constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(x.base_driver_, x.target_dtype_, x.input_conversion_, x.output_conversion_); }; internal::DriverPtr base_driver_; DataType target_dtype_; DataTypeConversionLookupResult input_conversion_; DataTypeConversionLookupResult output_conversion_; }; struct ReadChunkImpl { IntrusivePtr<CastDriver> self; ReadChunk::Impl base; absl::Status operator()(internal::LockCollection& lock_collection) { return base(lock_collection); } Result<NDIterable::Ptr> operator()(ReadChunk::BeginRead, IndexTransform<> chunk_transform, Arena* arena) { TENSORSTORE_ASSIGN_OR_RETURN( auto iterable, base(ReadChunk::BeginRead{}, std::move(chunk_transform), arena)); return GetConvertedInputNDIterable(std::move(iterable), self->target_dtype_, self->input_conversion_); } }; struct WriteChunkImpl { IntrusivePtr<CastDriver> self; WriteChunk::Impl base; absl::Status operator()(internal::LockCollection& lock_collection) { return base(lock_collection); } Result<NDIterable::Ptr> operator()(WriteChunk::BeginWrite, IndexTransform<> chunk_transform, Arena* arena) { TENSORSTORE_ASSIGN_OR_RETURN( auto iterable, base(WriteChunk::BeginWrite{}, std::move(chunk_transform), arena)); return GetConvertedOutputNDIterable( std::move(iterable), self->target_dtype_, self->output_conversion_); } WriteChunk::EndWriteResult operator()(WriteChunk::EndWrite, IndexTransformView<> chunk_transform, bool success, Arena* arena) { return base(WriteChunk::EndWrite{}, chunk_transform, success, arena); } bool operator()(WriteChunk::WriteArray, IndexTransformView<> chunk_transform, WriteChunk::GetWriteSourceArrayFunction get_source_array, Arena* arena, WriteChunk::EndWriteResult& end_write_result) { if (!(self->output_conversion_.flags & DataTypeConversionFlags::kCanReinterpretCast)) { return false; } return base(WriteChunk::WriteArray{}, chunk_transform, get_source_array, arena, end_write_result); } }; template <typename Chunk, typename ChunkImpl> struct ChunkReceiverAdapter { IntrusivePtr<CastDriver> self; AnyFlowReceiver<absl::Status, Chunk, IndexTransform<>> base; template <typename CancelReceiver> void set_starting(CancelReceiver receiver) { tensorstore::execution::set_starting(base, std::move(receiver)); } void set_value(Chunk chunk, IndexTransform<> transform) { tensorstore::execution::set_value( base, Chunk{ChunkImpl{self, std::move(chunk.impl)}, std::move(chunk.transform)}, std::move(transform)); } void set_done() { tensorstore::execution::set_done(base); } void set_error(absl::Status status) { tensorstore::execution::set_error(base, std::move(status)); } void set_stopping() { tensorstore::execution::set_stopping(base); } }; void CastDriver::Read(ReadRequest request, ReadChunkReceiver receiver) { base_driver_->Read(std::move(request), ChunkReceiverAdapter<ReadChunk, ReadChunkImpl>{ IntrusivePtr<CastDriver>(this), std::move(receiver)}); } void CastDriver::Write(WriteRequest request, WriteChunkReceiver receiver) { base_driver_->Write(std::move(request), ChunkReceiverAdapter<WriteChunk, WriteChunkImpl>{ IntrusivePtr<CastDriver>(this), std::move(receiver)}); } const internal::DriverRegistration<CastDriverSpec> driver_registration; } } namespace internal { Result<CastDataTypeConversions> GetCastDataTypeConversions( DataType source_dtype, DataType target_dtype, ReadWriteMode existing_mode, ReadWriteMode required_mode) { assert((existing_mode & required_mode) == required_mode); CastDataTypeConversions result = {}; if (required_mode == ReadWriteMode::dynamic && existing_mode != ReadWriteMode::read_write) { required_mode = existing_mode; } const ReadWriteMode requested_mode = required_mode == ReadWriteMode::dynamic ? existing_mode : required_mode; result.mode = requested_mode; if ((requested_mode & ReadWriteMode::read) == ReadWriteMode::read) { result.input = GetDataTypeConverter(source_dtype, target_dtype); if (!(result.input.flags & DataTypeConversionFlags::kSupported)) { if ((required_mode & ReadWriteMode::read) == ReadWriteMode::read) { return absl::InvalidArgumentError(tensorstore::StrCat( "Read access requires unsupported ", source_dtype, " -> ", target_dtype, " conversion")); } result.mode &= ~ReadWriteMode::read; } } if ((requested_mode & ReadWriteMode::write) == ReadWriteMode::write) { result.output = GetDataTypeConverter(target_dtype, source_dtype); if (!(result.output.flags & DataTypeConversionFlags::kSupported)) { if ((required_mode & ReadWriteMode::write) == ReadWriteMode::write) { return absl::InvalidArgumentError(tensorstore::StrCat( "Write access requires unsupported ", target_dtype, " -> ", source_dtype, " conversion")); } result.mode &= ~ReadWriteMode::write; } } if (result.mode == ReadWriteMode{}) { return absl::InvalidArgumentError(tensorstore::StrCat( "Cannot convert ", source_dtype, " <-> ", target_dtype)); } return result; } Result<Driver::Handle> MakeCastDriver(Driver::Handle base, DataType target_dtype, ReadWriteMode read_write_mode) { TENSORSTORE_ASSIGN_OR_RETURN( auto conversions, GetCastDataTypeConversions( base.driver->dtype(), target_dtype, base.driver.read_write_mode(), read_write_mode)); base.driver = internal::MakeReadWritePtr<internal_cast_driver::CastDriver>( conversions.mode, std::move(base.driver), target_dtype, conversions.input, conversions.output); return base; } Result<TransformedDriverSpec> MakeCastDriverSpec(TransformedDriverSpec base, DataType target_dtype) { if (!base.driver_spec) return {std::in_place}; DataType source_dtype = base.driver_spec->schema.dtype(); if (source_dtype.valid()) { TENSORSTORE_RETURN_IF_ERROR(GetCastDataTypeConversions( source_dtype, target_dtype, ReadWriteMode::read_write, ReadWriteMode::dynamic)); } auto driver_spec = internal::DriverSpec::Make<internal_cast_driver::CastDriverSpec>(); driver_spec->schema .Set(base.transform.valid() ? RankConstraint{base.transform.output_rank()} : base.driver_spec->schema.rank()) .IgnoreError(); driver_spec->schema.Set(target_dtype).IgnoreError(); driver_spec->context_binding_state_ = base.context_binding_state(); driver_spec->base.driver_spec = std::move(base.driver_spec); base.driver_spec = std::move(driver_spec); return base; } } Result<Spec> Cast(const Spec& base_spec, DataType target_dtype) { Spec spec; auto& base_impl = internal_spec::SpecAccess::impl(base_spec); auto& impl = internal_spec::SpecAccess::impl(spec); TENSORSTORE_ASSIGN_OR_RETURN( impl, internal::MakeCastDriverSpec(base_impl, target_dtype)); return spec; } }
#include "tensorstore/cast.h" #include <cstddef> #include <cstdint> #include <string> #include <utility> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "tensorstore/array.h" #include "tensorstore/box.h" #include "tensorstore/chunk_layout.h" #include "tensorstore/codec_spec.h" #include "tensorstore/context.h" #include "tensorstore/data_type.h" #include "tensorstore/driver/cast/cast.h" #include "tensorstore/driver/driver_testutil.h" #include "tensorstore/index.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/index_transform_builder.h" #include "tensorstore/index_space/json.h" #include "tensorstore/internal/global_initializer.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/json_serialization_options_base.h" #include "tensorstore/open.h" #include "tensorstore/open_mode.h" #include "tensorstore/schema.h" #include "tensorstore/spec.h" #include "tensorstore/strided_layout.h" #include "tensorstore/tensorstore.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status_testutil.h" namespace { using ::tensorstore::Cast; using ::tensorstore::ChunkLayout; using ::tensorstore::DataTypeConversionFlags; using ::tensorstore::DimensionIndex; using ::tensorstore::dtype_v; using ::tensorstore::Index; using ::tensorstore::MakeArray; using ::tensorstore::MatchesStatus; using ::tensorstore::ReadWriteMode; using ::tensorstore::Result; using ::tensorstore::zero_origin; using ::tensorstore::dtypes::string_t; using ::tensorstore::internal::CastDataTypeConversions; using ::tensorstore::internal::GetCastDataTypeConversions; using ::tensorstore::internal::GetCastMode; using ::tensorstore::internal::TestSpecSchema; using ::tensorstore::internal::TestTensorStoreCreateCheckSchema; #ifndef _MSC_VER template <class T> constexpr void test_helper(T&& t) {} #define TENSORSTORE_IS_CONSTEXPR(...) noexcept(test_helper(__VA_ARGS__)) static_assert(!TENSORSTORE_IS_CONSTEXPR( GetCastMode<std::byte, std::string>(ReadWriteMode::dynamic))); static_assert(!TENSORSTORE_IS_CONSTEXPR( GetCastMode<std::byte, std::string>(ReadWriteMode::read))); static_assert(!TENSORSTORE_IS_CONSTEXPR( GetCastMode<std::byte, std::string>(ReadWriteMode::write))); static_assert(!TENSORSTORE_IS_CONSTEXPR( GetCastMode<std::byte, std::string>(ReadWriteMode::read_write))); #endif static_assert(GetCastMode<std::int32_t, float>(ReadWriteMode::dynamic) == ReadWriteMode::dynamic); static_assert(GetCastMode<std::int32_t, float>(ReadWriteMode::read) == ReadWriteMode::read); static_assert(GetCastMode<std::int32_t, float>(ReadWriteMode::write) == ReadWriteMode::write); static_assert(GetCastMode<std::int32_t, float>(ReadWriteMode::read_write) == ReadWriteMode::read_write); static_assert(GetCastMode<std::int32_t, std::string>(ReadWriteMode::dynamic) == ReadWriteMode::read); static_assert(GetCastMode<std::int32_t, std::string>(ReadWriteMode::read) == ReadWriteMode::read); #ifndef _MSC_VER static_assert(!TENSORSTORE_IS_CONSTEXPR( GetCastMode<std::int32_t, std::string>(ReadWriteMode::write))); #endif static_assert(GetCastMode<std::int32_t, std::string>( ReadWriteMode::read_write) == ReadWriteMode::read); static_assert(GetCastMode<std::string, std::int32_t>(ReadWriteMode::dynamic) == ReadWriteMode::write); static_assert(GetCastMode<std::string, std::int32_t>(ReadWriteMode::write) == ReadWriteMode::write); #ifndef _MSC_VER static_assert(!TENSORSTORE_IS_CONSTEXPR( GetCastMode<std::string, std::int32_t>(ReadWriteMode::read))); #endif static_assert(GetCastMode<std::string, std::int32_t>( ReadWriteMode::read_write) == ReadWriteMode::write); static_assert(GetCastMode<std::int32_t, std::int32_t>( ReadWriteMode::read_write) == ReadWriteMode::read_write); static_assert(GetCastMode<std::int32_t, std::int32_t>(ReadWriteMode::dynamic) == ReadWriteMode::dynamic); static_assert(GetCastMode<std::int32_t, std::int32_t>(ReadWriteMode::read) == ReadWriteMode::read); static_assert(GetCastMode<std::int32_t, std::int32_t>(ReadWriteMode::write) == ReadWriteMode::write); static_assert(GetCastMode<std::int32_t, void>(ReadWriteMode::write) == ReadWriteMode::write); static_assert(GetCastMode<std::int32_t, void>(ReadWriteMode::read) == ReadWriteMode::read); static_assert(GetCastMode<std::int32_t, void>(ReadWriteMode::dynamic) == ReadWriteMode::dynamic); static_assert(GetCastMode<std::int32_t, void>(ReadWriteMode::read_write) == ReadWriteMode::dynamic); static_assert(GetCastMode<void, std::int32_t>(ReadWriteMode::write) == ReadWriteMode::write); static_assert(GetCastMode<void, std::int32_t>(ReadWriteMode::read) == ReadWriteMode::read); static_assert(GetCastMode<void, std::int32_t>(ReadWriteMode::dynamic) == ReadWriteMode::dynamic); static_assert(GetCastMode<void, std::int32_t>(ReadWriteMode::read_write) == ReadWriteMode::dynamic); static_assert(GetCastMode<void, void>(ReadWriteMode::write) == ReadWriteMode::write); static_assert(GetCastMode<void, void>(ReadWriteMode::read) == ReadWriteMode::read); static_assert(GetCastMode<void, void>(ReadWriteMode::dynamic) == ReadWriteMode::dynamic); static_assert(GetCastMode<void, void>(ReadWriteMode::read_write) == ReadWriteMode::dynamic); ::testing::Matcher<Result<CastDataTypeConversions>> MatchesCastDataTypeConversions(DataTypeConversionFlags input_flags, DataTypeConversionFlags output_flags, ReadWriteMode mode) { return ::testing::Optional(::testing::AllOf( ::testing::ResultOf([](const auto& x) { return x.input.flags; }, input_flags), ::testing::ResultOf([](const auto& x) { return x.output.flags; }, output_flags), ::testing::Field(&CastDataTypeConversions::mode, mode))); } TEST(GetCastDataTypeConversions, Basic) { constexpr static DataTypeConversionFlags kSupported = DataTypeConversionFlags::kSupported; constexpr static DataTypeConversionFlags kIdentity = DataTypeConversionFlags::kIdentity; constexpr static DataTypeConversionFlags kSafeAndImplicit = DataTypeConversionFlags::kSafeAndImplicit; constexpr static DataTypeConversionFlags kCanReinterpretCast = DataTypeConversionFlags::kCanReinterpretCast; constexpr static DataTypeConversionFlags kNone = {}; constexpr static DataTypeConversionFlags kAll = kSupported | kIdentity | kCanReinterpretCast | kSafeAndImplicit; constexpr static ReadWriteMode read = ReadWriteMode::read; constexpr static ReadWriteMode write = ReadWriteMode::write; constexpr static ReadWriteMode read_write = ReadWriteMode::read_write; constexpr static ReadWriteMode dynamic = ReadWriteMode::dynamic; constexpr auto IfMode = [](ReadWriteMode mode, ReadWriteMode condition, DataTypeConversionFlags true_value) { return ((mode & condition) == condition) ? true_value : kNone; }; for (const auto existing_mode : {read, write, read_write}) { for (const auto required_mode : {existing_mode, dynamic}) { EXPECT_THAT(GetCastDataTypeConversions(dtype_v<std::int32_t>, dtype_v<std::int32_t>, existing_mode, required_mode), MatchesCastDataTypeConversions( IfMode(existing_mode, read, kAll), IfMode(existing_mode, write, kAll), existing_mode)); } } for (const auto existing_mode : {read, write, read_write}) { for (const auto required_mode : {existing_mode, dynamic}) { EXPECT_THAT( GetCastDataTypeConversions(dtype_v<std::int32_t>, dtype_v<float>, existing_mode, required_mode), MatchesCastDataTypeConversions( IfMode(existing_mode, read, kSupported), IfMode(existing_mode, write, kSupported), existing_mode)); } } for (const auto existing_mode : {read, write, read_write}) { for (const auto required_mode : {existing_mode, dynamic}) { EXPECT_THAT( GetCastDataTypeConversions(dtype_v<std::int16_t>, dtype_v<float>, existing_mode, required_mode), MatchesCastDataTypeConversions( IfMode(existing_mode, read, kSupported | kSafeAndImplicit), IfMode(existing_mode, write, kSupported), existing_mode)); } } for (const auto existing_mode : {read, read_write}) { for (const auto required_mode : {read, dynamic}) { EXPECT_THAT(GetCastDataTypeConversions(dtype_v<std::int32_t>, dtype_v<std::string>, existing_mode, required_mode), MatchesCastDataTypeConversions( kSupported, kNone, read)); } } for (const auto required_mode : {write, read_write}) { EXPECT_THAT( GetCastDataTypeConversions(dtype_v<std::int32_t>, dtype_v<std::string>, read_write, required_mode), MatchesStatus(absl::StatusCode::kInvalidArgument)); } for (const auto required_mode : {write, dynamic}) { EXPECT_THAT( GetCastDataTypeConversions(dtype_v<std::int32_t>, dtype_v<std::string>, write, required_mode), MatchesStatus(absl::StatusCode::kInvalidArgument)); } for (const auto existing_mode : {write, read_write}) { for (const auto required_mode : {write, dynamic}) { EXPECT_THAT(GetCastDataTypeConversions(dtype_v<std::string>, dtype_v<std::int32_t>, existing_mode, required_mode), MatchesCastDataTypeConversions( kNone, kSupported, write)); } } for (const auto required_mode : {read, dynamic}) { EXPECT_THAT( GetCastDataTypeConversions(dtype_v<std::string>, dtype_v<std::int32_t>, read, required_mode), MatchesStatus(absl::StatusCode::kInvalidArgument)); } for (const auto required_mode : {read, read_write}) { EXPECT_THAT( GetCastDataTypeConversions(dtype_v<std::string>, dtype_v<std::int32_t>, read_write, required_mode), MatchesStatus(absl::StatusCode::kInvalidArgument)); } for (const auto existing_mode : {read, write, read_write}) { for (const auto required_mode : {read, write, read_write, dynamic}) { if ((existing_mode & required_mode) != required_mode) continue; EXPECT_THAT(GetCastDataTypeConversions( dtype_v<std::byte>, dtype_v<std::string>, existing_mode, required_mode & existing_mode), MatchesStatus(absl::StatusCode::kInvalidArgument)); } } } TEST(CastTest, Int32ToStringDynamic) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open( {{"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}}) .result()); EXPECT_EQ(store.read_write_mode(), ReadWriteMode::read_write); ASSERT_EQ(tensorstore::Box<1>({3}), store.domain().box()); auto cast_store = Cast(store, dtype_v<std::string>).value(); EXPECT_EQ(cast_store.read_write_mode(), ReadWriteMode::read); EXPECT_EQ(tensorstore::Read<zero_origin>(cast_store).result(), MakeArray<std::string>({"1", "2", "3"})); EXPECT_THAT( cast_store.spec().value().ToJson({tensorstore::IncludeDefaults{false}}), ::testing::Optional(tensorstore::MatchesJson( {{"driver", "cast"}, {"dtype", "string"}, {"transform", ::nlohmann::json(tensorstore::IdentityTransform<1>({3}))}, {"base", { {"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}, }}}))); } TEST(CastTest, StringToInt32Dynamic) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open({{"driver", "array"}, {"array", {"a", "b", "c"}}, {"dtype", "string"}}) .result()); EXPECT_EQ(store.read_write_mode(), ReadWriteMode::read_write); auto cast_store = Cast(store, dtype_v<std::int32_t>).value(); EXPECT_EQ(cast_store.read_write_mode(), ReadWriteMode::write); TENSORSTORE_EXPECT_OK( tensorstore::Write(MakeArray<std::int32_t>({1, 2, 3}), cast_store)); EXPECT_EQ(tensorstore::Read<zero_origin>(store).result(), MakeArray<std::string>({"1", "2", "3"})); } TEST(CastTest, OpenInt32ToInt64) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open( {{"driver", "cast"}, {"dtype", "int64"}, {"base", {{"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}}}}) .result()); EXPECT_EQ(store.read_write_mode(), ReadWriteMode::read_write); EXPECT_EQ(tensorstore::Read<zero_origin>(store).result(), MakeArray<std::int64_t>({1, 2, 3})); TENSORSTORE_EXPECT_OK(tensorstore::Write( tensorstore::MakeScalarArray<std::int64_t>(10), store)); EXPECT_EQ(tensorstore::Read<zero_origin>(store).result(), MakeArray<std::int64_t>({10, 10, 10})); } TEST(CastTest, OpenInputConversionError) { EXPECT_THAT( tensorstore::Open( {{"driver", "cast"}, {"dtype", "byte"}, {"base", {{"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}}}}, tensorstore::ReadWriteMode::read) .result(), MatchesStatus( absl::StatusCode::kInvalidArgument, "Error opening \"cast\" driver: " "Read access requires unsupported int32 -> byte conversion")); } TEST(CastTest, OpenOutputConversionError) { EXPECT_THAT( tensorstore::Open( {{"driver", "cast"}, {"dtype", "byte"}, {"base", {{"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}}}}, tensorstore::ReadWriteMode::write) .result(), MatchesStatus( absl::StatusCode::kInvalidArgument, "Error opening \"cast\" driver: " "Write access requires unsupported byte -> int32 conversion")); } TEST(CastTest, OpenAnyConversionError) { EXPECT_THAT( tensorstore::Open( {{"driver", "cast"}, {"dtype", "byte"}, {"base", {{"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}}}}) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error opening \"cast\" driver: " "Cannot convert int32 <-> byte")); } TEST(CastTest, OpenMissingDataType) { EXPECT_THAT( tensorstore::Open( {{"driver", "cast"}, {"base", {{"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}}}}) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*: dtype must be specified")); } TEST(CastTest, ComposeTransforms) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open( {{"driver", "cast"}, {"transform", {{"input_inclusive_min", {10}}, {"input_shape", {3}}, {"output", {{{"input_dimension", 0}, {"offset", -8}}}}}}, {"dtype", "int64"}, {"base", {{"driver", "array"}, {"array", {1, 2, 3}}, {"transform", {{"input_inclusive_min", {2}}, {"input_shape", {3}}, {"output", {{{"input_dimension", 0}, {"offset", -2}}}}}}, {"dtype", "int32"}}}}) .result()); EXPECT_THAT( store.spec().value().ToJson({tensorstore::IncludeDefaults{false}}), ::testing::Optional(tensorstore::MatchesJson( {{"driver", "cast"}, {"base", { {"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}, }}, {"dtype", "int64"}, {"transform", ::nlohmann::json(tensorstore::IndexTransformBuilder<>(1, 1) .input_origin({10}) .input_shape({3}) .output_single_input_dimension(0, -10, 1, 0) .Finalize() .value())}}))); } TEST(CastTest, ComposeTransformsError) { EXPECT_THAT(tensorstore::Open({{"driver", "cast"}, {"rank", 2}, {"dtype", "int64"}, {"base", {{"driver", "array"}, {"array", {1, 2, 3}}, {"rank", 1}, {"dtype", "int32"}}}}) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"base\": " "Error parsing object member \"rank\": " "Expected 2, but received: 1")); } TEST(CastTest, SpecRankPropagation) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec, tensorstore::Spec::FromJson({ {"driver", "cast"}, {"base", { {"driver", "array"}, {"array", {1, 2, 3}}, {"dtype", "int32"}, }}, {"dtype", "int64"}, })); EXPECT_EQ(1, spec.rank()); } TEST(CastTest, ChunkLayout) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open({ {"driver", "cast"}, {"dtype", "int32"}, {"base", {{"driver", "array"}, {"dtype", "int64"}, {"array", {{1, 2, 3}, {4, 5, 6}}}}}, }) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto expected_layout, ChunkLayout::FromJson({ {"grid_origin", {0, 0}}, {"inner_order", {0, 1}}, })); EXPECT_THAT(store.chunk_layout(), ::testing::Optional(expected_layout)); } TEST(SpecSchemaTest, CastArray) { TestSpecSchema( { {"driver", "cast"}, {"base", { {"driver", "array"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, {"dtype", "float32"}, {"schema", {{"dimension_units", {"4nm", "5nm"}}}}, }}, {"dtype", "int32"}, }, { {"rank", 2}, {"dtype", "int32"}, {"domain", {{"shape", {2, 3}}}}, {"chunk_layout", {{"grid_origin", {0, 0}}, {"inner_order", {0, 1}}}}, {"dimension_units", {"4nm", "5nm"}}, }); } TEST(DriverCreateCheckSchemaTest, CastArray) { TestTensorStoreCreateCheckSchema( { {"driver", "cast"}, {"base", { {"driver", "array"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, {"dtype", "float32"}, {"schema", {{"dimension_units", {"4nm", "5nm"}}}}, }}, {"dtype", "int32"}, }, { {"rank", 2}, {"dtype", "int32"}, {"domain", {{"shape", {2, 3}}}}, {"chunk_layout", {{"grid_origin", {0, 0}}, {"inner_order", {0, 1}}}}, {"dimension_units", {"4nm", "5nm"}}, }); } TEST(CastTest, FillValueNotSpecified) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open( { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, }, tensorstore::OpenMode::create, tensorstore::dtype_v<uint16_t>, tensorstore::Schema::Shape({100, 4, 3})) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Cast(base_store, tensorstore::dtype_v<int32_t>)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto fill_value, store.fill_value()); EXPECT_FALSE(fill_value.valid()); } TEST(CastTest, FillValueSpecified) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open( { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, }, tensorstore::OpenMode::create, tensorstore::dtype_v<uint16_t>, tensorstore::Schema::Shape({100, 4, 3}), tensorstore::Schema::FillValue( tensorstore::MakeScalarArray<uint16_t>(42))) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Cast(base_store, tensorstore::dtype_v<int32_t>)); EXPECT_THAT(store.fill_value(), ::testing::Optional(tensorstore::MakeScalarArray<int32_t>(42))); } TEST(CastTest, Codec) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open( { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"compressor", nullptr}}}, }, tensorstore::OpenMode::create, tensorstore::dtype_v<uint16_t>, tensorstore::Schema::Shape({100, 4, 3})) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Cast(base_store, tensorstore::dtype_v<int32_t>)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto expected_codec, tensorstore::CodecSpec::FromJson({ {"driver", "zarr"}, {"compressor", nullptr}, {"filters", nullptr}, })); EXPECT_THAT(store.codec(), ::testing::Optional(expected_codec)); } TEST(SpecSchemaTest, ChunkLayout) { TestSpecSchema( { {"driver", "cast"}, {"dtype", "uint32"}, {"base", { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dtype", "<u2"}, {"chunks", {3, 4, 5}}}}, }}, }, { {"dtype", "uint32"}, {"chunk_layout", { {"grid_origin", {0, 0, 0}}, {"chunk", {{"shape", {3, 4, 5}}}}, }}, {"codec", {{"driver", "zarr"}}}, }); } TEST(SpecSchemaTest, Codec) { TestSpecSchema( { {"driver", "cast"}, {"dtype", "uint32"}, {"base", { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dtype", "<u2"}, {"compressor", nullptr}}}, }}, }, { {"dtype", "uint32"}, {"codec", {{"driver", "zarr"}, {"compressor", nullptr}}}, }); } TEST(SpecSchemaTest, FillValue) { TestSpecSchema( { {"driver", "cast"}, {"dtype", "uint32"}, {"base", { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dtype", "<f4"}, {"fill_value", 3.5}}}, }}, }, { {"dtype", "uint32"}, {"fill_value", 3}, {"codec", {{"driver", "zarr"}}}, }); } TEST(SpecSchemaTest, FillValueSameDtype) { TestSpecSchema( { {"driver", "cast"}, {"dtype", "uint32"}, {"base", { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dtype", "<u4"}, {"fill_value", 3}}}, }}, }, { {"dtype", "uint32"}, {"fill_value", 3}, {"codec", {{"driver", "zarr"}}}, }); } TENSORSTORE_GLOBAL_INITIALIZER { tensorstore::internal::TestTensorStoreDriverSpecRoundtripOptions options; options.test_name = "cast"; options.create_spec = { {"driver", "cast"}, {"base", { {"driver", "array"}, {"dtype", "float32"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, }}, {"dtype", "uint32"}, }; options.full_spec = { {"driver", "cast"}, {"base", { {"driver", "array"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, {"dtype", "float32"}, }}, {"dtype", "uint32"}, {"transform", {{"input_inclusive_min", {0, 0}}, {"input_exclusive_max", {2, 3}}}}, }; options.full_base_spec = { {"driver", "array"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, {"dtype", "float32"}, {"transform", {{"input_inclusive_min", {0, 0}}, {"input_exclusive_max", {2, 3}}}}, }; options.minimal_spec = options.full_spec; options.check_not_found_before_create = false; options.check_not_found_before_commit = false; options.supported_transaction_modes = {}; tensorstore::internal::RegisterTensorStoreDriverSpecRoundtripTest( std::move(options)); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/driver/cast/cast.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/driver/cast/cast_test.cc
4f887a6430414cd6088e1743555015b10f116d50
c5b5d6df-a040-4c59-a775-cf98fef10b84
cpp
google/tensorstore
kvstore
tensorstore/kvstore/kvstore.cc
tensorstore/kvstore/kvstore_test.cc
#include "tensorstore/kvstore/kvstore.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <atomic> #include <cassert> #include <optional> #include <string> #include <string_view> #include <utility> #include "absl/base/attributes.h" #include "absl/base/no_destructor.h" #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/log/absl_log.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include <nlohmann/json.hpp> #include "tensorstore/context.h" #include "tensorstore/internal/cache_key/cache_key.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/log/verbose_flag.h" #include "tensorstore/internal/source_location.h" #include "tensorstore/kvstore/driver.h" #include "tensorstore/kvstore/generation.h" #include "tensorstore/kvstore/key_range.h" #include "tensorstore/kvstore/operations.h" #include "tensorstore/kvstore/read_result.h" #include "tensorstore/kvstore/registry.h" #include "tensorstore/kvstore/spec.h" #include "tensorstore/kvstore/supported_features.h" #include "tensorstore/serialization/fwd.h" #include "tensorstore/serialization/registry.h" #include "tensorstore/serialization/serialization.h" #include "tensorstore/transaction.h" #include "tensorstore/util/execution/execution.h" #include "tensorstore/util/execution/future_sender.h" #include "tensorstore/util/execution/sender.h" #include "tensorstore/util/execution/sender_util.h" #include "tensorstore/util/executor.h" #include "tensorstore/util/future.h" #include "tensorstore/util/garbage_collection/fwd.h" #include "tensorstore/util/garbage_collection/garbage_collection.h" #include "tensorstore/util/quote_string.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" using ::tensorstore::internal::IntrusivePtr; namespace tensorstore { namespace kvstore { namespace { ABSL_CONST_INIT internal_log::VerboseFlag kvstore_cache_logging( "kvstore_cache"); } void intrusive_ptr_increment(Driver* p) { p->reference_count_.fetch_add(1, std::memory_order_relaxed); } void intrusive_ptr_decrement(Driver* p) { if (!internal::DecrementReferenceCountIfGreaterThanOne(p->reference_count_)) { p->DestroyLastReference(); } } void EncodeCacheKeyAdl(std::string* out, const DriverPtr& ptr) { return ptr->EncodeCacheKey(out); } Result<Spec> KvStore::spec(SpecRequestOptions&& options) const { TENSORSTORE_ASSIGN_OR_RETURN(auto driver_spec, driver->spec(std::move(options))); return Spec(std::move(driver_spec), path); } Result<std::string> KvStore::ToUrl() const { TENSORSTORE_ASSIGN_OR_RETURN(auto spec, this->spec()); return spec.ToUrl(); } Result<KvStore> KvStore::base() const { return driver->GetBase(path, transaction); } Result<DriverSpecPtr> Driver::spec(SpecRequestOptions&& options) const { TENSORSTORE_ASSIGN_OR_RETURN(auto spec, GetBoundSpec()); internal::ApplyContextBindingMode(spec, options.context_binding_mode, ContextBindingMode::strip); TENSORSTORE_RETURN_IF_ERROR(spec.Set(std::move(options))); return spec; } Result<DriverSpecPtr> Driver::GetBoundSpec() const { return absl::UnimplementedError( "KeyValueStore does not support JSON representation"); } SupportedFeatures Driver::GetSupportedFeatures( const KeyRange& key_range) const { return SupportedFeatures::kNone; } void Driver::EncodeCacheKey(std::string* out) const { internal::EncodeCacheKey(out, reinterpret_cast<uintptr_t>(this)); } Result<KvStore> Driver::GetBase(std::string_view path, const Transaction& transaction) const { return {std::in_place}; } } namespace internal_kvstore { DriverRegistry& GetDriverRegistry() { static absl::NoDestructor<DriverRegistry> registry; return *registry; } } template serialization::Registry& serialization::GetRegistry<internal::IntrusivePtr<const kvstore::DriverSpec>>(); namespace kvstore { Driver::~Driver() = default; Future<KvStore> Open(Spec spec, OpenOptions&& options) { if (!spec.valid()) { return absl::InvalidArgumentError("Cannot open null kvstore spec"); } return MapFutureValue( InlineExecutor{}, [path = std::move(spec.path), transaction = std::move(options.transaction)](DriverPtr& driver) mutable { return KvStore(std::move(driver), std::move(path), std::move(transaction)); }, kvstore::Open(std::move(spec.driver), static_cast<DriverOpenOptions&&>(options))); } Future<KvStore> Open(::nlohmann::json json_spec, OpenOptions&& options) { TENSORSTORE_ASSIGN_OR_RETURN(auto spec, Spec::FromJson(std::move(json_spec))); return Open(std::move(spec), std::move(options)); } namespace { struct OpenDriverCache { absl::Mutex mutex; absl::flat_hash_map<std::string, Driver*> map ABSL_GUARDED_BY(mutex); }; OpenDriverCache& GetOpenDriverCache() { static absl::NoDestructor<OpenDriverCache> cache_; return *cache_; } } Future<DriverPtr> Open(DriverSpecPtr spec, DriverOpenOptions&& options) { TENSORSTORE_RETURN_IF_ERROR(spec.BindContext(options.context)); std::string cache_identifier; spec->EncodeCacheKey(&cache_identifier); { auto& open_cache = GetOpenDriverCache(); absl::MutexLock lock(&open_cache.mutex); auto it = open_cache.map.find(cache_identifier); if (it != open_cache.map.end()) { ABSL_LOG_IF(INFO, kvstore_cache_logging) << "Reusing cached kvstore: " << QuoteString(cache_identifier); return DriverPtr(it->second); } } return MapFutureValue( InlineExecutor{}, [cache_identifier = std::move(cache_identifier)](DriverPtr driver) mutable { auto& open_cache = GetOpenDriverCache(); absl::MutexLock lock(&open_cache.mutex); auto p = open_cache.map.emplace(cache_identifier, driver.get()); if (p.second) { driver->cache_identifier_ = std::move(cache_identifier); ABSL_LOG_IF(INFO, kvstore_cache_logging) << "Inserted kvstore into cache: " << QuoteString(driver->cache_identifier_); } else { ABSL_LOG_IF(INFO, kvstore_cache_logging) << "Reusing cached kvstore: " << QuoteString(cache_identifier); } return DriverPtr(p.first->second); }, spec->DoOpen()); } void Driver::DestroyLastReference() { auto& open_cache = GetOpenDriverCache(); if (!cache_identifier_.empty()) { absl::MutexLock lock(&open_cache.mutex); if (reference_count_.fetch_sub(1, std::memory_order_acq_rel) != 1) { return; } auto it = open_cache.map.find(cache_identifier_); if (it != open_cache.map.end()) { assert(it->second == this); open_cache.map.erase(it); ABSL_LOG_IF(INFO, kvstore_cache_logging) << "Removed kvstore from open cache: " << QuoteString(cache_identifier_); } } else { if (reference_count_.fetch_sub(1, std::memory_order_acq_rel) != 1) { return; } } delete this; } Future<ReadResult> Driver::Read(Key key, ReadOptions options) { return absl::UnimplementedError("KeyValueStore does not support reading"); } Future<TimestampedStorageGeneration> Driver::Write(Key key, std::optional<Value> value, WriteOptions options) { return absl::UnimplementedError("KeyValueStore does not support writing"); } #if 0 namespace { struct CopyRangeListReceiver : public internal::AtomicReferenceCount<CopyRangeListReceiver> { using Ptr = internal::IntrusivePtr<CopyRangeListReceiver>; internal::OpenTransactionPtr target_transaction; DriverPtr source_driver; absl::Time source_staleness_bound; DriverPtr target_driver; size_t source_prefix_length; std::string target_prefix; Promise<void> promise; FutureCallbackRegistration cancel_registration; template <typename Cancel> friend void set_starting(const Ptr& self, Cancel&& cancel) { self->cancel_registration = self->promise.ExecuteWhenNotNeeded(std::forward<Cancel>(cancel)); } friend void set_stopping(const Ptr& self) { self->cancel_registration.Unregister(); } friend void set_error(const Ptr& self, absl::Status&& error) { SetDeferredResult(self->promise, std::move(error)); } friend void set_done(const Ptr& self) {} friend void set_value(const Ptr& self, ListEntry&& entry) { ReadOptions options; options.staleness_bound = self->source_staleness_bound; std::string target_key = absl::StrCat(self->target_prefix, std::string_view(entry.key).substr(std::min( self->source_prefix_length, entry.key.size()))); auto read_future = self->source_driver->Read(std::move(entry.key), std::move(options)); Link( [self, target_key = std::move(target_key)]( Promise<void> promise, ReadyFuture<ReadResult> future) { TENSORSTORE_ASSIGN_OR_RETURN(auto read_result, std::move(future.result()), SetDeferredResult(self->promise, _)); if (!read_result.has_value()) return; Link( [](Promise<void> promise, ReadyFuture<TimestampedStorageGeneration> future) { TENSORSTORE_RETURN_IF_ERROR(future.result(), SetDeferredResult(promise, _)); }, std::move(promise), kvstore::Write(KvStore(self->target_driver, std::move(target_key), internal::TransactionState::ToTransaction( self->target_transaction)), "", read_result.value)); }, self->promise, std::move(read_future)); } }; } #endif Future<const void> Driver::ExperimentalCopyRangeFrom( const internal::OpenTransactionPtr& transaction, const KvStore& source, Key target_prefix, CopyRangeOptions options) { return absl::UnimplementedError("CopyRange not supported"); #if 0 auto receiver = internal::MakeIntrusivePtr<CopyRangeListReceiver>(); if (source.transaction != no_transaction) { return absl::UnimplementedError( "CopyRange does not support a source KvStore with a transaction"); } receiver->target_transaction = transaction; receiver->target_driver.reset(this); receiver->source_driver = source.driver; receiver->source_staleness_bound = options.source_staleness_bound; receiver->source_prefix_length = source.path.size(); receiver->target_prefix = std::move(target_prefix); auto [promise, future] = PromiseFuturePair<void>::Make(std::in_place); receiver->promise = std::move(promise); ListOptions list_options; list_options.staleness_bound = options.source_staleness_bound; list_options.range = KeyRange::AddPrefix(source.path, options.source_range); source.driver->ListImpl(std::move(list_options), std::move(receiver)); return std::move(future); #endif } Future<const void> Driver::DeleteRange(KeyRange range) { return absl::UnimplementedError( "KeyValueStore does not support deleting by range"); } void Driver::ListImpl(ListOptions options, ListReceiver receiver) { execution::submit(FlowSingleSender{ErrorSender{absl::UnimplementedError( "KeyValueStore does not support listing")}}, std::move(receiver)); } ListSender Driver::List(ListOptions options) { struct ListSender { IntrusivePtr<Driver> self; ListOptions options; void submit(ListReceiver receiver) { self->ListImpl(options, std::move(receiver)); } }; return ListSender{IntrusivePtr<Driver>(this), std::move(options)}; } std::string Driver::DescribeKey(std::string_view key) { return tensorstore::QuoteString(key); } absl::Status Driver::AnnotateError(std::string_view key, std::string_view action, const absl::Status& error, SourceLocation loc) { return AnnotateErrorWithKeyDescription(DescribeKey(key), action, error, loc); } absl::Status Driver::AnnotateErrorWithKeyDescription( std::string_view key_description, std::string_view action, const absl::Status& error, SourceLocation loc) { if (absl::StrContains(error.message(), key_description)) { return error; } return tensorstore::MaybeAnnotateStatus( error, absl::StrCat("Error ", action, " ", key_description), loc); } bool operator==(const KvStore& a, const KvStore& b) { return a.driver == b.driver && a.path == b.path && a.transaction == b.transaction; } } namespace serialization { namespace { using DriverSpecPtrNonNullDirectSerializer = RegistrySerializer<internal::IntrusivePtr<const kvstore::DriverSpec>>; using DriverSpecPtrNonNullSerializer = NonNullIndirectPointerSerializer< internal::IntrusivePtr<const kvstore::DriverSpec>, DriverSpecPtrNonNullDirectSerializer>; struct DriverPtrNonNullDirectSerializer { [[nodiscard]] static bool Encode(EncodeSink& sink, const kvstore::DriverPtr& value) { TENSORSTORE_ASSIGN_OR_RETURN(auto driver_spec, value->spec(retain_context), (sink.Fail(_), false)); return DriverSpecPtrNonNullSerializer().Encode(sink, driver_spec); } [[nodiscard]] static bool Decode(DecodeSource& source, kvstore::DriverPtr& value) { kvstore::DriverSpecPtr driver_spec; if (!DriverSpecPtrNonNullSerializer().Decode(source, driver_spec)) { return false; } TENSORSTORE_ASSIGN_OR_RETURN(value, kvstore::Open(std::move(driver_spec)).result(), (source.Fail(_), false)); return true; } }; using DriverPtrSerializer = IndirectPointerSerializer<kvstore::DriverPtr, DriverPtrNonNullDirectSerializer>; } } } TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::kvstore::DriverPtr, tensorstore::serialization::DriverPtrSerializer()) TENSORSTORE_DEFINE_SERIALIZER_SPECIALIZATION( tensorstore::kvstore::KvStore, tensorstore::serialization::ApplyMembersSerializer< tensorstore::kvstore::KvStore>()) TENSORSTORE_DEFINE_GARBAGE_COLLECTION_SPECIALIZATION( tensorstore::kvstore::Driver, tensorstore::garbage_collection::PolymorphicGarbageCollection< tensorstore::kvstore::Driver>) TENSORSTORE_DEFINE_GARBAGE_COLLECTION_SPECIALIZATION( tensorstore::kvstore::KvStore, tensorstore::garbage_collection::ApplyMembersGarbageCollection< tensorstore::kvstore::KvStore>)
#include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "tensorstore/context.h" #include "tensorstore/kvstore/kvstore.h" #include "tensorstore/util/future.h" #include "tensorstore/util/result.h" #include "tensorstore/util/status.h" #include "tensorstore/util/status_testutil.h" #include "tensorstore/util/str_cat.h" namespace { namespace kvstore = tensorstore::kvstore; using ::tensorstore::MatchesStatus; TEST(KeyValueStoreTest, OpenInvalid) { auto context = tensorstore::Context::Default(); EXPECT_THAT(kvstore::Open({{"driver", "invalid"}}, context).result(), MatchesStatus(absl::StatusCode::kInvalidArgument, "Error parsing object member \"driver\": " "\"invalid\" is not registered")); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/kvstore/kvstore.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/kvstore/kvstore_test.cc
4f887a6430414cd6088e1743555015b10f116d50
5eb65c3c-b5da-4d15-bec0-f019bbe5d977
cpp
google/tensorstore
index
python/tensorstore/index.cc
python/tensorstore/index_test.cc
#include <pybind11/pybind11.h> #include "python/tensorstore/index.h" #include <cstddef> #include <string> #include <variant> #include <vector> #include "python/tensorstore/sequence_parameter.h" #include "tensorstore/index.h" #include "tensorstore/index_space/index_vector_or_scalar.h" #include "tensorstore/index_space/internal/numpy_indexing_spec.h" #include "tensorstore/util/span.h" namespace tensorstore { namespace internal_python { IndexVectorOrScalarContainer ToIndexVectorOrScalarContainer( const OptionallyImplicitIndexVectorOrScalarContainer& x, Index implicit_value) { if (auto* index = std::get_if<OptionallyImplicitIndex>(&x)) { return index->value_or(implicit_value); } const auto& v = std::get<SequenceParameter<OptionallyImplicitIndex>>(x); std::vector<Index> out_v; out_v.reserve(v.size()); for (size_t i = 0; i < v.size(); ++i) { out_v.push_back(v[i].value_or(implicit_value)); } return out_v; } internal_index_space::IndexVectorOrScalarView ToIndexVectorOrScalar( const IndexVectorOrScalarContainer& x) { constexpr static Index temp = 0; if (auto* index = std::get_if<Index>(&x)) { return *index; } else { const auto& v = std::get<std::vector<Index>>(x); if (v.empty()) { return span(&temp, 0); } return span(v); } } std::string IndexVectorRepr(const IndexVectorOrScalarContainer& x, bool implicit, bool subscript) { return internal::IndexVectorRepr(ToIndexVectorOrScalar(x), implicit, subscript); } } } namespace pybind11 { namespace detail { handle type_caster<tensorstore::internal_python::PythonDimensionIndex>::cast( tensorstore::internal_python::PythonDimensionIndex x, return_value_policy , handle ) { return int_(x.value).release(); } bool type_caster<tensorstore::internal_python::PythonDimensionIndex>::load( handle src, bool convert) { value.value = PyNumber_AsSsize_t(src.ptr(), PyExc_IndexError); if (value.value == -1 && PyErr_Occurred()) { PyErr_Clear(); return false; } return true; } handle type_caster<tensorstore::internal_python::OptionallyImplicitIndex>::cast( tensorstore::internal_python::OptionallyImplicitIndex x, return_value_policy , handle ) { if (x.value == tensorstore::kImplicit) return none().release(); return int_(x.value).release(); } bool type_caster<tensorstore::internal_python::OptionallyImplicitIndex>::load( handle src, bool convert) { if (src.is_none()) { value.value = tensorstore::kImplicit; return true; } value.value = PyNumber_AsSsize_t(src.ptr(), PyExc_IndexError); if (value.value == -1 && PyErr_Occurred()) { PyErr_Clear(); return false; } return true; } } }
#include "python/tensorstore/index.h" #include <vector> #include <gtest/gtest.h> #include "tensorstore/index.h" namespace { TEST(OptionallyImplicitIndexReprTest, Basic) { using tensorstore::kImplicit; using tensorstore::internal_python::OptionallyImplicitIndexRepr; EXPECT_EQ("None", OptionallyImplicitIndexRepr(kImplicit)); EXPECT_EQ("3", OptionallyImplicitIndexRepr(3)); EXPECT_EQ("-3", OptionallyImplicitIndexRepr(-3)); } TEST(IndexVectorReprTest, Basic) { using tensorstore::Index; using tensorstore::kImplicit; using tensorstore::internal_python::IndexVectorRepr; for (bool subscript : {false, true}) { EXPECT_EQ("None", IndexVectorRepr(kImplicit, true, subscript)); for (bool implicit : {false, true}) { EXPECT_EQ("1", IndexVectorRepr(1, implicit, subscript)); EXPECT_EQ("-1", IndexVectorRepr(-1, implicit, subscript)); } } for (bool implicit : {false, true}) { EXPECT_EQ("[1,2,3]", IndexVectorRepr(std::vector<Index>{1, 2, 3}, implicit, false)); EXPECT_EQ("1,2,3", IndexVectorRepr(std::vector<Index>{1, 2, 3}, implicit, true)); EXPECT_EQ("[]", IndexVectorRepr(std::vector<Index>{}, implicit, false)); EXPECT_EQ("()", IndexVectorRepr(std::vector<Index>{}, implicit, true)); } EXPECT_EQ("[1,2,None]", IndexVectorRepr(std::vector<Index>{1, 2, kImplicit}, true, false)); EXPECT_EQ("1,2,None", IndexVectorRepr(std::vector<Index>{1, 2, kImplicit}, true, true)); } TEST(ToIndexVectorOrScalarContainerTest, Basic) { using tensorstore::Index; using tensorstore::kImplicit; using tensorstore::internal_python::IndexVectorOrScalarContainer; using tensorstore::internal_python::OptionallyImplicitIndex; using tensorstore::internal_python::ToIndexVectorOrScalarContainer; EXPECT_EQ( IndexVectorOrScalarContainer{Index{3}}, ToIndexVectorOrScalarContainer(OptionallyImplicitIndex{3}, kImplicit)); EXPECT_EQ(IndexVectorOrScalarContainer{3}, ToIndexVectorOrScalarContainer(OptionallyImplicitIndex{3}, 4)); EXPECT_EQ( IndexVectorOrScalarContainer{Index{3}}, ToIndexVectorOrScalarContainer(OptionallyImplicitIndex{kImplicit}, 3)); EXPECT_EQ(IndexVectorOrScalarContainer{kImplicit}, ToIndexVectorOrScalarContainer(OptionallyImplicitIndex{kImplicit}, kImplicit)); EXPECT_EQ(IndexVectorOrScalarContainer{std::vector<Index>({1, 2, 3})}, ToIndexVectorOrScalarContainer( std::vector<OptionallyImplicitIndex>{ OptionallyImplicitIndex{1}, OptionallyImplicitIndex{2}, OptionallyImplicitIndex{3}, }, kImplicit)); EXPECT_EQ(IndexVectorOrScalarContainer{std::vector<Index>({1, 2, kImplicit})}, ToIndexVectorOrScalarContainer( std::vector<OptionallyImplicitIndex>{ OptionallyImplicitIndex{1}, OptionallyImplicitIndex{2}, OptionallyImplicitIndex{kImplicit}, }, kImplicit)); EXPECT_EQ(IndexVectorOrScalarContainer{std::vector<Index>({1, 2, 3})}, ToIndexVectorOrScalarContainer( std::vector<OptionallyImplicitIndex>{ OptionallyImplicitIndex{1}, OptionallyImplicitIndex{2}, OptionallyImplicitIndex{kImplicit}, }, 3)); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/python/tensorstore/index.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/python/tensorstore/index_test.cc
4f887a6430414cd6088e1743555015b10f116d50
7e2c7a0e-34b4-43d0-83f0-bea87162eae3
cpp
google/tensorstore
downsample
tensorstore/driver/downsample/downsample.cc
tensorstore/driver/downsample/downsample_test.cc
#include "tensorstore/driver/downsample/downsample.h" #include <stddef.h> #include <algorithm> #include <cassert> #include <mutex> #include <utility> #include <vector> #include "absl/base/thread_annotations.h" #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/synchronization/mutex.h" #include "tensorstore/array.h" #include "tensorstore/array_storage_statistics.h" #include "tensorstore/box.h" #include "tensorstore/chunk_layout.h" #include "tensorstore/codec_spec.h" #include "tensorstore/context.h" #include "tensorstore/contiguous_layout.h" #include "tensorstore/data_type.h" #include "tensorstore/downsample_method.h" #include "tensorstore/driver/chunk.h" #include "tensorstore/driver/downsample/downsample_array.h" #include "tensorstore/driver/downsample/downsample_method_json_binder.h" #include "tensorstore/driver/downsample/downsample_nditerable.h" #include "tensorstore/driver/downsample/downsample_util.h" #include "tensorstore/driver/downsample/grid_occupancy_map.h" #include "tensorstore/driver/driver.h" #include "tensorstore/driver/driver_handle.h" #include "tensorstore/driver/driver_spec.h" #include "tensorstore/driver/read.h" #include "tensorstore/driver/registry.h" #include "tensorstore/index.h" #include "tensorstore/index_space/dim_expression.h" #include "tensorstore/index_space/dimension_units.h" #include "tensorstore/index_space/index_domain.h" #include "tensorstore/index_space/index_domain_builder.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/index_transform_builder.h" #include "tensorstore/index_space/transformed_array.h" #include "tensorstore/internal/arena.h" #include "tensorstore/internal/intrusive_ptr.h" #include "tensorstore/internal/json_binding/json_binding.h" #include "tensorstore/internal/json_binding/std_array.h" #include "tensorstore/internal/lock_collection.h" #include "tensorstore/internal/nditerable_transformed_array.h" #include "tensorstore/json_serialization_options.h" #include "tensorstore/kvstore/kvstore.h" #include "tensorstore/kvstore/spec.h" #include "tensorstore/open_mode.h" #include "tensorstore/open_options.h" #include "tensorstore/rank.h" #include "tensorstore/resize_options.h" #include "tensorstore/schema.h" #include "tensorstore/serialization/std_vector.h" #include "tensorstore/spec.h" #include "tensorstore/transaction.h" #include "tensorstore/util/execution/execution.h" #include "tensorstore/util/execution/sender_util.h" #include "tensorstore/util/executor.h" #include "tensorstore/util/future.h" #include "tensorstore/util/garbage_collection/std_vector.h" #include "tensorstore/util/iterate.h" #include "tensorstore/util/result.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace internal_downsample { namespace { using ::tensorstore::internal::DriverPtr; using ::tensorstore::internal::IntrusivePtr; using ::tensorstore::internal::LockCollection; using ::tensorstore::internal::NDIterable; using ::tensorstore::internal::OpenTransactionPtr; using ::tensorstore::internal::ReadChunk; using ::tensorstore::internal::TransformedDriverSpec; namespace jb = tensorstore::internal_json_binding; Result<IndexDomain<>> GetBaseDomainConstraintFromDownsampledDomain( IndexDomain<> downsampled_domain, tensorstore::span<const Index> downsample_factors) { assert(downsampled_domain.valid()); const DimensionIndex rank = downsampled_domain.rank(); assert(rank == downsample_factors.size()); IndexDomainBuilder builder(rank); builder.labels(downsampled_domain.labels()); auto& implicit_lower_bounds = builder.implicit_lower_bounds(); auto& implicit_upper_bounds = builder.implicit_upper_bounds(); auto origin = builder.origin(); auto shape = builder.shape(); for (DimensionIndex i = 0; i < rank; ++i) { if (downsample_factors[i] != 1) { implicit_lower_bounds[i] = true; implicit_upper_bounds[i] = true; origin[i] = -kInfIndex; shape[i] = kInfSize; } else { implicit_lower_bounds[i] = downsampled_domain.implicit_lower_bounds()[i]; implicit_upper_bounds[i] = downsampled_domain.implicit_upper_bounds()[i]; origin[i] = downsampled_domain.origin()[i]; shape[i] = downsampled_domain.shape()[i]; } } return builder.Finalize(); } Result<IndexTransform<>> GetBaseTransformForDownsampledTransform( IndexTransformView<> base_transform, IndexTransformView<> downsampled_transform, tensorstore::span<const Index> downsample_factors, DownsampleMethod downsample_method) { if (downsample_method == DownsampleMethod::kStride) { return base_transform | tensorstore::AllDims().Stride(downsample_factors) | downsampled_transform; } PropagatedIndexTransformDownsampling propagated; TENSORSTORE_RETURN_IF_ERROR( internal_downsample::PropagateAndComposeIndexTransformDownsampling( downsampled_transform, base_transform, downsample_factors, propagated)); return std::move(propagated.transform); } class DownsampleDriverSpec : public internal::RegisteredDriverSpec<DownsampleDriverSpec, internal::DriverSpec> { public: constexpr static char id[] = "downsample"; TransformedDriverSpec base; std::vector<Index> downsample_factors; DownsampleMethod downsample_method; constexpr static auto ApplyMembers = [](auto& x, auto f) { return f(internal::BaseCast<internal::DriverSpec>(x), x.base, x.downsample_factors, x.downsample_method); }; absl::Status InitializeFromBase() { TENSORSTORE_RETURN_IF_ERROR( this->schema.Set(RankConstraint{internal::GetRank(this->base)})); TENSORSTORE_RETURN_IF_ERROR( this->schema.Set(this->base.driver_spec->schema.dtype())); return absl::OkStatus(); } absl::Status ValidateDownsampleFactors() { TENSORSTORE_RETURN_IF_ERROR( this->schema.Set(RankConstraint(this->downsample_factors.size()))); return absl::OkStatus(); } absl::Status ValidateDownsampleMethod() { auto dtype = this->schema.dtype(); if (!dtype.valid()) return absl::OkStatus(); return internal_downsample::ValidateDownsampleMethod( dtype, this->downsample_method); } OpenMode open_mode() const override { return base.driver_spec->open_mode(); } absl::Status ApplyOptions(SpecOptions&& options) override { TENSORSTORE_RETURN_IF_ERROR(schema.Set(options.dtype())); TENSORSTORE_RETURN_IF_ERROR(schema.Set(options.rank())); auto transform = base.transform; if (!transform.valid()) { transform = tensorstore::IdentityTransform(downsample_factors.size()); } if (options.domain().valid()) { TENSORSTORE_RETURN_IF_ERROR(schema.Set(options.domain())); TENSORSTORE_ASSIGN_OR_RETURN(auto base_domain, GetBaseDomainConstraintFromDownsampledDomain( options.domain(), downsample_factors)); TENSORSTORE_RETURN_IF_ERROR(options.Override(std::move(base_domain))); } TENSORSTORE_ASSIGN_OR_RETURN( transform, transform | AllDims().Stride(downsample_factors)); TENSORSTORE_RETURN_IF_ERROR(options.TransformInputSpaceSchema(transform)); return internal::TransformAndApplyOptions(base, std::move(options)); } constexpr static auto default_json_binder = jb::Object( jb::Member("base", [](auto is_loading, const auto& options, auto* obj, auto* j) { return jb::Projection<&DownsampleDriverSpec::base>()( is_loading, JsonSerializationOptions(options, obj->schema.dtype(), obj->schema.rank()), obj, j); }), jb::Initialize([](auto* obj) { return obj->InitializeFromBase(); }), jb::Member("downsample_factors", jb::Validate( [](const auto& options, auto* obj) { return obj->ValidateDownsampleFactors(); }, jb::Projection<&DownsampleDriverSpec::downsample_factors>( jb::Array(jb::Integer<Index>(1))))), jb::Member( "downsample_method", jb::Validate( [](const auto& options, auto* obj) { return obj->ValidateDownsampleMethod(); }, jb::Projection<&DownsampleDriverSpec::downsample_method>())), jb::Initialize([](auto* obj) { SpecOptions base_options; static_cast<Schema&>(base_options) = std::exchange(obj->schema, {}); return obj->ApplyOptions(std::move(base_options)); })); Result<IndexDomain<>> GetDomain() const override { TENSORSTORE_ASSIGN_OR_RETURN(auto domain, internal::GetEffectiveDomain(base)); if (!domain.valid()) { return schema.domain(); } if (domain.rank() != downsample_factors.size()) { return absl::InternalError(tensorstore::StrCat( "Domain of base TensorStore has rank (", domain.rank(), ") but expected ", downsample_factors.size())); } auto downsampled_domain = internal_downsample::DownsampleDomain( domain, downsample_factors, downsample_method); return MergeIndexDomains(std::move(downsampled_domain), schema.domain()); } Result<ChunkLayout> GetChunkLayout() const override { return internal::GetEffectiveChunkLayout(base) | AllDims().Stride(downsample_factors); } Result<CodecSpec> GetCodec() const override { return internal::GetEffectiveCodec(base); } Result<SharedArray<const void>> GetFillValue( IndexTransformView<> transform) const override { return {std::in_place}; } Result<DimensionUnitsVector> GetDimensionUnits() const override { TENSORSTORE_ASSIGN_OR_RETURN(auto dimension_units, internal::GetEffectiveDimensionUnits(base)); if (!dimension_units.empty()) { tensorstore::span<const Index> downsample_factors = this->downsample_factors; TENSORSTORE_ASSIGN_OR_RETURN( auto transform, tensorstore::IdentityTransform(downsample_factors.size()) | tensorstore::AllDims().Stride(downsample_factors)); dimension_units = TransformOutputDimensionUnits(transform, std::move(dimension_units)); } return dimension_units; } kvstore::Spec GetKvstore() const override { return base.driver_spec->GetKvstore(); } Result<TransformedDriverSpec> GetBase( IndexTransformView<> transform) const override { TransformedDriverSpec new_base; new_base.driver_spec = base.driver_spec; if (transform.valid()) { TENSORSTORE_ASSIGN_OR_RETURN( new_base.transform, GetBaseTransformForDownsampledTransform( base.transform.valid() ? base.transform : tensorstore::IdentityTransform(downsample_factors.size()), transform, downsample_factors, downsample_method)); } return new_base; } Future<internal::Driver::Handle> Open( internal::DriverOpenRequest request) const override { if (!!(request.read_write_mode & ReadWriteMode::write)) { return absl::InvalidArgumentError("only reading is supported"); } request.read_write_mode = ReadWriteMode::read; return MapFutureValue( InlineExecutor{}, [spec = internal::DriverSpec::PtrT<const DownsampleDriverSpec>(this)]( internal::Driver::Handle handle) -> Result<internal::Driver::Handle> { TENSORSTORE_ASSIGN_OR_RETURN( auto downsampled_handle, MakeDownsampleDriver(std::move(handle), spec->downsample_factors, spec->downsample_method)); if (auto domain = spec->schema.domain(); domain.valid()) { TENSORSTORE_RETURN_IF_ERROR( MergeIndexDomains(domain, downsampled_handle.transform.domain()), tensorstore::MaybeAnnotateStatus( _, "downsampled domain does not match domain in schema")); } return downsampled_handle; }, internal::OpenDriver(base, std::move(request))); } }; class DownsampleDriver : public internal::RegisteredDriver<DownsampleDriver, internal::Driver> { public: Result<TransformedDriverSpec> GetBoundSpec( internal::OpenTransactionPtr transaction, IndexTransformView<> transform) override { auto driver_spec = internal::DriverSpec::Make<DownsampleDriverSpec>(); driver_spec->context_binding_state_ = ContextBindingState::bound; TENSORSTORE_ASSIGN_OR_RETURN( driver_spec->base, base_driver_->GetBoundSpec(std::move(transaction), base_transform_)); driver_spec->downsample_factors = downsample_factors_; driver_spec->downsample_method = downsample_method_; TENSORSTORE_RETURN_IF_ERROR(driver_spec->InitializeFromBase()); TransformedDriverSpec spec; spec.transform = transform; spec.driver_spec = std::move(driver_spec); return spec; } Result<ChunkLayout> GetChunkLayout(IndexTransformView<> transform) override { TENSORSTORE_ASSIGN_OR_RETURN(auto strided_base_transform, GetStridedBaseTransform()); return base_driver_->GetChunkLayout(strided_base_transform) | transform; } Result<CodecSpec> GetCodec() override { return base_driver_->GetCodec(); } Result<SharedArray<const void>> GetFillValue( IndexTransformView<> transform) override { if (downsample_method_ == DownsampleMethod::kStride) { TENSORSTORE_ASSIGN_OR_RETURN(auto strided_transform, GetStridedBaseTransform() | transform); return base_driver_->GetFillValue(strided_transform); } PropagatedIndexTransformDownsampling propagated; TENSORSTORE_RETURN_IF_ERROR( internal_downsample::PropagateAndComposeIndexTransformDownsampling( transform, base_transform_, downsample_factors_, propagated)); TENSORSTORE_ASSIGN_OR_RETURN( auto fill_value, base_driver_->GetFillValue(propagated.transform)); if (!fill_value.valid()) return {std::in_place}; TENSORSTORE_ASSIGN_OR_RETURN( auto broadcast_fill_value, BroadcastArray(std::move(fill_value), propagated.transform.domain().box())); TENSORSTORE_ASSIGN_OR_RETURN( auto downsampled_fill_value, internal_downsample::DownsampleArray( broadcast_fill_value, propagated.input_downsample_factors, downsample_method_)); return UnbroadcastArray(downsampled_fill_value); } Result<DimensionUnitsVector> GetDimensionUnits() override { TENSORSTORE_ASSIGN_OR_RETURN(auto dimension_units, base_driver_->GetDimensionUnits()); TENSORSTORE_ASSIGN_OR_RETURN(auto strided_base_transform, GetStridedBaseTransform()); return TransformOutputDimensionUnits(strided_base_transform, std::move(dimension_units)); } KvStore GetKvstore(const Transaction& transaction) override { return base_driver_->GetKvstore(transaction); } Result<internal::DriverHandle> GetBase( ReadWriteMode read_write_mode, IndexTransformView<> transform, const Transaction& transaction) override { internal::DriverHandle base_handle; base_handle.driver = base_driver_; base_handle.driver.set_read_write_mode(read_write_mode); base_handle.transaction = transaction; TENSORSTORE_ASSIGN_OR_RETURN(base_handle.transform, GetBaseTransformForDownsampledTransform( base_transform_, transform, downsample_factors_, downsample_method_)); return base_handle; } Future<ArrayStorageStatistics> GetStorageStatistics( GetStorageStatisticsRequest request) override; explicit DownsampleDriver(DriverPtr base, IndexTransform<> base_transform, tensorstore::span<const Index> downsample_factors, DownsampleMethod downsample_method) : base_driver_(std::move(base)), base_transform_(std::move(base_transform)), downsample_factors_(downsample_factors.begin(), downsample_factors.end()), downsample_method_(downsample_method) {} DataType dtype() override { return base_driver_->dtype(); } DimensionIndex rank() override { return base_transform_.input_rank(); } Executor data_copy_executor() override { return base_driver_->data_copy_executor(); } void Read(ReadRequest request, ReadChunkReceiver receiver) override; Result<IndexTransform<>> GetStridedBaseTransform() { return base_transform_ | tensorstore::AllDims().Stride(downsample_factors_); } Future<IndexTransform<>> ResolveBounds(ResolveBoundsRequest request) override; constexpr static auto ApplyMembers = [](auto&& x, auto f) { return f(x.base_driver_, x.base_transform_, x.downsample_factors_, x.downsample_method_); }; DriverPtr base_driver_; IndexTransform<> base_transform_; std::vector<Index> downsample_factors_; DownsampleMethod downsample_method_; }; Future<IndexTransform<>> DownsampleDriver::ResolveBounds( ResolveBoundsRequest request) { return MapFutureValue( InlineExecutor{}, [self = IntrusivePtr<DownsampleDriver>(this), transform = std::move(request.transform)]( IndexTransform<> base_transform) -> Result<IndexTransform<>> { Box<dynamic_rank(internal::kNumInlinedDims)> downsampled_bounds( base_transform.input_rank()); internal_downsample::DownsampleBounds( base_transform.domain().box(), downsampled_bounds, self->downsample_factors_, self->downsample_method_); return tensorstore::PropagateBoundsToTransform( downsampled_bounds, base_transform.implicit_lower_bounds(), base_transform.implicit_upper_bounds(), std::move(transform)); }, base_driver_->ResolveBounds({std::move(request.transaction), base_transform_, std::move(request.options)})); } struct ReadState : public internal::AtomicReferenceCount<ReadState> { IntrusivePtr<DownsampleDriver> self_; internal::ReadChunkReceiver receiver_; absl::Mutex mutex_; SharedOffsetArray<void> data_buffer_; Index remaining_elements_; internal_downsample::GridOccupancyTracker independently_emitted_chunks_; absl::InlinedVector<Index, internal::kNumInlinedDims> downsample_factors_; DimensionIndex original_input_rank_; IndexDomain<> base_transform_domain_; AnyCancelReceiver on_cancel_; absl::Status error_; bool done_signal_received_ = false; bool done_sent_ = false; bool canceled_ = false; size_t chunks_in_progress_ = 0; void Cancel() { std::lock_guard<ReadState> guard(*this); canceled_ = true; } void lock() ABSL_NO_THREAD_SAFETY_ANALYSIS { mutex_.Lock(); } void unlock() ABSL_NO_THREAD_SAFETY_ANALYSIS { bool has_error = !error_.ok(); bool send_done = !done_sent_ && chunks_in_progress_ == 0 && (done_signal_received_ || has_error); if (send_done) done_sent_ = true; AnyCancelReceiver on_cancel; if (canceled_ && on_cancel_) { on_cancel = std::move(on_cancel_); } mutex_.Unlock(); if (on_cancel) on_cancel(); if (!send_done) return; if (has_error) { execution::set_error(receiver_, error_); } else { execution::set_done(receiver_); } execution::set_stopping(receiver_); } void SetError(absl::Status error, size_t decrement_chunks_in_progress = 0) { std::lock_guard<ReadState> guard(*this); chunks_in_progress_ -= decrement_chunks_in_progress; if (!error_.ok()) return; error_ = std::move(error); canceled_ = true; } void EmitBufferedChunkForBox(BoxView<> base_domain); void EmitBufferedChunks(); }; struct BufferedReadChunkImpl { internal::IntrusivePtr<ReadState> state_; absl::Status operator()(LockCollection& lock_collection) const { return absl::OkStatus(); } Result<NDIterable::Ptr> operator()(internal::ReadChunk::BeginRead, IndexTransform<> chunk_transform, internal::Arena* arena) const { TENSORSTORE_ASSIGN_OR_RETURN( auto propagated, internal_downsample::PropagateIndexTransformDownsampling( chunk_transform, state_->data_buffer_.domain(), state_->downsample_factors_)); TENSORSTORE_ASSIGN_OR_RETURN( auto transformed_array, MakeTransformedArray(state_->data_buffer_, std::move(propagated.transform))); TENSORSTORE_ASSIGN_OR_RETURN( auto base_nditerable, GetTransformedArrayNDIterable(transformed_array, arena)); return internal_downsample::DownsampleNDIterable( std::move(base_nditerable), transformed_array.domain().box(), propagated.input_downsample_factors, state_->self_->downsample_method_, chunk_transform.input_rank(), arena); } }; IndexTransform<> GetDownsampledRequestIdentityTransform( BoxView<> base_domain, tensorstore::span<const Index> downsample_factors, DownsampleMethod downsample_method, DimensionIndex request_rank) { assert(base_domain.rank() == downsample_factors.size()); assert(request_rank <= base_domain.rank()); IndexTransformBuilder builder(base_domain.rank(), request_rank); internal_downsample::DownsampleBounds(base_domain, builder.input_bounds(), downsample_factors, downsample_method); builder.output_identity_transform(); return builder.Finalize().value(); } void ReadState::EmitBufferedChunkForBox(BoxView<> base_domain) { auto request_transform = GetDownsampledRequestIdentityTransform( base_domain, downsample_factors_, self_->downsample_method_, original_input_rank_); ReadChunk downsampled_chunk; downsampled_chunk.transform = IdentityTransform(request_transform.domain().box()); downsampled_chunk.impl = BufferedReadChunkImpl{IntrusivePtr<ReadState>(this)}; execution::set_value(receiver_, std::move(downsampled_chunk), std::move(request_transform)); } void ReadState::EmitBufferedChunks() { if (independently_emitted_chunks_.occupied_chunks.empty()) { EmitBufferedChunkForBox(base_transform_domain_.box()); } else { internal_downsample::GridOccupancyMap emitted_chunk_map( std::move(independently_emitted_chunks_), base_transform_domain_.box()); const DimensionIndex rank = emitted_chunk_map.rank(); Index grid_cell[kMaxRank]; tensorstore::span<Index> grid_cell_span(&grid_cell[0], rank); Box<dynamic_rank(internal::kNumInlinedDims)> grid_cell_domain; grid_cell_domain.set_rank(rank); emitted_chunk_map.InitializeCellIterator(grid_cell_span); do { if (!emitted_chunk_map.GetGridCellDomain(grid_cell_span, grid_cell_domain)) { continue; } EmitBufferedChunkForBox(grid_cell_domain); } while (emitted_chunk_map.AdvanceCellIterator(grid_cell_span)); } { std::lock_guard<ReadState> guard(*this); --chunks_in_progress_; } } struct IndependentReadChunkImpl { internal::IntrusivePtr<ReadState> state_; internal::ReadChunk base_chunk_; absl::Status operator()(LockCollection& lock_collection) { return base_chunk_.impl(lock_collection); } Result<NDIterable::Ptr> operator()(internal::ReadChunk::BeginRead, IndexTransform<> chunk_transform, internal::Arena* arena) { TENSORSTORE_ASSIGN_OR_RETURN( auto propagated, internal_downsample::PropagateIndexTransformDownsampling( chunk_transform, state_->base_transform_domain_.box(), state_->downsample_factors_)); TENSORSTORE_ASSIGN_OR_RETURN( auto base_transform, ComposeTransforms(base_chunk_.transform, propagated.transform)); TENSORSTORE_ASSIGN_OR_RETURN( auto base_nditerable, base_chunk_.impl(internal::ReadChunk::BeginRead{}, std::move(base_transform), arena)); return internal_downsample::DownsampleNDIterable( std::move(base_nditerable), propagated.transform.domain().box(), propagated.input_downsample_factors, state_->self_->downsample_method_, chunk_transform.input_rank(), arena); } }; bool MaybeEmitIndependentReadChunk( ReadState& state, ReadChunk& base_chunk, IndexTransformView<> base_request_transform) { if (!internal_downsample::CanDownsampleIndexTransform( base_request_transform, state.base_transform_domain_.box(), state.downsample_factors_)) { return false; } TENSORSTORE_ASSIGN_OR_RETURN(auto inverse_request_transform, InverseTransform(base_request_transform), false); TENSORSTORE_ASSIGN_OR_RETURN( base_chunk.transform, ComposeTransforms(base_chunk.transform, inverse_request_transform), false); const Index num_elements = base_chunk.transform.domain().num_elements(); bool emit_buffered_chunk; { absl::MutexLock lock(&state.mutex_); bool has_data_buffer = state.data_buffer_.byte_strided_origin_pointer() != nullptr; bool remaining_data = (state.remaining_elements_ -= num_elements) != 0; emit_buffered_chunk = (!remaining_data && has_data_buffer); if (has_data_buffer || remaining_data) { state.independently_emitted_chunks_.MarkOccupied( base_chunk.transform.domain().box()); } } internal::ReadChunk downsampled_chunk; auto request_transform = GetDownsampledRequestIdentityTransform( base_chunk.transform.domain().box(), state.downsample_factors_, state.self_->downsample_method_, state.original_input_rank_); downsampled_chunk.impl = IndependentReadChunkImpl{ internal::IntrusivePtr<ReadState>(&state), std::move(base_chunk)}; downsampled_chunk.transform = IdentityTransform(request_transform.domain().box()); execution::set_value(state.receiver_, std::move(downsampled_chunk), request_transform); if (emit_buffered_chunk) { state.self_->data_copy_executor()( [state = internal::IntrusivePtr<ReadState>(&state)] { state->EmitBufferedChunks(); }); } else { std::lock_guard<ReadState> guard(state); --state.chunks_in_progress_; } return true; } struct ReadReceiverImpl { internal::IntrusivePtr<ReadState> state_; void set_starting(AnyCancelReceiver on_cancel) { { absl::MutexLock lock(&state_->mutex_); if (!state_->canceled_) { state_->on_cancel_ = std::move(on_cancel); return; } } if (on_cancel) on_cancel(); } void set_value(ReadChunk chunk, IndexTransform<> cell_transform) { if (cell_transform.domain().box().is_empty()) return; { absl::MutexLock lock(&state_->mutex_); if (state_->canceled_) return; ++state_->chunks_in_progress_; } if (MaybeEmitIndependentReadChunk(*state_, chunk, cell_transform)) return; state_->self_->data_copy_executor()([state = state_, chunk = std::move(chunk), cell_transform = std::move( cell_transform)]() mutable { const Index num_elements = cell_transform.domain().num_elements(); { std::lock_guard<ReadState> guard(*state); if (state->canceled_) { --state->chunks_in_progress_; return; } if (state->data_buffer_.byte_strided_origin_pointer() == nullptr) { state->data_buffer_ = AllocateArray(state->base_transform_domain_.box(), c_order, default_init, state->self_->base_driver_->dtype()); } } TENSORSTORE_ASSIGN_OR_RETURN( auto transformed_data_buffer, MakeTransformedArray(state->data_buffer_, std::move(cell_transform)), state->SetError(_, 1)); TENSORSTORE_RETURN_IF_ERROR( internal::CopyReadChunk(chunk.impl, chunk.transform, transformed_data_buffer), state->SetError(_, 1)); { std::lock_guard<ReadState> guard(*state); bool elements_done = (state->remaining_elements_ -= num_elements) == 0; if (state->canceled_ || !elements_done) { --state->chunks_in_progress_; return; } } state->EmitBufferedChunks(); }); } void set_error(absl::Status status) { state_->SetError(std::move(status)); } void set_done() { std::lock_guard<ReadState> guard(*state_); state_->done_signal_received_ = true; } void set_stopping() { absl::MutexLock lock(&state_->mutex_); state_->on_cancel_ = {}; } }; void DownsampleDriver::Read(ReadRequest request, ReadChunkReceiver receiver) { if (downsample_method_ == DownsampleMethod::kStride) { TENSORSTORE_ASSIGN_OR_RETURN( request.transform, GetStridedBaseTransform() | request.transform, execution::set_error(FlowSingleReceiver{std::move(receiver)}, _)); base_driver_->Read(std::move(request), std::move(receiver)); return; } auto base_resolve_future = base_driver_->ResolveBounds( {request.transaction, base_transform_, {fix_resizable_bounds}}); auto state = internal::MakeIntrusivePtr<ReadState>(); state->self_.reset(this); state->original_input_rank_ = request.transform.input_rank(); state->receiver_ = std::move(receiver); execution::set_starting(state->receiver_, [state = state.get()] { state->Cancel(); }); std::move(base_resolve_future) .ExecuteWhenReady([state = std::move(state), request = std::move(request)]( ReadyFuture<IndexTransform<>> future) mutable { auto& r = future.result(); if (!r.ok()) { state->SetError(std::move(r.status())); return; } IndexTransform<> base_transform = std::move(*r); PropagatedIndexTransformDownsampling propagated; TENSORSTORE_RETURN_IF_ERROR( internal_downsample::PropagateAndComposeIndexTransformDownsampling( request.transform, base_transform, state->self_->downsample_factors_, propagated), state->SetError(_)); state->remaining_elements_ = propagated.transform.domain().num_elements(); state->downsample_factors_ = std::move(propagated.input_downsample_factors); state->base_transform_domain_ = propagated.transform.domain(); auto* state_ptr = state.get(); request.transform = std::move(propagated.transform); state_ptr->self_->base_driver_->Read( std::move(request), ReadReceiverImpl{std::move(state)}); }); } Future<ArrayStorageStatistics> DownsampleDriver::GetStorageStatistics( GetStorageStatisticsRequest request) { if (downsample_method_ == DownsampleMethod::kStride) { TENSORSTORE_ASSIGN_OR_RETURN(request.transform, GetStridedBaseTransform() | request.transform); return base_driver_->GetStorageStatistics(std::move(request)); } auto [promise, future] = PromiseFuturePair<ArrayStorageStatistics>::Make(); auto base_resolve_future = base_driver_->ResolveBounds( {request.transaction, base_transform_, {fix_resizable_bounds}}); LinkValue(WithExecutor( data_copy_executor(), [self = IntrusivePtr<DownsampleDriver>(this), request = std::move(request)]( Promise<ArrayStorageStatistics> promise, ReadyFuture<IndexTransform<>> future) mutable { IndexTransform<> base_transform = std::move(future.value()); PropagatedIndexTransformDownsampling propagated; TENSORSTORE_RETURN_IF_ERROR( internal_downsample:: PropagateAndComposeIndexTransformDownsampling( request.transform, base_transform, self->downsample_factors_, propagated), static_cast<void>(promise.SetResult(_))); request.transform = std::move(propagated.transform); LinkResult(std::move(promise), self->base_driver_->GetStorageStatistics( std::move(request))); }), std::move(promise), std::move(base_resolve_future)); return std::move(future); } const internal::DriverRegistration<DownsampleDriverSpec> driver_registration; } } namespace internal { Result<Driver::Handle> MakeDownsampleDriver( Driver::Handle base, tensorstore::span<const Index> downsample_factors, DownsampleMethod downsample_method) { if (downsample_factors.size() != base.transform.input_rank()) { return absl::InvalidArgumentError(tensorstore::StrCat( "Number of downsample factors (", downsample_factors.size(), ") does not match TensorStore rank (", base.transform.input_rank(), ")")); } if (!(base.driver.read_write_mode() & ReadWriteMode::read)) { return absl::InvalidArgumentError( "Cannot downsample write-only TensorStore"); } if (std::any_of(downsample_factors.begin(), downsample_factors.end(), [](Index factor) { return factor < 1; })) { return absl::InvalidArgumentError(tensorstore::StrCat( "Downsample factors ", downsample_factors, " are not all positive")); } TENSORSTORE_RETURN_IF_ERROR(internal_downsample::ValidateDownsampleMethod( base.driver->dtype(), downsample_method)); auto downsampled_domain = internal_downsample::GetDownsampledDomainIdentityTransform( base.transform.domain(), downsample_factors, downsample_method); base.driver = internal::MakeReadWritePtr<internal_downsample::DownsampleDriver>( ReadWriteMode::read, std::move(base.driver), std::move(base.transform), downsample_factors, downsample_method); base.transform = std::move(downsampled_domain); return base; } } Result<Spec> Downsample(const Spec& base_spec, tensorstore::span<const Index> downsample_factors, DownsampleMethod downsample_method) { using internal_spec::SpecAccess; Spec downsampled_spec; auto& impl = SpecAccess::impl(downsampled_spec); auto driver_spec = internal::DriverSpec::Make<internal_downsample::DownsampleDriverSpec>(); driver_spec->context_binding_state_ = base_spec.context_binding_state(); driver_spec->base = SpecAccess::impl(base_spec); TENSORSTORE_RETURN_IF_ERROR(driver_spec->InitializeFromBase()); driver_spec->downsample_factors.assign(downsample_factors.begin(), downsample_factors.end()); driver_spec->downsample_method = downsample_method; TENSORSTORE_RETURN_IF_ERROR(driver_spec->ValidateDownsampleFactors()); TENSORSTORE_RETURN_IF_ERROR(driver_spec->ValidateDownsampleMethod()); impl.driver_spec = std::move(driver_spec); if (base_spec.transform().valid()) { impl.transform = internal_downsample::GetDownsampledDomainIdentityTransform( base_spec.transform().domain(), downsample_factors, downsample_method); } return downsampled_spec; } }
#include "tensorstore/downsample.h" #include <stdint.h> #include <memory> #include <string> #include <utility> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include <nlohmann/json.hpp> #include "tensorstore/array.h" #include "tensorstore/chunk_layout.h" #include "tensorstore/context.h" #include "tensorstore/data_type.h" #include "tensorstore/downsample_method.h" #include "tensorstore/driver/array/array.h" #include "tensorstore/driver/driver_testutil.h" #include "tensorstore/driver/read.h" #include "tensorstore/index.h" #include "tensorstore/index_space/dim_expression.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/index_space/transformed_array.h" #include "tensorstore/internal/global_initializer.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/open.h" #include "tensorstore/open_mode.h" #include "tensorstore/schema.h" #include "tensorstore/spec.h" #include "tensorstore/static_cast.h" #include "tensorstore/tensorstore.h" #include "tensorstore/util/execution/execution.h" #include "tensorstore/util/execution/sender_util.h" #include "tensorstore/util/status_testutil.h" #include "tensorstore/util/str_cat.h" #include "tensorstore/util/unit.h" namespace { using ::tensorstore::BoxView; using ::tensorstore::ChunkLayout; using ::tensorstore::Context; using ::tensorstore::DimensionIndex; using ::tensorstore::DownsampleMethod; using ::tensorstore::Index; using ::tensorstore::MakeArray; using ::tensorstore::MakeOffsetArray; using ::tensorstore::MatchesJson; using ::tensorstore::MatchesStatus; using ::tensorstore::ReadWriteMode; using ::tensorstore::Spec; using ::tensorstore::TensorStore; using ::tensorstore::internal::CollectReadChunks; using ::tensorstore::internal::MakeArrayBackedReadChunk; using ::tensorstore::internal::MockDriver; using ::tensorstore::internal::ReadAsIndividualChunks; using ::tensorstore::internal::TestSpecSchema; using ::tensorstore::internal::TestTensorStoreCreateCheckSchema; using ::testing::Optional; using ::testing::Pair; TEST(DownsampleTest, Rank1Mean) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(MakeArray<float>({1, 2, 5, 7}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(store, {2}, DownsampleMethod::kMean)); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<float>({1.5, 6}))); } TEST(DownsampleTest, Rank1Median) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(MakeArray<float>({1, 2, 5, 7}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(store, {2}, DownsampleMethod::kMin)); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<float>({1, 5}))); } TEST(DownsampleTest, Rank1Empty) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(tensorstore::AllocateArray<float>({2, 0, 3}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(store, {2, 3, 2}, DownsampleMethod::kMean)); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(tensorstore::AllocateArray<float>({1, 0, 2}))); } TEST(DownsampleTest, Rank1MeanTranslated) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(MakeOffsetArray<float>({1}, {1, 2, 5, 7}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(store, {2}, DownsampleMethod::kMean)); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<float>({1, 3.5, 7}))); } TEST(DownsampleTest, Rank1Stride) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(MakeArray<float>({1, 2, 5, 7}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(store, {2}, DownsampleMethod::kStride)); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<float>({1, 5}))); } TEST(DownsampleTest, Rank1MeanChunked) { ::nlohmann::json base_spec{{"driver", "n5"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dataType", "uint8"}, {"dimensions", {11}}, {"blockSize", {3}}, {"compression", {{"type", "raw"}}}}}}; auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open(base_spec, context, tensorstore::OpenMode::create) .result()); TENSORSTORE_ASSERT_OK(tensorstore::Write( MakeArray<uint8_t>({0, 2, 3, 9, 1, 5, 7, 3, 4, 0, 5}), base_store)); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Open({{"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2}}, {"downsample_method", "mean"}}, context) .result()); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<uint8_t>({1, 6, 3, 5, 2, 5}))); } TEST(DownsampleTest, Rank1MeanChunkedTranslated) { ::nlohmann::json base_spec{{"driver", "n5"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dataType", "uint8"}, {"dimensions", {11}}, {"blockSize", {3}}, {"compression", {{"type", "raw"}}}}}, {"transform", { {"input_inclusive_min", {1}}, {"input_exclusive_max", {12}}, {"output", { {{"input_dimension", 0}, {"offset", -1}}, }}, }}}; auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open(base_spec, context, tensorstore::OpenMode::create) .result()); TENSORSTORE_ASSERT_OK(tensorstore::Write( MakeArray<uint8_t>({0, 2, 3, 9, 1, 5, 7, 3, 4, 0, 5}), base_store)); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Open({{"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2}}, {"downsample_method", "mean"}}, context) .result()); EXPECT_THAT(ReadAsIndividualChunks(downsampled_store).result(), Optional(::testing::UnorderedElementsAre( Pair(MakeOffsetArray<uint8_t>({0}, {0, 2}), IdentityTransform(BoxView({0}, {2}))), Pair(MakeOffsetArray<uint8_t>({5}, {2}), IdentityTransform(BoxView({5}, {1}))), Pair(MakeOffsetArray<uint8_t>({2}, {5, 6, 4}), IdentityTransform(BoxView({2}, {3})))))); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<uint8_t>({0, 2, 5, 6, 4, 2}))); } TEST(DownsampleTest, Rank1MeanChunkedIndexArray) { ::nlohmann::json base_spec{{"driver", "n5"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dataType", "uint8"}, {"dimensions", {11}}, {"blockSize", {3}}, {"compression", {{"type", "raw"}}}}}}; auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open(base_spec, context, tensorstore::OpenMode::create) .result()); TENSORSTORE_ASSERT_OK(tensorstore::Write( MakeArray<uint8_t>({0, 2, 3, 9, 1, 5, 7, 3, 4, 0, 5}), base_store)); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Open({{"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2}}, {"downsample_method", "mean"}}, context) .result()); EXPECT_THAT(tensorstore::Read(downsampled_store | tensorstore::Dims(0).IndexArraySlice( MakeArray<Index>({0, 3, 2}))) .result(), Optional(MakeArray<uint8_t>({1, 5, 3}))); } TEST(DownsampleTest, JsonSpecArray) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open({{"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2}}, {"downsample_method", "mean"}}) .result()); EXPECT_THAT(tensorstore::Read(store).result(), Optional(MakeArray<float>({1.5, 3.5}))); } TEST(DownsampleTest, JsonSpecArrayRank0) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", 42}, }; TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open({{"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", ::nlohmann::json::array_t{}}, {"downsample_method", "mean"}}) .result()); EXPECT_THAT(tensorstore::Read(store).result(), Optional(tensorstore::MakeScalarArray<float>(42))); } TEST(DownsampleTest, JsonSpecErrorMissingBase) { EXPECT_THAT( tensorstore::Open({ {"driver", "downsample"}, {"downsample_factors", {2}}, {"downsample_method", "mean"}, }) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*\"base\".*")); } TEST(DownsampleTest, JsonSpecErrorMissingDownsampleFactors) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; EXPECT_THAT(tensorstore::Open({ {"driver", "downsample"}, {"base", base_spec}, {"downsample_method", "mean"}, }) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*\"downsample_factors\".*")); } TEST(DownsampleTest, JsonSpecErrorDownsampleFactorsInvalidRank) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; EXPECT_THAT(tensorstore::Open({ {"driver", "downsample"}, {"base", base_spec}, {"downsample_method", "mean"}, {"downsample_factors", {2, 3}}, }) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*\"downsample_factors\": .*rank.*")); } TEST(DownsampleTest, JsonSpecErrorDownsampleFactorsZero) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; EXPECT_THAT( tensorstore::Open({ {"driver", "downsample"}, {"base", base_spec}, {"downsample_method", "mean"}, {"downsample_factors", {0}}, }) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*\"downsample_factors\":.*Expected .*, but received: 0")); } TEST(DownsampleTest, JsonSpecErrorDownsampleFactorsNegative) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; EXPECT_THAT(tensorstore::Open({ {"driver", "downsample"}, {"base", base_spec}, {"downsample_method", "mean"}, {"downsample_factors", {-2}}, }) .result(), MatchesStatus( absl::StatusCode::kInvalidArgument, ".*\"downsample_factors\":.*Expected .*, but received: -2")); } TEST(DownsampleTest, JsonSpecErrorMissingDownsampleMethod) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; EXPECT_THAT(tensorstore::Open({ {"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2}}, }) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*\"downsample_method\".*")); } TEST(DownsampleTest, JsonSpecErrorInvalidDownsampleMethod) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; EXPECT_THAT(tensorstore::Open({ {"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2}}, {"downsample_method", 42}, }) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*\"downsample_method\".*42.*")); } TEST(DownsampleTest, ErrorOpenWriteOnly) { ::nlohmann::json base_spec{ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, }; for (auto mode : {ReadWriteMode::write, ReadWriteMode::read_write}) { SCOPED_TRACE(tensorstore::StrCat("mode=", mode)); EXPECT_THAT(tensorstore::Open( { {"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2}}, {"downsample_method", "mean"}, }, mode) .result(), MatchesStatus(absl::StatusCode::kInvalidArgument, ".*: only reading is supported")); } } TEST(DownsampleTest, AdapterErrorNegativeDownsampleFactor) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(MakeArray<float>({1, 2, 5, 7}))); EXPECT_THAT( tensorstore::Downsample(store, {-2}, DownsampleMethod::kMean), MatchesStatus(absl::StatusCode::kInvalidArgument, "Downsample factors \\{-2\\} are not all positive")); } TEST(DownsampleTest, AdapterErrorZeroDownsampleFactor) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(MakeArray<float>({1, 2, 5, 7}))); EXPECT_THAT(tensorstore::Downsample(store, {0}, DownsampleMethod::kMean), MatchesStatus(absl::StatusCode::kInvalidArgument, "Downsample factors \\{0\\} are not all positive")); } TEST(DownsampleTest, AdapterErrorDownsampleFactorsRankMismatch) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( TensorStore<float> store, tensorstore::FromArray(MakeArray<float>({1, 2, 5, 7}))); EXPECT_THAT( tensorstore::Downsample(store, {2, 2}, DownsampleMethod::kMean), MatchesStatus(absl::StatusCode::kInvalidArgument, "Number of downsample factors \\(2\\) does not match " "TensorStore rank \\(1\\)")); } TEST(DownsampleTest, AdapterErrorDataType) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::FromArray(MakeArray<std::string>({"a", "b", "c"}))); TENSORSTORE_EXPECT_OK( tensorstore::Downsample(store, {2}, DownsampleMethod::kStride)); EXPECT_THAT(tensorstore::Downsample(store, {2}, DownsampleMethod::kMean), MatchesStatus(absl::StatusCode::kInvalidArgument, "Downsample method \"mean\" does not support " "data type \"string\"")); } TEST(DownsampleTest, AdapterErrorWriteOnly) { tensorstore::TensorStore<float, 1> store; TENSORSTORE_ASSERT_OK_AND_ASSIGN( store, tensorstore::FromArray(MakeArray<float>({1, 2, 3}))); store = tensorstore::ModeCast<ReadWriteMode::write, tensorstore::unchecked>( std::move(store)); EXPECT_THAT(tensorstore::Downsample(store, {2}, DownsampleMethod::kMean), MatchesStatus(absl::StatusCode::kInvalidArgument, "Cannot downsample write-only TensorStore")); } TEST(DownsampleTest, ReadError) { auto mock_driver = MockDriver::Make(tensorstore::ReadWriteMode::dynamic, tensorstore::dtype_v<float>, 1); auto mock_store = mock_driver->Wrap(tensorstore::IdentityTransform<1>({10})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(mock_store, {2}, DownsampleMethod::kMean)); auto read_future = tensorstore::Read(downsampled_store); { auto read_req = mock_driver->read_requests.pop(); EXPECT_EQ(tensorstore::IdentityTransform<1>({10}), read_req.transform); tensorstore::execution::set_error( tensorstore::FlowSingleReceiver{std::move(read_req.receiver)}, absl::UnknownError("read error")); } EXPECT_THAT(read_future.result(), MatchesStatus(absl::StatusCode::kUnknown, "read error")); } TEST(DownsampleTest, CancelRead) { auto mock_driver = MockDriver::Make(tensorstore::ReadWriteMode::dynamic, tensorstore::dtype_v<float>, 1); auto mock_store = mock_driver->Wrap(tensorstore::IdentityTransform<1>({10})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(mock_store, {2}, DownsampleMethod::kMean)); auto read_future = tensorstore::Read(downsampled_store); auto canceled = std::make_shared<bool>(false); { auto read_req = mock_driver->read_requests.pop(); tensorstore::execution::set_starting(read_req.receiver, [canceled] { *canceled = true; }); read_future = {}; EXPECT_EQ(true, *canceled); tensorstore::execution::set_done(read_req.receiver); tensorstore::execution::set_stopping(read_req.receiver); } } TEST(DownsampleTest, IndependentChunkCompletesBufferedChunk) { auto mock_driver = MockDriver::Make(tensorstore::ReadWriteMode::dynamic, tensorstore::dtype_v<float>, 1); auto mock_store = mock_driver->Wrap(tensorstore::IdentityTransform<1>({4})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(mock_store, {2}, DownsampleMethod::kMean)); auto read_future = tensorstore::Read(downsampled_store); { auto read_req = mock_driver->read_requests.pop(); tensorstore::execution::set_starting(read_req.receiver, [] {}); tensorstore::execution::set_value( read_req.receiver, MakeArrayBackedReadChunk(MakeArray<float>({0, 1})), (tensorstore::IdentityTransform(1) | tensorstore::Dims(0).IndexArraySlice(MakeArray<Index>({0, 1}))) .value()); tensorstore::execution::set_value( read_req.receiver, MakeArrayBackedReadChunk(MakeOffsetArray<float>({2}, {2, 3})), tensorstore::IdentityTransform(BoxView<1>({2}, {2}))); tensorstore::execution::set_done(read_req.receiver); tensorstore::execution::set_stopping(read_req.receiver); } ASSERT_TRUE(read_future.ready()); EXPECT_THAT(read_future.result(), Optional(MakeArray<float>({0.5, 2.5}))); } TEST(DownsampleTest, EmptyChunk) { auto mock_driver = MockDriver::Make(tensorstore::ReadWriteMode::dynamic, tensorstore::dtype_v<float>, 1); auto mock_store = mock_driver->Wrap(tensorstore::IdentityTransform<1>({10})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(mock_store, {2}, DownsampleMethod::kMean)); auto read_future = tensorstore::Read(downsampled_store); { auto read_req = mock_driver->read_requests.pop(); EXPECT_EQ(tensorstore::IdentityTransform<1>({10}), read_req.transform); tensorstore::execution::set_error( tensorstore::FlowSingleReceiver{std::move(read_req.receiver)}, absl::UnknownError("read error")); } EXPECT_THAT(read_future.result(), MatchesStatus(absl::StatusCode::kUnknown, "read error")); } TEST(DownsampleTest, ReadChunkWithIndexTransform) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto store, tensorstore::FromArray(MakeArray<float>({ {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, }))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Downsample(store, {2, 3}, DownsampleMethod::kMean)); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<float>({ {4.5, 7}, {12, 14.5}, }))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto chunks, CollectReadChunks(downsampled_store).result()); ASSERT_THAT(chunks, ::testing::ElementsAre(Pair( ::testing::_, tensorstore::IdentityTransform<2>({2, 2})))); auto& entry = chunks[0]; { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto transform, entry.second | tensorstore::Dims(0).IndexArraySlice( MakeArray<Index>({0, 1, 1, 0}))); auto target_array = tensorstore::AllocateArray<float>({4, 2}); TENSORSTORE_ASSERT_OK(tensorstore::internal::CopyReadChunk( entry.first.impl, transform, tensorstore::TransformedArray(target_array))); EXPECT_EQ(MakeArray<float>({ {4.5, 7}, {12, 14.5}, {12, 14.5}, {4.5, 7}, }), target_array); } { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto transform, entry.second | tensorstore::Dims(0, 1).IndexArraySlice( MakeArray<Index>({0, 1, 1}), MakeArray<Index>({0, 0, 1}))); auto target_array = tensorstore::AllocateArray<float>({3}); TENSORSTORE_ASSERT_OK(tensorstore::internal::CopyReadChunk( entry.first.impl, transform, tensorstore::TransformedArray(target_array))); EXPECT_EQ(MakeArray<float>({4.5, 12, 14.666666666666666}), target_array); } } TEST(DownsampleTest, ConvertError) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Open({ {"driver", "downsample"}, {"base", { {"driver", "cast"}, {"base", { {"driver", "array"}, {"dtype", "json"}, {"array", {1, "abc", 2}}, }}, {"dtype", "uint8"}, }}, {"downsample_method", "mean"}, {"downsample_factors", {2}}, }) .result()); auto dest = tensorstore::MakeArray<uint8_t>({0, 0}); EXPECT_THAT( tensorstore::Read(downsampled_store, dest).result(), MatchesStatus( absl::StatusCode::kInvalidArgument, "Expected integer in the range \\[0, 255\\], but received: \"abc\"")); EXPECT_EQ(dest, MakeArray<uint8_t>({0, 0})); } TENSORSTORE_GLOBAL_INITIALIZER { tensorstore::internal::TestTensorStoreDriverSpecRoundtripOptions options; options.test_name = "downsample"; options.create_spec = { {"driver", "downsample"}, {"base", { {"driver", "array"}, {"dtype", "float32"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, }}, {"downsample_method", "mean"}, {"downsample_factors", {1, 2}}, }; options.full_spec = { {"driver", "downsample"}, {"base", { {"driver", "array"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, {"transform", {{"input_inclusive_min", {0, 0}}, {"input_exclusive_max", {2, 3}}}}, }}, {"dtype", "float32"}, {"downsample_method", "mean"}, {"downsample_factors", {1, 2}}, {"transform", {{"input_inclusive_min", {0, 0}}, {"input_exclusive_max", {2, 2}}}}, }; options.full_base_spec = { {"driver", "array"}, {"array", {{1, 2, 3}, {4, 5, 6}}}, {"dtype", "float32"}, {"transform", {{"input_inclusive_min", {0, 0}}, {"input_exclusive_max", {2, 3}}}}, }; options.minimal_spec = options.full_spec; options.check_not_found_before_create = false; options.check_not_found_before_commit = false; options.supported_transaction_modes = {}; tensorstore::internal::RegisterTensorStoreDriverSpecRoundtripTest( std::move(options)); } TEST(DownsampleTest, Spec) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto spec, Spec::FromJson({ {"driver", "array"}, {"dtype", "float32"}, {"array", {1, 2, 3, 4}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_spec, tensorstore::Downsample(spec, {2}, DownsampleMethod::kMean)); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_store, tensorstore::Open(downsampled_spec).result()); EXPECT_THAT(tensorstore::Read(downsampled_store).result(), Optional(MakeArray<float>({1.5, 3.5}))); EXPECT_THAT( downsampled_spec.ToJson(), Optional(MatchesJson(::nlohmann::json({ {"driver", "downsample"}, {"dtype", "float32"}, {"base", { {"driver", "array"}, {"array", {1, 2, 3, 4}}, {"transform", {{"input_inclusive_min", {0}}, {"input_exclusive_max", {4}}}}, }}, {"downsample_factors", {2}}, {"downsample_method", "mean"}, {"transform", {{"input_inclusive_min", {0}}, {"input_exclusive_max", {2}}}}, })))); } TEST(DownsampleTest, ChunkLayout) { ::nlohmann::json base_spec{ {"driver", "n5"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dataType", "uint8"}, {"dimensions", {100, 200}}, {"blockSize", {10, 21}}, {"compression", {{"type", "raw"}}}}}, }; auto context = Context::Default(); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open(base_spec, context, tensorstore::OpenMode::create) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Open({{"driver", "downsample"}, {"base", base_spec}, {"downsample_factors", {2, 3}}, {"downsample_method", "mean"}}, context) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto expected_layout, ChunkLayout::FromJson({ {"write_chunk", {{"shape", {5, 7}}}}, {"read_chunk", {{"shape", {5, 7}}}}, {"grid_origin", {0, 0}}, {"inner_order", {1, 0}}, })); EXPECT_THAT(store.chunk_layout(), ::testing::Optional(expected_layout)); } TEST(SpecSchemaTest, Basic) { TestSpecSchema( { {"driver", "downsample"}, {"downsample_method", "mean"}, {"downsample_factors", {1, 2}}, {"base", { {"driver", "array"}, {"array", {{1, 2, 3, 4}, {5, 6, 7, 8}}}, {"dtype", "float32"}, }}, {"schema", {{"dimension_units", {"4nm", "5nm"}}}}, }, { {"rank", 2}, {"dtype", "float32"}, {"domain", {{"shape", {2, 2}}}}, {"chunk_layout", {{"grid_origin", {0, 0}}, {"inner_order", {0, 1}}}}, {"dimension_units", {"4nm", "5nm"}}, }); } TEST(TensorStoreCreateCheckSchemaTest, Basic) { TestTensorStoreCreateCheckSchema( { {"driver", "downsample"}, {"downsample_method", "mean"}, {"downsample_factors", {1, 2}}, {"base", { {"driver", "array"}, {"array", {{1, 2, 3, 4}, {5, 6, 7, 8}}}, {"dtype", "float32"}, }}, {"schema", {{"dimension_units", {"4nm", "5nm"}}}}, }, { {"rank", 2}, {"dtype", "float32"}, {"domain", {{"shape", {2, 2}}}}, {"chunk_layout", {{"grid_origin", {0, 0}}, {"inner_order", {0, 1}}}}, {"dimension_units", {"4nm", "5nm"}}, }); } TEST(DownsampleTest, DomainSpecified) { TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto base_spec, tensorstore::Spec::FromJson({ {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, })); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto downsampled_spec, tensorstore::Downsample(base_spec, {2, 1}, DownsampleMethod::kMean)); TENSORSTORE_ASSERT_OK( downsampled_spec.Set(tensorstore::Schema::Shape({10, 10}))); EXPECT_THAT(downsampled_spec.ToJson(), ::testing::Optional(MatchesJson({ {"driver", "downsample"}, {"base", { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"schema", { {"domain", {{"inclusive_min", {{"-inf"}, 0}}, {"exclusive_max", {{"+inf"}, 10}}}}, }}, {"transform", { {"input_exclusive_max", {{"+inf"}, {10}}}, {"input_inclusive_min", {0, 0}}, }}, }}, {"downsample_factors", {2, 1}}, {"downsample_method", "mean"}, {"schema", { {"domain", { {"inclusive_min", {0, 0}}, {"exclusive_max", {10, 10}}, }}, }}, {"transform", {{"input_exclusive_max", {10, 10}}, {"input_inclusive_min", {0, 0}}}}, }))); } TEST(DownsampleTest, FillValueNotSpecified) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open( { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dtype", {{"x", "<u4", {4, 3}}}}}}, }, tensorstore::OpenMode::create, tensorstore::Schema::Shape({100, 4, 3})) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Downsample(base_store, {1, 2, 1}, tensorstore::DownsampleMethod::kMean)); TENSORSTORE_ASSERT_OK_AND_ASSIGN(auto fill_value, store.fill_value()); EXPECT_FALSE(fill_value.valid()); } TEST(DownsampleTest, FillValueSpecified) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::Open( { {"driver", "zarr"}, {"kvstore", {{"driver", "memory"}}}, {"metadata", {{"dtype", {{"x", "<u4", {4, 3}}}}}}, }, tensorstore::OpenMode::create, tensorstore::Schema::Shape({100, 4, 3}), tensorstore::Schema::FillValue(tensorstore::MakeArray<uint32_t>( {{1, 2, 3}, {40, 50, 60}, {7, 8, 9}, {100, 110, 120}}))) .result()); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Downsample(base_store, {1, 2, 1}, tensorstore::DownsampleMethod::kMean)); EXPECT_THAT(store.fill_value(), ::testing::Optional(tensorstore::MakeArray<uint32_t>( {{20, 26, 32}, {54, 59, 64}}))); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto transformed, store | tensorstore::Dims(2).SizedInterval(1, 2)); EXPECT_THAT(transformed.fill_value(), ::testing::Optional( tensorstore::MakeArray<uint32_t>({{26, 32}, {59, 64}}))); } TEST(DownsampleTest, DimensionUnits) { TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto base_store, tensorstore::FromArray( tensorstore::MakeArray<int>({{1, 2, 3}, {4, 5, 6}}), tensorstore::DimensionUnitsVector{"4nm", "5nm"})); TENSORSTORE_ASSERT_OK_AND_ASSIGN( auto store, tensorstore::Downsample(base_store, {1, 2}, tensorstore::DownsampleMethod::kMean)); EXPECT_THAT(store.dimension_units(), ::testing::Optional(::testing::ElementsAre( tensorstore::Unit("4nm"), tensorstore::Unit("10nm")))); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/driver/downsample/downsample.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/driver/downsample/downsample_test.cc
4f887a6430414cd6088e1743555015b10f116d50
0f10e362-7fd0-45fb-9e53-3b3d601049b6
cpp
google/tensorstore
array
tensorstore/internal/json/array.cc
tensorstore/internal/json_binding/array_test.cc
#include "tensorstore/internal/json/array.h" #include <stddef.h> #include <algorithm> #include <cassert> #include <utility> #include <vector> #include "absl/functional/function_ref.h" #include "absl/status/status.h" #include <nlohmann/json.hpp> #include "tensorstore/array.h" #include "tensorstore/contiguous_layout.h" #include "tensorstore/data_type.h" #include "tensorstore/data_type_conversion.h" #include "tensorstore/index.h" #include "tensorstore/internal/element_copy_function.h" #include "tensorstore/internal/elementwise_function.h" #include "tensorstore/rank.h" #include "tensorstore/strided_layout.h" #include "tensorstore/util/byte_strided_pointer.h" #include "tensorstore/util/iterate.h" #include "tensorstore/util/result.h" #include "tensorstore/util/span.h" #include "tensorstore/util/status.h" #include "tensorstore/util/str_cat.h" namespace tensorstore { namespace internal_json { ::nlohmann::json JsonEncodeNestedArrayImpl( ArrayView<const void, dynamic_rank, offset_origin> array, absl::FunctionRef<::nlohmann::json(const void*)> encode_element) { if (array.rank() == 0) { assert(array.data()); return encode_element(array.data()); } using array_t = ::nlohmann::json::array_t; array_t* path[kMaxRank]; DimensionIndex level = 0; array_t j_root; j_root.reserve(array.shape()[0]); path[0] = &j_root; if (array.shape()[0] == 0) { return j_root; } ByteStridedPointer<const void> pointer = array.byte_strided_origin_pointer(); while (true) { array_t* j_parent = path[level]; if (level == array.rank() - 1) { assert(pointer.get()); j_parent->push_back(encode_element(pointer.get())); } else { const Index size = array.shape()[level + 1]; array_t next_array; next_array.reserve(size); j_parent->emplace_back(std::move(next_array)); j_parent = j_parent->back().get_ptr<array_t*>(); if (size != 0) { path[++level] = j_parent; continue; } } while (true) { array_t* j_array = path[level]; const Index i = j_array->size(); const Index size = array.shape()[level]; const Index byte_stride = array.byte_strides()[level]; pointer += byte_stride; if (i != size) break; pointer -= i * byte_stride; if (level-- == 0) { return j_root; } } } } Result<SharedArray<void>> JsonParseNestedArrayImpl( const ::nlohmann::json& j_root, DataType dtype, absl::FunctionRef<absl::Status(const ::nlohmann::json& v, void* out)> decode_element) { assert(dtype.valid()); using array_t = ::nlohmann::json::array_t; SharedArray<void> array; ByteStridedPointer<void> pointer; const Index byte_stride = dtype->size; Index shape_or_position[kMaxRank]; const array_t* path[kMaxRank]; DimensionIndex nesting_level = 0; const ::nlohmann::json* j = &j_root; const auto allocate_array = [&] { array = AllocateArray(tensorstore::span(&shape_or_position[0], nesting_level), c_order, default_init, dtype); pointer = array.byte_strided_origin_pointer(); std::fill_n(&shape_or_position[0], nesting_level, static_cast<Index>(0)); }; while (true) { const array_t* j_array = j->get_ptr<const ::nlohmann::json::array_t*>(); if (!j_array) { if (!array.data()) allocate_array(); if (nesting_level != array.rank()) { return absl::InvalidArgumentError(tensorstore::StrCat( "Expected rank-", array.rank(), " array, but found non-array element ", j->dump(), " at position ", span(&shape_or_position[0], nesting_level), ".")); } TENSORSTORE_RETURN_IF_ERROR( decode_element(*j, pointer.get()), MaybeAnnotateStatus( _, tensorstore::StrCat("Error parsing array element at position ", span(&shape_or_position[0], nesting_level)))); pointer += byte_stride; } else { if (nesting_level == kMaxRank) { return absl::InvalidArgumentError(tensorstore::StrCat( "Nesting level exceeds maximum rank of ", kMaxRank)); } path[nesting_level++] = j_array; const Index size = j_array->size(); if (!array.data()) { shape_or_position[nesting_level - 1] = size; if (size == 0) { allocate_array(); return array; } } else if (nesting_level > static_cast<size_t>(array.rank())) { return absl::InvalidArgumentError(tensorstore::StrCat( "Expected rank-", array.rank(), " array, but found array element ", j->dump(), " at position ", span(&shape_or_position[0], nesting_level - 1), ".")); } else if (array.shape()[nesting_level - 1] != size) { return absl::InvalidArgumentError(tensorstore::StrCat( "Expected array of shape ", array.shape(), ", but found array element ", j->dump(), " of length ", size, " at position ", span(&shape_or_position[0], nesting_level - 1), ".")); } j = &(*j_array)[0]; continue; } while (true) { if (nesting_level == 0) { return array; } const array_t* j_array = path[nesting_level - 1]; const Index size = j_array->size(); const Index i = ++shape_or_position[nesting_level - 1]; if (i != size) { j = &(*j_array)[i]; break; } shape_or_position[nesting_level - 1] = 0; --nesting_level; } } } Result<::nlohmann::json> JsonEncodeNestedArray(ArrayView<const void> array) { auto convert = internal::GetDataTypeConverter( array.dtype(), dtype_v<::tensorstore::dtypes::json_t>); if (!(convert.flags & DataTypeConversionFlags::kSupported)) { return absl::InvalidArgumentError(tensorstore::StrCat( "Conversion from ", array.dtype(), " to JSON is not implemented")); } bool error = false; absl::Status status; ::nlohmann::json j = JsonEncodeNestedArrayImpl( array, [&](const void* ptr) -> ::nlohmann::json { if ((convert.flags & DataTypeConversionFlags::kCanReinterpretCast) == DataTypeConversionFlags::kCanReinterpretCast) { return *reinterpret_cast<const ::tensorstore::dtypes::json_t*>(ptr); } ::nlohmann::json value; if ((*convert.closure .function)[internal::IterationBufferKind::kContiguous]( convert.closure.context, {1, 1}, internal::IterationBufferPointer(const_cast<void*>(ptr), Index(0), Index(0)), internal::IterationBufferPointer(&value, Index(0), Index(0)), &status) != 1) { error = true; return nullptr; } return value; }); if (error) return internal::GetElementCopyErrorStatus(std::move(status)); return j; } Result<SharedArray<void>> JsonParseNestedArray(const ::nlohmann::json& j, DataType dtype, DimensionIndex rank_constraint) { auto convert = internal::GetDataTypeConverter( dtype_v<::tensorstore::dtypes::json_t>, dtype); if (!(convert.flags & DataTypeConversionFlags::kSupported)) { return absl::InvalidArgumentError(tensorstore::StrCat( "Conversion from JSON to ", dtype, " is not implemented")); } TENSORSTORE_ASSIGN_OR_RETURN( auto array, JsonParseNestedArrayImpl( j, dtype, [&](const ::nlohmann::json& v, void* out) -> absl::Status { if ((convert.flags & DataTypeConversionFlags::kCanReinterpretCast) == DataTypeConversionFlags::kCanReinterpretCast) { *reinterpret_cast<::tensorstore::dtypes::json_t*>(out) = v; return absl::OkStatus(); } else { absl::Status status; if ((*convert.closure .function)[internal::IterationBufferKind::kContiguous]( convert.closure.context, {1, 1}, internal::IterationBufferPointer( const_cast<::nlohmann::json*>(&v), Index(0), Index(0)), internal::IterationBufferPointer(out, Index(0), Index(0)), &status) != 1) { return internal::GetElementCopyErrorStatus(std::move(status)); } return absl::OkStatus(); } })); if (rank_constraint != dynamic_rank && array.rank() != rank_constraint) { return absl::InvalidArgumentError(tensorstore::StrCat( "Array rank (", array.rank(), ") does not match expected rank (", rank_constraint, ")")); } return array; } } }
#include "tensorstore/internal/json_binding/array.h" #include <memory> #include <utility> #include <gtest/gtest.h> #include <nlohmann/json_fwd.hpp> #include "tensorstore/array.h" #include "tensorstore/data_type.h" #include "tensorstore/internal/json/json.h" #include "tensorstore/internal/json_binding/gtest.h" #include "tensorstore/internal/json_gtest.h" #include "tensorstore/json_serialization_options_base.h" using ::nlohmann::json; using ::tensorstore::dtype_v; namespace jb = tensorstore::internal_json_binding; namespace { TEST(JsonParseNestedArray, NestedArrayBinder) { tensorstore::TestJsonBinderRoundTrip<tensorstore::SharedArray<void>>( { {tensorstore::MakeArray<std::int64_t>({{1, 2, 3}, {4, 5, 6}}), ::nlohmann::json{{1, 2, 3}, {4, 5, 6}}}, }, jb::NestedVoidArray(tensorstore::dtype_v<std::int64_t>)); tensorstore::TestJsonBinderRoundTrip<tensorstore::SharedArray<std::int64_t>>( { {tensorstore::MakeArray<std::int64_t>({{1, 2, 3}, {4, 5, 6}}), ::nlohmann::json{{1, 2, 3}, {4, 5, 6}}}, }, jb::NestedArray()); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/internal/json/array.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/internal/json_binding/array_test.cc
4f887a6430414cd6088e1743555015b10f116d50
080feecb-ebad-4a7e-98c1-4692f8c306fe
cpp
google/tensorstore
progress
tensorstore/progress.cc
tensorstore/progress_test.cc
#include "tensorstore/progress.h" #include <ostream> namespace tensorstore { bool operator==(const ReadProgress& a, const ReadProgress& b) { return a.total_elements == b.total_elements && a.copied_elements == b.copied_elements; } bool operator!=(const ReadProgress& a, const ReadProgress& b) { return !(a == b); } std::ostream& operator<<(std::ostream& os, const ReadProgress& a) { return os << "{ total_elements=" << a.total_elements << ", copied_elements=" << a.copied_elements << " }"; } bool operator==(const WriteProgress& a, const WriteProgress& b) { return a.total_elements == b.total_elements && a.copied_elements == b.copied_elements && a.committed_elements == b.committed_elements; } bool operator!=(const WriteProgress& a, const WriteProgress& b) { return !(a == b); } std::ostream& operator<<(std::ostream& os, const WriteProgress& a) { return os << "{ total_elements=" << a.total_elements << ", copied_elements=" << a.copied_elements << ", committed_elements=" << a.committed_elements << " }"; } bool operator==(const CopyProgress& a, const CopyProgress& b) { return a.total_elements == b.total_elements && a.read_elements == b.read_elements && a.copied_elements == b.copied_elements && a.committed_elements == b.committed_elements; } bool operator!=(const CopyProgress& a, const CopyProgress& b) { return !(a == b); } std::ostream& operator<<(std::ostream& os, const CopyProgress& a) { return os << "{ total_elements=" << a.total_elements << ", read_elements=" << a.read_elements << ", copied_elements=" << a.copied_elements << ", committed_elements=" << a.committed_elements << " }"; } }
#include "tensorstore/progress.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorstore/util/str_cat.h" namespace { using ::tensorstore::CopyProgress; using ::tensorstore::ReadProgress; using ::tensorstore::WriteProgress; TEST(ReadProgressTest, Comparison) { ReadProgress a{1, 1}; ReadProgress b{2, 2}; ReadProgress c{2, 1}; EXPECT_EQ(a, a); EXPECT_EQ(b, b); EXPECT_EQ(c, c); EXPECT_NE(a, b); EXPECT_NE(a, c); EXPECT_NE(b, c); } TEST(ReadProgressTest, Ostream) { EXPECT_EQ("{ total_elements=2, copied_elements=1 }", tensorstore::StrCat(ReadProgress{2, 1})); } TEST(WriteProgressTest, Comparison) { WriteProgress a{1, 1, 1}; WriteProgress b{2, 2, 2}; WriteProgress c{2, 1, 1}; WriteProgress d{2, 1, 2}; EXPECT_EQ(a, a); EXPECT_EQ(b, b); EXPECT_EQ(c, c); EXPECT_EQ(d, d); EXPECT_NE(a, b); EXPECT_NE(a, c); EXPECT_NE(a, d); EXPECT_NE(b, d); EXPECT_NE(b, c); EXPECT_NE(c, d); } TEST(WriteProgressTest, Ostream) { EXPECT_EQ("{ total_elements=3, copied_elements=2, committed_elements=1 }", tensorstore::StrCat(WriteProgress{3, 2, 1})); } TEST(CopyProgressTest, Comparison) { CopyProgress a{1, 1, 1, 1}; CopyProgress b{2, 1, 1, 1}; CopyProgress c{1, 2, 1, 1}; CopyProgress d{1, 1, 2, 1}; CopyProgress e{1, 1, 1, 2}; EXPECT_EQ(a, a); EXPECT_EQ(b, b); EXPECT_EQ(c, c); EXPECT_EQ(d, d); EXPECT_EQ(e, e); EXPECT_NE(a, b); EXPECT_NE(a, c); EXPECT_NE(a, d); EXPECT_NE(a, e); } TEST(CopyProgressTest, Ostream) { EXPECT_EQ( "{ total_elements=4, read_elements=3, copied_elements=2, " "committed_elements=1 }", tensorstore::StrCat(CopyProgress{4, 3, 2, 1})); } }
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/progress.cc
https://github.com/google/tensorstore/blob/4f887a6430414cd6088e1743555015b10f116d50/tensorstore/progress_test.cc
4f887a6430414cd6088e1743555015b10f116d50