Commit fba8a316 by Abseil Team Committed by Andy Getz

Export of internal Abseil changes

--
2dd5008c7b4176859e320c7c337078adb173b662 by Tom Manshreck <shreck@google.com>:

Internal change

PiperOrigin-RevId: 304022549

--
6442abd78697b03cfe698b0d0dac7f1eb4b5cb38 by Andy Getzendanner <durandal@google.com>:

Internal change

PiperOrigin-RevId: 303890410

--
eb8b37b468b0f23da09d3de714272928ef61f942 by Gennadiy Rozental <rogeeff@google.com>:

Roll changes forward with ChunkIterator templatized.

This should facilitate usage of "small" chunk iterator for a regular usage and proper "big" iterator internally in Cord implementation. This way Cord users are not exposed to stack size overhead if they have a lot of chunk iterators or recursive implementation which relies on chunk iterators.

PiperOrigin-RevId: 303877118

--
9623c569e7c55b45254e95f2d14c5badf9c901aa by Gennadiy Rozental <rogeeff@google.com>:

Switch Flags implementation of fast type id to use absl/base/internal/fast_type_id.h

PiperOrigin-RevId: 303861019

--
e2931e8d53c86d0816da6bbc8ba58cf5a3a443bb by Matthew Brown <matthewbr@google.com>:

Internal Change

PiperOrigin-RevId: 303832407

--
b549ed6e441e920b8ad6f02a80b9fd543820ef86 by Tom Manshreck <shreck@google.com>:

Update Cord header file comments to Abseil standards

PiperOrigin-RevId: 303823232

--
fc633d4f31a2d058f2b6a7029fc7c9820cd71c92 by Evan Brown <ezb@google.com>:

Remove top-level const from K/V in map_slot_type::mutable_value and map_slot_type::key.

This allows us to move between `map_slot_type::mutable_value`s internally even when the key_type and/or mapped_type specified by the user are const.

PiperOrigin-RevId: 303811694

--
909b3ce7cb3583ee9c374d36ff5f82bba02a1b64 by Derek Mauro <dmauro@google.com>:

Add hardening assertions to the preconditions of absl::Cord

PiperOrigin-RevId: 303419537

--
9d32f79eabd54e6cb17bcc28b53e9bcfeb3cf6f4 by Greg Falcon <gfalcon@google.com>:

Don't use MSVC-specific bit manipulations when using Clang on Windows.

This fixes a compiler warning.  Note that we do not have continuous testing for this configuration; this CL is best-effort support.

PiperOrigin-RevId: 303322582

--
f6e0a35a2b9081d2a9eef73789b7bc1b5e46e5ad by Gennadiy Rozental <rogeeff@google.com>:

Introduce standlone FastTypeId utility to represent compile time unique type id.

PiperOrigin-RevId: 303180545

--
99120e9fbdb5b2d327139ab8f617533d7bc3345b by Abseil Team <absl-team@google.com>:

Changed absl's import of std::string_view to
using string_view = std::string_view.
This should help tools (e.g. include-what-you-use) discover where absl::string_view is defined.

PiperOrigin-RevId: 303169095
GitOrigin-RevId: 2dd5008c7b4176859e320c7c337078adb173b662
Change-Id: I1e18ae08e23686ac963e7ea5e5bd499e18d51048
parent 79e0dc11
......@@ -19,6 +19,7 @@ set(ABSL_INTERNAL_DLL_FILES
"base/internal/errno_saver.h"
"base/internal/exponential_biased.cc"
"base/internal/exponential_biased.h"
"base/internal/fast_type_id.h"
"base/internal/hide_ptr.h"
"base/internal/identity.h"
"base/internal/invoke.h"
......@@ -130,7 +131,6 @@ set(ABSL_INTERNAL_DLL_FILES
"random/bit_gen_ref.h"
"random/discrete_distribution.cc"
"random/discrete_distribution.h"
"random/distribution_format_traits.h"
"random/distributions.h"
"random/exponential_distribution.h"
"random/gaussian_distribution.cc"
......
......@@ -750,3 +750,28 @@ cc_binary(
"@com_github_google_benchmark//:benchmark_main",
],
)
cc_library(
name = "fast_type_id",
hdrs = ["internal/fast_type_id.h"],
copts = ABSL_DEFAULT_COPTS,
linkopts = ABSL_DEFAULT_LINKOPTS,
visibility = [
"//absl:__subpackages__",
],
deps = [
":config",
],
)
cc_test(
name = "fast_type_id_test",
size = "small",
srcs = ["internal/fast_type_id_test.cc"],
copts = ABSL_TEST_COPTS,
linkopts = ABSL_DEFAULT_LINKOPTS,
deps = [
":fast_type_id",
"@com_google_googletest//:gtest_main",
],
)
......@@ -674,3 +674,28 @@ absl_cc_test(
gmock
gtest_main
)
absl_cc_library(
NAME
fast_type_id
HDRS
"internal/fast_type_id.h"
COPTS
${ABSL_DEFAULT_COPTS}
LINKOPTS
${ABSL_DEFAULT_LINKOPTS}
DEPS
absl::config
)
absl_cc_test(
NAME
fast_type_id_test
SRCS
"internal/fast_type_id_test.cc"
COPTS
${ABSL_TEST_COPTS}
DEPS
absl::fast_type_id
gtest_main
)
......@@ -24,7 +24,7 @@
// Clang on Windows has __builtin_clzll; otherwise we need to use the
// windows intrinsic functions.
#if defined(_MSC_VER)
#if defined(_MSC_VER) && !defined(__clang__)
#include <intrin.h>
#if defined(_M_X64)
#pragma intrinsic(_BitScanReverse64)
......@@ -36,7 +36,7 @@
#include "absl/base/attributes.h"
#if defined(_MSC_VER)
#if defined(_MSC_VER) && !defined(__clang__)
// We can achieve something similar to attribute((always_inline)) with MSVC by
// using the __forceinline keyword, however this is not perfect. MSVC is
// much less aggressive about inlining, and even with the __forceinline keyword.
......@@ -73,14 +73,14 @@ ABSL_BASE_INTERNAL_FORCEINLINE int CountLeadingZeros64Slow(uint64_t n) {
}
ABSL_BASE_INTERNAL_FORCEINLINE int CountLeadingZeros64(uint64_t n) {
#if defined(_MSC_VER) && defined(_M_X64)
#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_X64)
// MSVC does not have __buitin_clzll. Use _BitScanReverse64.
unsigned long result = 0; // NOLINT(runtime/int)
if (_BitScanReverse64(&result, n)) {
return 63 - result;
}
return 64;
#elif defined(_MSC_VER)
#elif defined(_MSC_VER) && !defined(__clang__)
// MSVC does not have __buitin_clzll. Compose two calls to _BitScanReverse
unsigned long result = 0; // NOLINT(runtime/int)
if ((n >> 32) && _BitScanReverse(&result, n >> 32)) {
......@@ -90,7 +90,7 @@ ABSL_BASE_INTERNAL_FORCEINLINE int CountLeadingZeros64(uint64_t n) {
return 63 - result;
}
return 64;
#elif defined(__GNUC__)
#elif defined(__GNUC__) || defined(__clang__)
// Use __builtin_clzll, which uses the following instructions:
// x86: bsr
// ARM64: clz
......@@ -126,13 +126,13 @@ ABSL_BASE_INTERNAL_FORCEINLINE int CountLeadingZeros32Slow(uint64_t n) {
}
ABSL_BASE_INTERNAL_FORCEINLINE int CountLeadingZeros32(uint32_t n) {
#if defined(_MSC_VER)
#if defined(_MSC_VER) && !defined(__clang__)
unsigned long result = 0; // NOLINT(runtime/int)
if (_BitScanReverse(&result, n)) {
return 31 - result;
}
return 32;
#elif defined(__GNUC__)
#elif defined(__GNUC__) || defined(__clang__)
// Use __builtin_clz, which uses the following instructions:
// x86: bsr
// ARM64: clz
......@@ -163,11 +163,11 @@ ABSL_BASE_INTERNAL_FORCEINLINE int CountTrailingZerosNonZero64Slow(uint64_t n) {
}
ABSL_BASE_INTERNAL_FORCEINLINE int CountTrailingZerosNonZero64(uint64_t n) {
#if defined(_MSC_VER) && defined(_M_X64)
#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_X64)
unsigned long result = 0; // NOLINT(runtime/int)
_BitScanForward64(&result, n);
return result;
#elif defined(_MSC_VER)
#elif defined(_MSC_VER) && !defined(__clang__)
unsigned long result = 0; // NOLINT(runtime/int)
if (static_cast<uint32_t>(n) == 0) {
_BitScanForward(&result, n >> 32);
......@@ -175,7 +175,7 @@ ABSL_BASE_INTERNAL_FORCEINLINE int CountTrailingZerosNonZero64(uint64_t n) {
}
_BitScanForward(&result, n);
return result;
#elif defined(__GNUC__)
#elif defined(__GNUC__) || defined(__clang__)
static_assert(sizeof(unsigned long long) == sizeof(n), // NOLINT(runtime/int)
"__builtin_ctzll does not take 64-bit arg");
return __builtin_ctzll(n);
......@@ -196,11 +196,11 @@ ABSL_BASE_INTERNAL_FORCEINLINE int CountTrailingZerosNonZero32Slow(uint32_t n) {
}
ABSL_BASE_INTERNAL_FORCEINLINE int CountTrailingZerosNonZero32(uint32_t n) {
#if defined(_MSC_VER)
#if defined(_MSC_VER) && !defined(__clang__)
unsigned long result = 0; // NOLINT(runtime/int)
_BitScanForward(&result, n);
return result;
#elif defined(__GNUC__)
#elif defined(__GNUC__) || defined(__clang__)
static_assert(sizeof(int) == sizeof(n),
"__builtin_ctz does not take 32-bit arg");
return __builtin_ctz(n);
......
//
// Copyright 2020 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#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;
};
template <typename Type>
constexpr char FastTypeTag<Type>::dummy_var;
// FastTypeId<Type>() evaluates at compile/link-time to a unique pointer for the
// passed-in type. These are meant to be good match for keys into maps or
// straight up comparisons.
using FastTypeIdType = const void*;
template <typename Type>
constexpr inline FastTypeIdType FastTypeId() {
return &FastTypeTag<Type>::dummy_var;
}
} // namespace base_internal
ABSL_NAMESPACE_END
} // namespace absl
#endif // ABSL_BASE_INTERNAL_FAST_TYPE_ID_H_
// Copyright 2020 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/base/internal/fast_type_id.h"
#include <cstdint>
#include <map>
#include <vector>
#include "gtest/gtest.h"
namespace {
namespace bi = absl::base_internal;
// NOLINTNEXTLINE
#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>());
}
} // namespace
......@@ -366,6 +366,7 @@ cc_library(
linkopts = ABSL_DEFAULT_LINKOPTS,
deps = [
"//absl/memory",
"//absl/meta:type_traits",
"//absl/utility",
],
)
......@@ -378,6 +379,7 @@ cc_test(
tags = NOTEST_TAGS_NONMOBILE,
deps = [
":container_memory",
":test_instance_tracker",
"//absl/strings",
"@com_google_googletest//:gtest_main",
],
......
......@@ -421,6 +421,7 @@ absl_cc_library(
${ABSL_DEFAULT_COPTS}
DEPS
absl::memory
absl::type_traits
absl::utility
PUBLIC
)
......@@ -435,6 +436,7 @@ absl_cc_test(
DEPS
absl::container_memory
absl::strings
absl::test_instance_tracker
gmock_main
)
......
......@@ -31,6 +31,7 @@
#include <utility>
#include "absl/memory/memory.h"
#include "absl/meta/type_traits.h"
#include "absl/utility/utility.h"
namespace absl {
......@@ -319,11 +320,12 @@ union map_slot_type {
map_slot_type() {}
~map_slot_type() = delete;
using value_type = std::pair<const K, V>;
using mutable_value_type = std::pair<K, V>;
using mutable_value_type =
std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
value_type value;
mutable_value_type mutable_value;
K key;
absl::remove_const_t<K> key;
};
template <class K, class V>
......
......@@ -22,6 +22,7 @@
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/internal/test_instance_tracker.h"
#include "absl/strings/string_view.h"
namespace absl {
......@@ -29,9 +30,11 @@ ABSL_NAMESPACE_BEGIN
namespace container_internal {
namespace {
using ::testing::Gt;
using ::absl::test_internal::CopyableMovableInstance;
using ::absl::test_internal::InstanceTracker;
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::Gt;
using ::testing::Pair;
TEST(Memory, AlignmentLargerThanBase) {
......@@ -222,6 +225,31 @@ TEST(DecomposePair, NotDecomposable) {
std::make_tuple(0.5)));
}
TEST(MapSlotPolicy, ConstKeyAndValue) {
using slot_policy = map_slot_policy<const CopyableMovableInstance,
const CopyableMovableInstance>;
using slot_type = typename slot_policy::slot_type;
union Slots {
Slots() {}
~Slots() {}
slot_type slots[100];
} slots;
std::allocator<
std::pair<const CopyableMovableInstance, const CopyableMovableInstance>>
alloc;
InstanceTracker tracker;
slot_policy::construct(&alloc, &slots.slots[0], CopyableMovableInstance(1),
CopyableMovableInstance(1));
for (int i = 0; i < 99; ++i) {
slot_policy::transfer(&alloc, &slots.slots[i + 1], &slots.slots[i]);
}
slot_policy::destroy(&alloc, &slots.slots[99]);
EXPECT_EQ(tracker.copies(), 0);
}
} // namespace
} // namespace container_internal
ABSL_NAMESPACE_END
......
......@@ -147,6 +147,7 @@ cc_library(
":marshalling",
"//absl/base:config",
"//absl/base:core_headers",
"//absl/base:fast_type_id",
"//absl/strings",
"//absl/types:optional",
],
......
......@@ -128,6 +128,7 @@ absl_cc_library(
${ABSL_DEFAULT_LINKOPTS}
DEPS
absl::config
absl::fast_type_id
absl::flags_config
absl::flags_marshalling
absl::core_headers
......
......@@ -24,6 +24,7 @@
#include <typeinfo>
#include "absl/base/config.h"
#include "absl/base/internal/fast_type_id.h"
#include "absl/base/macros.h"
#include "absl/flags/config.h"
#include "absl/flags/marshalling.h"
......@@ -34,23 +35,12 @@ namespace absl {
ABSL_NAMESPACE_BEGIN
namespace flags_internal {
// An alias for flag static type id. Values of type identify the flag value type
// simialarly to typeid(T), but without relying on RTTI being available. In most
// An alias for flag fast type id. This value identifies the flag value type
// simialarly to typeid(T), without relying on RTTI being available. In most
// cases this id is enough to uniquely identify the flag's value type. In a few
// cases we'll have to resort to using actual RTTI implementation if it is
// available.
using FlagStaticTypeId = void* (*)();
// Address of this function template is used in current implementation as a flag
// static type id.
template <typename T>
void* FlagStaticTypeIdGen() {
#if defined(ABSL_FLAGS_INTERNAL_HAS_RTTI)
return const_cast<std::type_info*>(&typeid(T));
#else
return nullptr;
#endif
}
using FlagFastTypeId = base_internal::FastTypeIdType;
// Options that control SetCommandLineOptionWithMode.
enum FlagSettingMode {
......@@ -97,7 +87,7 @@ class CommandLineFlag {
// Return true iff flag has type T.
template <typename T>
inline bool IsOfType() const {
return TypeId() == &flags_internal::FlagStaticTypeIdGen<T>;
return TypeId() == base_internal::FastTypeId<T>();
}
// Attempts to retrieve the flag value. Returns value on success,
......@@ -150,7 +140,7 @@ class CommandLineFlag {
// Returns true iff this is a handle to an Abseil Flag.
virtual bool IsAbseilFlag() const;
// Returns id of the flag's value type.
virtual FlagStaticTypeId TypeId() const = 0;
virtual FlagFastTypeId TypeId() const = 0;
virtual bool IsModified() const = 0;
virtual bool IsSpecifiedOnCommandLine() const = 0;
virtual std::string DefaultValue() const = 0;
......
......@@ -48,9 +48,9 @@ const char kStrippedFlagHelp[] = "\001\002\003\004 (unknown) \004\003\002\001";
namespace {
// Currently we only validate flag values for user-defined flag types.
bool ShouldValidateFlagValue(FlagStaticTypeId flag_type_id) {
bool ShouldValidateFlagValue(FlagFastTypeId flag_type_id) {
#define DONT_VALIDATE(T) \
if (flag_type_id == &FlagStaticTypeIdGen<T>) return false;
if (flag_type_id == base_internal::FastTypeId<T>()) return false;
ABSL_FLAGS_INTERNAL_BUILTIN_TYPES(DONT_VALIDATE)
#undef DONT_VALIDATE
......@@ -161,24 +161,24 @@ absl::Mutex* FlagImpl::DataGuard() const {
return reinterpret_cast<absl::Mutex*>(&data_guard_);
}
void FlagImpl::AssertValidType(FlagStaticTypeId type_id) const {
FlagStaticTypeId this_type_id = flags_internal::StaticTypeId(op_);
void FlagImpl::AssertValidType(FlagFastTypeId rhs_type_id,
const std::type_info* (*gen_rtti)()) const {
FlagFastTypeId lhs_type_id = flags_internal::FastTypeId(op_);
// `type_id` is the type id corresponding to the declaration visibile at the
// call site. `this_type_id` is the type id corresponding to the type stored
// during flag definition. They must match for this operation to be
// well-defined.
if (ABSL_PREDICT_TRUE(type_id == this_type_id)) return;
// `rhs_type_id` is the fast type id corresponding to the declaration
// visibile at the call site. `lhs_type_id` is the fast type id
// corresponding to the type specified in flag definition. They must match
// for this operation to be well-defined.
if (ABSL_PREDICT_TRUE(lhs_type_id == rhs_type_id)) return;
void* lhs_runtime_type_id = type_id();
void* rhs_runtime_type_id = this_type_id();
const std::type_info* lhs_runtime_type_id =
flags_internal::RuntimeTypeId(op_);
const std::type_info* rhs_runtime_type_id = (*gen_rtti)();
if (lhs_runtime_type_id == rhs_runtime_type_id) return;
#if defined(ABSL_FLAGS_INTERNAL_HAS_RTTI)
if (*reinterpret_cast<std::type_info*>(lhs_runtime_type_id) ==
*reinterpret_cast<std::type_info*>(rhs_runtime_type_id))
return;
if (*lhs_runtime_type_id == *rhs_runtime_type_id) return;
#endif
ABSL_INTERNAL_LOG(
......@@ -233,8 +233,8 @@ std::string FlagImpl::Help() const {
: help_.gen_func();
}
FlagStaticTypeId FlagImpl::TypeId() const {
return flags_internal::StaticTypeId(op_);
FlagFastTypeId FlagImpl::TypeId() const {
return flags_internal::FastTypeId(op_);
}
bool FlagImpl::IsModified() const {
......@@ -429,7 +429,7 @@ void FlagImpl::Read(void* dst) const {
void FlagImpl::Write(const void* src) {
absl::MutexLock l(DataGuard());
if (ShouldValidateFlagValue(flags_internal::StaticTypeId(op_))) {
if (ShouldValidateFlagValue(flags_internal::FastTypeId(op_))) {
std::unique_ptr<void, DynValueDeleter> obj{flags_internal::Clone(op_, src),
DynValueDeleter{op_}};
std::string ignored_error;
......
......@@ -23,6 +23,7 @@
#include <memory>
#include <string>
#include <type_traits>
#include <typeinfo>
#include "absl/base/call_once.h"
#include "absl/base/config.h"
......@@ -50,7 +51,8 @@ enum class FlagOp {
kCopy,
kCopyConstruct,
kSizeof,
kStaticTypeId,
kFastTypeId,
kRuntimeTypeId,
kParse,
kUnparse,
kValueOffset,
......@@ -96,10 +98,15 @@ inline size_t Sizeof(FlagOpFn op) {
return static_cast<size_t>(reinterpret_cast<intptr_t>(
op(FlagOp::kSizeof, nullptr, nullptr, nullptr)));
}
// Returns static type id coresponding to the value type.
inline FlagStaticTypeId StaticTypeId(FlagOpFn op) {
return reinterpret_cast<FlagStaticTypeId>(
op(FlagOp::kStaticTypeId, nullptr, nullptr, nullptr));
// Returns fast type id coresponding to the value type.
inline FlagFastTypeId FastTypeId(FlagOpFn op) {
return reinterpret_cast<FlagFastTypeId>(
op(FlagOp::kFastTypeId, nullptr, nullptr, nullptr));
}
// Returns fast type id coresponding to the value type.
inline const std::type_info* RuntimeTypeId(FlagOpFn op) {
return reinterpret_cast<const std::type_info*>(
op(FlagOp::kRuntimeTypeId, nullptr, nullptr, nullptr));
}
// Returns offset of the field value_ from the field impl_ inside of
// absl::Flag<T> data. Given FlagImpl pointer p you can get the
......@@ -112,6 +119,16 @@ inline ptrdiff_t ValueOffset(FlagOpFn op) {
op(FlagOp::kValueOffset, nullptr, nullptr, nullptr)));
}
// Returns an address of RTTI's typeid(T).
template <typename T>
inline const std::type_info* GenRuntimeTypeId() {
#if defined(ABSL_FLAGS_INTERNAL_HAS_RTTI)
return &typeid(T);
#else
return nullptr;
#endif
}
///////////////////////////////////////////////////////////////////////////////
// Flag help auxiliary structs.
......@@ -374,9 +391,10 @@ class FlagImpl final : public flags_internal::CommandLineFlag {
// For example if flag is declared as absl::Flag<int> FLAGS_foo, a call to
// absl::GetFlag(FLAGS_foo) validates that the type of FLAGS_foo is indeed
// int. To do that we pass the "assumed" type id (which is deduced from type
// int) as an argument `op`, which is in turn is validated against the type id
// stored in flag object by flag definition statement.
void AssertValidType(FlagStaticTypeId type_id) const;
// int) as an argument `type_id`, which is in turn is validated against the
// type id stored in flag object by flag definition statement.
void AssertValidType(FlagFastTypeId type_id,
const std::type_info* (*gen_rtti)()) const;
private:
template <typename T>
......@@ -433,7 +451,7 @@ class FlagImpl final : public flags_internal::CommandLineFlag {
std::string Filename() const override;
absl::string_view Typename() const override;
std::string Help() const override;
FlagStaticTypeId TypeId() const override;
FlagFastTypeId TypeId() const override;
bool IsModified() const override ABSL_LOCKS_EXCLUDED(*DataGuard());
bool IsSpecifiedOnCommandLine() const override
ABSL_LOCKS_EXCLUDED(*DataGuard());
......@@ -539,14 +557,14 @@ class Flag {
U u;
#if !defined(NDEBUG)
impl_.AssertValidType(&flags_internal::FlagStaticTypeIdGen<T>);
impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
#endif
if (!value_.Get(&u.value)) impl_.Read(&u.value);
return std::move(u.value);
}
void Set(const T& v) {
impl_.AssertValidType(&flags_internal::FlagStaticTypeIdGen<T>);
impl_.AssertValidType(base_internal::FastTypeId<T>(), &GenRuntimeTypeId<T>);
impl_.Write(&v);
}
void SetCallback(const FlagCallbackFunc mutation_callback) {
......@@ -595,8 +613,10 @@ void* FlagOps(FlagOp op, const void* v1, void* v2, void* v3) {
return nullptr;
case FlagOp::kSizeof:
return reinterpret_cast<void*>(static_cast<uintptr_t>(sizeof(T)));
case FlagOp::kStaticTypeId:
return reinterpret_cast<void*>(&FlagStaticTypeIdGen<T>);
case FlagOp::kFastTypeId:
return const_cast<void*>(base_internal::FastTypeId<T>());
case FlagOp::kRuntimeTypeId:
return const_cast<std::type_info*>(GenRuntimeTypeId<T>());
case FlagOp::kParse: {
// Initialize the temporary instance of type T based on current value in
// destination (which is going to be flag's default value).
......
......@@ -284,14 +284,14 @@ namespace {
class RetiredFlagObj final : public flags_internal::CommandLineFlag {
public:
constexpr RetiredFlagObj(const char* name, FlagStaticTypeId type_id)
constexpr RetiredFlagObj(const char* name, FlagFastTypeId type_id)
: name_(name), type_id_(type_id) {}
private:
absl::string_view Name() const override { return name_; }
std::string Filename() const override { return "RETIRED"; }
absl::string_view Typename() const override { return ""; }
FlagStaticTypeId TypeId() const override { return type_id_; }
FlagFastTypeId TypeId() const override { return type_id_; }
std::string Help() const override { return ""; }
bool IsRetired() const override { return true; }
bool IsModified() const override { return false; }
......@@ -317,7 +317,7 @@ class RetiredFlagObj final : public flags_internal::CommandLineFlag {
// Data members
const char* const name_;
const FlagStaticTypeId type_id_;
const FlagFastTypeId type_id_;
};
void DestroyRetiredFlag(flags_internal::CommandLineFlag* flag) {
......@@ -327,7 +327,7 @@ void DestroyRetiredFlag(flags_internal::CommandLineFlag* flag) {
} // namespace
bool Retire(const char* name, FlagStaticTypeId type_id) {
bool Retire(const char* name, FlagFastTypeId type_id) {
auto* flag = new flags_internal::RetiredFlagObj(name, type_id);
FlagRegistry::GlobalRegistry()->RegisterFlag(flag);
return true;
......
......@@ -79,12 +79,12 @@ bool RegisterCommandLineFlag(CommandLineFlag*);
//
// Retire flag with name "name" and type indicated by ops.
bool Retire(const char* name, FlagStaticTypeId type_id);
bool Retire(const char* name, FlagFastTypeId type_id);
// Registered a retired flag with name 'flag_name' and type 'T'.
template <typename T>
inline bool RetiredFlag(const char* flag_name) {
return flags_internal::Retire(flag_name, &FlagStaticTypeIdGen<T>);
return flags_internal::Retire(flag_name, base_internal::FastTypeId<T>());
}
// If the flag is retired, returns true and indicates in |*type_is_bool|
......
......@@ -313,6 +313,7 @@ cc_test(
":strings",
"//absl/base",
"//absl/base:config",
"//absl/base:core_headers",
"//absl/base:endian",
"//absl/base:raw_logging_internal",
"//absl/container:fixed_array",
......
......@@ -578,6 +578,7 @@ absl_cc_test(
absl::strings
absl::base
absl::config
absl::core_headers
absl::endian
absl::raw_logging_internal
absl::fixed_array
......
......@@ -18,6 +18,7 @@
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/macros.h"
#include "absl/container/fixed_array.h"
#include "absl/strings/cord_test_helpers.h"
#include "absl/strings/str_cat.h"
......@@ -1402,6 +1403,53 @@ TEST(CordChunkIterator, Operations) {
VerifyChunkIterator(subcords, 128);
}
TEST(CordChunkIterator, MaxLengthFullTree) {
// Start with a 1-byte cord, and then double its length in a loop. We should
// be able to do this until the point where we would overflow size_t.
absl::Cord cord;
size_t size = 1;
AddExternalMemory("x", &cord);
EXPECT_EQ(cord.size(), size);
const int kCordLengthDoublingLimit = std::numeric_limits<size_t>::digits - 1;
for (int i = 0; i < kCordLengthDoublingLimit; ++i) {
cord.Prepend(absl::Cord(cord));
size <<= 1;
EXPECT_EQ(cord.size(), size);
auto chunk_it = cord.chunk_begin();
EXPECT_EQ(*chunk_it, "x");
}
EXPECT_DEATH_IF_SUPPORTED(
(cord.Prepend(absl::Cord(cord)), *cord.chunk_begin()),
"Cord is too long");
}
TEST(CordChunkIterator, MaxDepth) {
// By reusing nodes, it's possible in pathological cases to build a Cord that
// exceeds both the maximum permissible length and depth. In this case, the
// violation of the maximum depth is reported.
absl::Cord left_child;
AddExternalMemory("x", &left_child);
absl::Cord root = left_child;
for (int i = 0; i < absl::cord_internal::MaxCordDepth() - 2; ++i) {
size_t new_size = left_child.size() + root.size();
root.Prepend(left_child);
EXPECT_EQ(root.size(), new_size);
auto chunk_it = root.chunk_begin();
EXPECT_EQ(*chunk_it, "x");
std::swap(left_child, root);
}
EXPECT_DEATH_IF_SUPPORTED(root.Prepend(left_child), "Cord is too long");
}
TEST(CordCharIterator, Traits) {
static_assert(std::is_copy_constructible<absl::Cord::CharIterator>::value,
"");
......@@ -1580,3 +1628,23 @@ TEST(Cord, SmallBufferAssignFromOwnData) {
}
}
}
TEST(CordDeathTest, Hardening) {
absl::Cord cord("hello");
// These statement should abort the program in all builds modes.
EXPECT_DEATH_IF_SUPPORTED(cord.RemovePrefix(6), "");
EXPECT_DEATH_IF_SUPPORTED(cord.RemoveSuffix(6), "");
bool test_hardening = false;
ABSL_HARDENING_ASSERT([&]() {
// This only runs when ABSL_HARDENING_ASSERT is active.
test_hardening = true;
return true;
}());
if (!test_hardening) return;
EXPECT_DEATH_IF_SUPPORTED(cord[5], "");
EXPECT_DEATH_IF_SUPPORTED(*cord.chunk_end(), "");
EXPECT_DEATH_IF_SUPPORTED(static_cast<void>(cord.chunk_end()->empty()), "");
EXPECT_DEATH_IF_SUPPORTED(++cord.chunk_end(), "");
}
......@@ -155,8 +155,7 @@ enum class FormatConversionChar : uint8_t {
d, i, o, u, x, X, // int
f, F, e, E, g, G, a, A, // float
n, p, // misc
kNone,
none = kNone
kNone
};
// clang-format on
......@@ -288,11 +287,6 @@ class FormatConversionSpec {
// negative value.
int precision() const { return precision_; }
// Deprecated (use has_x_flag() instead).
Flags flags() const { return flags_; }
// Deprecated
FormatConversionChar conv() const { return conversion_char(); }
private:
friend struct str_format_internal::FormatConversionSpecImplFriend;
FormatConversionChar conv_ = FormatConversionChar::kNone;
......@@ -344,15 +338,7 @@ enum class FormatConversionCharSet : uint64_t {
kFloating = a | e | f | g | A | E | F | G,
kNumeric = kIntegral | kFloating,
kString = s,
kPointer = p,
// The following are deprecated
star = kStar,
integral = kIntegral,
floating = kFloating,
numeric = kNumeric,
string = kString,
pointer = kPointer
kPointer = p
};
// Type safe OR operator.
......
......@@ -48,7 +48,7 @@
namespace absl {
ABSL_NAMESPACE_BEGIN
using std::string_view;
using string_view = std::string_view;
ABSL_NAMESPACE_END
} // namespace absl
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment